How to limit the user input in range? - python

2 inputs has to enter by the user. first number is How many elements you can enter?
Let's say 5, then user can only insert 5 elements
K = int(input())
L =[]
for i in range(K):
L.append(i)
K =5
we need to enter 5 values like 11 22 33 44 55
Desired out put
L = [11,22,33,44,55]
Can we do something like
k=int(input())
L = list(input().split()) for _ in range(k)
so that I can give the digits in one shot

All you're missing here is the second input that the for loop.
K = int(input())
L =[]
for i in range(K):
L.append(input())
print(L)

Can you be specific and clear.I cant understand what you are trying to ask.Limiting the range in input? You aldready limit you input by fixing a range.
If i understood your question correctly then here is my solution:
k=int(input())
print([input() for i in range(k)])
This is the easiest way rather than appending.
If you need to give space seperated input then you can use split funtion

K = int(raw_input())
print K
finalList = []
for i in range(K):
finalList.append(int(raw_input()))
print finalList
OUTPUT:
python test4.py
5
5
11
22
33
44
55
[11, 22, 33, 44, 55]

If I'm understanding the question correctly, you're just missing one line. You ask for the user to specify K, which they do. You follow it with a loop that runs K-times. However, you forgot to have the user input these K values into L
Adding that extra line would look something like this:
for i in range(K):
input_int = int( input() )
L.append( input_int )

Related

For all sets in a list, extract the first number only

I have a list that looks like this:
b = [{'dg_12.942_ch_293','dg_22.38_ca_627'},
{'dg_12.651_cd_286','dg_14.293_ce_334'},
{'dg_17.42_cr_432','dg_18.064_cm_461','dg_18.85_cn_474','dg_20.975_cf_489'}]
I want to keep only the first number for each item in each set:
b = [{'12','22'},
{'12','14'},
{'17','18','18','20'}]
I then want to find the difference between the smallest and the largest number of each set and put it in a list, so in this case I would have:
b = [3,2,3]
Ugly and without any sanity check, but do the work.
import re
SEARCH_NUMBER_REGEX = re.compile("(\d+)")
def foo(dataset):
out = []
for entries in dataset:
numbers = []
for entry in entries:
# Search for the first number in the str
n = SEARCH_NUMBER_REGEX.search(entry).group(1)
n = int(n)
numbers.append(n)
# Sort the numbers and sustract the last one (largest)
# by the first one (smallest)
numbers.sort()
out.append(numbers[-1] - numbers[0])
return out
b = [
{'dg_12.942_ch_293', 'dg_22.38_ca_627'},
{'dg_12.651_cd_286', 'dg_14.293_ce_334'},
{'dg_17.42_cr_432', 'dg_18.064_cm_461', 'dg_18.85_cn_474', 'dg_20.975_cf_489'}
]
print(b)
# > [10, 2, 3]
This is giving o/p as [10,2,3]
(The difference b/w 22 and 12 is 10)
b = [{'12','22'},
{'12','14'},
{'17','18','18','20'}]
l = []
for i in b:
large ,small = -99, 99
for j in i:
j = int(j)
if large < j:
large = j
if small >j:
small = j
l.append(large - small)
print(l)
Here's yet another way to do it:
import re
ba = [{'dg_12.942_ch_293', 'dg_22.38_ca_627'},
{'dg_12.651_cd_286', 'dg_14.293_ce_334'},
{'dg_17.42_cr_432', 'dg_18.064_cm_461', 'dg_18.85_cn_474', 'dg_20.975_cf_489'}]
bb = []
for s in ba:
ns = sorted([int(re.search(r'(\d+)', ss)[0]) for ss in s])
bb.append(ns[-1]-ns[0])
print(bb)
Output:
[10, 2, 3]
Or, if you want to be ridiculous:
ba = [{'dg_12.942_ch_293', 'dg_22.38_ca_627'},
{'dg_12.651_cd_286', 'dg_14.293_ce_334'},
{'dg_17.42_cr_432', 'dg_18.064_cm_461', 'dg_18.85_cn_474', 'dg_20.975_cf_489'}]
bb = [(n := sorted([int(re.search(r'(\d+)', ss)[0]) for ss in s]))[-1]-n[0] for s in ba]
print(bb)
In your final product I see it was "[3,2,3]" but if I am understanding your question correct, it would be [10,2,3]. Either way the code I have below will atleast point you in the right direction (hopefully).
This code will iterate through each tuple in the list and split the str (since that is all we want to compare) and add them into lists. These numbers are then evaluated and subtracts the smallest number from the biggest number, and places it in a separate array. This "separate array" is the final one as shown in your question.
Goodluck - hopefully this helps!
import re
b = [('dg_12.942_ch_293','dg_22.38_ca_627'), ('dg_12.651_cd_286','dg_14.293_ce_334'), ('dg_17.42_cr_432','dg_18.064_cm_461','dg_18.85_cn_474','dg_20.975_cf_489')]
final_array = []
for tup in b:
x = tup
temp_array = []
for num in x:
split_number = re.search(r'\d+', num).group()
temp_array.append(split_number)
difference = int(max(temp_array)) - int(min(temp_array))
final_array.append(difference)
print(final_array)

Python - multiple combinations maths question

I'm trying to make a program that lists all the 64 codons/triplet base sequences of DNA...
In more mathematical terms, there are 4 letters: A, T, G and C.
I want to list all possible outcomes where there are three letters of each and a letter can be used multiple times but I have no idea how!
I know there are 64 possibilities and I wrote them all down on paper but I want to write a program that generates all of them for me instead of me typing up all 64!
Currently, I am at this point but I have most surely overcomplicated it and I am stuck:
list = ['A','T','G','C']
list2 = []
y = 0
x = 1
z = 2
skip = False
back = False
for i in range(4):
print(list[y],list[y],list[y])
if i == 0:
skip = True
else:
y=y+1
for i in range(16):
print(list[y],list[y],list[x])
print(list[y],list[x], list[x])
print(list[y],list[x], list[y])
print(list[y],list[x], list[z])
if i == 0:
skip = True
elif z == 3:
back = True
x = x+1
elif back == True:
z = z-1
x = x-1
else:
x = x+1
z = z+1
Any help would be much appreciated!!!!
You should really be using itertools.product for this.
from itertools import product
l = ['A','T','G','C']
combos = list(product(l,repeat=3 ))
# all 64 combinations
Since this produces an iterator, you don't need to wrap it in list() if you're just going to loop over it. (Also, don't name your list list — it clobbers the build-in).
If you want a list of strings you can join() them as John Coleman shows in a comment under your question.
list_of_strings = ["".join(c) for c in product(l,repeat=3) ]
Look for for pemuations with repetitions there tons of code available for Python .
I would just use library , if you want to see how they implemented it look inside the library . These guys usually do it very efficiency
import itertools
x = [1, 2, 3, 4, 5, 6]
[p for p in itertools.product(x, repeat=2)]

Keep elements in list whose digits add up to a certain value

From a list find out those values whose addition makes 9
aList=[81,26,27,19,108]
output, 81(because: 8+1),27(because: 2+7) and 108 (because:1+0+8)
I tried 2 approaches:
1st approach: I could not find a way to get the value, just get the sum
s=[81,18]
sum=0
for l in s:
while l:
l,dig=divmod(l,10)
sum=sum+dig
print(sum)
2nd approach: Nasty one indeed. Take individual values from list, convert to string to separate them and again convert to int.
s=[81] #9
sum=0
for item in s: #81
item=str(item) # 81 to string so I can get 8 and 1
for i in item:
while i:
i =int(i)
i,dig=divmod(i,10)
sum=sum+dig
print(sum,item)
Problem: In both cases it only works when I have single value in the list. When I have more than 1 value aList=[81,18] it gives me sum of those 2.
I would appreciate some hints/ideas on this one. Thanks in advance.
You could use the following list comprehension:
l = [81,26,27,19,108]
[i for i in l if sum(int(d) for d in str(i)) == 9]
# [81, 27, 108]
Which is equivalent to the following for loop:
res = []
for i in aList:
temp = []
for d in str(i):
temp.append(int(d))
if sum(temp) == 9:
res.append(i)

How to take Nested List as input in Python

I have to take input from the user in the following format and make a nested list from it. The first line is the number of rows.
3
Sourav Das 24 M
Titan Das 23 M
Gagan Das 22 F
The nested list should be like :
parentlist = [
['Sourav', 'Das', '24', 'M']
['Titan', 'Das', '23', 'M']
['Gagan', 'Das', '22', 'M']
]
I have written the following code :
k = int(raw_input())
parentlist = [[]]
for i in range(0, k):
str1 = raw_input()
parentlist[i] = str1.split()
But it gives some index out of bound exception after entering the 2nd row (as shown below). What's wrong in the code for which it is giving this exception ?
3
Sourav Das 24 M
Titan Das 23 M
Traceback (most recent call last):
File "nested.py", line 5, in <module>
parentlist[i] = str1.split()
IndexError: list assignment index out of range
(I am new to Python. So point out any other mistakes too if you find any in my code.)
When your reading the second line, you attempt to store the splitted line into parentlist[1]. But your parentlist has only one element (parentlist[0]).
The solution is to append the list.
k = int(raw_input())
parentlist = []
for i in range(0, k):
str1 = raw_input()
parentlist.append(str1.split())
Your parentlist is a list with one element. On the second iteration for your for loop, you try to access the second element of parentlist, that causes the IndexError. Lists in Python work different from e.g. arrays in JavaScript or PHP.
What you actually want to do is create an empty list and then append the result of str1.split() to it.
k = int(raw_input())
parentlist = []
for i in range(0, k):
str1 = raw_input()
parentlist.append(str1.split())
You should simply use list comprehension as code will be shorter and faster.
k = int(raw_input())
l = []
print [raw_input().split() for i in range(0, k)]
In Python 3:
l= [[input(), float(input())] for _ in range(int(input()))]
print l
Input:
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
Output:
[[Harry,37.21],[Berry,37.21],[Tina,37.2],[Akriti,41],[Harsh,39]]
You were quite close
k = int(raw_input())
parentlist = []
for i in range(k):
str1 = raw_input()
parentlist.append(str1.split())
initialize parentlist to an empty list, it is important because later we want to extend it
read an input line
split the input line -> a list
tell the parentlist to append the new list to what it has already got
If you want to go in a bad direction, you can do, similar to your code
parentlist = [[]]*k
for i in range(k):
parentlist[i] = raw_input().split()
Exercise, find what the syntax [[]]*k stands for...
Size of your parentlist [[]] is 1, where on 0 position empty list.
Your code would be work if you put into parentlist k lists:
parentlist = [[]] * k
Or use append instead, but with append additional look up of method name is necessary.
l=[]
for _ in range(int(input())):
name = input()
score = float(input())
l.append([name,score])
print(l)
scorelist =[]
n = int(input())
for i in range(n):
name.append(str(input()))
score.append(float(input()))
for i in range(n):
scorelist.append([name[i],score[i]])
print(scorelist)
k = int(input())
parentlist = [None]*k
for i in range(0, k):
str1 = input()
parentlist[i] = str1.split()
print(parentlist)
You can also use something like this :-
k = int(input())
parentlist = []
for i in range(k):
parentlist.append([j for j in input().split()])
print(parentlist)

Looping a specific amount of times, each time making a new list

Basically what I want to do is have a program that makes a list based on user input, such as:
a=input
b=input
c=input
list1=[a,b,c]
then have it do it again (forming list2) and again and so on, until it reaches list37, where I want to make a list of lists, such as:
listMASTER=[list1,list2,list3...list36]
I don't want to write this:
a=input
b=input
c=input
listn=[a,b,c]
36 times, so I want it to loop over and over again with each time forming a new list.
Try something like this:
outer_listen = []
n = 36 #Or howmany ever times you want to loop
for i in range(n): #0 through 35
a = input()
b = input()
c = input()
lstn = [a, b, c]
outer_listen.append(lstn)
Use this way to do it easily:
olist=[]
for i in range(n): #n is the number of items you need the list (as in your case, 37)
lis=[input(),input(),input()]
olist.append(lis)
This will reduce the number of steps
You could use nested loops:
list_of_lists = [[input() for _ in range(3)] for _ in range(36)]
Or more conveniently, also accept the input from a file e.g., using csv format:
a,b,c
d,f,g
...
Corresponding code:
import csv
import fileinput
list_of_lists = list(csv.reader(fileinput.input()))
Usage:
$ python make-list.py input.csv
Or
$ echo a,b,c | python make-list.py
A bit dense but still readable with a list comprehension
n = 36
prompt = 'Please enter for {}{}: '
all_inputs = [[input(prompt.format(char, num)) for char in 'abc']
for num in range(n)]
print(all_inputs)
Gives you 36 x 3 input prompts:
Please enter for a0: 1
Please enter for b0: 2
Please enter for c0: 3
Please enter for a1: 4
Please enter for b1: 5
Please enter for c1: 6
...
[['1', '2', '3'], ['4', '5', '6'], ...]
master = [[input(),input(),input()] for i in xrange(37)]

Categories