Calculate a serie in python - python-3.x

n is a knwon integer.
I need to print the serie:
Sn = 1/n + 2/(n-1) + 3/(n-2) + ... + n.
I tried:
n =2
soma =1
for i in range(1,n+1):
if n>i:
soma+=i/n + i/(n-1)
What is wrong?

You are doing it like this for now:
(1/2 + 1/1) + (2/2 + 2/1) .....
When actually what you want is to accumulate only one of them each iteration.
Therefore: soma+=i/(n-(i-1))
Also the condition n>i is always true in that case so you can try and omit it.

Related

Why i = 1, and i = i + 1 would become 2?

i = 1
i = i + 1
print(i)
I am pretty confused about the code's logic. Why would i eventually become 2?
Lets begin with the first assignment:
i = 1
This creates the variable i and initialize it to the integer value 1.
Then we get to what you seem to have problem understanding:
i = i + 1
This statement can be split into two parts:
The addition
The assignment
The addition i + 1 will take the current values of the variable i, which is 1, and add the value 1 to that. In essence the expression i + 1 is the same as 1 + 1.
The result of the addition will be 2. And this result is then assigned to the variable i, making the value of i be equal to 2.
You then print the (new) current value of i:
print(i)
This will of course print the value 2.
The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.
Just for completeness:
x += y is not always doing an in-place operation, there are (at least) three exceptions:
If x doesn't implement an __iadd__ method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int
If __iadd__ returns NotImplemented, Python falls back to x = x + y.
The __iadd__ method could theoretically be implemented to not work in place. It'd be really weird to do that, though.
As it happens your bs are numpy.ndarrays which implements __iadd__ and return itself so your second loop modifies the original array in-place.
You can read more on this in the Python documentation of "Emulating Numeric Types".
'i' is a variable which stored 1 if We add 1 again in 'i' that means
i=1;
i+1 means 1+1=2
i=1
i=i+1// i has already 1 and here we are adding 1 again so result will be 2.
hope you understood.
Let's start from i = 1. So you are assigning i to 1. Now your situation is:
i = i + 1
So if i is 1, then the abovementioned code would be "translated" to:
i = 1 + 1
That's why i = i + 1 is equal to 2.

Python: is there a way to force code to ignore a variable if user input is only whitespace?

this is my first time posting and I haven't been learning to code for very long. This is the first script I've tried to build on my own, please be nice.
The program is linked to a CSV of elements and their atomic mass. The user inputs a chemical formula and the return is the molecular mass and a breakdown of the molecular mass percentage. It runs fine but as it stands it requires 6 values, eg H 2 S 1 O 4 for H2SO4. Obviously I want to have the option for long formulae but for shorter ones the script returns an error saying it expected 6 variables but only had 4 to unpack eg: H2O1.
Is there a straightforward way to make the script skip/ignore variables if there is no user input/the input is only white-space? I've been Googling it but either it's more difficult than I imagine or I'm not using the search engine well enough. I messed around with for loops but couldn't get anything to play ball.
Attached is the code, I'm aware that it could probably be twice as simple/slick if I had a little more knowledge. Thanks in advance.
def formula():
element_1, element_1_size, element_2, element_2_size, element_3, element_3_size = input("Enter your formula: ").split()
element_1_mass = float(elements_data_symbols.loc[element_1, "Atomic Mass"])
element_2_mass = float(elements_data_symbols.loc[element_2, "Atomic Mass"])
element_3_mass = float(elements_data_symbols.loc[element_3, "Atomic Mass"])
element_1_molecular_mass = element_1_mass * int(element_1_size)
element_2_molecular_mass = element_2_mass * int(element_2_size)
element_3_molecular_mass = element_3_mass * int(element_3_size)
molecular_mass = element_1_molecular_mass + element_2_molecular_mass + element_3_molecular_mass
molecule_name = str(element_1 + element_1_size + element_2 + element_2_size + element_3 + element_3_size)
print("Molecular mass of " + molecule_name + ": " + str(molecular_mass) + " g/mol")
element_1_percentage = element_1_molecular_mass / molecular_mass * 100
element_2_percentage = element_2_molecular_mass / molecular_mass * 100
element_3_percentage = element_3_molecular_mass / molecular_mass * 100
print(element_1 + ": " + str(element_1_percentage) + " %")
print(element_2 + ": " + str(element_2_percentage) + " %")
print(element_3 + ": " + str(element_3_percentage) + " %")
print(" ")
You're right a more efficient way of doing this would be using a loop to go through each pair of elements within the array, but keeping it simple you could amend your code to conditionally set elements only if the input array is at a certain length:
# Receive user input as an array
elements = input("Enter your formula").split()
# First element should always exist (but could also do this conditionally)
element_1 = elements[0]
element_1_size = elements[1]
# Check if array has at least 4 elements
if len(elements) >= 4:
element_2 = elements[2]
element_2_size = elements[3]
# Check if array has at leat 6 elements
if len(elements) >= 6:
element_3 = elements[4]
element_3_size = elements[5]

How do I get all possible numbers that can be achieved by removing digits from an existing number?

I need to find all the possible numbers I can get by removing one or more digits from a certain number, but not reordering them (i.e. 1234 can become 124 or 134 or 12, but not 143).
I've tried this to find them:
xdigits = list(map(int, str(x)))
ydigits = list(map(int, str(y)))
for m in xdigits:
if m in xdigits and m in ydigits:
xdigits.remove(m)
ydigits.remove(m)
numerator = int(''.join(str(i) for i in xdigits))
denominator = int(''.join(str(i) for i in ydigits))
try:
if (numerator/denominator) == (x/y)
print('Remove ' + str(removelist) + ': ' + str(x) + '/' + str(y) + ' equals ' + str(numerator) + '/' + str(denominator) )
except ZeroDivisionError:
pass
But this does not give me all the possible situations (i.e. when 134 and 124 are both possible answers, only 134 is outputted). How can I get all the possible values?
Thank you for your help!
I didn't quite understand your code. What would be "x" and "y", for example?
Anyway, I believe this code should solve your problem. It basically creates all combinations of lists in which each element can be the digit for that position , or a empty string. After that it removes the first list (which would be all empty elements), then it joins the lists and converts it to integers.
import itertools
def list2num(x):
return int(''.join(x))
def get_digit_combinations(number):
number_str = str(number)
possibilities = [['',digit] for digit in number_str]
list_of_digits = list(itertools.product(*possibilities))
list_of_digits.pop(0) # removing first element, where the string is empty
return [list2num(x) for x in list_of_digits]
all_numbers = get_digit_combinations(1234)
print(all_numbers)
print(len(all_numbers))
Let me know if that works.

How can i remove the exact number of middle characters from a string?

I am trying to remove the number of middle characters in a string according to a given number. For example, if the string is mahir and I am told to remove one middle character, that would be h and the output would be mair, if the given number was 2, the output would have been mar.
I have worked out how the remove the middle characters but having troubles in removing it correctly. This is my code:
remover = int(input())
s = "mahir"
counter = len(s) - remover
while True:
h = len(s)//2
mod = (len(s) + 1) % 2
s = s[:h - mod] + s[h + 1:]
if len(s) == counter:
break
print(s)
If i enter remover more than one I end up getting an inifinte loop. How can i fix this and remove the correct number of middle characters?
You can slice the string like this:
s = 'mahir'
n = int(input())
i = (len(s) - n + 1) // 2
print(s[:i] + s[i + n:])

Printing specific parts of a function for Python

I am currently learning to program in python. I am trying to build a basic program that will output how many of each type of coin (quarter, nickel, dime, penny) based off of what number the user inputs. I currently have it so that it will print a 0. However, I'd like it to omit those values in the print statement. I'm not sure how to do that without making each of the different total values and having them print each off of an if statement.
#for if statement and to ask for what coin number it is
y = 1
#asks user for how many coins
x = int(input("How much change are you trying to give (in cents)? "))
while(y <= 1):
q = 25
d = 10
n = 5
p = 1
#Take total and divide by 25 as many times as you can output as quarter
totalq = x // 25
#Take total from that and divide by 10 as many times as you can and output as dime
totald = (x-(q*(totalq))) // 10
#Take total from above and divide by 5 as many times as you can and output as nickel
totaln = (x-(q*(totalq))-(d*(totald))) //5
#Finally take total from above and see how many is left over and output as penny
totalp = (x-(q*(totalq))-(d*(totald))-(n*(totaln))) // 1
y = y + 1
total = (str(totalq) +" quarters " + str(totald) +" dimes " + str(totaln) +" nickels " + str(totalp) + " pennies")
print(total)
I think the most straightforward way to approach this is, as you suggest, using a bunch of ifs - something like:
if totalq:
print(totalq, "quarters", end=' ')
if totald:
print(totalq, "dimes", end=' ')
if totaln:
print(totalq, "nickels", end=' ')
if totalp:
print(totalq, "pennies")
Or, you could make this a little less repetitive using a generator expression:
pairs = [(totalq, 'quarters'),
(totald, 'dimes'),
(totaln, 'nickels'),
(totalp, 'pennies')]
total = ' '.join(str(value) + ' ' + name
for value, name in pairs
if value)
print(total)
Personally, I think the latter approach is prettier, but it's also a bit more complicated. If there's something about this latter code you don't understand, let me know.

Resources