I am new to python and trying to append characters of a card number to two different arrays. 4003600000000014 every other digit, starting with the number’s second-to-last digit so the first digit is 1(that is left of the 4) and by jumping one number going all the way to the 0. After that, numbers that did NOT appended to the first array (mbt) should be appended to the 2nd array(normal).
mbt should be like = 4 0 6 0 0 0 0 1
normal should be like = 0 3 0 0 0 0 0 4
(two arrays combined will be again equal to 4003600000000014)
import math
def digitnumber(n):
if n > 0:
digits = int(math.log10(n)) + 1
return digits
def isvalid(n, mbt=[], normal=[]):
cardnumber = 4003600000000014
dnumber = digitnumber(4003600000000014)
n = dnumber - 1,
mbt = []
while 1 <= n < dnumber:
x = int(cardnumber / pow(10, n) % 10)
mbt.append(x)
n -= 2
n = dnumber - 2
normal = []
while 1 <= n < dnumber:
x = int(cardnumber / pow(10, n) % 10)
normal.append(x)
n -= 2
def main():
mbt = []
normal = []
isvalid(4003600000000014, mbt=[], normal=[])
print(len(mbt))
main()
From what I understand you are trying to slice number to get individual digits.
You can find more information on slicing in Python:
Understanding slice notation
Here's a solution using python slicing to the problem. The output arrays can be reversed as needed.
def isvalid(n):
string_num = str(n)
mbt = [int(x) for x in string_num[1::2]]
normal = [int(x) for x in string_num[0::2]]
return mbt, normal
def main():
mbt, normal = isvalid(378282246310005)
print(len(mbt))
main()
Assuming that your input is an integer and you expect 2 lists of integers as output:
x = 4003600000000014
x = list(str(x))
a = list(map(int, x[1::2]))
b = list(map(int, x[0::2]))
print(a)
print(b)
[0, 3, 0, 0, 0, 0, 0, 4]
[4, 0, 6, 0, 0, 0, 0, 1]
You can use this function:
def split(num):
num = [n for n in str(num)]
num1 = []
num2 = []
for n in range(len(num)//2): # Move all element from num to num1 and num2. Since we are moving elements from 1 list to 2 lists, divide by two to distribute evenly. If the number of elements in num is odd, the // will get get rid of the decimal part
num1.append(num.pop()) # Removes last element from num and adds it to num1
num2.append(num.pop()) # Removes last element from num and adds it to num2
if num: # If there is still an element left (as in, the number of elements in num was odd to begin with):
num1.append(num.pop()) # Move that element to num1
return ' '.join(reversed(num1)),' '.join(reversed(num2))
print(split(4003600000000014))
Output:
('0 3 0 0 0 0 0 4', '4 0 6 0 0 0 0 1')
Related
LeetCode: longest consecutive sequence
Question:Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
nums = [0,3,7,2,5,8,4,6,0,1]
nums = list(set(nums)) # O(n) operation
res = 0
count = 1
if len(nums)==1: # edge case
res = 1
for i in range(len(nums)-1):
if abs(nums[i] - nums[i+1]) == 1:
count+=1
print(count)
else:
res = max(res, count)
count = 1
print(res)```
this prints as follows (print(count)) adds an unneccessary
2
3
4
5
6
7
8
9
0
And when input is nums = [100,4,200,1,3,2]
Output is for print(count):
2
3
3
Count variable is misbehaving
This one should work efficiently enough (for each element,the set is accessed about 3 times so, including the creation of the set, that would make the complexity O(4n), which is still O(n)):
def longest_seq(a: list) -> int :
a = set(a)
max_seq = 0
for i in a:
if i-1 in a:
continue
else:
j= i+1
while j in a:
j += 1
max_seq = max(max_seq, j-i)
return max_seq
You could also do something like this, without using sets. Just create an array of zeros and assign the values of the given array variables as one and calculate the max_seq.
def longest_seq(a: list) -> int :
bit = [0 for i in range(max(a)+2)]
for i in a:
bit[i] = 1
max_seq = count = 1
for i in range(1,len(bit)):
if bit[i] == bit[i-1] == 1:
count+=1
else:
max_seq = max(max_seq, count)
count = 1
return max_seq
print(longest_seq([5,4,7,8,1,2,3,4,9,10,11,12,13])) # ans = 7
I need to sum 2 binary numbers (max len 8 and min 1) using only selective structures (if, elif, else) and loops (for, while).
You need to know in the binary sum:
0 + 1 = 1
1 + 0 = 1
1 + 1 = 0 (with carry 1)
The result must be the sum of these two numbers.
Also, show the partial results that are generated by adding two digits and carrying
I know you could easily do this, but the idea is use only selective structure and loops.
a = input("first binary: ")
b = input("second binary: ")
c = bin(int(a,2) + int(b,2))
OUTPUT example:
sum:
11001011
10001011
=========
101010110
Partial results:
digit = 0 Carry = 1
digit = 1 Carry = 1
digit = 1 Carry = 0
digit = 0 Carry = 1
digit = 1 Carry = 0
digit = 0 Carry = 0
digit = 1 Carry = 0
digit = 0 Carry = 1
This question is different to the others made, because none of the others answer just using selective and repetitive structures
If you are allowed to use slicing, you can do this:
num1 = '11001011' # you can replace these with input() calls
num2 = '10001011'
# reverse the strings as we will be doing the operations from the left, otherwise you will need to pass reversed strings in the for loop iterator
num1 = num1[::-1]
num2 = num2[::-1]
# to tackle uneven lengths you can pad with 0s
if len(num2)>len(num1):
padding = len(num2) - len(num1)
num1 = num1 + '0'*padding
else:
padding = len(num2) - len(num1)
num1 = num1 + '0'*padding
currentresult = ''
nextdigit = 0
# iterate over two numbers
for i, j in zip(num1,num2): # if you are not allowed to use zip, you can use two nested loops one for num1 and one for num2, and add an if condition to do the operations only when i == j
i = int(i) + nextdigit
if int(i) + int(j) == 3:
# case where current bits are 1 and 1, and carry from the last addition is 1
carry = 1
digit = 1
elif int(i)+int(j) == 2:
carry = 1
digit = 0
elif int(i)+int(j) == 1:
carry = 0
digit = 1
else:
carry = 0
digit = 0
currentresult += str(digit)
nextdigit = carry
# add next digit (if in case the carry from the last bits are 1)
if nextdigit == 1:
currentresult += str(nextdigit)
# reverse the strings as we got the result in reverse
finalresult = currentresult[::-1]
print(finalresult)
import random
def lottery(lucky_numbers, run):
i = 0
while i < run:
x = random.uniform(0, 1) #prints out a random number between 0 and 1
numbers = lucky_numbers
NewNumbers = numbers[-1:] + numbers[:-1] #shifts each element in the to the right
lucky_numbers = NewNumbers
print(lucky_numbers, x)
i += 1
lottery([1, 2, 0], 3)
This code prints out something like:
>>>>>>>>>>
[0, 1, 2] 0.33016179294984127
[2, 0, 1] 0.7797639530009745
[1, 2, 0] 0.6292245916315391
>>>>>>>>>>
The x values will always be different because they are random numbers between 0 and 1.
I am trying to add a function that says if x is the lowest value(min) in the loop then the programme should print the list of that iteration, for example in this case the lowest value of x in this loop is 0.33016179.. , the program should therefore print the list [0, 1, 2]
I would just save the info in a variable and print it after the loop ends:
import random
def lottery(lucky_numbers, run):
i = 0
min_x = 1
while i < run:
x = random.uniform(0, 1) #prints out a random number between 0 and 1
numbers = lucky_numbers
NewNumbers = numbers[-1:] + numbers[:-1] #shifts each element in the to the right
lucky_numbers = NewNumbers
if x < min_x:
min_x = x
min_lucky_numbers = lucky_numbers
i += 1
print(min_lucky_numbers, min_x)
lottery([1, 2, 0], 3)
You can create a "cache" that stores all the x values then call the lowest value.
cache = []
for _ in range(3):
x = random.uniform(0, 1)
cache.append(x)
print min(cache)
to do what you want, you have just to store your items in two different lists, sort them and display the firt elements of each one :
import random
luckiest_num = list()
luckiest_list = list()
def lottery(lucky_numbers, run):
i = 0
while i < run:
x = random.uniform(0, 1)
numbers = lucky_numbers
NewNumbers = numbers[-1:] + numbers[:-1]
print(NewNumbers, x)
i += 1
luckiest_num.append(x)
luckiest_list.append(NewNumbers)
lottery([1, 2, 0], 3)
luckiest_num.sort()
luckiest_list.sort()
print ("The luckiest item is : ")
print(luckiest_num[0],luckiest_list[0])
I am trying to calculate the number of trailing zeros in a factorial.
def count(x):
zeros = 0
for i in range (2,x+1):
print(i)
if x > 0:
if i % 5 == 0:
print("count")
zeros +=1
else:
("False")
print(zeros)
count(30)
I think the number of trailing zeros is incorrect.
When using count(30), there are 7 trailing 0's in 30. However it is returning 6.
def count (x):
i = 5
zeros = 0
while x >= i:
zeros += x // i
i *= 5
return zeros
print(count(30))
Wikipedia has a short article on this specific topic, which says that this can be computed with a straight-forward summation that counts factors of 5.
def trailing_zeros_of_factorial(n):
assert n >= 0, n
zeros = 0
q = n
while q:
q //= 5
zeros += q
return zeros
# 32! = 263130836933693530167218012160000000
print(trailing_zeros_of_factorial(32)) # => 7
We would first count the number of multiples of 5 between 1 and n (which is X ), then the number of multiples of 25 ( ~s ), then 125, and so on.
To count how many multiples of mare in n, we can just divide n by m
def countFactZeros(num):
count = 0
i = 5
if num < 0:
return False
while num//i > 0:
count = count + num//i
i = i * 5
return count
countFactZeros(10) # output should be 2
countFactZeros(100) # output should be 24
Your algorithm has problem:
import math
def count_zeroes(x):
zeroes = 0
if x <= 0:
return zeroes
for i in range(5, x+1, 5):
for base in range(int(math.log(i, 5)), 0, -1):
if i % pow(5, base) == 0:
zeroes += base
break
return zeroes
Here is my original code:
x = input("Please input an integer: ")
x = int(x)
i = 1
sum = 0
while x >= i:
sum = sum + i
i += 1
print(sum)
Here is what the second part is:
b) Modify your program by enclosing your loop in another loop so that you can find consecutive sums. For example , if 5 is entered, you will find five sum of consecutive numbers so that:
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
I have been stuck on this for 3 days now, and I just can't understand how to do it. I have tried this but to no avail.
while x >= i:
sum_numbers = sum_numbers + i
past_values = range(i)
for ints in past_values:
L = []
L.append(ints)
print(L, "+", i, "=", sum_numbers)
i += 1
Can anyone just help steer my in the correct direction? BTW. it is python 3.3
You could do this in one loop, by using range to define your numbers, and sum to loop through the numbers for you.
>>> x = input("Please input an integer: ")
Please input an integer: 5
>>> x = int(x)
>>>
>>> for i in range(1, x+1):
... nums = range(1, i+1)
... print(' + '.join(map(str, nums)), '=', sum(nums))
...
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
range(1, x+1) would give me [1, 2, 3, 4, 5], this acts as the controller for how many times we want to print out a sum. So, this for loop will happen 5 times for your example.
nums = range(1, i+1) notice we are using i instead here, (taken from the range above), which I am using to define which number I am up to in the sequence.
' + '.join(map(str, nums)):
map(str, nums) is used to convert all elements of nums into strings using str, since the join method expects an iterable filled with strings.
' + '.join is used to "join" elements together with a common string, in this case, ' + '. In cases where there is only 1 element, join will just return that element.
sum(nums) is giving you the sum of all numbers defined in range(1, i+1):
When nums = range(1, 2), sum(nums) = 1
When nums = range(1, 3), sum(nums) = 3
Etc...
reduce(lambda x,y:x+y,range(x+1))
You don't have to use a while loop, 2 for will do the trick nicely and with a more natural feeling.
x = input("Please input an integer : ")
x = int(x)
item = range(1, x + 1)
for i in item:
sum = 0
for j in range(1, i + 1):
sum = sum + j
print(str(sum))
Using list comprehension in python:
x = input("Please input an integer: ")
x = int(x)
i = 1
sums = [(((1+y)*y)//2) for y in range(i, x+1)] # creates list of integers
print(sums) # prints list of sums on one line
OR
[print(((1+y)*y)//2) for y in range(i, x+1)] # prints sums on separate line