Given a list of integers write a Python code to triple all the values in the list

Python: Triple all numbers of a given list of integers using map function

Last update on October 13 2020 17:28:52 (UTC/GMT +8 hours)

Python: Add three lists using map function and lambda

Last update on October 14 2020 06:36:45 (UTC/GMT +8 hours)

Python | Find all triplets in a list with given sum

Given a list of integers, write a Python program to find all triplets that sum up to given integer ‘k’.

Examples:

Input : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 10 Output : [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)] Input : [12, 3, 6, 1, 6, 9], k = 24 Output : [(12, 6, 6), (12, 9, 3)]

Approach #1 : Naive (Using set)
In this approach, we use two for loops. The first loop sets first element, another to check whether other two elements including first sums up to k or not. This approach takes O(n2) time complexity.




# Python3 program to Find total number
# of triplets in a temp_list with given k
def findTriplets(lst, k):
triplet_count = 0
final_temp_list =[]
for i in range(0, len(lst)-1):
s = set()
temp_list = []
# Adding first element
temp_list.append(lst[i])
curr_k = k - lst[i]
for j in range(i + 1, len(lst)):
if (curr_k - lst[j]) in s:
triplet_count += 1
# Adding second element
temp_list.append(lst[j])
# Adding third element
temp_list.append(curr_k - lst[j])
# Appending tuple to the final list
final_temp_list.append(tuple(temp_list))
temp_list.pop(2)
temp_list.pop(1)
s.add(lst[j])
return final_temp_list
# Driver Code
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
k = 10
print(findTriplets(lst, k))
Output: [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)]


Approach #2 : Using itertools
Python itertools module provide combination(iterable, r) function. This tool returns the r length subsequences of elements from the input iterable. Every time we make a combination of 3 elements and check if they sums up to k or not.




# Python3 program to Find total number
# of triplets in a list with given sum
from itertools import combinations
def findTriplets(lst, key):
def valid(val):
return sum(val) == key
return list(filter(valid, list(combinations(lst, 3))))
# Driver Code
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(findTriplets(lst, 10))
Output: [(1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python Programs
Python list-programs
Read Full Article

Python | Ways to create triplets from given list

Given a list of words, write a Python program to create triplets from the given list.

Examples :

Input: [‘Geeks’, ‘for’, ‘Geeks’, ‘is’, ‘best’, ‘resource’, ‘for’, ‘study’]
Output:
[[‘Geeks’, ‘for’, ‘Geeks’], [‘for’, ‘Geeks’, ‘is’],
[‘Geeks’, ‘is’, ‘best’], [‘is’, ‘best’, ‘resource’],
[‘best’, ‘resource’, ‘for’], [‘resource’, ‘for’, ‘study’]]

Input: [‘I’, ‘am’, ‘Paras’, ‘Jain’, ‘I’, ‘Study’, ‘From’, ‘GFG’]
Output:
[[‘I’, ‘am’, ‘Paras’], [‘am’, ‘Paras’, ‘Jain’],
[‘Paras’, ‘Jain’, ‘I’], [‘Jain’, ‘I’, ‘Study’],
[‘I’, ‘Study’, ‘From’], [‘Study’, ‘From’, ‘GFG’]]

Let’s see some of the methods to do this task.



Method #1: Using List comprehension




# Python code to create triplets from list of words.
# List of word initialization
list_of_words = ['I', 'am', 'Paras', 'Jain',
'I', 'Study', 'DS', 'Algo']
# Using list comprehension
List = [list_of_words[i:i + 3]
for i in range(len(list_of_words) - 2)]
# printing list
print(List)
Output: [['I', 'am', 'Paras'], ['am', 'Paras', 'Jain'], ['Paras', 'Jain', 'I'], ['Jain', 'I', 'Study'], ['I', 'Study', 'DS'], ['Study', 'DS', 'Algo']]


Method #2: Using Iteration




# Python code to create triplets from list of words.
# List of word initialization
list_of_words = ['Geeks', 'for', 'Geeks', 'is',
'best', 'resource', 'for', 'study']
# Output list initialization
out = []
# Finding length of list
length = len(list_of_words)
# Using iteration
for z in range(0, length-2):
# Creating a temp list to add 3 words
temp = []
temp.append(list_of_words[z])
temp.append(list_of_words[z + 1])
temp.append(list_of_words[z + 2])
out.append(temp)
# printing output
print(out)
Output: [['Geeks', 'for', 'Geeks'], ['for', 'Geeks', 'is'], ['Geeks', 'is', 'best'], ['is', 'best', 'resource'], ['best', 'resource', 'for'], ['resource', 'for', 'study']]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python Programs
Python list-programs
python-list
Practice Tags :
python-list
Read Full Article

3. An Informal Introduction to Python¶

In the following examples, input and output are distinguished by the presence or absence of prompts (>>> and ): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.

You can toggle the display of prompts and output by clicking on >>> in the upper-right corner of an example box. If you hide the prompts and output for an example, then you can easily copy and paste the input lines into your interpreter.

Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, #, and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.

Some examples:

# this is the first comment spam = 1 # and this is the second comment # ... and now a third! text = "# This is not a comment because it's inside quotes."

How to Use Python: Your First Steps

by Leodanis Pozo Ramos basics python
Mark as Completed
Tweet Share Email

Table of Contents

Remove ads

Are you looking for a place to learn the basics of how to use Python from a beginner’s perspective? Do you want to get up and running with Python but don’t know where to start? If so, then this tutorial is for you. This tutorial focuses on the essentials you need to know to start programming with Python.

In this tutorial, you’ll learn:

  • What Python is and why you should use it
  • What basic Python syntax you should learn to start coding
  • How to handle errors in Python
  • How to get help quickly in Python
  • What code style you should apply in your code
  • Where to get extra functionalities without reinventing the wheel
  • Where to find quality Python content and grow your skills

You’ll also have the opportunity to create your first Python program and run it on your computer. Finally, you’ll have a chance to evaluate your progress with a quiz that’ll give you an idea of how much you’ve learned.

Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Video liên quan

Postingan terbaru

LIHAT SEMUA