Here's issue I am learning python newly i want to use loop for generating inputs from user which are then operated for some custom function (say Lcm or squaring them and returning ) so how to perform code
Consider
k,l=0,0
while l>=10:
n_k=input("Enter")
k=k+1
l=l+1
#Do something within for loop
#here problem begins
#lets say i am dividing each variable by c which is here in for loop
for c in range(somevalue,0,-1):
now how should i operate the variables clearly i have no intention writting n_0%c ,n_1%c etc
Any Help???
Instead of n_k being a single variable i think you want n to be a list. A list is just a bunch of variables stored together. For example the code:
n = [1, 4, 2]
print(n[0]) #0th element of the list
print(n[1]) #1st element of the list
print(n[2]) #2nd element of the list
outputs
1
4
2
the line n = [1, 4, 2] is just defining the list. The elements of the list are accessed using the n[index] notation.
In python you can also add elements to a list at any time using the append statement. To illustrate let's define an empty list and add some elements to it.
n = []
n.append(8)
Now if we try
print(n[0])
the code will print 8.
So let's say we wanted to square a list of numbers we receive from user input, we would write
n = []
k = 0
num_inputs = 10
while k < num_inputs:
n.append(input("Enter:"))
k = k + 1
k = 0
while k < num_inputs:
print(n[k] * n[k])
k = k + 1
Hope it helps.
Related
I am trying to create a list of data in a for loop then store this list in a list if it satisfies some condition. My code is
R = 10
lam = 1
proc_length = 100
L = 1
#Empty list to store lists
exponential_procs_lists = []
for procs in range(0,R):
#Draw exponential random variables
z_exponential = np.random.exponential(lam,proc_length)
#Sort values to increase
z_exponential.sort()
#Insert 0 at start of list
z_dat_r = np.insert(z_exponential,0,0)
sum = np.sum(np.diff(z_dat_r))
if sum < 5*L:
exponential_procs_lists.append(z_dat_r)
which will store some of the R lists that satisfies the sum < 5L condition. My question is, what is the best way to store R lists where the sum of each list is less than 5L? The lists can be different length but they must satisfy the condition that the sum of the increments is less than 5*L. Any help much appreciated.
Okay so based on your comment, I take that you want to generate an exponential_procs_list, inside which every sublist has a sum < 5*L.
Well, I modified your code to chop the sublists as soon as the sum exceeds 5*L.
Edit : See answer history to see my last answer for the approach above.
Well looking closer, notice you don't actually need the discrete difference array. You're finding the difference array, summing it up and checking whether the sum's < 5L and if it is, you append the original array.
But notice this:
if your array is like so: [0, 0.00760541, 0.22281415, 0.60476231], it's difference array would be [0.00760541 0.21520874 0.38194816].
If you add the first x terms of the difference array, you get the x+1th element of the original array. So you really just need to keep elements which are lesser than 5L:
import numpy as np
R = 10
lam = 1
proc_length = 5
L = 1
exponential_procs_lists = []
def chop(nums, target):
good_list = []
for num in nums:
if num >= target:
break
good_list.append(num)
return good_list
for procs in range(0,R):
z_exponential = np.random.exponential(lam,proc_length)
z_exponential.sort()
z_dat_r = np.insert(z_exponential,0,0)
good_list = chop(z_dat_r, 5*L)
exponential_procs_lists.append(good_list)
You could probably also just do a binary search(for better time complexity) or use a filter lambda, that's up to you.
I want to check if the input number is in the list, and if so - add its index in the original list to the new one. If it's not in the list - I want to add a -1.
I tried using the for loop and adding it like that, but it is kind of bad on the speed of the program.
n = int(input())
k = [int(x) for x in input().split()]
z = []
m = int(input())
for i in range(m):
a = int(input())
if a in k: z.append(k.index(a))
else: z.append(-1)
The input should look like this :
3
2 1 3
1
8
3
And the output should be :
1
-1
2
How can I do what I'm trying to do more efficiently/quickly
There are many approaches to this problem. This is typical when you're first starting in programming as, the simpler the problem, the more options you have. Choosing which option depends what you have and what you want.
In this case we're expecting user input of this form:
3
2 1 3
1
8
3
One approach is to generate a dict to use for lookups instead of using list operations. Lookup in dict will give you better performance overall. You can use enumerate to give me both the index i and the value x from the list from user input. Then use int(x) as the key and associate it to the index.
The key should always be the data you have, and the value should always be the data you want. (We have a value, we want the index)
n = int(input())
k = {}
for i, x in enumerate(input().split()):
k[int(x)] = i
z = []
for i in range(n):
a = int(input())
if a in k:
z.append(k[a])
else:
z.append(-1)
print(z)
k looks like:
{2: 0, 1: 1, 3: 2}
This way you can call k[3] and it will give you 2 in O(1) or constant time.
(See. Python: List vs Dict for look up table)
There is a structure known as defaultdict which allows you to specify behaviour when a key is not present in the dictionary. This is particularly helpful in this case, as we can just request from the defaultdict and it will return the desired value either way.
from collections import defaultdict
n = int(input())
k = defaultdict(lambda: -1)
for i, x in enumerate(input().split()):
k[int(x)] = i
z = []
for i in range(n):
a = int(input())
z.append(k[a])
print(z)
While this does not speed up your program, it does make your second for loop easier to read. It also makes it easier to move into the comprehension in the next section.
(See. How does collections.defaultdict work?
With these things in place, we can use, yes, list comprehension, to very minimally speed up the construction of z and k. (See. Are list-comprehensions and functional functions faster than “for loops”?
from collections import defaultdict
n = int(input())
k = defaultdict(lambda: -1)
for i, x in enumerate(input().split()):
k[int(x)] = i
z = [k[int(input())] for i in range(n)]
print(z)
All code snippets print z as a list:
[1, -1, 2]
See Printing list elements on separated lines in Python if you'd like different print outs.
Note: The index function will find the index of the first occurrence of the value in a list. Because of the way the dict is built, the index of the last occurrence will be stored in k. If you need to mimic index exactly you should ensure that a later index does not overwrite a previous one.
for i, x in enumerate(input().split()):
x = int(x)
if x not in k:
k[x] = i
Adapt this solution for your problem.
def test(list1,value):
try:
return list1.index(value)
except ValueError as e:
print(e)
return -1
list1=[2, 1, 3]
in1 = [1,8,3]
res= [test(list1,i) for i in in1]
print(res)
output
8 is not in list
[1, -1, 2]
The question is to take 4 integers as input entered in separate lines.
ex:=
1
1
1
2
The below code does the required thing. I am trying to understand its working part.
x,y,z,n=[int(input()) for _ in range(4)]
welcome!
This code is the equivalent of
x = int(input())
y = int(input())
z = int(input())
n = int(input())
The input() function reads an input from the user and the int tries to transform it to an integer, which is assigned to each variable (x,y, z and n).
The code can be also written as:
numbers = []
for i in range(4): # Loop 4 times
numbers[i] = int(input())
x = numbers[0]
y = numbers[1]
z = numbers[2]
n = numbers[3]
Which is more similar to the form you provided. But the author uses two python features that makes the code smaller (and more expressive). I'll explain both:
List Comprehensions
Lot of times during programming, you will be whiling to execute a command several times and get the results into an list, or for example, map values from one list to other. In this case, you would have something like this:
numbers_til_5 = [0,1,2,3,4,5]
squares_til_5 = []
for n in numbers_til_5:
squares_til_5.append(n*n)
With the List Comprehension syntaxe, we could do:
sqaures_til_5 = [ n*n for n in numbers_til_5]
The other feature is:
Destructuring
This is a feature that allows you to get elements of a list in one single statement.
In the example we have this:
x = numbers[0]
y = numbers[1]
z = numbers[2]
n = numbers[3]
Which could be replaced by x,y,z,n = numbers.
Another form interesting, is when you care only for the first arguments, for example:
first = numbers[0]
rest = numbers[1:] # This get all elements starting from the first
could be written as first, *rest = numbers.
I hope I was able to make it clear.
for _ in range(4) repeats int(input()) 4 times, so the brackets contain now the first four inputs [1, 1, 1, 2].
In Python you can assign multiple variables at one time, so x,y,z and n will be assigned to the corresponding values of the bracket.
For better understanding, you could extract the individial parts like this:
x = int(input())
y = int(input())
z = int(input())
n = int(input())
It is running a loop to input values as integers and feeding those values to the variable x,y,z,n in that sequence. range(n) runs the loop for a range 0-n (in this case, 4 times). _ is used to denote "anything" while running the loop.
The given python code is supposed to accept a number and make a list containing
all odd numbers between 0 and that number
n = int(input('Enter number : '))
i = 0
series = []
while (i <= n):
if (i % 2 != 0):
series += [i]
print('The list of odd numbers :\n')
for num in series:
print(num)
So, when dealing with lists or arrays, it's very important to understand the difference between referring to an element of the array and the array itself.
In your current code, series refers to the list. When you attempt to perform series + [i], you are trying to add [i] to the reference to the list. Now, the [] notation is used to access elements in a list, but not place them. Additionally, the notation would be series[i] to access the ith element, but this still wouldn't add your new element.
One of the most critical parts of learning to code is learning exactly what to google. In this case, the terminology you want is "append", which is actually a built in method for lists which can be used as follows:
series.append(i)
Good luck with your learning!
Do a list-comprehension taking values out of range based on condition:
n = int(input('Enter number : '))
print([x for x in range(n) if x % 2])
Sample run:
Enter number : 10
[1, 3, 5, 7, 9]
I have a problem with an output in Python
I'm trying to have an input in the form
2
1 10
2 20
2 being the number of tests and each line representing the number used by the function
To be able to have a single output, I'm storing the values in a tab in Python. The problem is that my tab doesn't have the correct values. Using the values given before, I have the following result when looking into the tab
1 2 20 5
Here's my code, thanks :
nbTest = input()
Tab = range(1,2*nbTest + 2)
for i in range(1,nbTest + 1):
a,b = map(int,sys.stdin.readline().split())
Tab[i] = a
Tab[i+1] = b
i = i + 1
print Tab[1], Tab[2], Tab[3], Tab[4]
First you don't have to "initialize" a list in python, so
Tab = range(1,2*nbTest + 2)
is unnecessary.
Second: the line
i = i + 1
doesn't do anything since the variable i is reassigned immediately afterwards.
Third: You should append tuples of values to your output list like this:
nbTest = int(raw_input())
inputs = []
for i in range(0,nbTest):
a,b = map(int, raw_input().split())
inputs.append((a,b))
print nbTest
for el in inputs:
print el[0], el[1]
Your should not modify the loop variable i inside the loop.
The line i = i + 1 does nothing since i is reassigned by the for loop, so you overwrite the Tab[i+1] of the previous iteration with Tab[i]. If you want i to increase by 2 at each iteration use range(1, nbTest+1, 2) instead.
Also note that you don't have to initialise the size of your list, you can simply do Tab=list(), and then use Tab += [a,b]
Also, pythons arrays start at 0, so your range must be start from 0 as well. Otherwise the first slot of the list will not be replaced.
Note If you are using python3, you must do Tab = list(range(1, 2*nbTest+2)) if you want Tab to be a list.