How to solve this "Jumping numbers" task - python

Implement the is_jumping function, which accepts the number number and returns the string JUMPING, if each digit in the number differs from the adjacent one by 1. If the condition is not met - the string NOT JUMPING.
def is_jumping(number: int) -> str:
newStr = str(number)
for i in range(len(newStr)):
if len(newStr) == 1:
return "JUMPING"
elif int(newStr[i + 1]) - int(newStr[i]) == 1:
return "JUMPING"
else: return "NOT JUMPING"
AssertionError: assert is_jumping(12543) == "NOT JUMPING", ( "Function 'is_jumping' should return 'NOT JUMPING' " "when number is 12543" )
Where is a problem? why can not pass number 12543? Thank you!
UPD
According to your advice I made some change, but still it doesn't work. Any chance to make my code work?
def is_jumping(number: int) -> str:
newStr = str(number)
for i in range(len(newStr) - 1):
if int(newStr[i + 1]) - int(newStr[i]) != 1 or int(newStr[i + 1]) - int(newStr[i]) != -1:
return "NOT JUMPING"
return "JUMPING"
#Michael Butscher #bbbbbbbbb #Johnny

Problems in your code already explained in the comment section.
Regardless, no need to convert your input number to a string; try this:
def is_jumping(num: int) -> str:
while num >= 10:
x = num % 10
num //= 10
if num % 10 not in [x - 1, x + 1]:
return "NOT JUMPING"
return "JUMPING"

Related

Why is my Python prime number checker not working?

Why is my code below giving me wrong results? When I give it numbers like 2 and 3, it says they're not prime numbers. Only some numbers work but for the most part it gives wrong answers.
def prompt_input(input_msg, error_msg):
while True:
userinput = input(input_msg)
try:
integer = int(userinput)
if integer > 1:
return integer
print(error_msg)
except ValueError:
print(error_msg)
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
primenum = prompt_input(
"Give an integer that's bigger than 1: ",
"You had one job"
)
if check_prime(primenum):
print("This is a prime.")
else:
print("This is not a prime.")
First issue: Your for loop returns after one iteration, so the correct return logic would be:
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
However you are implementing this incorrectly as well, the loop needs to iterate up to the sqrt of the number.
def check_prime(number):
for i in range(2, int(sqrt(number))+1):
if number % i == 0:
return False
return True
Hope this helps!
Need to unindent the return True.
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True

Recursive function to reduce zeros from number

I have a mission to write a recursive function named Reduce. This function should reduce all the zeros from number and return new number.
for example:
Reduce(-160760) => -1676
Reduce(1020034000) => 1234
I started to to something but I got stuck in the condition. here's the code I wrote so far:
def Reduce(num):
while num != 0:
if num % 10 != 0:
newNum = (num % 10) +
Reduce(num//10)
def reduce(num):
if num == 0: return 0
if num < 0: return -reduce(-num)
if num % 10 == 0:
return reduce(num // 10)
else:
return num % 10 + 10 * reduce(num // 10)
String version of recursive function:
def reduce(n):
return int(reduce_recursive(str(n), ''))
def reduce_recursive(num, res):
if not num: # if we've recursed on the whole input, nothing left to do
return res
if num[0] == '0': # if the character is '0', ignore it and recurse on the next character
return reduce_recursive(num[1:], res)
return reduce_recursive(num[1:], res+num[0]) # num[0] is not a '0' so we add it to the result and we move to the next character
>>> reduce(1200530060)
12536

How to generate alternating substrings using recursion

I have a practice question that requires me to generate x number of alternating substrings, namely "#-" & "#--" using both recursion as well as iteration. Eg.string_iteration(3) generates "#-#--#-".
I have successfully implemented the solution for the iterative method,
but I'm having trouble getting started on the recursive method. How can I proceed?
Iterative method
def string_iteration(x):
odd_block = '#-'
even_block = '#--'
current_block = ''
if x == 0:
return ''
else:
for i in range(1,x+1):
if i % 2 != 0:
current_block += odd_block
elif i % 2 == 0:
current_block += even_block
i += 1
return current_block
For recursion, you almost always just need a base case and everything else. Here, your base case it pretty simple — when x < 1, you can return an empty string:
if x < 1:
return ''
After than you just need to return the block + the result of string_iteration(x-1). After than it's just a matter of deciding which block to choose. For example:
def string_iteration(x):
# base case
if x < 1:
return ''
blocks = ('#--', '#-')
# recursion
return string_iteration(x-1) + blocks[x % 2]
string_iteration(5)
# '#-#--#-#--#-'
This boils down to
string_iteration(1) + string_iteration(2) ... string_iteration(x)
The other answer doesn't give the same result as your iterative method. If you always want it to start with the odd block, you should add the block on the right of the recursive call instead of the left:
def string_recursion(x):
odd_block = '#-'
even_block = '#--'
if x == 0:
return ''
if x % 2 != 0:
return string_recursion(x - 1) + odd_block
elif x % 2 == 0:
return string_recursion(x - 1) + even_block
For recursive solution, you need a base case and calling the function again with some other value so that at the end you will have the desired output. Here, we can break this problem recursively like - string_recursive(x) = string_recursive(x-1) + string_recursive(x-2) + ... + string_recursive(1).
def string_recursion(x, parity):
final_str = ''
if x == 0:
return ''
if parity == -1: # when parity -1 we will add odd block
final_str += odd_block
elif parity == 1:
final_str += even_block
parity *= -1 # flip the parity every time
final_str += string_recursion(x-1, parity)
return final_str
odd_block = '#-'
even_block = '#--'
print(string_recursion(3, -1)) # for x=1 case we have odd parity, hence -1
# Output: #-#--#-

Python: Is there an equivalent of mid, right, and left from BASIC?

I want to do something like this:
>>> mystring = "foo"
>>> print(mid(mystring))
Help!
slices to the rescue :)
def left(s, amount):
return s[:amount]
def right(s, amount):
return s[-amount:]
def mid(s, offset, amount):
return s[offset:offset+amount]
If I remember my QBasic, right, left and mid do something like this:
>>> s = '123456789'
>>> s[-2:]
'89'
>>> s[:2]
'12'
>>> s[4:6]
'56'
http://www.angelfire.com/scifi/nightcode/prglang/qbasic/function/strings/left_right.html
Thanks Andy W
I found that the mid() did not quite work as I expected and I modified as follows:
def mid(s, offset, amount):
return s[offset-1:offset+amount-1]
I performed the following test:
print('[1]23', mid('123', 1, 1))
print('1[2]3', mid('123', 2, 1))
print('12[3]', mid('123', 3, 1))
print('[12]3', mid('123', 1, 2))
print('1[23]', mid('123', 2, 2))
Which resulted in:
[1]23 1
1[2]3 2
12[3] 3
[12]3 12
1[23] 23
Which was what I was expecting. The original mid() code produces this:
[1]23 2
1[2]3 3
12[3]
[12]3 23
1[23] 3
But the left() and right() functions work fine. Thank you.
You can use this method also it will act like that
thadari=[1,2,3,4,5,6]
#Front Two(Left)
print(thadari[:2])
[1,2]
#Last Two(Right)# edited
print(thadari[-2:])
[5,6]
#mid
mid = len(thadari) //2
lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]
Hope it will help
This is Andy's solution. I just addressed User2357112's concern and gave it meaningful variable names. I'm a Python rookie and preferred these functions.
def left(aString, howMany):
if howMany <1:
return ''
else:
return aString[:howMany]
def right(aString, howMany):
if howMany <1:
return ''
else:
return aString[-howMany:]
def mid(aString, startChar, howMany):
if howMany < 1:
return ''
else:
return aString[startChar:startChar+howMany]
These work great for reading left / right "n" characters from a string, but, at least with BBC BASIC, the LEFT$() and RIGHT$() functions allowed you to change the left / right "n" characters too...
E.g.:
10 a$="00000"
20 RIGHT$(a$,3)="ABC"
30 PRINT a$
Would produce:
00ABC
Edit : Since writing this, I've come up with my own solution...
def left(s, amount = 1, substring = ""):
if (substring == ""):
return s[:amount]
else:
if (len(substring) > amount):
substring = substring[:amount]
return substring + s[:-amount]
def right(s, amount = 1, substring = ""):
if (substring == ""):
return s[-amount:]
else:
if (len(substring) > amount):
substring = substring[:amount]
return s[:-amount] + substring
To return n characters you'd call
substring = left(string,<n>)
Where defaults to 1 if not supplied. The same is true for right()
To change the left or right n characters of a string you'd call
newstring = left(string,<n>,substring)
This would take the first n characters of substring and overwrite the first n characters of string, returning the result in newstring. The same works for right().
There are built-in functions in Python for "right" and "left", if you are looking for a boolean result.
str = "this_is_a_test"
left = str.startswith("this")
print(left)
> True
right = str.endswith("test")
print(right)
> True
Based on the comments above, it would seem that the Right() function could be refactored to handle errors better. This seems to work:
def right(s, amount):
if s == None:
return None
elif amount == None:
return None # Or throw a missing argument error
s = str(s)
if amount > len(s):
return s
elif amount == 0:
return ""
else:
return s[-amount:]
print(right("egg",2))
print(right(None, 2))
print(right("egg", None))
print(right("egg", 5))
print("a" + right("egg", 0) + "b")

reprompting after invalid input

There was no problem until I tried to make an input go through validity check and if invalid ask again for input
i'm counting on you for ideas thanks in advance :)
a=0
def reinp(a,b):
while True:
if a in [1,2,3,4,5,6]: #checking for valid input
return int(a)
break
a=input(b)
else:
return print("error")
tried, not working either
def reinp(a,b):
for c in [1,2,3,4,5,6]:
if int(c)==int(a):
return int(a)
break
else:
a=input(b)
a=reinp(a,'Test: ')
This one is the first to make a problem
def reinp2(a,b): #trying to check if it's a number and can be turned to float if not ask again
while check(a):
a=input(b)
return float(a)
def check(a):
try:
float(a)
return False
except ValueError:
return True
Right now the problem is after the check it never breaks free from any while loop
i tried in place of while True:if...break,
while correct:
if... correct=False
didn't work
and it just asks again and again even a condition is met...
there is no raw_input in python 3.2 so i can't use that either
reinp2() is there so if there a solution found for reinp() the same could apply for reinp2() as well a and b are just variables ans[n]=reinp2(ans[n],"Input n: ") the same with reinp() just for another type of variable (one that can be float as well)
The code as it is now show no syntax errors
P.S. i'm using Python 3.2
[EDIT: Deleted original answer, since no longer relevant with fixed formatting on question]
The problem with reinp is that a will be a string, and you're checking it against integers.
...so change:
if a in [1,2,3,4,5,6]: #checking for valid input
to:
if a in ['1','2','3','4','5','6']: #checking for valid input
If you still have a problem with reinp2, perhaps you can show some code that demonstrates the issue. It looks fine to me.
P.S. It's complete i just wanted all of you who helped to know it's running without is any glitches i even customized it so it could receive initial data :) if someone need a permutation solver you know where to find it :)
If someone wants the script:
from math import *
ans=['n','k','choice',0,0,0,0,0]
n,k=0,1
a=['''1 For Permutations P (from n) = n
2 For Variations V (k emelments from n-th class) = n!/(n-k)!
3 For Combinations C (k emelments from n-th class) = n!/(k!(n-k)!) = ( n )
4 Use last answer. ( k )
5 Second Memory
6 Clear memory
Your choice is : ''',
'''+ to add
- to substract
* to multiply
/ to divide
You will undertake?: ''',
"The answer is: "]
def perm():
global ans
ans[n]=reinp2(ans[n],"Input n: ")
if ans[5]==0:
ans[3]=factorial(ans[n])
ans[6]=ans[3]
return print(a[2], ans[6])
else:
ans[4]=factorial(ans[n])
ans[6]=ops(ans[3],ans[4],ans[5])
return print(a[2], ans[6])
ans[n]=''
ans[k]=''
def var():
global ans
ans[n]=reinp2(ans[n],"Input n: ")
ans[k]=reinp2(ans[k],"Input k: ")
if ans[5]==0:
ans[3]=factorial(ans[n])/(factorial(ans[n]-ans[k]))
ans[6]=ans[3]
return print(a[2], ans[6])
else:
ans[4]=factorial(ans[n])/(factorial(ans[n]-ans[k]))
ans[6]=ops(ans[3],ans[4],ans[5])
return print(a[2], ans[6])
ans[n]=''
ans[k]=''
def comb():
global ans
ans[n]=reinp2(ans[n],"Input n: ")
ans[k]=reinp2(ans[k],"Input k: ")
if ans[5]==0:
ans[3]=factorial(ans[n])/((factorial(ans[n]-ans[k]))*(factorial(ans[k])))
ans[6]=ans[3]
return print(a[2], ans[6])
else:
ans[4]=factorial(ans[n])/((factorial(ans[n]-ans[k]))*(factorial(ans[k])))
ans[6]=ops(ans[3],ans[4],ans[5])
return print(a[2], ans[6])
ans[n]=''
ans[k]=''
def ent():
global ans,a
ans[2]=reinp(ans[2],a[0])
if ans[2]==5:
if ans[3]!=0:
ans[7]=ans[3]
print(ans[7])
ent()
if ans[2]==6:
clear()
print("Done!")
ent()
if ans[3]==0 and ans[2]==4:
print('The memory is empty...')
ent()
elif ans[3]!=0 and ans[2]==4:
ans[3]=ans[3]
ans[5]=reinp1(ans[5],a[1])
if ans[5] == '+' :
ans[5]='add'
print("Adding")
elif ans[5] == '-' :
ans[5]='sub'
print("Substracting")
elif ans[5] == '*' :
ans[5]='mul'
print("Multiplication")
elif ans[5] == '/' :
ans[5]='div'
print("Dividing")
ans[2]='choice'
ent()
if ans[2]==1:
perm()
elif ans[2]==2:
var()
elif ans[2]==3:
comb()
clear1()
ent()
def ops(a,b,c):
if c=='add':
return a+b
if c=='sub':
return a-b
if c=='mul':
return a*b
if c=='div':
return a/b
def reinp(a,b):
while True:
a=input(b)
if str(a) in ['1','2','3','4','5','6']:
return int(a)
break
else:
print('There was an error please try again:')
def reinp1(a,b):
while True:
a=input(b)
if a in ["+", "-", "*", "/"]:
return a
break
def reinp2(a,b):
while check2(a):
a=input(b)
return float(a)
def check2(a):
try:
float(a)
return False
except ValueError:
return True
def clear():
ans[0]='n'
ans[1]='k'
ans[2]='choice'
ans[3]=0
ans[4]=0
ans[5]=0
ans[7]=ans[6]
ans[6]=0
def clear1():
ans[0]='n'
ans[1]='k'
ans[2]='choice'
ent()

Categories

Resources