How to make an operator variable? - python

How do I make an operator a variable? for example I want to store the value 1 in operator '+' that is "+" = 1. But python is showing an error, what do I do?
my project is this: while True:
current_number = int(input("Enter the number that you wish to be displayed: "))
print(f"The current displayed number is: {current_number}")
print("The value of '+' and '-' is limited to 5")
n = input()
if n == "+" or "++" or "+++" or "++++" or "+++++":
if n == "+":
print(current_number + 1)
if n == "++":
print(current_number + 2)
if n == "+++":
print(current_number + 3)
if n == "++++":
print(current_number + 4)
if n == "+++++":
print(current_number + 5)
elif n == "-" or "--" or "---" or "----" or "-----":
if n == "-":
print(current_number - 1)
if n == "--":
print(current_number - 2)
if n == "---":
print(current_number - 3)
if n == "----":
print(current_number - 4)
if n == "-----":
print(current_number - 5)
I want to simplify the code by making "+" = 1, how do I do it?

Use len() to count the number of characters in n:
while True:
current_number = int(input("Enter the number that you wish to be displayed: "))
print(f"The current displayed number is: {current_number}")
n = input()
if set(n) == {"+"}:
print(current_number + len(n))
elif set(n) == {"-"}:
print(current_number - len(n))
Enter the number that you wish to be displayed: 37
The current displayed number is: 37
+++++
42
Note that with this approach there's no need to arbitrarily limit the number of characters, although you can still do that explicitly by rejecting inputs where len(n) > 5.
Your original version of the check for if the string contains all "+" or "-" doesn't work:
if n == "+" or "++" or "+++" or "++++" or "+++++":
because (n == "+") or ("++") will simply return "++" (which is true) if n == "+" is not True. A "correct" way to write this check would be:
if n in ("+", "++", "+++", "++++", "+++++"):
or more simply (since these specific strings are all substrings of "+++++":
if n in "+++++":
My version of the code does this instead:
if set(n) == {"+"}:
which works by converting n to a set (reducing it to only the unique characters) -- if n contains all "+"s, then its set is {"+"}. This works for any length of n.

Things other than [A-Za-z0-9_] are not allowed as names of variables
If you 100% need that, use a dictionary
ie
specialVars={'+':1, "-":-1}
then call
specialVars['+']
edit: if you jut need to add 1 for each '+' and -1 for each '-'
do this
print(current_number+n.count('+')-n.count('-'))

Related

how to store a value to a variable while in a for loop

I'm programming a calculator.
For example, I have the following:
result = 0
splitted_calculation = ["2", "+", "2"]
for thing in splited_calculation:
if thing == "+":
result = result + number
else:
number = int(thing)
print(result)
I want that, if the variable in the for loop is an integer, then that value is stored such that I can add the previous integer to the next integer currently in the for loop. However, when I run the code, I always get 0. It seems that the "number = int(thing)" isn't working. Any tips to solve this?
The issue with your code (besides the typo) is that the last digit is ignored. Step through it - in your head, on paper, or with a debugger.
Iterations of the loop. For this example, change it to ['2','+','3'] for clarity:
SIteration
thing
Action
number
result
1
2
assign it to number
2
0
2
+
add number to result
2
2
3
3
assign it to number
3
2
After the loop, the last digit is just hanging out in number but was never added to result. So result ends up at 2 not 5.
If the format is always "number operator number" there is no need for a loop. Access the values directly from the list:
splitted_calculation = ["2", "+", "2"]
left_number = int(splitted_calculation[0])
right_number = int(splitted_calculation[2])
operator = splitted_calculation[1]
if operator == '+':
result = left_number + right_number
elif operator == '-'
result = left_number - right_number
# repeat for others.
If the formulas are more complex ("2 + 2 + 2" for example) you can modify the loop to store the last operator and do the math on the numbers:
splitted_calculation = ["-5", "+", "2", "-", "3"]
result = 0
last_op = "+"
for n in splitted_calculation:
if n in "+-*/":
last_op = n
else:
if last_op == '+': result += int(n)
elif last_op == '-': result -= int(n)
elif last_op == '*': result *= int(n)
elif last_op == '/': result /= int(n)
Output:
-6
Find Modified Code Below:
result = 0
splited_calculation = ["2", "+", "2"]
for thing in splited_calculation:
if thing != "+":
result += int(thing)
print(result)

Find ordinal numbers with loop dynamically: find th - st - nd - rd

I would like to find dynamically the correct ordinal number root for instance:
111 = 111st
112 = 112nd
113 = 113rd ...
I tried other solutions but I can't find a good one.
This is my code:
for number in range(1, 114):
print(number)
ex1 = 11
ex2 = 12
ex3 = 13
if number == ex1:
print("is the " + str(number) + "th number.")
elif number % 10 == 1 or not ex1:
print("is the " + str(number) + "st number.")
elif number == ex2:
print("is the " + str(number) + "nd number.")
elif number % 10 == 2 or not ex2:
print("is the " + str(number) + "nd number.")
elif number == ex3:
print("is the " + str(number) + "rd number.")
elif number % 10 == 3 or not ex3:
print("is the " + str(number) + "rd number")
else:
print("is the " + str(number) + "th number.")
Note that 11, 12 and 13 have th suffix.
Also note you can change the end of the line in print function (default \n):
print('text', end=' ')
print('another text')
Then, I suggest you to use formatted string using f"{data} constant text" or "{} constant text".format(data).
Here is my solution to your problem:
def getSuffix(n):
if n < 0: raise Exception("Ordinal negative numbers are not allowed")
if n % 100 in [11, 12, 13]: return 'th'
if n % 10 == 1: return 'st'
if n % 10 == 2: return 'nd'
if n % 10 == 3: return 'rd'
return 'th'
for number in range(1, 114):
print(f"{number} is the {number}{getSuffix(number)} number")
I hope I was helpful.
So, the problem is that 111 gets displayed as 111st instead of 111th.
You have 11 as ex1, I assume short for "exception 1", but your condition:
if number == ex1:
Clearly doesn't match 111.
Instead you could do:
if number % 100 == ex1:
Which will be true for 11, 111, 211 etc.
On a side note:
elif number % 10 == 1 or not ex1:
Clearly isn't what you intended. This is interpreted as:
elif (number % 10 == 1) or (not ex1):
not ex1 does not depend on number and will always evaluate the same way (False). But since you're already checking ex1 separately, it would be redundant to do it correctly here.
If you wanted to correct that, so that you don't need to check ex1 twice, you'd do this:
if number % 10 == 1 and number % 100 != 11:
I think in this case using != is clearer than not and I don't think there is any benefit from assigning a variable to 11.
This is a pretty good solution:
ordinal = lambda n: "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10::4])
for number in range(1, 114):
print(f'the {ordinal(number)} number. :) ')
EDIT For Human Beings
NOTE: Variables name aren't meant to be used in a production environment, I tried to make it more explicit what each step on the lambda function does!
def get_ordinal(n):
hacking_string = "tsnrhtdd" # 1)
is_num_divisible_by_ten = (n // 10 % 10 != 1) # 2)
is_num_reminder_0_3= (n % 10 < 4) # 3)
are_both_false_or_both_true= is_num_divisible_by_ten * is_num_between_0_3 # 4)
get_index = are_both_false_or_both_true* n % 10 # 5)
return f'{number}{hacking_string[get_index::4]}' #6) ---> starts at t | s | n | r
for number in range(1, 114):
print(f'the {get_ordinal(number)} number. :) ')
Considerations
The solution found is very Hacky and smart and I probably would never come up my self, is using some clever math tricks to find the off sets of the number.
As requested I however simplified the function and added some explanation to it.
Step 1. This string is better seen it as this "tsnr" "htdd" | On the left side you heve the "root" of the string, on the right the end. (more explanation below)
Step 2. is_num_divisible_by_ten --> using a floor division the result is True or False.
Step 3. is_num_reminder_0_3 If checking if the reminder of N and 10 is between 0 & 3, returns a True / False Flag.
Step 4. are_both_false_or_both_true is multiplying 2 bool value, in Python True is a 1 and False is a 0, so is like do --> 1 * 0. The Variable is True only if both values are True or both are False, otherwise is always False.
Step 5. get_index - > Returns either 0 or 1 or 2 or 3.
Step 6. Here the hacky part, with the received index from get_index, is laverage the hacking_string variable with indexing-and-slicing:
The get_index value is always one of these: "tsnr" and the steps taken (4) any of these "rhtdd" hence the possible combination are:
get_index = 0 = "th"
get_index = 1 = "st"
get_index = 2 = "nd"
get_index = 3 = "rd"
Finally
The exact mathematics that goes behind it may be better asked on math.stackexchange or if someone knows it would be good to either add a comment or edit my answer!
References (It wasn't my solution)
Ordinal numbers replacement
outputting ordinal numbers 1st,2nd,3rd
Guides
python-lambda
python-string-formatting
python-booleans-as-numbers
You can do it like that:
for number in range(1, 114):
printedString = str(number)+' is the '+str(number)
if str(number) == '1' or (str(number)[-1] == '1' and str(number)[-2] != '1'):
printedString += 'st'
elif str(number) == '2' or (str(number)[-1] == '2' and str(number)[-2] != '1'):
printedString += 'nd'
elif str(number) == '3' or (str(number)[-1] == '3' and str(number)[-2] != '1'):
printedString += 'rd'
else:
printedString += 'th'
print(printedString+' number.')

How to create list of 15-digit numbers with condition?

I want to create list of random 20 15-digit numbers and each of this 15-digit numbers must follow 1 rule.
The rule is that I want this 15-digit number to be made out of 5 3-digit numbers in which first digit + second digit = third digit or if sum of first two digits is greater than 10 then third digit must be, equal to second digit of sum of first two digits. for example if first digit is 5 and second is 8, third digit must be 3 since 5 + 8 = 13.
I've written code that fills list with 15-digit numbers with the same rule, but it only works for first three digits.
import random as rd
def numchoose(start, end):
arr=[]
num=0
while num<20:
a=(rd.randint(start, end))
if int(str(a)[0]) + int(str(a)[1]) == int(str(a)[2]):
arr.append(a)
num+=1
elif int(str(a)[0]) + int(str(a)[1]) > 10 and int(str(a)[2]) == int(str(int(str(a)[0]) +
int(str(a)[1]))[1]) :
arr.append(a)
num+=1
else: continue
print(numchoose(100000000000000, 999999999999999))
How do I write this code so that entire 15-digit number is made out of 3-digit numbers that follow the stated rule and first three digits are not the only ones that follow rule?
This seems to work, but i replaced the big number with how long you want the number to be.
import random as rd
def numchoose(len):
number = ""
for i in range(int(len/3)):
a = rd.randint(0, 9)
while i == 0 and a == 0:
a = rd.randint(0, 9)
b = rd.randint(0, 9)
c = a + b
if c >= 10:
c -= 10
number += str(a) + str(b) + str(c)
return int(number)
print(numchoose(15))
Bit more compact then #eav28 but credit goes to them for answering first:
import random
def NumberGen(Length):
Number = ""
for X in range(int(Length // 3)):
A = random.randint(0, 9)
## To drop leading zero's:
## if X == 0 and A == 0:
## A = random.randint(1, 9)
B = random.randint(0, 9)
C = A + B
if C > 9:
C -= 10
Number += str(A) + str(B) + str(C)
return Number
print(NumberGen(15))
I hope this answers your question

Connection and Disconnection (AtCoder Grand Contest 039_A)

I am trying to solve this task. Source
A string S is given. Let T be the concatenation of K copies of S. We can repeatedly perform the following operation: Choose a character in T and replace it with a different character. Find the minimum number of operations required to satisfy the following condition: Any two adjacent characters in T are different.
Input is given from Standard Input in the following format:
S
K
Print the minimum number of operations required.
Below is the code that I've written.
I've separated the problem into 5 cases.
i) S is a single letter.
ii) S is two letters and they are the same.
iii) S is two letters and they are different.
iv) S is more than two letters and the first and last letters are different.
v) S is more than two letters and the first and last letters are the same.
S = input()
K = int(input())
L = len(S)
sum = 0
x = 1
if L == 1: # i)
print(K//2)
elif L == 2 and S[0] == S[1]: # ii)
print(K)
elif L == 2: # iii)
print(0)
elif S[0] != S[-1]: # iv)
for i in range(0, L-1):
if S[i] == S[i+1]:
x += 1
else:
sum += (x // 2)*K
x = 1
sum += (x // 2)*K
print(sum)
else: # v)
for i in range(0, L-1):
if S[i] == S[i+1]:
x += 1
else:
sum += (x // 2)
break
y = x
x = 1
for i in range(y, L-1):
if S[i] == S[i+1]:
x += 1
else:
sum += (x // 2)*K
x = 1
sum += (x // 2)
sum += ((x+y) // 2) * (K-1)
print(sum)
My code fails 2 out of 15 test cases. I have no idea what part of my work is causing the issue. Can somebody point out which part of the code is problematic? Thank you!

A function takes a string of numbers and inserts a dash before and after each odd digit: The exception: string cannot begin or end with '-'

The task: Write a method that takes in a number and returns a string, placing single dash before and after each odd digit. There is one exception: don't start or end the string with a dash.
Here is what I have:
num = "32343"
dash = ""
for digit in num:
if int(num[0]) % 2 != 0:
dash = digit + "-"
else:
dash += digit
if int(digit) % 2 != 0:
dash += "-" + digit + "-"
else:
dash += digit
if int(num[-1]) % 2 != 0:
dash += "-" + digit
else:
dash += digit
print(dash)
It is printing "3--3--3"
If someone could tell me where I'm going wrong, it would be much appreciated!
The solution is just a series of if - else cases to consider, which is quite self-explanatory:
num = "32343"
string = ""
for i in xrange(0,len(num)):
if i == 0 and i == len(num) - 1 and int(num[i]) % 2 != 0:
string = num[i]
elif i == 0 and int(num[i]) % 2 != 0:
string = num[i] + "-"
elif i == len(num) - 1 and int(num[i]) % 2 != 0:
string = string + "-" + num[i]
elif int(num[i]) % 2 !=0:
string = string + "-" + num[i] + "-"
elif int(num[i]) % 2 == 0:
string = string + num[i]
print string
You can approach this in various ways using splicing (the [:] syntax) but my first crack at it would be via a generator. Your use of mod (%) is a great start, but you can avoid several elif using string formatting and implicit else's.
edit: I noticed you should still have a trailing - on the first number and a preceding - on the end number as per example. Using splicing, I remove these in the revision and no longer yield 0th and last elements unaltered:
def dash(num):
""" add surrounding -'s to any digit in num which is odd """
for n in num:
if int(n) % 2 != 0:
n = "-%s-" % n
yield n
def remove_bookends(_str):
""" if - is at the start or end of _str, remove it """
if _str[0] is "-":
_str = _str[1:]
if _str[-1] is "-":
_str = _str[:-1]
return _str
if __name__ == '__main__':
num = "32343"
_str = "".join([n for n in dash(num)])
_str = remove_bookends(_str)
print _str

Categories

Resources