I would like to double the value of every second digit and then add up the digits that are in their tens. Finally adding all the digits together
E.g: 123456789 -> 1 4 3 8 5 12 7 16 9 -> 1 4 3 8 5 3 7 7 9 -> 47
edit: the user would input any number and the function would still work eg: 5153 -> 5 2 5 6 -> 18
-SORRY first post I'm still getting used to this-
So I would like my function to
1. Reverse the inputted number
2. Double the value of the second digit
3. Sum all the digits together
4. Check if it's divisible by 7
Here is my code so far
my testing
def checksum(num):
#print(rev)
odd_digit = ""
even_digit = ""
even_sum = 0
odd_sum = 0
total_sum = 0
if num < 10 and num != 7:
return False
else:
return True
rev = (num[::-1])
for i in range(len(rev)):
if i % 2 == 0:
odd_digit += rev[i]
else:
even_digit += rev[i]
#print(even_digit)
even_digit = int(even_digit)
while even_digit > 0:
even_digit, even_sum = even_digit//10,even_sum+(even_digit%10)
#print(even_sum)
even_sum_2 = even_sum * 2
#print(even_sum_2)
odd_digit = int(odd_digit)
while odd_digit > 0:
odd_digit, odd_sum = odd_digit//10,odd_sum+(odd_digit%10)
#print(odd_sum)
total_sum = even_sum_2 + odd_sum
#print(total_sum)
if total_sum % 7 == 0:
return True
else:
return False
print(checksum(12345678901))
Try using this sum with a map, and a list comprehension:
>>> sum(map(int,''.join([str(int(v)*2) if i%2 else v for i,v in enumerate(s)])))
47
Or use:
>>> sum([sum(map(int,str(int(v)*2))) if i%2 else int(v) for i,v in enumerate(s)])
47
sum([sum(map(int, str(i * 2))) if i % 2 == 0 else i for i in range(1, 10)])
Related
I'm new to python and have a question
I want to print 10 values per line and I can't figure out how to do it. Here's my attempt at it;
a = 1
b = 15
count = 0
count_end = 10
while count < count_end:
while a < b:
count = count + 1
print(a, end = " ")
a = a + 1
if(count == count_end):
break
The output is 1 2 3 4 5 6 7 8 9 10 but I want the output to go from 1 to 10 on one line and then continue from 11 to 15 on a new line under it. I've seen some people use lists to answer a similar question but I don't want to use lists for this question.
Any help would be greatly appreciated :)
Just use one loop, and then check if count % count_end == 0 to detect every multiple of count_end.
for count, current in enumerate(range(a, b)):
print(current, end=" ")
if count % count_end == 0 or current == b-1:
print()
a = 1
b = 15
count = 0
count_end = 10
while count < count_end:
while a <= b:
count = count + 1
print(a, end = " ")
a = a + 1
if(count == count_end):
print("")
something like this ?
Junior Python Coder here! Trying to print multiplication table with user input but stuck.
min_num=1
max_num=11
starting_range = int(input ("Enter the minimum number: "))
ending_range = int(input ("Enter the maximum number: "))
print ("The Multiplication Table of: ", starting_range)
for count in range(1, 11):
print (starting_range, 'x', count, '=', ending_range * count)
if max_num - min_num > 10 :
print('invalid range ')
else:
for num in range (min_num,max_num):
print ("The Multiplication Table of: ", ending_range)
for count in range(min_num, max_num):
print (starting_range, 'x', count, '=', ending_range * count)
I'm not sure I really understand what you're trying to do as your code isn't formatted, but for a multiplication table, a nested loop is a solution.
The basic idea is: For every number in the given range, loop over the whole range and multiply it by each element. This will print the whole multiplication table.
start = 1 # You can change these to be inputted by the user.
end = 10
for i in range(start, end + 1): # We add 1 to the end because range() is exclusive on endpoint.
for j in range(start, end + 1):
print(f"{i} x {j} = {i * j}")
If you only need the table as something like:
15 x 1
15 x 2
15 x 3
...
You can do this with one loop:
num = 10
for i in range(1, num + 1):
print(f"{num} x {i} = {num * i}")
I recommend you search up on F-strings in Python if you do not understand the print(f"..") parts. They're very convenient. Good luck!
Minimal change to original code:
min_num = 1
max_num = 11
starting_range = 4 # You can use int() and input() as in your original code to make this user defined.
ending_range = 7
# Removed the error checking, wasn't sure precisely what it was meant to do.
for num in range(starting_range,ending_range):
print ("The Multiplication Table of: ", num)
for count in range(min_num, max_num):
print (num, 'x', count, '=', num * count)
Try it at https://www.mycompiler.io/view/7JVNtxkT53k
This prints:
The Multiplication Table of: 4
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
The Multiplication Table of: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
The Multiplication Table of: 6
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
Alternative code defining a function:
def print_multiplication_table(n, max_value=11):
if n > max_value or n <= 0:
raise ValueError
print(f"The Multiplication Table of: {n}")
for m in range(1, max_value):
print(f"{n} x {m} = {n*m}")
starting_range = 4 # You can use int() and input() as in your original code to make this user defined.
ending_range = 7
for i in range(starting_range, ending_range):
print_multiplication_table(i)
Try it at https://www.mycompiler.io/view/1uttFLmFEiD
i can't understand why the output of my code concatnates the digits instead of showing their sum:
#Get a number, and show the number of digits and the sum of the digits.
num = int(input('Enter a number: '))
j = 0
i = 1
k = 0
while i < num:
i = i*10
j += 1
k += (num - k)%i
print (f' The number has {j} digit(s), and the sum is: {k}')
Follow the code. Let's say num = 432:
i = 1 * 10 = 10
j = 0 + 1 = 1
k = 0 + (432 - 0)%10 = 2
---
i = 10 * 10 = 100
j = 1 + 1 = 2
k = 2 + (432 - 2)%100 = 2 + 32 = 34
---
i = 100 * 10 = 1000
j = 2 + 1 = 3
k = 34 + (432 - 34)%1000 = 34 + 398 = 432
This algorithm is most definitely not adding every digit. There are several ways to do what you intend in python. One way is inputting the number as a string and summing every digit casting them as integers inside a generator:
num = input('Enter a number: ')
total = sum(int(digit) for digit in num)
print(total)
If you want the number to be an integer since the beginning, you can also do this:
num = int(input('Enter a number: '))
total = 0
while num > 0:
digit = num%10
total += digit
num /= 10 # num //= 10 in python 3
print(total)
Given an integer. for each individual digit that is greater than 4, i need to add it to all the next digits that greater than 4.
For example: a = 4567; the result should be 0 + (5) + (5+6) + (5+6+7) = 34
So far in my code, I was able to get the sum for single digit only. If the integer is greater 10, it will only give the sum of the very first digit. Any idea why this happening?
def morethanfour(number):
num = 0
num = [int(d) for d in str(number)] #seperate into individual digit
total = 0
for i in range (len(num)):
if num[i] > 4:
total = sum(x for x in range(5, num[i]+1)) #adding the sum
return total
num = 9
print(morethanfour(num))
the result when num = 9 is 35 (5+6+7+8+9)
However, when num = 178, it gave me 0
Try this:
>>> def morethanfour(number):
return sum(sum(range(5,x+1)) for x in map(int,str(number)) if x>4)
>>> morethanfour(9)
35
>>> morethanfour(4567)
34
>>> morethanfour(178)
44
>>> sum(sum(num[j] for j in range(0, i+1) if num[j] > 4) for i in range(len(num)))
34
Trying to solve hackerrank problem.
There are plants in a garden. Each of these plants has been added with some amount of pesticide. After each day, if any plant has more pesticide than the plant at its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each plant. Print the number of days after which no plant dies, i.e. the time after which there are no plants with more pesticide content than the plant to their left.
I have used stacks to solve this problem. Example below:
a = 6 5 8 4 7 10 9
10 > 9 a = 6 5 8 4 7 10 b = 9
7 > 10 a = 6 5 8 4 7 b = 9
4 > 7 a = 6 5 8 4 b = 9
8 > 4 a = 6 5 8 b = 9 4
5 > 8 a = 6 5 b = 9 4
6 > 5 a = 6 5 b = 9 4
after this just make a new list with a = a + b.reverse(). Start the process again and exit when list is sorted in reverse order.
This still is giving me time exceeded. Any idea?
n = int(input())
first_list = input().split()
first_list = [int(i) for i in first_list]
count = 0
second_list = []
data_1, data_2 = 0, 0
while True:
b = []
if sorted(first_list, reverse=True) == first_list:
break
data_1 = first_list.pop()
for i in range(len(first_list)-1):
data_2 = first_list.pop()
if data_1 > data_2:
pass
elif data_1 < data_2:
second_list.append(data_1)
elif data_1 == data_2:
second_list.append(data_1)
second_list.append(data_2)
data_1 = data_2
if len(first_list)>=1 and data_1 < first_list[0]:
first_list.append(data_1)
second_list.reverse()
first_list = first_list + second_list
count += 1
print(count)
Edited code:
n = int(input())
input = [int(i) for i in input().split()]
count, t_length = 0, 0
cmp = input[0]
while True:
length = len(input)
for i in range(1, length):
if input[i] == -1:
t_length += 1
continue
if input[i] > cmp:
cmp = input[i]
input[i] = -1
else:
t_length += 1
cmp = input[i]
if t_length+1 == length:
break
count += 1
cmp, t_length = input[0], 0
print(count)
I agree with Woot4Moo that something doesn't look right, and I suggest you focus more on stack use (instead of doubly linked lists). See this link to the Stock Span problem which helps detail an O(N) solution for tracking differences in a list of prices. This can be extended with a condition for pesticide.
For example, it'd be filling in the gaps of:
import sys
ps = [int(s) for s in list(sys.stdin)[1].strip().split()]
stack = [ps[0]]
max_days = 0
for i in range(1, len(ps)):
days[i] = 1 if ps[i] > ps[i-1] else 0
# TODO - Logic to update days[i]
while len(stack) > 0 and ps[i] <= stack[-1][1]:
(ps_other, days_other) = stack.pop()
stack.append((ps[i], days[i])
max_days = max(max_days, days[i])
print(max_days)
I quickly implemented in O(N^2), and found 80% of tests pass (the rest timing out), so more cleverly using the stack according to the link above should do the job.
import collections
import sys
ps = [int(s) for s in list(sys.stdin)[1].strip().split()]
ps_prev = []
days = 0
while collections.Counter(ps_prev) != collections.Counter(ps):
ps_prev = ps[:]
i = len(ps) - 1
while i > 0:
if ps[i] > ps[i-1]:
ps.pop(i)
i -= 1
days += 1
print(days - 1)
Edit: note that the sketchy sys.stdin use is to cater for the HackerRank test input.
Sorting is N log N and your data structure seems wrong to me. Why would you not use a doubly linked list since the requirement is that it is the left most neighbor. You would simply dereference the pointers that died.