Here are two problems which I do not know what I am coding wrong:
In physics, for a pendulum with length L and initial angle A, its horizontal displacement X(T) at time T is given by the formula
X(T) = L × cos(A × cos(T × √9.8/L)) - L × cos(A)
Write a program which takes two lines of input; the first line is L and the second line is A. The output should be ten lines, giving the values of X(0), X(1), X(2), ..., X(9). For example, if the first line of input is 53.1 and the second line of input is 0.8, then the first line of output is 0.0 and the second line of output is 53.1*cos(0.8*cos(1*√9.8/53.1)) - 53.1*cos(0.8) ~ 2.6689.
Here is what I have, although the grader shows that I am doing some of the math wrong:
import math
L = float(input())
A = float(input())
for i in range (0, 10):
x = L * math.cos(A * math.cos(i * math.sqrt(9.8/L))-L * math.cos(A))
print(x)
For this program, the first line of input is an integer width. Then, there are some lines of text; the line "END" indicates the end of the text. For each line of text, you need to print out a centered version of it, by adding periods .. to the left and right, so that the total length of each line of text is width. (All input lines will have length at most width.) Centering means that the number of periods added to the left and added to the right should be equal if possible; if needed we allow one more period on the left than the right. For example, for input
Here is what I have, although it isn't correct either:
width = int(input())
hi=input()
while hi != "END":
WordInput=input()
x=len(WordInput)
y=width-x
half=y%2
if half == 0:
a = int(y/2)
print("." * a)
elif half == 1:
b = int(y/2) + 1
c = int(y/2)
print("." * b,WordInput,"." * c)
It may help you debug if your inputs have text prompts, as in width = int(input("enter width: ")), which will give you a better idea of where in the code your input will be stored.
I'm not seeing the problem with #1, but it's been a while since I've taken physics. If your grader says just the math is wrong, double check the equation you're using, and add appropriate parentheses in the code to make sure the correct order of operations is done.
There are several problems with #2. First, your program requests input the wrong number of times. Your loop depends on the variable hi, which you only assign once; once your code enters the loop, nothing will change it to "END" and the loop will never exit. Not only that, but the first word you enter (at the hi prompt) is not considered by code in your loop, so anything other than "END" is simply ignored. You'll want something more like this :
WordInput=input()
while WordInput != "END":
# Do your processing and printing code here
(...)
# Then get some new input at the end of the loop
WordInput=input()
The new value of WordInput will be evaluated when the loop restarts.
Second, look at your if statement. You correctly determine that the length is even (half==0), but in the even case you don't tell the code to actually print the input word, just the periods! In practice, it's good to avoid setting up if/else blocks like this with multiple similar print statements; if you want to go back and change the formatting of one, you have to remember to manually change the others too. As your code gets more complicated this will become a real pain, so it's generally best to condense your print statements as much as you can. Without changing your structure too much here's how I would do it:
if half == 0:
a = int(y/2)
elif half == 1:
a = int(y/2) + 1
b = int(y/2)
print("." * a,WordInput,"." * b)
This way, b is assigned in either case and the same print statement will execute no matter what.
Third, any word that is printed and centered by your code is padded by spaces. This is because when you give print() multiple parameters, by default they are joined by spaces. To override this, you can change the separator parameter to an empty string (or anything else you need);
>>>print("." * 4, "Hey", "." * 4)
.... Hey ....
>>>print("." * 4, "Hey", "." * 4, sep="")
....Hey....
For 1. The parentheses are wrong!
import math
L = float(input())
A = float(input())
for i in range (0, 10):
x = L * math.cos(A * math.cos(i * math.sqrt(9.8/L)))-L * math.cos(A)
print(x)
Related
I want to write a code for this question:
write a code which creates a new number 'n2' which consists reverse order of digits of a number 'n' which divides it without any remainder for example if input is 122
it will print 221 because 1,2,2 can divide 122 without any remainder another example is 172336 here 1,2,3,3,6 can divide it without any remainder so the output should be 63321(reverse order).
my code is:
n = str(input())
x = ""
z = 0
for z in range(len(n)):
if int(n)%int(n[z])==0:
x = n[z] + ""
else:
n.replace(n[z],"")
z = z+1
print(x[::-2])
if I input the number 122 here i get the output 2 but i should be getiing output of 221 why.
The reason why you are not getting the desired output in this code is because of several logical and syntactical errors in your code. Here are some of them:
You are using x = n[z] + "" to append the digits that divide n without any remainder, but this will overwrite the previous value of x every time. You should use x = x + n[z] instead.
You are using n.replace(n[z],"") to remove the digits that do not divide n without any remainder, but this will not modify the original value of n, since strings are immutable in Python. You should assign the result of n.replace(n[z],"") to a new variable, or use a different approach to filter out the unwanted digits.
You are using z = z+1 to increment the loop variable, but this is unnecessary and redundant, since the for loop already does that for you. You can remove this line.
You are using print(x[::-2]) to print the reversed value of x, but this will skip every other digit, since the negative step of -2 means you are slicing the string from the end to the beginning with a step of 2. You should use print(x[::-1]) instead, which will reverse the whole string. A possible corrected version of your code is:
python
n = str(input())
x = ""
for z in range(len(n)):
if int(n)%int(n[z])==0:
x = x + n[z]
print(x[::-1])
This code will print the reversed order of the digits of n that divide it without any remainder, as expected. For example, if the input is 122, the output will be 221.
The code works by iterating over each digit of the input number n, which is converted to a string for convenience. For each digit, it checks if it divides n without any remainder, using the modulo operator %. If it does, it appends the digit to the end of the string x, using the + operator. If it does not, it ignores the digit. After the loop, it prints the reversed value of x, using the slicing notation [::-1], which means start from the end and go backwards until the beginning.
This should do the Trick
num = input()
new_num = ""
for i in num:
if int(num)%int(i) == 0:
new_num += i
print(new_num[::-1])
I have been trying to plot the twelve tone scale, from the lowest to the highest audible pitch, in hertz.
I found a way to do this using a while loop that is always true and then use break to exit the loop once the pitch is either lower or higher than the audible human range.
I know that this kind of loop is bad practice, but--as a novice programmer--I can't think of how to do this the proper way. How can I achieve the same result without using "while True"?
I have tried putting the condition "note > highest or note < lowest" where "True" is currently in the while loop, but then "note" is only defined within the loop so I get a "NameError: name 'note' is not defined" error.
highest = 20000
lowest = 20
key = 440
TET = 12
equal_temper = [key]
i = 1
while True:
note = key * (2**(1/TET))**i
if note > highest or note < lowest:
break
equal_temper.append(note)
i += 1
i = 1
while True:
note = key * (2**(1/TET))**-i
if note > highest or note < lowest:
break
equal_temper.append(note)
i += 1
equal_tempered = sorted(equal_temper)
for i in range(len(equal_temper)):
print(equal_tempered[i])
The output to the terminal seems to be correct. It may round down or up differently than other tables I have seen. I just want to know how to do this without using "while True."
I notice you're making your compiler re-make the same calculations over and over again while they only need to be done once! (And they can be done by you).
You have a set equation for your note value: note = key * ( 2 ** (1/TET) ) ** i. This can easily be inverted to solve for i as a function of note: i = TET * log_2(note / key). With this, and knowing your upper and lower bounds for note, we can determine the bounds for i.
Plugging in your upper limit, 20000 gives i=66.07. Anything above this will result in a note greater than your upper limit, so we want to take the floor of this value. i_upper = 66.
Plugging in your lower limit, 20, gives i=-53.51. Anything lower than this will give a note lower than your lower limit, so we want to take the ceiling of this value. i_lower = -53
Now all we have to do is loop from i_lower to i_upper and fill your array with the note values.
This method avoids using while loops, is easily generalized if you change any of the parameters, and just through construction, returns a sorted array so you don't have to sort it afterwards.
import math
highest = 20000
lowest = 20
key = 440
TET = 12
def note_value(key, TET, i):
""" Returns the note value for a given key, TET, and i"""
return key * (2**(1/TET))**i
def i_value(key, TET, N):
""" The inverse of note_value. Re-arranged to solve for i."""
return TET * math.log(N/key) / math.log(2)
notes_above = math.floor(i_value(key, TET, highest))
print(f"Number of notes above = {notes_above}")
notes_below = - math.ceil(i_value(key, TET, lowest))
print(f"Number of notes below = {notes_below}")
print(f"Total number of notes = {notes_below+notes_above+1}")
equal_temper = [ ]
for i in range(-notes_below, notes_above+1):
# We have to add 1 to notes_above since range is NOT inclusive of the ending term.
equal_temper.append(note_value(key, TET, i))
print(*equal_temper, sep="\n")
Some notes:
Log(x)/Log(B) gives log base B of X, no matter what the original base of Log is. This is why we divide by math.log(2) in our i_value function -- it gives us log base 2 of N/key.
The letter f used right before a string indicates a format string and will replace anything within {} with the whatever it evaluates to. For example, x=5; print(f"My x is {x}") will print My x is 5. This shorthand feature is new to python 3.6. If you're using a version prior to python 3.6, then you will need to replace the format statements with the longer version: print("Number of notes above = {}".format(notes_above))
The very last print statement at the end uses * to 'unpack' the list of equal_temper notes and then prints them with a newline (\n) between each element.
You could simply write something like
while lowest <= note <= highest:
...
That way you make the reverse of the condition in the if-statement the condition for the while loop and get rid of the hardcoded boolean value.
Edit:
I have made some slight modifications to your code and came up with this:
def get_equal_tempers(multiplier):
tempers = list()
note = 20
i = 1
while lowest <= note <= highest:
note = key * (2 ** (1 / TET)) ** (i*multiplier)
if note > highest or note < lowest:
break
tempers.append(note)
i += 1
return tempers
highest = 20000
lowest = 20
key = 440
TET = 12
equal_temper = [key]
equal_temper += get_equal_tempers(1)
equal_temper += get_equal_tempers(-1)
equal_tempered = sorted(equal_temper)
for i in range(len(equal_temper)):
print(equal_tempered[i])
When i run it on my machine, it produces the same output as your code. Can you please check?
I am making a program where I can count the number of a in a string. This is my Code:
def repeatedString(s, n):
converged = s*n
got_it = converged[0:n]
count = 0
for x in got_it:
if "a" in x:
count += 1
return count
s = input()
n = int(input())
result = repeatedString(s, n)
print(result)
The variable s is where the string is entered, and variable n is for upto how long the string will repeat. My Code works OK, but for some reason when I give a bigger integer, it falls apart and gives me a Memory Error. For example, my input is:
a
1000000000000
It gives me this error:
Traceback (most recent call last):
File "programs.py", line 11, in <module>
result = repeatedString(s, n)
File "programs.py", line 2, in repeatedString
converged = s*n
MemoryError
How can I fix this Memory Error? If there's a better way to do it, it would also be helpful.
The problem with your code is where you do converged = s*n. In that line, you are asking the program to take the string s and allocate enough memory to fit the number of bytes in s * n, which, as you have seen, has a limit because your computer has a finite amount of free memory available (most modern-day computers only carry 4 - 16 gigabytes of RAM).
One way you can fix the memory error is by exploiting one aspect of your function - you are simply checking how many "a"'s fit in a string s repeated up to a length of n. So, instead of doing converged = s*n and subsequent modifications that require a lot of memory to store such a large string, you can instead use simple math to get the answer you are looking for.
Also, another optimization you could do is that you do not have to convert your string into an array to loop over it. Instead of doing for x in got_it, you could do for c in s.
Here is a working example of how you can accomplish what you need:
import math
def repeatedString(s, n):
if len(s) == 0:
return 0
reps = float(n) / len(s)
count = 0
for c in s:
if c == "a":
count += 1
# After testing the code, it turns out that Python does not play nicely
# with rounding UP from 0.5, so this is necessary to get the correct answer
result = count * reps
if result - math.floor(result) < 0.5:
return math.floor(result)
return math.ceil(result)
s = input()
n = int(input())
result = repeatedString(s, n)
print(result)
this program
takes a input string named s
repeats this string concatenated n times
takes only the first n charactes in the concatenated
counts how many times the letter "a" appears
you
you give the string "a"
you give the number 1000000000000
then the program should count and return 1000000000000
memmory problem
I guess this string with 1000000000000 letters "a" is too big
for the type in the python language
or for the computer memmory
the way it is
given that the program searches for the fixed occurrences of letter "a"
you passed exactly the letter "a" and the number 1000000000000
the better way is that it's not necessary a program
if you want to know how many times there is the letter "a"
in a string with 1000000000000 letters "a"
the answer is obviously 1000000000000
extra:
it would be complicated:
to rewrite the program
to search for a pattern
given as input parameter,
with variable length
AND
avoid the memmory problem
I guess I would write a program that
concatenates the "s" input just to have a length bigger than the searched pattern (if already not is)
check if the pattern occurs
after that multiply by "n"
ajust the how many times it will 'fit' in the final
one-line solution: find no of 'a' in string s, multiply with floor division of no.of repetition with the length of s + finding 'a' in the remaining length of s
s.count("a") * (n // len(s)) + s[:n % len(s)].count("a")
Thanks for all the help guys, I managed to solve the problem by handling the exception using try and except MemoryError
Sorry that I ask this here, because this seems really elementary and is most likely asked before. However, I have been searching and trying for hours and I couldn't find anything that helped me out. I want to write a program that asks for an upper bound and returns a table with pairs of numbers (m,n) such that the sum of of divisors of n (excluding n) equals m, and vice versa.
Now I wrote the following
bound = int(input('upper bound = '))
l = len(str(bound))
for x in range(1,l):
print(' ', end='')
print('m', end=' ')
for y in range(1,l):
print(' ', end='')
print('n', end='')
for i in range(1,bound):
for j in range (1, bound):
if j == i:
break
som_i = 0
som_j = 0
for k in range(1,i):
if i % k == 0:
som_i += k
for l in range(1,j):
if j % l == 0:
som_j += l
if som_i == j and som_j == i:
print('{:{prec}d}'.format(j, prec = l).rstrip(''), end="")
print('{:{prec}d}'.format(i, prec = l+2).lstrip(''), end="")
The problem is that I want the pair to be displayed in tabular form side to side and with the right indentation, depending on the length of the number. Whatever I tried (I read so many treads with similar questions already) Python keeps adding a whitespace.
Can anyone help me out on this? I am really new to Python and I cannot figure this out myself. If relevant, I am using version 3.6.
EDIT:
For example, when I run the program I get:
upper bound = 300
m n
220
284
while I would like to get
upper bound = 300
m n
220 284
And similar for larger inputs.
EDIT2 My question is not a duplicate, since i already tried adding
end=""
which did not work.
The first problem is that you're not using end='' after printing the j value, but you apparently already know about that. You also are using it after printing the n header, which you don't want.
Your edited version fixes the missing end='' after the j print, but then adds one after the i print, which, again, you don't want.
I'm not sure you understand what end='' means, so you're just putting it into your code randomly. That isn't going to get you very far. You can read the docs for print, but the short version is: use end='' when you're printing something that isn't supposed to be the end of a line, like that m header and j value, but don't use it when you're printing something that is supposed to be the end of a line, like that n header and i value.
The second problem is that l is just way too big. After for l in range(1,j):, it's going to be the same value as j, which means it's going to be 219, so you're going to print that 220 filled out to 219 characters, and that 284 filled out to 221 characters. So, unless your terminal is more than 446 characters wide, it's going to scroll across multiple lines and look like a mess. I think what you may want here is to use 3 and 5.
Or, maybe, you have some other variable that's supposed to be 3, and you want to use (let's call that variable x) x and x+2 instead of l and l+2. But I don't see any obvious candidates in your code.
So:
# ... unchanged lines
print('n') # no end='' here
# ... more unchanged lines
# using 3 and 5 instead of l and l+2, and adding end=''
print(('{:{prec}d}'.format(j, prec = 3)).rstrip(''), end='')
print(('{:{prec}d}'.format(i, prec = 5)).lstrip(''))
And now, the output is:
upper bound = 300
m n
220 284
I am trying to define a function that will include a variable n where n will be a string of numbers e.g. "3884892993", the definition of the function starts as is_true(n), however if n is going to be a string should it be is_true(n) and then once the string is defined I can test the function with an example string such as n = "3884892993". I get a syntax error when I use is_true(n) however. And I am just wondering how I would go about testing this function with an example string for n.
My entire function to define is shown here: http://oi44.tinypic.com/282i3qo.jpg but bear in mind I am an absolute novice so there will most probably be many mistakes, but I would appreciate some help from some experts if at all possible :)
def is_valid("n"): #n is the number to be checked.
number =
[int(y) for y in A] #converts the string into a list of useable digits.
altern1 = integer[-2::-2] #sets altern1 as one set of alternating digits.
double = [x*2 for x in altern1] #doubles each element of the list altern1.
sum1 = sum(double) # adds together all the doubled items of the list.
altern2 = integer[-1::-2] #sets altern2 as the other set of alternating digits.
return sum2 = sum(altern2)#sums the other set of alternating digits.
sumtotal = sum1 + sum2 #works out the total sum to be worked with.
for mod = sumtotal % 10: #works out remainder when sumtotal is divided by 10
if mod == 0 : #if remainder is zero sumtotal is a multiple of 10
print 'True' #sumtotal is a multiple of 10 therefore n is a credit card number
else:
print 'False' #sumtotal is NOT a multiple of 10 therefore not a valid credit card number
Here is the actual question:
The algorithm for verifying a number is as follows:
(a) Starting with the penultimate digit, and working towards the rst digit, double each alternating digit.
(b) Sum the doubled digits, treating 13 as 1+3, etc, and add the result to the sum of the undoubled
digits
(c) If the sum is divisible by 10 the number is a valid credit card number.
Write and test a function is_valid() which takes as an argument a credit card number as a string
(eg is valid("49927398716")) and returns True or False depending on whether the number is a
valid credit card number.
Quotes are only used for string literals, you wouldn't enclose a variable or parameter name in quotes to indicate that it will be a string. The function definition would look like:
def is_true(n):
And then in the body of the function you use n to reference the value that is passed in by the caller.
To call the function on a specific value, you do:
is_true("3884892993")
Side suggestion: Think of more explanatory names for your functions and variables. For instance, it seems like your function might be reasonably called is_valid_card_number.
I am not sure what is your question, but if you are trying to:
correctly define the function:
pay attention to the indentation (this is required by Python!),
see here for examples of function definitions,
convert a string variable into integer, you can do this:
new_var = int(old_var)
Generally please pay attention to types, because it is not like in some other dynamically typed languages and strings are not dynamically converted into numbers - you should do it explicitly.
read the value of the variable, based on its name:
my_var = vars().get('variable_name')
(where variable_name is the name of the variable and optionally you can give context within brackets after vars - see help(vars) for details)
Did any of the above solve your problem?
EDIT (based on the clarification):
This should solve your problem:
def is_true(my_variable):
# Here the variable named "my_variable" is accessible
If you want to do something "in-place" on the passed variable, I have a bad news: strings and integers are immutable in Python, thus you are not able to simply change them - you should probably return them as a result of the function (there are at least two workarounds, but I do not recommend them if you are a novice in Python).
EDIT (for proper code styling):
You should probably read PEP 8 to get familiar with what is the coding standard for Python scripts - this is commonly used across Python community and you should follow that (at some point you should appreciate it).
From the Wikipedia article on the Luhn algorithm:
def is_luhn_valid(cc):
num = map(int, str(cc))
return sum(num[::-2] + [sum(divmod(d * 2, 10)) for d in num[-2::-2]]) % 10 == 0
I have no idea what your function is supposed to do, but here are some remarks.
First of all, if you define the function then you use the following syntax
def is_true(n):
# do something
you can call this function like this is_true("3884892993"), i.e. you can pass string as n. Your function now need to treat variable n as a string. So you can use
number = [int(d) for d in n]
which will result in converting string into a list of digits.
One more remark: you used a return statement inside your is_true function. This statement will stop executing the function and return the value. Every code below return will never be executed.
May be like this. I leave your comments
def is_valid(n): #n is the number to be checked.
numbers = [int(y) for y in n] #converts the string into a list of useable digits.
double_alt = [sum([int(i) for i in str(x*2)]) for x in numbers[-2::-2]] #doubles and sum if more than 10each element of the list altern1.
sum1 = sum(double_alt) # adds together all the doubled items of the list.
sum2 = sum(numbers[-1::-2]) #sums the other set of alternating digits.
sumtotal = sum1 + sum2 #works out the total sum to be worked with.
return not sumtotal % 10
Here an implementation of the luhn algorithm that I had to make recently.
def is_valid_luhn(cc):
return not sum([sum(divmod(int(d) * 2, 10)) for d in cc[-2::-2]] + [int(d) for d in cc[-1::-2]]) % 10
# | double | |--- every -2th --| |--- every -1th --|
# |--------- step 1 -----------------|
# |------------- sum doubled digits --------------| |-- sum undoubled digits --|
# |---------------------- step 2: sum doubled/undoubled digits -----------------------|
# |-------------------------- step 3: sum % 10 == 0 --> not sum % 10 --------------------------|
Or if you'd like a more verbose version:
def is_valid_luhn(cc):
total = 0
# Double and sum every 2nd digit starting at -2.
for d in cc[-2::-2]:
# divmod(d*2, 10) returns (d*2 // 10, d*2 % 10)
# sum(divmod) return (d*2 // 10) + (d*2 % 10)
total += sum(divmod(int(d) * 2, 10))
# Sum every 2nd digit starting at -1.
for d in cc[-1::-2]:
total += int(d)
# Check module 10 of total: total % 10 == 0 --> not total % 10
return not total % 10