Well, we got parables exam preparations and instead of me typing everything a million times, I thought of rather making a little Python script. It's done, but something's bugged. I've been stuck on it for around 30 minutes and just can't figure it out as my Python is a bit rusty.
You can find my code at: https://repl.it/#Rrrei/CurvySecondaryService
As mentioned before, for x in x: is indeed bad naming :p. You can easily get confused about what x you are talking about, the inner or the outer one.
Also a = input(..) makes a a string, a string multiplied by a number repeats the string in Python. e.g.:
'1'*5 == '11111'
To solve this, wrap input in a int: a=int(input(...))
You are going to append the string values. Python is not typesafe and a is a string after calling input()...
Here you can see a safe example with corrected values and better names (cleancode).
check my code
It´s the correct version of yours.
If you want the same form b=0 c=0....
Related
This question already has answers here:
Sum a list of numbers in Python
(26 answers)
Closed last month.
I have been stuck trying to write code that will dynamically take user input from a list and preform general arithmetic operators. In order to work around this I used indexing and slicing which did solve my problem temporarily but a new problem rose from doing this.
listgrades= []
num_students = int(input("How many students are you evaluating?"))
def student_info():
for i in range(0, num_students):
student_name=input("Enter your name here: ")
studnet_age=input("Enter your age here: ")
student_total_grade=int(float(input("What is your total grade")))
listgrades.append(student_total_grade)
student_info()
grades_sum= (listgrades[0] + listgrades[1] + listgrades[2]) / num_students
print(f"The average of all the student grades is {grades_sum}")
`
I'm trying to change the (listgrades[0] + listgrades[1] + listgrades[2]) to something more changeable, workable and scalable
I was trying to look and find a solution or a way to work around this but I hit a dead end and I ran out of ideas at this point.
I think a loop of some sorts might work for this but I'm not sure.
side note: I kinda looked into numpy and I can't use it since my school lab computers won't allow anything out of the default python module library.
I have some general advice and some specific suggestions.
For general advice, to see what built in methods are available is to use python itself.
At the command line type python3
then, within python type dir(list)
and you will see the available methods for lists.
You get more detailed information about any specific method by typing help and the class you are interested in followed by a dot, than the method name. For example help(list.count).
You can also type help(list) to get a more in depth list of all the functions and instructions for use. Type space to continue to the next screen, and b to backup a screen. Type q to end the help screens.
To exit python type exit()
More specifically, I agree that a loop would be a more dynamic direction to go, given you are asking how many students to evaluate in your input.
One way to loop through your list would be:
for x in listgrades:
sum = sum + x
Of course, you can perform other math operations inside the loop, or in similar loops. Presumably you will initialize your value before the loop.
At some point you may need to count how many grades are in your list. Fortunately, there's a built-in method for lists that gives you that information called count. You'll see this if you use python's dir(list) or help(list).
number_of_grades = listgrades.count
I think this will point you in the direction you were thinking with the code, without giving away much in exactly how, which is what you are learning. Best of luck!
As you probably already figured by my question, I am pretty new to programming which is why this question is so basic. But I couldn't really find a question that had an answer to my problem so I thought I might just ask. I have a list that contains integers that I wanted to compare to each other so they can be sorted from highest to lowest. Now for that I wanted to use a for-loop that is executed exactly as many times as there are integers in my list. How do I do that? I tried:
for len(a): # (a is my list)
*code*
Thought it is returning me an error, saying that it couldn't be assigned to the function call. I am not sure why :/ . I hope you can help me.
for i in range(len(a)):
is the usual way; the official Python tutorial is a good place to start for understanding range(), and the fact that the loop is executed as many times as there are elements in your list when you first entered the loop
I will start this off by saying that I have not done any schooling. All of my programming knowledge has come from 12 years of doing various projects in which I had to write a program of some sort in some language.
That said. I am helping my friend who is just getting into programming and who is taking a introductory python class. Her class is currently learning about recursive functions. Due to my lack of schooling this is the first time I have heard about them. So when she asked me to explain why the function she had worked I couldn't do it. I had to learn them myself.
I have been looking around at various posts about solving this same problem. I found one here at geeksforgeeks that is a function that does exactly what we need. With my elementary understanding of recursion this is the function that I would have thought would have been the right choice.
def bintodec(n):
if len(n) == 1:
bin_digit= int(n)
return bin_digit * 2**(len(n) - 1)
else:
bin_digit = int(n[0])
return bintodec(n[1:]) + bin_digit * 2**(len(n) - 1)
This is the function she came up with
def convertToDecimal(binNum):
if len(binNum) == 0:
return 0
else:
return convertToDecimal(binNum[:-1]) * 2 + int(binNum[-1])
When I print the function call it works.
print(convertToDecimal("11111111"))
# results in 255
print(convertToDecimal("00000111"))
# results in 7
I understand that sometimes there is a shorthand way to things. I can't see any shorthand methods mentions in the documentation that I have read.
The thing that really confuses me is how it takes that string and does math with it. I see the typecast for int, but the other side doesn't have it.
This is where everything falls apart and my brain starts melting. I am thinking there is a core mechanic of recursion that I am missing. Normally that is the case.
So along to figuring out why that works, I would love to know how this method would compare to say the method we found over at geeksforgeeks
What your friend has implemented is the typical implementation of Horner's method for polynomial evaluation. Here is the formula.
Now think of the binary number as a polynomial with a's equal to one or zero, and x equals to 2.
The thing that really confuses me is how it takes that string and does math with it. I see the typecast for int, but the other side doesn't have it.
The "other side" will take the value as int number which is result of latest recursive function call. in this case it will be 0.
Ok, so in words, what this program is doing is, on each invocation, taking the string and splitting it into 2 parts, lets call them a and b. a contains the entire string, apart from the final character, while b only contains the final digit.
Next, it takes a and calls the same function again, but this time with the shorter string, and then takes the result of this and doubles it. The doubling is done, as if you were to add an additional 0 to the end of a binary number, you would be doubling it.
Finally, it converts the value of b into an integer, either 1, or 0, and adds this to the previous result, which will be the decimal version of your binary string.
In other words, this function is only computing the result one character at a time, then it calls back to itself as a way of 'looping' to the next character.
It's important that there is an exit condition in a recursive function, to prevent infinite looping, in this case, when the string is empty, the program just returns 0, ending the loop.
Now on to the syntax. The only potentially confusing thing here I can see is python's array/slice syntax. Firstly, by trying to access the -1 index in an array, you are actually accessing the final element.
Also in that snippet is slice notation, which is the colon : in the array index. This is essentially used to select a subset of an array, in this case, all elements but the final one.
I honestly couldn’t make her function run as written. I got the below error
if len(binNum) == 0:
TypeError: object of type 'int' has no len()
I'm guessing however that under testing even working this would fail at some point, I’d like to see if you have it returning say, 221 (11011101) where the 1s and 0s are not consecutive and see if that works or fails.
Lastly, back to my error, I’m assuming the intention is to go out of the loop if it’s a zero. Even if zero wasn’t a null character, len(binNum) == 1 would still exit the loop as written. A try/catch block would be better
for i in reversed(bin(n|(n+1))[2:]):#loops through representation of
# integer n, converted to binary, and flips first 0 bit
if i == '0':
print(str(count))
count=0
break
count +=1
If n is an integer, the above sample code flips the first zero bit, then finds and prints the index of what was the second zero bit.
I'm working on CodeFights, to practice my skills and can't seem to figure out how to format an algorithm that accomplishes basically what this one does.
I'm supposed to find the appropriate index and raise 2 to that power, in one line. I'm looked into using generators and llambdas... not sure what to do.
So, specifically how can I can I get
2**index of second zero in integer n
#in one line of code?
def secondRightmostZeroBit(n):
return 2**bin(n|(n+1))[::-1].index('0')
Researched this for days, stumbled upon the answer five minutes after asking on here.
'.replace(0,1,1)' and
'.find(0)' would also have been useful.
The above is what I ended up submitting. As explained in the question n|(n=1), serves to flip the rightmost zero in the binary representation of n. From there I reversed the order of the string/binary representation of that result, and used '.index' to retrieve the first '0' to be found.
Another way to do it has more to do with manipulation of binary numbers than with the way I phrased the original question.
def secondRightmostZeroBit(n):
return ~n & (~n-1) & -(~n & (~n-1))
I haven't found much reason to do this sort of bit manipulation in the past, so I'm always looking at a reference when I interpret code like this. https://www.tutorialspoint.com/python/bitwise_operators_example.htm If you want to understand it, I suggest plugging in a specific number for n, convert to binary, and work it through. Do that a couple of times and it should become clear what's going on. You can also plug individual peices of it into your interactive pain, but that won't do you much good unless you're looking at the binary. bin(n) and format(n, "8b") are good for that.
I'm considering porting a rather unwieldy bash script to python but I'm stuck on how to handle the following aspect: The point of the script is to generate a png image depending on dynamically fetched data. The bash script grabs the data, and builds a very long invocation of the convert utility, with lots of options. It seemed like python's template strings would be a good solution (I would vastly prefer to stay within the standard library, since I'll be deploying to shared hosting), but I discovered that you can't evaluate expressions as you can in bash:
>>> from string import Template
>>> s = Template('The width times one is ${width}')
>>> s.substitute(width=45)
'The width times one is 45'
>>> t = Template('The width times two is ${width*2}')
>>> t.substitute(width=45)
# Raises ValueError
Since my bash script depends quite heavily on such arithmetic (otherwise the number of variables to keep track of would increase exponentially) I'd like to know if there's a way to emulate this behavior in python. I saw that this question, asking roughly the same, has a comment, reading:
This would be very unPythonic, because it's counterintuitive -- strings are just
strings, they shouldn't run code!
If this is the case, what would be a more idiomatic way to approach this problem?
The proposed answer to the question linked above is to use string formatting with either the % syntax or the format() function, but I don't think that would work well with the number of variables in my string (around 50).
Why not use built-in string formatting?
width = 45
"Width times one is {width}".format(width=width)
"Width times two is {width}".format(width=2*width)
results in
Width times one is 45
Width times two is 90
The Pythonic solution to this problem is to forget about string formatting and pass a list of arguments to one of the subprocess functions, e.g.
# I have no idea about convert's command line usage,
# so here's an example using echo.
subprocess.call(["echo", str(1 + 1), "bla"])
That way, there's no need to build a single string and no need to worry about quoting.
You probably need a better templating engine. Jinja2 supports this kind of stuff and a lot more. I don't think the standard library has anything equally powerful, but from what I figured, the library is pure Python, so you can integrate it into your application by just copying it along.
If Jinja doesn't fit you for some reason, have a look at the Python wiki, which has a section specifically for those kinds of libraries. Amongst them is the very lightweight Templite, which is only one class and seems to do exactly what you need.
The task is not that hard, why don't you just make some coding for fun? And here is the function almost does what you want.
import re
def TempEval(template,**kwargs):
mark = re.compile('\${(.*?)}')
for key in kwargs:
exec('%s=%s'%(key,kwargs[key]))
for item in mark.findall(template):
template=template.replace('${%s}'%item,str(eval(item)))
return template
print TempEval('The width times one is ${width}',width=5)
#The width times one is 5
print TempEval('The width times two is ${width*2}',width=5)
#The width times two is 10