What's x for x in input()? - python-3.x

I am new to coding and is trying to solve this python question
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Following are the fixed values of C and H:
C is 50. H is 30.
D is the variable whose values should be input to your program in a comma-separated sequence.
Example
Let us assume the following comma separated input sequence is given to the program:
100,150,180
The output of the program should be:
18,22,24
Hints:
If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26)
In case of input data being supplied to the question, it should be assumed to be a console input.
This is the solution given. I have not seen 'x for x in input()'expression, may I know what does this expression do ?
import math
c=50
h=30
value = []
items=[x for x in input().split(',')]
for d in items:
value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))
print (','.join(value))
This is my own solution but somehow I got a syntax error.
def sr(D):
For item in D:
return ((2*50*D)/30)**0.5
try:
a=int(input())
j=a.split(",")
print(sr(j))
except:
print('Please enter an integers or intergers seperated by comma')

The x is just a variable that gets assigned to the input that comes in via the input() function.
If you're aware of C style language (or Java), it's similar to
for(int i=0;<some_condition>;<some_operation>){}
This is just a condensed, pythonic and easy to read way to do this.
You can read more Python loops here
https://wiki.python.org/moin/ForLoop

Related

I don't know why the correct answer isn't coming up

I'm novice programmer.
I want the smallest of the input values ​​to be output, but I don't know what's wrong.
Input example :
10
10 4 2 3 6 6 7 9 8 5
Output example :
2
n = int(input())
a = input().split()
min=a[0]
for i in range(n) :
if a[i] < min :
min = a[i]
print(min)
what is the problem? please help me
Your code should work (and it does for me).
Nevertheless, min is a reserved Python word. Taking that into consideration, I also recommend the following changes for it to be more idiomatic:
a = input().split()
min_num = a[0]
for element in a:
if element < min :
min = element
print(min)
Variables can be either number or strings. For example "2" is different from 2.
The function split returns an array of strings. You would need to convert each to a number if you want to do number comparison, like:
n = int(input())
a = input().split()
min=int(a[0])
for i in range(n) :
if int(a[i]) < min :
min = int(a[i])
print(min)
Note: you already did that for n (first line in original code), but you did not do the same when you access a.
So, min is actually a python built-in, which would be very useful in this scenario. Also, you are not making the input values in a into integers, so we can do that too:
n = int(input())
a = list(map(int, input().split()))
print(min(a))
We use map to turn all the values from the split list into integers, then turn the map object back into a list. Then, using min, we can find the smallest number very easily, without a for loop.
I think you should convert each element to integers before comparing them.
a = [int(i) for i in input().split()]
Your code should work, but it will compare strings against strings instead of integers against integers.

error shows while using type casting for input in python3

I am trying to take multiple numbers as input and use those numbers as parameters as *args in function,but python interpreter shows it is a s error.I tried in different type and it works well.But i want to know the difference between them.?
#numbers = [int(x) for x in input("Enter multiple value: ").split(",")] # gives no error
numbers=int(input()).split(",") #Giving error
def add(*numbers):
sum=0
for number in numbers:
sum=sum+number
print(sum)
print(add(*numbers))
int(input()).split(",") -> of course this will return error.
The split() method splits a string into a list. Your code implies converting input into int type and split the integer.
numbers = [int(x) for x in input("Enter multiple value: ").split(",")]
this will not throw an error as you are creating a list of integers by iterating through list generated by split.

how do I call an element in a list?

a= int(input())
# I input 12345
b = a
list(map(int, b))
print (list[0]*2+list[3]*1)
#can't seem to get 6 as my answer
how do I attain my answer? I can't seem to call the elements in the list. Thank you for your help.
Since you're treating the input as individual digits, you should avoid converting the input to an integer as a whole, but map the individual digits to integers as a sequence of characters:
a= input()
b = list(map(int, a))
print(b[0] * 2 + b[3] * 1)
There are several reasons why your code won't work, including your use of the map function, the fact that you do not assign the result to a variable and the use of list (which is a keyword in Python).
However, consider this code snippet which calculates your desired output:
a = int(input('Enter a number: '))
b = [int(digit) for digit in str(a)]
res = 2 * b[0] + b[3]
print(res)
Basically you have to transform your integer into a string to be able to iterate over it. Afterwards you create your list of digits out of it and can do your calculations.
Generally speaking, you should learn the basics of Python properly. A good starting point would be the official documentation (LINK).

When to use ast.literal_eval

I came across this code and it works, but I am not entirely sure about when to use ast and whether there are performance issues when this is used instead of getting the string value from input() and converting it to int.
import ast
cyper_key = ast.literal_eval(input("Enter the key (a value between 0 and 25) : "))
# this get the user input as an int to the variable cyper_key
I read the docs I understand what it does.
This can be used for safely evaluating strings containing Python
values from untrusted sources without the need to parse the values
oneself. It is not capable of evaluating arbitrarily complex
expressions, for example involving operators or indexing.
I am looking for an explanation on above bold points.
When to use it.
ast.literal_eval(input()) would be useful if you expected a list (or something similar) by the user. For example '[1,2]' would be converted to [1,2].
If the user is supposed to provide a number ast.literal_eval(input()) can be replaced with float(input()), or int(input()) if an integer is expected.
Performance
Note that premature [micro-]optimization is the root of all evil. But since you asked:
To test the speed of ast.literal_eval(input()) and float(input() you can use timeit.
Timing will vary based on the input given by the user.
Ints and floats are valid input, while anything else would be invalid. Giving 50% ints, 40% floats and 10% random as input, float(input()) is x12 faster.
With 10%, 10%, 80% and float(input()) is x6 faster.
import timeit as tt
lst_size = 10**5
# Set the percentages of input tried by user.
percentages = {'ints': .10,
'floats': .10,
'strings': .80}
assert 1 - sum(percentages.values()) < 0.00000001
ints_floats_strings = {k: int(v*lst_size) for k, v in percentages.items()}
setup = """
import ast
def f(x):
try:
float(x)
except:
pass
def g(x):
try:
ast.literal_eval(x)
except:
pass
l = [str(i) for i in range({ints})]
l += [str(float(i)) for i in range({floats})]
l += [']9' for _ in range({strings}//2)] + ['a' for _ in range({strings}//2)]
""".format(**ints_floats_strings)
stmt1 = """
for i in l:
f(i)
"""
stmt2 = """
for i in l:
g(i)
"""
reps = 10**1
t1 = tt.timeit(stmt1, setup, number=reps)
t2 = tt.timeit(stmt2, setup, number=reps)
print(t1)
print(t2)
print(t2/t1)
ast -> Abstract Syntax Trees
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.
This link AST is useful for you to understand ast.
If it's going to be used as an int, then just use:
cypher_key = int(input("Enter the key (a value between 0 and 25) : "))
Only use that if you expect the user to be entering 10e7 or something. If you want to handle different bases, you can use int(input(...), 0) to automatically divine the base. If it really is an integer value between 0 and 25, there's no reason to use ast.
Running this in a python-3.x shell, I get no differences when I give correct input:
>>> cyper_key = ast.literal_eval(input("Enter the key (a value between 0 and 25) : "))
Enter the key (a value between 0 and 25) : 5
>>> cyper_key
5
However, when you give a string or something that cannot be converted, the error can be confusing and/or misleading:
>>> cyper_key = ast.literal_eval(input("Enter the key (a value between 0 and 25) : "))
Enter the key (a value between 0 and 25) : foo
Traceback (most recent call last):
File "python", line 3, in <module>
ValueError: malformed node or string: <_ast.Name object at 0x136c968>
However, this can be useful if you don't want to cast either float or int to your input, which may lead to ValueErrors for your int or floating points for your float.
Thus, I see no necessary use in using ast to parse your input, but it can work as an alternate.

Max Sample Value (sound file) python

I am trying to write a code to determine the minimum, maximum, and total zero values for a .wav file. The output should return something like
Largest Sample Value is:xxxx
Smallest Sample Value is:xxxx
There are x amount of 0's in sample.
I am having trouble determining if using the max() for the .wav sample is the right thing to do after using a for loop.
f=pickAFile()
sound=makeSound(f)
for i in range(0,getLength(sound)):
value=getSampleValueAt(sound,i)
print max(value)
print min(value)
Not sure how to find the zero values within it either. I can use the print function to output the smallest and largest statement however I cannot figure out the min/max to start.
Repetition of Max() function using python from loop:
def largest():
f = pickAFile()
sound = makeSound(f)
value = [getSampleValueAt(sound, i) for i in range(1, getLength(sound))]
print max(value)
print min(value)
print value.count(0)
Also, as you tagged the question as python-3.x, the print statements should be print(max(values))

Resources