Whhat is the meaning of given below code? - python

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.

Related

Why doesn't my if...in statement work in python?

this program takes 3 lists of numbers, and compares A and B to the list n. if a term from A is in n, the happiness increases. if a term from B is in n, the happiness decreases. However, when I am doing these calculations, the if ... in statement to check if a term from A/B is in n doesn't work - I have done print(happy) after each one to check, and I get no result
A = []
B = []
n = []
happy = 0
lengthn, lengthAB = input("").split()
for i in lengthn:
numbers = input("")
newNumbers = numbers.split()
n.append(newNumbers)
for i in lengthAB:
numbers = input("")
ANumbers = numbers.split()
A.append(ANumbers)
for i in lengthAB:
numbers = input("")
BNumbers = numbers.split()
B.append(BNumbers)
long = int(lengthAB)
for i in range(long):
j = int(i)
if A[j - 1] in n:
happy = happy + 1
print(happy)
if B[j - 1] in n:
happy = happy - 1
print(happy)
i = i + 1
print(happy)
Thank you so much for the help!!
You appended a list to n, not each element of that list. You can write
n.extend(newNumbers)
instead.
You could just write n = newNumbers.split(), but as pointed out in a comment, you probably have an indentation error:
for i in lengthn:
numbers = input("")
newNumbers = numbers.split()
n.extend(newNumbers)
Or, you don't need split at all:
for i in lengthn:
number = int(input(""))
n.append(number)
At some point, you probably mean to convert the string inputs to integers; may as well do that immediately after reading the string. (I'm declaring various techniques for handling conversion errors beyond the scope of this answer.)
Contrary to what you seem to expect the variables: lengthn, lengthAB are strings
The for-loop
for i in lengthn:
numbers = input("")
iterates over the characters in the string lengthn. If lengthn='12' it will ask to provide input twice.
If lengthAB is '13' for example you will get 2 numbers in your list BNumbers but later on you try to test 13 values because int('13') is 13.
for i in lengthn:
numbers = input("")
so the numbers you are getting are the form of string it's will iterate on string rather then a number.
You should look for beeter python book. Based on desription I think this should look like this:
def happiness(A, B, n):
return sum(x in n for x in A) - sum(x in n for x in B)
def get_data(prompt=""):
return [int(x) for x in input(prompt).split()]
print(happiness(get_data(), get_data(), get_data()))
https://ideone.com/Q2MZCo

If the input number is in the list add its index to a new one

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]

How to sort only positive numbers from a list?

I am trying to make a list of only sorted positive list when the user gives positive and negative integers in that list. For example, if the user gave "10 -7 4 39 -6 12 2" my program would only sort the positive numbers and give out '2 4 10 12 39'.
So far this is what my code looks like:
list = input().split()
positive_list = []
for i in range(list):
if list[i] > 0:
positive_list.append(list[i])
i+=1
positive_list.sort()
print(positive_list)
You have several issues:
you have a variable that's named the same as a basic type (list), which shadows the type; pick a better name
for i in range(my_list): doesn't do what you think; you could do for i in range(len(my_list)):, but you can also just for n in my_list: and n will be every element in my_list in turn
your user enters text, you'll need to turn those strings into integers before comparing them to other integers, using int()
you do for i .. but also i += 1 you don't need to increment the for-loop variable yourself.
Look into list comprehensions, they are perfect for what you're trying to do in a more complicated way, to construct positive_list.
Your solution could be as simple as:
print(sorted([int(x) for x in input().split() if int(x) > 0]))
But staying closer to what you were trying:
numbers = [int(x) for x in input().split()]
sorted_positive_numbers = sorted([x for x in numbers if x > 0])
print(sorted_positive_numbers)
If you insist on a for-loop instead of a list comprehension:
numbers = [int(x) for x in input().split()]
positive_numbers = []
for number in numbers:
if number > 0:
positive_numbers.append(number)
print(sorted(positive_numbers))
Rename list to something other than that. list is a python keyword.
For example list_new or list_temp
My suggestion is to try it like this:
positive_list = []
for num in listNew:
if num > 0:
positive_list.append(num)
positive_list.sort()

Python: Find Every Fibonacci Sequence in a Given List of Numbers

a program that takes a list of numbers separated with "," from the user and extracts and prints every fibonacci sequence from the list.
like this:
In: 5,6,9,3,0,1,1,2,3,8,2,9,3,0,1,1,2,3,5,98
Out:
[0,1,1,2,3]
[0,1,1,2,3,5]
i tried to use "for" loops to find the first 0 and process the program after it. like it checks and follows the list for the fibonacci sequence until it's out of the sequence, prints the list, and then looks for the next 0.
i wrote the part of the code that gets the input, but i don't know how to do the rest
numbers = input("Enter your numbers list and use comma to seperate them: ")
numlist = numbers.split(",")
numlist = [int(x) for x in numlist]
result = []
"result" is the output list (or lists).
i hope my explanations were clear. anyone can help?
Below program should work, it will check for the fibbonaci series in the list of numbers
numbers = [5,6,9,3,0,1,1,2,3,8,2,9,3,0,1,1,2,3,5,98]
first = numbers[0]
second = numbers[1]
fibbonacci = []
result = []
for number in numbers[2:]:
if first + second == number:
if not fibbonacci:
fibbonacci.extend([first, second, number])
else:
fibbonacci.append(number)
elif fibbonacci:
result.append(fibbonacci)
fibbonacci = []
first = second
second = number
print(result)
Idea is very similar to #Vuplex but can use os.path.commonprefix to remove extra code to compare two series
import os
numlist = list(map(int,input.split(',')))
answer = []
fib_series = [0,1,1,2,3,5,8,13]
answer = []
i = 0
while i < len(numlist):
if not numlist[i]:
answer.append(os.path.commonprefix([fib_series,numlist[i:]]))
i += 1
print(answer) #[[0, 1, 1, 2, 3], [0, 1, 1, 2, 3, 5]]
FIB = [0,1,1,2,3,5,8,13]
def checkSequence(numArr):
i = 0
while i < len(numArr):
if FIB[i] == int(numArr[i]):
i += 1
else:
return i
numbers = input("Enter your numbers list and use comma to seperate them: ")
numlist = numbers.split(",")
answer = list()
i = 0
while i < len(numlist):
if int(numlist[i]) == 0:
ret = checkSequence(numlist[i:])
answer.append(numlist[i:i+ret])
i += 1
As you can see, you can quite easily make a CheckSquence method to check the array splice for a squence and return the amount of entries you've found. With the answer from the checkSequence you then can create a splice for your answer list. This produces the results you've specified in your question.
EDIT: You'll need to define the Fibunacci sequence before. You can either use a static sequence like I did, or compute till a certain point and then compair against that result.

How to add values into an empty list from a for loop in python?

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]

Categories