Just I check if for example 1 + 2 is equal to 3 so it means 0011 in binary code.
ox_number = 361
output = []
for num in ox_number.split():
if 1 == num:
output.append("001")
elif 1 + 2 == num:
output.append("011")
else 1 + 2 + 4 == num:
output.append("111")
connected = ''.join(output)
rever_ = reversed(connected)
print(rever_)
You can convert your integer to and from an octal formatted string by using
your_int = 386
its_octal_is = f"{your_int:o}"
# Equivalent to
its_octal_is = "{:o}".format(your_int)
int_from_octal_string = int("386",8)
You might want to have a look at int documentation as well as the formatting expressions here.
Related
So I am trying to make something that subtracts a certain amount from a string to make the 2 strings equal in length the problem is when I try to find the length of the element 1 which is stored as 0000 0000 it returns 1. Also, the code is grabbing from a file but the only relevant element is 1. Here is the code in question:
import re
insSpec2 = {}
z = 0
bool(z)
TestString = "0100 0001"
while z == 0:
f = open("Specifier", 'r')
for word in f:
i = 0
insSpec2[i] = re.split('r|a', word)
print(insSpec2[i])
insLength = len(insSpec2[i])
testLength = len(TestString)
if testLength > insLength:
diff = testLength-insLength
else:
diff = insLength-testLength
print(insLength)#returns 1
print(testLength, insLength) #returns 9 1
print(diff)#returns 8
print(insSpec2[0].__len__()) #returns 1
if insLength < testLength:
changeVar = 8 - insLength
while TestString != insSpec2:
#print(testLength)
newStr = TestString[:-diff]
#print(newStr)
elif insSpec2[i] == TestString:
print("Found Match", insSpec2[i])
z = 1
break
i += 1
That is because re.split returns a list not a string, insSpec[i] = ['0000 0000']. It has length 1
Hello lovely stackoverflowians!
I am fairly new to programming. Only have been programming a little under 2 months using CS50 which uses C and MITx Python. I went on Codewars and am trying to solve a problem where you basically get an id and then come out with a license plate number like this aaa001...aaa999, aab001...zzz999
if you catch my drift. For some reason my code compiles but when I run it I get this error.
File "/Users/pauliekennedy/Desktop/temp.py", line 9, in find_the_number_plate
a_str = (a_numb.zfill(3), range(0, 10))
AttributeError: 'int' object has no attribute 'zfill'
Because of this I am not able to test my code. If you could help me with this problem I would be much appreciated. As well, if you have anything to say about my code in general, tips, advice how to make it better, and if it will achieve this goal at all. Here is my code thanks again all.
#set number to 1 to start
a_numb = 1
#incrementing loop when 999 go back set back 0
while a_numb <1001:
a_numb += 1
a_str = str(a_numb)
# giving the number 00 or just 0 in front
if a_numb < 100:
a_str = (a_numb.zfill(3), range(0, 10))
#resetting the number back to 1
if a_numb == 999:
a_numb = 1
# Setting i to 0 and incrementing the characters
i = 0
ch = 'a'
ch2 = 'a'
ch3 = 'a'
#looping through alphabet
for i in range(26):
ch = chr(ord(ch) + 1)
print(ch)
if i == 26:
i = 0
if ch == 'z':
ch2 = chr(ord(ch) + 1)
if ch == 'z' & ch2 == 'z':
ch3(ord(ch) + 1)
# Adding results together and returning the string of them all
letter_plate = str(ch3 + ch2 + ch)
plate = str(a_numb) + str(letter_plate)
return plate```
Maybe you could consider using f-string string formatting instead:
def find_the_number_plate(customer_id):
number_part = customer_id % 999 + 1
customer_id //= 999
letter_part = ['a', 'a', 'a']
i = 0
while customer_id:
letter_part[i] = chr(ord('a') + customer_id % 26)
customer_id //= 26
i += 1
return f"{''.join(letter_part)}{number_part:03}"
You could use product from itertools to form the license plate numbers from 3 letters and numbers from 1 to 999 formatted with leading zeros:
from itertools import product
letter = "abcdefghijklmnopqrstuvwxyz"
numbers = (f"{n:03}" for n in range(1,1000))
plates = [*map("".join,product(letter,letter,letter,numbers))]
for plate in plates: print(plate)
aaa001
aaa002
aaa003
aaa004
aaa005
aaa006
aaa007
aaa008
...
If you only need to access a license place at a specific index, you don't have to generate the whole list. You can figure out which plate number will be at a given index by decomposing the index in chunks of 999,26,26,26 corresponding to the available option at each position/chunk of the number.
def plate(i):
letter = "abcdefghijklmnopqrstuvwxyz"
result = f"{i%999+1:03}"
i //= 999
for _ in range(3):
result = letter[i%26] + result
i //= 26
return result
output:
for i in range(10):print(plate(i))
aaa001
aaa002
aaa003
aaa004
aaa005
aaa006
aaa007
aaa008
aaa009
aaa010
plate(2021) # aac024
I am trying to reformat somewhat inconsistent values (OCR) to a standard form based on a set of rules. These values come over typically as a fraction i.e. 4 3/4 but the values are sometimes polluted with other random characters i.e. 4 .3/4. The values can also be non fractional floats (4.75). The goal is to grab the values and produce the number; input = 'T 3/' output = 3. The values will never exceed 11.
I'm sure there's a better way to do this, but this is what I have so far, and it works on most but it doesn't catch everything. Any help to help handle exceptions like 'T 3/' would be appreciated.
a = ' Y 3/'
def get_num(t):
return str(''.join(ele for ele in t if ele.isdigit()))
t = get_num(a)
y = int(t)
z = a.split('.')[0]
print len(t)
if '/' in a:
if int(str(y)[:1]) == 1 and int(str(t)[1]) != 1 and len(t) == 4 and t <1199:
print '{}{} {}/{}'.format(*t)
if int(str(y)[:1]) == 1 and int(str(t)[1]) != 1 and len(t) == 4 and t >1199:
print '{} {}/{}'.format(*t[1:])
if int(str(y)[:1]) != 1 and int(str(t)[1]) != 1 and len(t) == 3:
print '{} {}/{}'.format(*t)
if int(str(y)[:1]) != 1 and int(str(t)[1]) == 1 and len(t) == 3:
print '{} {}/{}'.format(*t)
elif '.' in a and '/' not in a:
if int(z) == 1 and len(z) == 1:
print a.replace(' ','')
if int(z) > 11 and len(z) > 1 and int(t[:1]) == 1:
print a.replace(' ','')[1:]
if int(z) != 1 and len(z) <= 2:
print a.replace(' ','')
elif '.' not in a and '/' not in a:
if int(str(y)[:1]) == 1 and int(str(t)[1]) != 1 and len(t) == 4 and t <1199:
print '{}{} {}/{}'.format(*t)
if int(str(y)[:1]) == 1 and int(str(t)[1]) != 1 and len(t) == 4 and t >1199:
print '{} {}/{}'.format(*t[1:])
if int(str(y)[:1]) != 1 and int(str(t)[1]) != 1 and len(t) == 3:
print '{} {}/{}'.format(*t)
if int(str(y)[:1]) != 1 and int(str(t)[1]) == 1 and len(t) == 3:
print '{} {}/{}'.format(*t)
else:
print(a)
Common Sample Inputs/Outputs (many more combos):
In: 4 3/4 | Out: 4 3/4
In: 4.75 | Out: 4.75
In: T 3/ | Out: 3
In: 14 3/4 | Out: 4 3/4 (leading 1 does not belong >11
In: 4 .33 | Out: 4.33
In: 3 2./3 | Out: 3 2/3
In: 3 ..33 | Out: 3.33
Essentially its a fraction if there is a '/' in the string even if it contains a '.'. If its not in the string, it's a decimal. If neither, then there is an opportunity there as well for some logic
Alright #FanScience, got an answer here. It works with all the inputs you gave, but it's slightly brittle -- happy to try to expand if you find there are inputs that it doesn't get along with.
First I imported two helpful libraries:
import re
from fractions import Fraction
Next I defined a dictionary with your inputs + expected outputs, so I could write a function that tested my methodology:
expected_results = {
"4 3/4": 4.75,
"4.75": 4.75,
"T 3/": 3,
"14 3/4": 4.75,
"4 .33": 4.33,
"3 2./3": 3.67,
"3 ..33": 3.33,
}
Next I got to writing the actual function -- let me know if you have any questions, as this is somewhat complex:
def generate_correct_float(to_convert):
# Removes any alphabetical character (A, B, a, b...)
to_convert = re.sub("[a-zA-Z]", "", elem)
# Removes extra whitespace on either end
to_convert = to_convert.strip()
final_answer = 0
if " " in to_convert: #two-part, ie 4 3/4
primary_number, secondary_number = to_convert.split()
final_answer += int(primary_number)
if "/" in secondary_number: # Fraction case
secondary_number = secondary_number.replace(".", "")
secondary_number = secondary_number.strip("/")
secondary_number = Fraction(secondary_number)
else: #Decimal Case
secondary_number = Fraction(int(secondary_number.replace(".", "")), 100)
final_answer += round(secondary_number.__float__(), 2)
else: # Single element, ie 3/
final_answer = to_convert.strip("/")
final_answer = float(final_answer)
# Eliminate cases where we're higher than 11
while final_answer > 11:
final_answer -= 10
return final_answer
Finally I wrote a wrapper function that tests inputs vs outputs and gives us a correct vs incorrect count:
incorrect = 0
for elem in expected_results:
answer = generate_correct_float(elem)
if answer != expected_results[elem]:
print('------')
print(elem)
print(expected_results[elem])
print(answer)
incorrect += 1
correct = len(expected_results) - incorrect
print(f"correct: {correct}")
print(f"incorrect: {incorrect}")
Running this with our code gives us 7/7, all with floats!
Hopefully this helps -- let me know if there are any points of clarification I can make #FanScience
I have really been struggling to solve this problem. This is the problem:
Given a string describing the circuit, calculate the total resistance
of the circuit.
Here is an example:
input: 3 5 S
expected output: 8
The operands in the string are trailed by the operator, denoting if the resistors are either in Series or Parallel. However let's analyze a more complicated circuit:
input: 3 5 S 0 P 3 2 S P
expected output: 0
Step by step:
The 3 5 S at the beginning of the input gives us 8 and hence the first intermediate step is the string 8 0 P 3 2 S P.
8 0 P gives us 0, as one resistor is short-circuited and consequently we get 0 3 2 S P.
3 2 P is 5.
and finally 0 5 P is 0.
Here is my attempt. I tried using recursion as it seemed like a problem that can be solved that way. Firstly I wrote a helper function:
def new_resistance(a,b,c):
if c == '':
if int(a) == 0 or int(b) == 0:
return 0
else:
return 1/(1/int(a) + 1/int(b))
else:
return int(a) + int(b)
And the function that calculates the newn resistance of the circuit:
def resistance(array):
if isinstance(array, int):
return array
else:
if isinstance(array,list):
temp = array
else:
temp = array.split(" ")
i = 0
while True:
try:
a = new_resistance(temp[i], temp[i+1], temp[i+2])
except Exception as e:
i += 1
if len(temp[i+3:]) == 0:
return resistance(new_resistance(temp[i], temp[i+1], temp[i+2]))
else:
return resistance(temp[:i] + [new_resistance(temp[i], temp[i+1], temp[i+2])] + temp[i+3:])
The idea behind the program is to start at the beginning of the list and calculate the resistance of the first three elements of the list, then to append them at the beginning of a new list (without the three elements) and call the function again with the new list. Do this until only a single integer remains and return the integers.
Any help is appreciated.
UPDATE:
The solution to the problem, using a stack and a parser similar to a NPR parser.
operator_list = set('PS')
def resistance(circuit):
temp = circuit.split(" ")
stack = []
for char in temp:
if char in operator_list:
a = new_resistance(stack.pop(), stack.pop(), char)
print(a)
stack.append(a)
else:
print(char)
stack.append(char)
return stack[-1]
def new_resistance(a,b,c):
if c == 'P':
if float(a) == 0 or float(b) == 0:
return 0
else:
return 1/(1/float(a) + 1/float(b))
else:
return float(a) + float(b)
circuit = '3 5 S 0 P 3 2 S P'
resistance(circuit)
# 3
# 5
# 8.0
# 0
# 0
# 3
# 2
# 5.0
# 0
The problem is that once you reach 0 3 2 S P, you cannot simply take the first 3 elements. You need to look for number number S_or_P, wherever it is in the string.
You can use a regex for this task:
import re
circuit = '3 5 S 0 P 3 2 S P'
pattern = re.compile('(\d+) +(\d+) +([SP])')
def parallel_or_serie(m):
a, b, sp = m.groups()
if sp == 'S':
return str(int(a) + int(b))
else:
if a == '0' or b == '0':
return '0'
else:
return str(1/(1/int(a) + 1/int(b)))
while True:
print(circuit)
tmp = circuit
circuit = re.sub(pattern, parallel_or_serie, circuit, count=1)
if tmp == circuit:
break
# 3 5 S 0 P 3 2 S P
# 8 0 P 3 2 S P
# 0 3 2 S P
# 0 5 P
# 0
Note that 1 1 P will output 0.5. You could replace int by float and modify the regex in order to parse floats.
Your program, or more specifically your parser, seems to be relying on the Reverse Polish Notation, which in turn is a small variant of the Normal Polish Notation. Simply put, the RPN is an abstract representation where the operators of an arithmetical expression follow their operands, unlike in the Normal Polish Notation where the operators precede their operands. Parsers based on this representation can be easily implemented by using stacks (and usually do not need to interpret parentheses).
If you are tasked with developing that parser you may get some input from the Wikipedia article I linked above.
Credits to #none who first recognized the RPN.
Old memories came to my mind. I was playing with the FORTH language on 8-bit computers in 1980s. OK, back to Python:
circuit = '3 5 S 0 P 3 2 S P'
stack = []
for n in circuit.split():
if n == 'S':
r1 = stack.pop()
r2 = stack.pop()
stack.append(r1+r2)
elif n == 'P':
r1 = stack.pop()
r2 = stack.pop()
stack.append(0.0 if (r1 == 0 or r2 == 0) else 1/(1/r1+1/r2))
else:
stack.append(float(n))
assert len(stack) == 1
print(stack[0])
On in the spirit of VPfB for any combination of serial parallel (not only in pairs)
def calculateresistor(dataString):
stack = []
r = []
cicuit=dataString
for n in circuit.split():
if n == 'S':
stackSize=size(stack)
if size(stack)>=2:
for k in range(0,size(stack)-1):
r.append(float(stack.pop()))
r.append(float(stack.pop()))
stack.append((r[-1]+r[-2]))
elif n == 'P':
stackSize=size(stack)
if size(stack)>=2:
for k in range(0,size(stack)-1):
r.append(float(stack.pop()))
r.append(float(stack.pop()))
r.append(0.0 if (r[-1] == 0 or r[-2] == 0) else (1/(1/r[-1]+1/r[-2])))
stack.append(r[-1])
else:
stack.append(float(n))
assert len(stack) == 1
return(stack)
I'm creating a python script which prints out the whole song of '99 bottles of beer', but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.
This is my full script,
def reverse(str):
return str[::-1]
def plural(word, b):
if b != 1:
return word + 's'
else:
return word
def line(b, ending):
print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)
for i in range(99, 0, -1):
line(i, "of beer on the wall")
line(i, "of beer"
print reverse("Take one down, pass it around")
line(i-1, "of beer on the wall \n")
I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.
Without converting the number to a string:
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?
def line(bottles, ending):
return "{0} {1} {2}".format(bottles,
plural("bottle", bottles),
ending)
Which runs like:
>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'
Then pass the result to reverse:
>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'
This makes it much easier to test each part of the code separately and see what's going on when you put it all together.
Something like this?
>>> x = 123
>>> str(x)
'123'
>>> str(x)[::-1]
'321'
best way is
x=12345
a=str(x)[::-1]\\ In this process i have create string of inverse of integer (a="54321")
a=int(a) \\ Here i have converted string a in integer
or
one line code is
a=int(str(x)[::-1]))
def reverse(x):
re = 0
negative = x < 0
MAX_BIG = 2 ** 31 -1
MIN_BIG = -2 ** 31
x = abs(x)
while x != 0:
a = int(x % 10)
re = re * 10 + a
x = int(x // 10)
reverse = -1 * re if negative else re
return 0 if reverse < MIN_BIG or reverse > MAX_BIG else reverse
this is for 32 - bit integer ( -2^31 ; 2^31-1 )
def reverse_number(n):
r = 0
while n > 0:
r = (r*10) + (n % 10)
print(r)
r *=10
n //= 10
return r
print(reverse_number(123))
You can cast an integer to string with str(i) and then use your reverse function.
The following line should do what you are looking for:
def line(b, ending):
print reverse(str(b)) or reverse('No more'), plural(reverse('bottle'),reverse(str(b))), reverse(ending)
Original number is taken in a
a = 123
We convert the int to string ,then reverse it and again convert in int and store reversed number in b
b = int("".join(reversed(str(a))))
Print the values of a and b
print(a,b)
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
This code will not work if the number ends with zeros, example 100 and 1000 return 1
def reverse(num):
rev = 0
while(num != 0):
reminder = num % 10
rev = (rev * 10 ) + reminder
num = num // 10
print ("Reverse number is : " , rev )
num=input("enter number : ")
reverse(int(num))
#/ always results into float
#// division that results into whole number adjusted to the left in the number line
I think the following code should be good to reverse your positive integer.
You can use it as a function in your code.
n = input() # input is always taken as a string
rev = int(str(n)[::-1])
If you are having n as integer then you need to specify it as str here as shown. This is the quickest way to reverse a positive integer
import math
def Function(inputt):
a = 1
input2 = inputt
while(input2 > 9):
input2 = input2/10
a = a + 1
print("There are ", a, " numbers ")
N = 10
m = 1
print(" THe reverse numbers are: ")
for i in range(a):
l = (inputt%N)/m
print(math.floor(l), end = '')
N = N*10
m = m*10
print(" \n")
return 0
enter = int(input("Enter the number: "))
print(Function(enter))
More robust solution to handle negative numbers:
def reverse_integer(num):
sign = [1,-1][num < 0]
output = sign * int(str(abs(num))[::-1])
An easy and fast way to do it is as follows:
def reverse(x: int|str) -> int:
reverse_x = int(''.join([dgt for dgt in reversed(num:=str(x)) if dgt != '-']))
if '-' in num:
reverse_x = -reverse_x'
return reverse_x
First we create a list (using list comprehension) of the digits in reverse order. However, we must exclude the sign (otherwise the number would turn out like [3, 2, 1, -]). We now turn the list into a string using the ''.join() method.
Next we check if the original number had a negative sign in it. If it did, we would add a negative sign to reverse_x.
Easily you can write this class:
class reverse_number:
def __init__(self,rvs_num):
self.rvs_num = rvs_num
rvs_ed = int(str(rvs_num)[::-1])
print(rvs_ed)
You can use it by writing:
reverse_number(your number)
I have written it in a different way, but it works
def isPalindrome(x: int) -> bool:
if x<0:
return False
elif x<10:
return True
else:
rev=0
rem = x%10
quot = x//10
rev = rev*10+rem
while (quot>=10):
rem = quot%10
quot = quot//10
rev = rev*10+rem
rev = rev*10+quot
if rev==x:
return True
else:
return False
res=isPalindrome(1221)