I want to get multiple inputs as tuples in a list. Example: [(1,2),(1,3),(1,4),(2,5)] I wrote this code, it works not bad. But I'm just wondering if there is another way to do this or can we make this code clear?
def make_tuple(k):
tup_list = []
for i in range(0, len(k)-1, 2):
tup_list.append((k[i],k[i+1]))
return tup_list
list1 = list(map(int, input("Enter multiple values: ").split()))
make_tuple(list1)
In this way, user should enter the input like; 1 2 1 3 1 4 2 5 for getting [(1,2),(1,3),(1,4),(2,5)]. The actual thing I want is enter the input like; 1,2 1,3 1,4 2,5
import ast
a = ast.literal_eval(input('some text: '))
input-(1,2)
output-(1,2)
input-[(1,2)]
output=[(1,2)]
This function will accept any input that look like Python literals, such as integers, lists, dictionaries and strings
ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.
you can use Zip function to achieve this.You can read more on Splitting a long tuple into smaller tuples
a = [int(char) for char in input("Enter multiple values: ")]
def zipper(iterable,n):
args = [iter(iterable)] * n
return zip(*args)
print(*zipper(a,2))
This way if user inputs only 5 digits it can output only 2 tuples of 2 elements each
Related
I want to find if the Input String has Odd Product for distinct numbers:
I did this so far:
# To get input string into list of integer
input = [int(i) for i in input.split()]
# to get odd numbers
sequence=filter(lambda i: i % 2, sequence)
I want to use an operation where I can filter distinct odd numbers in a list and multiply until I get odd number and return true if the result is not odd return false.
I am new to lamda and filter.
I want to know how can I do using this in one statement in Python
You can use itertools.accumulate to repeatedly apply a function (e.g. multiplication) to an iterable:
>>> from itertools import accumulate
>>> bool(list(accumulate({int(i) for i in input().split() if int(i) % 2}, int.__mul__))[-1] % 2)
1 2 3 4 5
True
For filtering distinct odd numbers in a list you can use list comprehension along with set(set is used to get distinct values).
input = [int(i) for i in input().split()]
input = list(set([i for i in input if i%2!=0])) # it would give distinct odd values
I'm a beginner to Python 3 and when I try this code it works:
a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i) for i in b]
print(mylist)
Output:
Enter three digits separated by space:2 3 4
[2, 3, 4]
However I get errors when I try this:
a = input('Enter three digits separated by space:')
b = a.split()
mylist = [int(i**2) for i in b]
print(mylist)
Error: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
In fact this works as well:
list1 = [2,3,4]
mylist = [int(i**2) for i in list1]
print(mylist)
What am I doing wrong?
You might want to do exponentiation after converting to an int:
mylist = [int(i)**2 for i in list1]
You can't raise a string to a power (do you know what the square of the string "blah" is?), but you can raise a number to a power. So you need to convert the string to a number first.
Of course, a.split() returns a list of smaller strings derived from the original string, and you have to turn them into numbers yourself, but you already figured this out.
Error in your code: you are trying to raise power before converting it to int
int(i**2)
#should be
int(i)**2
Another approach, using map function.
Syntax: map(func, iterable)
In python, String is iterable which means you can iterate over it. For example:
for i in "hello":
print(i)
#output will be:
h
e
l
l
o
Another simple concept before moving to map function: split() function will return the list.
print(type("hello".split()))
#output will be
<class 'list'>
Lets use map function to answer your question:
a = map(int, input('Enter three digits separated by space:').split())
mylist = [i**2 for i in a]
print(mylist)
Explanation:
The input() function will ask user to enter three numbers separated by space and that
will be a string, now you can use split function over the string returned by input().
Here, split function will return a list.
Now, map function comes into the picture, it will take each element
from the list returned at step 2 and map it to the function, in
this case, it will map each element of the list to int.
Variable a is map object, and map object is iterable, so you can
apply for loop or list comprehension(you used list comprehension) to get desired output
you have to give condition for split like " "
suppose the input is 2 3 4 and you want to split it as 2,3,4. and also the input return value as str so you have to change it to int as follows then you can use **
a = input('Enter three digits separated by space:')
b = map(int,a.split(" "))
mylist = [i**2 for i in b]
this will work for you..
How to read an integer list from single line input along with a range in Python 3?
Requirement: reading integer values for a given list separated by a space from single line input but with a range of given size.
example:
Range = 4
Then list size = 4
Then read the input list from a single line of size 4
I tried below list comprehension statement, but it is reading a list from 4 lines [i.e creating 4 lists with each list representing values from a given line] instead of reading only 1 list with a size of 4
no_of_marks = 4
marksList = [list(int(x) for x in input().split()) for i in range(no_of_marks)]
Can someone help me in achieving my requirement?
You can use str.split directly, passing the no_of_marks for being maxsplit parameter:
no_of_marks = 4
res = [int(x) for x in input().split(" ", no_of_marks)]
Here you have the live example
Split the string, slice it to only take the first n words, and then turn them into integers.
marks = [int(x) for x in input().split()[:n]]
This will not fail if the input has fewer than n integers, so you should also check the length of the list
if len(marks) < n:
raise ValueError("Not enough inputs")
Given List:
l = [1,32,523,336,13525]
I am having a number 23 as an output of some particular function.
Now,
I want to remove all the numbers from list which contains either 2 or 3 or both 2 and 3.
Output should be:[1]
I want to write some cool one liner code.
Please help!
My approach was :
1.) Convert list of int into list of string.
2.) then use for loop to check for either character 2 or character 3 like this:
A=[x for x in l if "2" not in x] (not sure for how to include 3 also in this line)
3.) Convert A list into integer list using :
B= [int(numeric_string) for numeric_string in A]
This process is quiet tedious as it involves conversion to string of the number 23 as well as all the numbers of list.I want to do in integer list straight away.
You could convert the numbers to sets of characters:
>>> values = [1, 32, 523, 336, 13525]
>>> number = 23
>>> [value for value in values
... if set(str(number)).isdisjoint(set(str(value)))]
[1]
You're looking for the filter function. Say you have a list of ints and you want the odd ones only:
def is_odd(val):
return val % 2 == 1
filter(is_odd, range(100))
or a list comprehension
[x for x in range(100) if x % 2 == 1]
The list comprehension in particular is perfectly Pythonic. All you need now is a function that returns a boolean for your particular needs.
So I'm a freshman comp sci major. I'm taking a class that teaches Python. This is my assignment:
Create a function that takes a string and a list as parameters. The string should contain the first ten letters of the alphabet and the list should contain the corresponding numbers for each letter. Zip the string and list into a list of tuples that pair each letter and number. The function should then print the number and corresponding letter respectively on separate lines. Hint: Use the zip function and a loop!
This is what I have so far:
def alpha(letter, number):
letter = "abcdefghij"
number = [1,2,3,4,5,6,7,8,9,10]
return zip(letter, number)
print alpha(letter, number)
The problem I have is an error on line 5 that says 'letter' is not defined. I feel like there should be a for loop but, I don't know how to incorporate it. Please help me.
zip works on iterables (strings and lists are both iterables), so you don't need a for loop to generate the pairs as zip is essentially doing that for loop for you. It looks like you want a for loop to print the pairs however.
Your code is a little bit confused, you'd generally want to define your variables outside of the function and make the function as generic as possible:
def alpha(letter, number):
for pair in zip(letter, number):
print pair[0], pair[1]
letter = "abcdefghij"
number = [1,2,3,4,5,6,7,8,9,10]
alpha(letter, number)
The error you are having is due to the scope of the variables. You are defining letter and number inside of the function, so when you call alpha(letter,number) they have not been defined.
For printing the result you could iterate the result of zip, as in the following example:
def alpha(letters, numbers):
for c,n in zip(letters,numbers):
print c,n
letters = "abcdefghij"
numbers = range(1,11)
alpha(letters, numbers)
Output:
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10