How to take specific number of input in python - python-2.7

How do I take a specific number of input in python. Say, if I only want to insert 5 elements in a list then how can I do that?
I tried to do it but couldn't figure out how.
In the first line I want to take an integer which will be the size of the list.
Second line will consist 5 elements separated by a space like this:
5
1 2 3 4 5
Thanks in advance.

count = int(raw_input("Number of elements:"))
data = raw_input("Data: ")
result = data.split(sep=" ", maxsplit=count)
if len(result) < count:
print("Too few elements")
You can also wrap int(input("Number of elements:")) in try/except to ensure that first input is actually int.
p.s. here is helpful q/a how to loop until correct input.

Input :-
5
1 2 3 4 5
then, use the below code :
n = int(input()) # Number of elements
List = list ( map ( int, input().split(" ") ) )
Takes the space separated input as list of integers. Number of elements count is not necessary here.
You can get the size of the List by len(List) .
Here list is a keyword for generating a List.
Or you may use an alternative :
n = int(input()) # Number of elements
List = [ int(elem) for elem in input().split(" ") ]
If you want it as List of strings, then use :
List = list( input().split(" ") )
or
s = input() # default input is string by using input() function in python 2.7+
List = list( s.split(" ") )
Or
List = [ elem for elem in input().split(" ") ]
Number of elements count is necessary while using a loop for receiving input in a new line ,then
Let the Input be like :
5
1
2
3
4
5
The modified code will be:-
n = int(input())
List = [ ] #declare an Empty list
for i in range(n):
elem = int(input())
List.append ( elem )
For Earlier version of python , use raw_input ( ) instead of input ( ), which receives default input as String.

Related

Python 3.5 loop to generate a new list each iteration

I'm trying to write some code that (pseudo-randomly) generates a list of 7 numbers. I have it working for a single run. I'd like to be able to loop this code to generate multiple lists, which I can output to a txt file (I don't need help with this I'm quite comfortable working with i/o and files :)
I'm now using this code (thanks Jason for getting it this far):
import random
pool = []
original_pool = list( range( 1,60))
def selectAndPrune(x):
pool = []
list1 = []
random.shuffle(pool)
pool = original_pool.copy()
current_choice = random.choice(pool)
list1.append(current_choice)
pool.remove(current_choice)
random.shuffle(pool)
print(list1)
def repeater():
for i in range(19):
pool_list = []
pool = original_pool.copy()
a = [ selectAndPrune(pool) for x in range(7)]
pool_list.append(a)
repeater()
This is giving output of single value lists like:
[21]
[1]
[54]
[48]
[4]
[32]
[15]
etc.
The output I want is 19 lists, all containing 7 random ints:
[1,4,17,23,45,51,3]
[10,2,9,38,4,1,24]
[15,42,35,54,43,28,14]
etc
If I am understanding the question correctly, the objective is to repeat a function 19 times. However, this function slowly removes items from the list at each call, making it impossible to run past the size of the pool as currently written in the question. I suspect that the solution is something like this:
import random
def spinAndPrune():
random.shuffle( pool )
current_choice = random.choice( pool )
pool.remove( current_choice )
random.shuffle( pool )
return current_choice
First, I added a return command at the end of the function call. Next, you can make copy of the original pool, so that it is possible to re-run it as many times as desired. Also, you need to store the lists you want to keep:
# create an original pool of values
original_pool = list( range( 1, 60 ) )
# initialize a variable that stores previous runs
pool_list = []
# repeat 19 times
for i in range( 19 ):
# create a copy of the original pool to a temporary pool
pool = original_pool.copy()
# run seven times, storing the current choice in variable a
a = [ spinAndPrune() for x in range( 7 ) ]
# keep track of variable a in the pool_list
pool_list.append( a )
print( a )
Note the .copy() function to make a copy of the list. As an aside, the range() makes it easy to create lists containing integers 1-59.
If you need to extract a specific list, you can do something along the lines of this:
# print first list
print( pool_list[ 0 ] )
# print fifth list
print( pool_list[ 4 ] )
# print all the lists
print( pool_list )
In my other answer, I approached it by modifying the code in the original question. However, if the point is just to extract X number of values without repeat in a collection/list, it is probably easiest to just use the random.sample() function. The code can be something along the lines of this:
import random
pool = list( range( 1, 60 ) )
pool_list = []
# sample 19 times and store to the pool_list
for i in range( 19 ):
sample = random.sample( pool, 7 )
pool_list.append( sample )
print( sample )

Find starting and ending index of each unique charcters in a string in python

I have a string with characters repeated. My Job is to find starting Index and ending index of each unique characters in that string. Below is my code.
import re
x = "aaabbbbcc"
xs = set(x)
for item in xs:
mo = re.search(item,x)
flag = item
m = mo.start()
n = mo.end()
print(flag,m,n)
Output :
a 0 1
b 3 4
c 7 8
Here the end index of the characters are not correct. I understand why it's happening but how can I pass the character to be matched dynamically to the regex search function. For instance if I hardcode the character in the search function it provides the desired output
x = 'aabbbbccc'
xs = set(x)
mo = re.search("[b]+",x)
flag = item
m = mo.start()
n = mo.end()
print(flag,m,n)
output:
b 2 5
The above function is providing correct result but here I can't pass the characters to be matched dynamically.
It will be really a help if someone can let me know how to achieve this any hint will also do. Thanks in advance
String literal formatting to the rescue:
import re
x = "aaabbbbcc"
xs = set(x)
for item in xs:
# for patterns better use raw strings - and format the letter into it
mo = re.search(fr"{item}+",x) # fr and rf work both :) its a raw formatted literal
flag = item
m = mo.start()
n = mo.end()
print(flag,m,n) # fix upper limit by n-1
Output:
a 0 3 # you do see that the upper limit is off by 1?
b 3 7 # see above for fix
c 7 9
Your pattern does not need the [] around the letter - you are matching just one anyhow.
Without regex1:
x = "aaabbbbcc"
last_ch = x[0]
start_idx = 0
# process the remainder
for idx,ch in enumerate(x[1:],1):
if last_ch == ch:
continue
else:
print(last_ch,start_idx, idx-1)
last_ch = ch
start_idx = idx
print(ch,start_idx,idx)
output:
a 0 2 # not off by 1
b 3 6
c 7 8
1RegEx: And now you have 2 problems...
Looking at the output, I'm guessing that another option would be,
import re
x = "aaabbbbcc"
xs = re.findall(r"((.)\2*)", x)
start = 0
output = ''
for item in xs:
end = start + len(item[0])
output += (f"{item[1]} {start} {end}\n")
start = end
print(output)
Output
a 0 3
b 3 7
c 7 9
I think it'll be in the Order of N, you can likely benchmark it though, if you like.
import re, time
timer_on = time.time()
for i in range(10000000):
x = "aabbbbccc"
xs = re.findall(r"((.)\2*)", x)
start = 0
output = ''
for item in xs:
end = start + len(item[0])
output += (f"{item[1]} {start} {end}\n")
start = end
timer_off = time.time()
timer_total = timer_off - timer_on
print(timer_total)

nested list of lists of inegers - doing arithmetic operation

I have a list like below and need to firs add items in each list and then multiply all results 2+4 = 6 , 3+ (-2)=1, 2+3+2=7, -7+1=-6 then 6*1*7*(-6) = -252 I know how to do it by accessing indexes and it works (as below) but I also need to do it in a way that it will work no matter how many sublist there is
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
a= nested_lst[0][0] + nested_lst[0][1]
b= nested_lst[1][0] + nested_lst[1][1]
c= nested_lst[2][0] + nested_lst[2][1] + nested_lst[2][2]
d= nested_lst[3][0] + nested_lst[3][1]
def sum_then_product(list):
multip= a*b*c*d
return multip
print sum_then_product(nested_lst)
I have tried with for loop which gives me addition but I don't know how to perform here multiplication. I am new to it. Please, help
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
for i in nested_lst:
print sum(i)
Is this what you are looking for?
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]] # your list
output = 1 # this will generate your eventual output
for sublist in nested_lst:
sublst_out = 0
for x in sublist:
sublst_out += x # your addition of the sublist elements
output *= sublst_out # multiply the sublist-addition with the other sublists
print(output)

Sorting of numeric values in python

Here i get the input from the user.
This is my code
num_array=list()
x=int(raw_input('Enter the numbers:'))
for i in range(int(x)):
n=raw_input("")
num_array.append(int(n))
print("\nThe numbers in ascending order are:%d" %(num_array.sort())
And when i want to print the numbers ,it is showing me an error.
I want output to look like this
Enter the number:
5
4
3
2
1
The numbers in ascending order are 1 2 3 4 5
Here is your code
num_array=list()
x=int(raw_input('Enter the numbers:'))
for i in range(int(x)):
n=raw_input("")
num_array.append(int(n))
#print(sorted(num_array))
arr = sorted(num_array)
output = ""
for x in arr:
output = output + str(x) + " "
print(output)
this may be what you want (replaced % print statement with .format() syntax).
num_array.sort() will sort your array but will return None (and that is what your print statement will try to print). sorted on the other hand returns a list.
num_array = []
x = int(raw_input('Enter length of the array: '))
for i in range(int(x)):
n = raw_input("number '{}': ".format(i))
num_array.append(int(n))
print("\nThe numbers in ascending order are: {}".format(sorted(num_array)))
if you do not want the output to look like a python list you could to this:
sorted_str = ' '.join(str(n) for n in sorted(num_array))
print("\nThe numbers in ascending order are: {}".format(sorted_str))

Taking First Two Elements in List

I am trying to script a dynamic way way to only take the first two elements in a list and I am having some trouble. Below is a breakdown of what I have in my List
Declaration:
Set List = CreateObject("Scripting.Dictionary")
List Contents:
List(0) = 0-0-0-0
List(1) = 0-1-0-0
List(2) = 0-2-0-0
Code so far:
for count = 0 To UBound(List) -1 step 1
//not sure how to return
next
What I currently have does not work.
Desired Return List:
0-0-0-0
0-1-0-0
You need to use the Items method of the Dictionary. For more info see here
For example:
Dim a, i
a = List.Items
For i = 0 To List.Count - 1
MsgBox(a(i))
Next i
or if you just want the first 2:
For i = 0 To 1
MsgBox(a(i))
Next i
UBound() is for arrays, not dictionaries. You need to use the Count property of the Dictionary object.
' Show all dictionary items...
For i = 0 To List.Count - 1
MsgBox List(i)
Next
' Show the first two dictionary items...
For i = 0 To 1
MsgBox List(i)
Next