Lets say I have two numbers,
Number 1:
1646
Number 2:
2089
You see adding them left to right without the carry on adds up to 3625 how would I do this in python? I'm not sure but I need it to add 9+6 which is 15 but not to carry on the 1 when it adds 8+4 is there any way to add like this in python? And the end result i'm looking for is
3625
Since it doesn't carry on remaining numbers
This will work with varying N of integers of varying lengths:
from itertools import izip_longest
nums = [1646,
2089,
345]
revs = [str(n)[-1::-1] for n in nums] # nums as reversed strings
izl = izip_longest(*revs, fillvalue = '0') # zip the digits together
xsum = lambda ds: str(sum(map(int, ds)))[-1] # digits -> last digit of their sum
rres = ''.join(xsum(ds) for ds in izl) # result, but as reversed string
res = int(rres[-1::-1]) # result: 3960
Similar idea, but using map rather than izip_longest. I like this one better.
revs = [str(n)[-1::-1] for n in nums] # nums as reversed strings
dsum = lambda *ds: sum(int(d or 0) for d in ds) # str-digits -> their sum
sums = map(dsum, *revs)[-1::-1] # digit sums, in order
ones = [str(s % 10) for s in sums] # last digits of the sums
res = int(''.join(ones)) # result: 3960
Because I like to take poetic license with open-ended requests for 'more efficient':
In [49]: a,b = 1646,2089
In [50]: ''.join(str(sum(map(int,x)))[-1] for x in zip(str(a),str(b)))
Out[50]: '3625'
This will work even if the numbers of digits is not the same in both the numbers.
num1, num2, i, temp = 1646, 2089, 10, 0
total = num1 + num2
while num1 or num2:
if (num1 % 10) + (num2 % 10) > 9: temp += i
num1, num2, i = num1 // 10, num2 // 10, i * 10
print total - temp
Output
3625
The following code demonstrates what you want, but please just consider this as a hint. The var names and lack of exception handling will jeopardize your real code.
import operator
n1 = 1646
n2 = 2089
l1 = [int(x) for x in str(n1)]
l2 = [int(x) for x in str(n2)]
res1 = map(operator.add, l1, l2)
res2 = [str(x)[-1] for x in res1]
num = "".join(res2)
print int(num)
This is kind of ugly because I do not know how to index a digit in an integer, only a string, but it works.
If the two strings are always the same size:
A = str(1646)
B = str(2089)
result = ""
for i in range(0,len(A)):
result += str((int(A[i]) + int(B[i]))%10)
result = int(result)
If the two strings are not always the same size, find which one is bigger (length wise). Say the length of the biggest is X and the others length is Y where X > Y. Append the first X-Y indexes of the bigger string onto result, then repeat the above with the remaining digits.
The numbers might be different length, so convert both to strings, reverse order (makes indexing easier), reverse using extended slice ([::-1], Reverse a string in Python), reverse back,
result=""
A=str(1646)[::-1]
B=str(2089)[::-1]
for ndx in range(0,max(len(A),len(B)):
result += str(int(A[ndx])+int(B[ndx]))
resut = int(result[::-1])
You can get carry pretty easily, and handle unequal length strings (explicitly),
#!/bin/env python
a=1646
b=20893
A=str(a)[::-1]
B=str(b)[::-1]
lenA = len(A)
lenB = len(B)
length = max(lenA,lenB)
print "length: "+str(length)
#string add,no carry
total=""
for ndx in range(0,length):
digit = 0
if(ndx<lenA):
digit += int(A[ndx])
if(ndx<lenB):
digit += int(B[ndx])
digit = digit%10
#print "digit: "+str(digit)+", carry: "+str(carry)
total += str(digit)
print "a: " +str(a)+"+b: " +str(b)
result = total[::-1]
resut = int(result)
print "result: " +str(result)
#string add,with carry
total=""
carry=0
for ndx in range(0,length):
digit = carry
if(ndx<lenA):
digit += int(A[ndx])
if(ndx<lenB):
digit += int(B[ndx])
carry = digit/10
digit = digit%10
#print "digit: "+str(digit)+", carry: "+str(carry)
total += str(digit)
if(carry>0):
total += str(carry)
#print "digit: "+str(digit)+", carry: "+str(carry)
print "a: " +str(a)+"+b: " +str(b)
result = total[::-1]
resut = int(result)
print "result: " +str(result)
First convert the numbers into strings so we can iterate over the digits:
>>> n1 = str(1646)
>>> n2 = str(2089)
We can then add the corresponding digits then do %10 to get the last digit. All numbers which result from adding two integers 0-9 will be <= 18, therefore %10 will always return the last digit.
>>> [(int(a)+int(b))%10 for a,b in zip(n1,n2)]
[3, 6, 2, 5]
We then convert each int into a string, join the digits and convert back to a int:
>>> int(''.join(map(str,((int(a)+int(b))%10 for a,b in zip(n1,n2)))))
3625
Or alternatively (converting the digits as you go):
>>> int(''.join(str((int(a)+int(b))%10) for a,b in zip(n1,n2)))
3625
Use izip_longest(...,fillvalue="0") to add numbers of different lengths.
Related
I have a binary string. I have a list of bit indices to flip. How can I generate all possible combinations of binary strings with flips at those specific indices? The output list should contain 2^n unique elements where n is the length of the indices list. I believe itertools.product() could be used here, but I can't figure out how to line up all the parameters, especially since the length of the indices list is variable.
Example:
binaryString = "0000000000"
indicesToFlip = [0,1,9]
outputCombinations = magic()
print(outputCombinations)
["0000000000",
"1000000000",
"0100000000",
"1100000000",
"0000000001",
"0100000001",
"1000000001",
"1100000001"]
You could iterate all binary representations with the number of binary digits that corresponds to the number of indices (like 000, 001, 010, 011, ...) and then use a regular expression replacement that injects those digits in the larger binary string.
import re
def combis(binaryString, indicesToFlip):
# Prepare the regex...
n = len(indicesToFlip)
regex = re.compile("(.)" * n)
# ... and the replacement pattern
mask = list(binaryString)
for i, idx in enumerate(indicesToFlip):
mask[idx] = rf"\g<{i+1}>"
replacer = "".join(mask)
# Apply that transformation to each number in the range [0..2^n)
return [regex.sub(replacer, f"{num:>0{n}b}") for num in range(1 << n)]
binaryString = "0000000000"
indicesToFlip = [0,1,9]
print(combis(binaryString, indicesToFlip))
Try:
from itertools import combinations
binaryString = "0000000000"
indicesToFlip = [0, 1, 9]
out = []
for i in range(len(indicesToFlip) + 1):
for c in combinations(indicesToFlip, i):
out.append(
"".join(
("1" if ch == "0" else "0") if i in c else ch
for i, ch in enumerate(binaryString)
)
)
print(*out, sep="\n")
Prints:
0000000000
1000000000
0100000000
0000000001
1100000000
1000000001
0100000001
1100000001
There's answer that cycles through the all combinations of indices to toggle using itertools but here's a recursive implementation of your magic() function.
def magic(S, indices):
L = list(S) # convert to list of binary characters for mutation
def recurse(L, indices, curr):
if curr == len(indices): # done
return [''.join(L)] # return as list in order to accumulate results
res = recurse(L, indices, curr + 1) # do not flip
og = L[indices[curr]]
L[indices[curr]] = '1' if og == '0' else '0' # change
res += recurse(L, indices, curr + 1) # re-run, effectively doing a flip
L[indices[curr]] = og # revert
return res
return recurse(L, list(reversed(indices)), 0) # reversed input indices to get desired order
for elm in magic("0" * 10, [0, 1, 9]): # your test case
print(elm)
Prints:
0000000000
1000000000
0100000000
1100000000
0000000001
1000000001
0100000001
1100000001
A question is asking me to convert an int into binary, but it also must be in reverse (why!??!?!). After a bunch of tinkering, I was able to get it to print the number in binary. But I can't for the life of me figure out how to make it output in reverse.
The instructions say:
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary.
For an integer x, the algorithm is:
As long as x is greater than 0
Output x modulo 2 (remainder is either 0 or 1)
Assign x with x divided by 2
My code is:
x = int(input())
while x > 0:
x = x//2
print( x % 2, end = ' ')
Testing with input of 6, I get 1 1 0 but it wants me to output 011.
I even tried putting the answer into a list but when I try to reverse the list, I get an error. List method I tried:
x = int(input())
while x > 0:
x = x//2
J = [x % 2]
L = reversed(J)
print(L)
output using list method:
<list_reverseiterator object at 0x7f2cd69484f0>
<list_reverseiterator object at 0x7f2cd6948ee0>
<list_reverseiterator object at 0x7f2cd69484f0>
I feel like there's no way this needs some sort of slicing since that method hasn't even been covered yet in the material I'm learning.
You didn't follow the provided algorithm steps in the given order. Swap the statements in the while loop so they align with what was described.
And a small detail: there was no instruction to separate the output with spaces, so you should provide end = '':
x = int(input())
while x > 0:
print( x % 2, end = '')
x = x//2
You're reading in the least significant bit first, which results in the output being reversed. You don't need to make an explicit call to reversed().
This produces the desired output:
x = int(input())
result = []
while x > 0:
result.append(x % 2)
x = x // 2
# str() transforms each integer to a string.
# We then concatenate them all together
# to get the desired output using ''.join().
print(''.join(str(item) for item in result))
>>> x = 100
>>> res = []
>>> while x > 0:
... x = x//2
... J = x%2
... res.append(J)
...
>>> res
[0, 1, 0, 0, 1, 1, 0]
>>> "".join(str(i) for i in res[::-1])
'0110010'
step1 = input("what number? ")#gets your input
step2 = int(step1) #makes sure it's an int not float
step3 = bin(step2) #converts it to binairy (you method doesn't work for e.g. 7)
step4 = step3.replace("0b", "") #removes 0b from the binairy number
step5 = step4[::-1] #reveses the string
print (step5)
should work
or
print(bin(int(input("what number? "))).replace("0b", "")[::-1])
if you want in more compressed
you can use special function of python to convert integer to binary input and the print reverse of binary input by [:1:-1] in J list, so:
integer_input = int(input()) # input integert number
binary_of_integer_input = bin(integer_input) # convert integer to binary
print(binary_of_integer_input[2:]) # Print binary of integer input
print(binary_of_integer_input[:1:-1]) # Print reverse binary of integer input
Example:
integer number = 8
binary of input = 1000
reverse of binary = 0001
integer_input = int(input()) # input integert number
binary_of_integer_input = bin(integer_input) # convert integer to binary
x = binary_of_integer_input[2:]
J = binary_of_integer_input[:1:-1]
print(x) # Print binary of integer input
print(J) # Print reverse binary of integer input
I am taking This class!!!! Here's a code with materials learned so far that works! For actual Binary. Except reversing a string may not have been mentioned [::-1].
The lab wants answers per strictly that algorithm. So reversed binary and expects it to end with new line.
num = int(input())
while num > 0:
y =(num % 2)
print(y, end='')
num = (num//2)
print()
The Note: The above algorithm outputs the 0's and 1's in reverse order. If interpreted "as Convert to binary using this algorithm but reverse it"
num = int(input("Enter a number"))
string = ""
while num > 0:
y =str(num % 2)
string+=y
num = (num//2)
reverse=string[::-1]
print(reverse)
Given string str containing alphanumeric characters. The task is to calculate the sum of all the numbers present in the string.
Example 1:
Input:
str = 1abc23
Output: 24
Explanation: 1 and 23 are numbers in the
a string which is added to get the sum as
24.
Example 2:
Input:
str = geeks4geeks
Output: 4
Explanation: 4 is the only number, so the
the sum is 4.
I broke down the problem into smaller parts, for first I just want to extract the numbers.
s = "a12bc3d"
number = ""
for i in range(0, len(s)):
if s[i].isdigit():
n=0
number = number + s[i]
while s[i].isdigit():
n = n+1
if s[i + n].isdigit():
number = number + s[i+n] + " "
else:
break
i = i + n + 1
else:
continue
print(number)
my output from the above code is 12 23 but it should be 12 3, as the for loop is starting from the initial point making 2 coming twice, I have tried to move the for loop forward by updating i = i + n + 1 but it's not working out like that.
It will be great if someone gives me a direction, any help is really appreciated.
A slightly simpler approach with regex:
import re
numbers_sum = sum(int(match) for match in re.findall(r'(\d+)', s))
Use itertools.groupby to break the string into groups of digits and not-digits; then convert the digit groups to int and sum them:
>>> from itertools import groupby
>>> def sum_numbers(s: str) -> int:
... return sum(int(''.join(g)) for d, g in groupby(s, str.isdigit) if d)
...
>>> sum_numbers("1abc23")
24
>>> sum_numbers("geeks4geeks")
4
you can use regex.
import re
s='a12bc3d'
sections = re.split('(\d+)',s)
numeric_sections = [int(x) for x in sections if x.isdigit()]
sum_ = sum(numeric_sections)
print(sum_)
I appreciate the solutions with regex and group-by. And I got the solution using logic as well.
`s = "4a7312cfh86"
slist = [i for i in s]
nlist = []
for i in range(len(slist)):
if slist[i].isdigit() and (i != (len(slist) - 1)):
if not slist[i + 1].isdigit():
nlist.append(slist[i])
else:
slist[i + 1] = slist[i] + slist[i + 1]
elif slist[i].isdigit() and (i == (len(slist) - 1)):
nlist.append(slist[i])
def addingElement(arr):
if len(arr) == 0:
return 0
return addingElement(arr[1:]) + int(arr[0])
print(addingElement(nlist))
Output - 7402
Task:
Given an integer as input, Add code to take the individual digits and increase by 1.
For example, if the digit is 5, then it becomes 6. Please note that if the digit is 9 it becomes 0.
More examples
input: 2342 output: 3453
input: 9999 output: 0
input: 835193 output: 946204
I wrote this function but I know for sure this isn't way to write this code and I'm looking for some tips to write it in a more concise, efficient way. Please advise.
def new_num (num):
newnum = []
for i in range (0,len(str(num))):
upper = num%10
print(upper)
num = int(num/10)
print(num)
if upper == 9:
upper = 0
newnum.append(upper)
else:
upper+=1
newnum.append(upper)
strings = [str(newnum) for newnum in newnum]
a_string = "".join(strings)
an_integer = str(a_string)
new_int = int(an_integer[::-1])
return(new_int)
You could do this:-
n = '2349'
nn = ''
for i in n:
nn += '0' if i == '9' else str(int(i) + 1)
print(nn)
one of many possible improvements... replace the if/else with:
upper = (upper+1)%10
newnum.append(upper)
x= input('no = ')
x= '' + x
ans=[]
for i in x :
if int(i) == 9 :
ans.append(str(0))
else:
ans.append(str(int(i)+1))
ans=''.join(ans)
if int(ans) == 0:
ans = 0
print(ans.strip('0'))
This is the most basic code I can write, it can also be shortened to few lines
testInputs = [2342, 9999, 835193, 9]
def new_num (num):
return int("".join([str((int(d) + 1) % 10) for d in str(num)]))
result = [new_num(test) for test in testInputs]
print(result)
# [3453, 0, 946204, 0]
convert the num to string
convert the digit by using (int(d) + 1) % 10
join back the digits
parse the string as int
def newnum(x):
lis = list(str(x))
new_list = [int(i)+1 if int(i)<9 else 0 for i in lis]
new_list = map(str,new_list)
return int(''.join(new_list))
Take the number and convert to list of strings
Iterate through the list. Convert each element to int and add 1. The condition of digit 9 is included to produce 0 instead of 10
Map it back to strings and use join.
Return the output as int.
We want to find the number of 'a's in a given string s multiplied infinite times.
We will be given a number n that is the slicing size of the infinite string.
sample input:
aba 10
output:
7
Here aba is multiplied with 10, resulting in 'abaabaabaa'
and the no. of 'a's are 7.
This is my code:
def repeatedString(s, n):
count = 0
inters = s * n
reals = s[0:n+1]
for i in reals:
if (i == 'a'):
count += 1
return count
I'm getting 2 instead of 7 as the output (test case 'aba' 10). Where did I go wrong? I just multiplied the given string with n because it will never be greater than the slicing size.
Here's the link to the problem:
https://www.hackerrank.com/challenges/repeated-string/problem
Much simpler solution using python3.
s = input().strip()
n = int(input())
print(s[:n%len(s)].count('a')+(s.count('a')*(n//len(s))))
There's no reason to slice the string
def repeatedString(s, n):
count = 0
for index, i in enumerate(s*n):
if index >= n:
return count
if(i == 'a'):
count += 1
# empty string
return count
I used a simple unitary method.
Number of 'a' in one repetition is cnt_a so the number of 'a' in first n characters will be (cnt_a/len(s)) * n
def repeatedString(s, n):
if len(s)==1 and s=='a':
return n
cnt_a=0
for i in s:
if i == 'a':
cnt_a+=1
if cnt_a % 2 == 0:
no_a = (cnt_a/len(s)) * n
return math.ceil(no_a)
else:
no_a = (cnt_a/len(s)) * n
return math.floor(no_a)
If you would like a more readable answer....
def repeatedString(s, n):
target = 'a'
target_count = 0
# how many times does the string need to be repeated: (n // len(s) * s) + s[:(n % len(s))]
quotient = n // len(s)
remainder = n % len(s)
for char in s: # how many times target appears in 1 instance of the substring
if char == target:
target_count += 1
# how many times the target appears in many instances of the substring provided
target_count = target_count * quotient
for char in s[:remainder]: # count the remaining targets in the truncated substring
if char == target:
target_count += 1
return target_count
One liner answer:
return [s[i%len(s)] for i in range(n)].count('a')
There is only two problem in your code
s = 'aba'
n = 10
count = 0
inters = s * n
# Here you need to slice(inters) not (s) because s only hold 'aba'
# And not n+1 it's take 11 values only n
reals = inters[0:n]
for i in reals:
if (i == 'a'):
count += 1
print(count)
so if the string contains "a"s only simply return n. otherwise, count the number of a's in the string s, now using divmond() function I have found the number of string that can be added without surpassing n. for example string s is "aba" and n=10, so I can add 3 "abs"s completely without the length of string going over 10. now the number of a's in the added string (3*2). Now the places left to be filled are equal to the remainder(y) of divmond() function. Now slice the string s up to y and find the number of a's in it and add it to count.
divmond(10,3) returns (10//3) and it's remainder.
def repeatedString(s, n):
if len(s)==1 and s=="a":
return n
count=s.count("a")
x,y=divmod(n,len(s))
count=count*x
str=s[:y]
return count+str.count("a")
The solution in Python 3:
def repeatedString(s,n):
i = 0
c = 0
for i in s:
if i == 'a':
c += 1
q = int(n / len(s)) #Finding the quotient
r = int(n % len(s)) #Finding the remainder
if r == 0:
c *= q
else:
x = 0
for i in range(r):
if s[i] == 'a':
x += 1
c = c*q + x
return int(c)
s = input()
n = int(input())
print(repeatedString(s,n))
if character 'a' is present in a given string pattern, then its quite faster to get the repeated count for it and later based on the total length of final string mentioned, will be trying to repeat the given pattern for same number of times & hence will multiple the repeated count with number of times a string pattern is going to repeat. Importantly if final string input is in odd numbers then we need to identify the those odd pattern and separately count the occurance of character 'a' in odd string pattern. Finally summing up the total count ( even & odd ) will gives us the expected result
def repeatedString(s, n):
# Get the length of input string
strlen = len(s)
a_repeat = 0
# Get the total count of a repeated character from the input string
for i in range(0,strlen):
if s[i] == 'a':
a_repeat = a_repeat + 1
# Get the multiplier to make sure that desired input string length achieved
str_multiplier = int(n // strlen)
# Get the repeated count if new string is been created
result = a_repeat*str_multiplier
new_str = s[:int( n % strlen )]
# for odd length of string, get the remaining characters and find repated characters count and add up it to final count
for i in range(0, len(new_str)):
if new_str[i] == 'a':
result += 1
return result
For this problem,
Get the length of string s.
First, if conditions: constrain
Now, instead of using a loop to add to space and time complexity, we use basic math's. Find the quotient of n//Len (s). Now find the number of times "a" is used in our string.
We can multiply the quotient with this number to get the total "a" used. Now, we can find the remainder of the string and use slice to search for "a" in the string we have left in the last.
Add both to get our answer.
def repeatedString(s, n):
#finding quotient and remainder of division
str1=len(s)
remainder=0
if 1<=str1<=100 and 1<=n<=10**12:
quotient= n//str1
a_s = s.count("a")
if a_s==0:
return 0
else:
remainder=s[:n%str1].count('a')
return quotient*a_s + remainder
Simple answer:
def repeatedString(s, n):
totalNumber = 0 // setting total of a's to 0
// using count function to find the total number of a's in the substring
totalNumber = s.count('a')
// finding how many number of times the substring fits in "n" and multiplying that by the number of a's we found earlier
totalNumber = n//len(s) * totalNumber
// if there is a remainder, we loop through the remainder string and add the number of "a's" found in that substring to the total
for i in s[:n%len(s)]:
if(i == "a"):
totalNumber +=1
return totalNumber