There is inreger a which represents the amount of stairs. Each number in list b represents the amount of stairs you can jump from current stair. You need to find out if it is possible to get from first to last stair.
Example of input:
case a)
8
1 3 0 0 2 0 1 1
case b)
3
0 1 1
Example of output:
case a)
True
case b)
False
I managed to create a code which works, but exceeds the time limit. All numbers are positive and have int type. Could you give me an idea how to improve my algorithm (if you can name it so).
My code:
a = int(input())
b = list(map(int, input().split()))
flag = True
count = 0
for i in range(a):
if b[i] > 0:
if count != 0:
position = i - count - 1
if b[position] <= count:
flag = False
break
count = 0
elif b[i] == 0:
if i == 0:
flag = False
break
else:
count += 1
print(flag)
Thank you.
Related
Recall in class that we discussed the hailstone numbers where xn = 3xn−1 +1 if xn−1 is odd and xn = xn−1/2 ifxn−1 iseven. Thehailstonenumbersconvergetoasortofholdingpattern4→2→1→4→2→1→ 4 → 2 → 1. We call this kind of pattern a convergence because it repeats.
Write a program to test generalized hailstone numbers where xn = axn−1 + b if xn−1 is odd and xn = xn−1/2 if xn−1 is even where a and b are positive integers. For each of the a, b pairs less than or equal to 10, find whether or not the sequence seems to converge. Once you can do that, tell me how many different holding patternsthesequenceconvergesto. Forinstance,whena=3andb=5then1→8→4→2→1this is holding pattern. However, if we start with a different number, say 5 we get a different holding pattern 5 → 20 → 10 → 5.
def validation(x,a,b):
steps = 1
start = x
set1 = set()
while x not in set1:
steps += 1
set1.add(x)
if x % 2 == 0:
x = x//2
else:
x = a*x + b
if steps == 100:
break;
if x == start:
return True
else:
return False
def hailstone(number):
List = []
for i in range(1,11):
for j in range(1,11):
count = 0
for x in range(1, number+1):
if (((i%2 != 0 ) and (j%2 == 0)) or ((i%2 == 0 ) and (j%2 != 0))):
break
else:
if validation(x,i,j): #calling 'validation' to check if it is true
count += 1
List.append([i,j,count])
return(List)
pattern_count = hailstone(number = 100)
print(pattern_count)
Given an array of integers arr of even length n and an integer k.
We want to divide the array into exactly n/2 pairs such that the sum of each pair is divisible by k.
Return True If you can find a way to do that or False otherwise.
e.g.
arr = [1,2,3,4,5,10,6,7,8,9], k = 5, output: True
arr = [-1,-1,-1,-1,2,2,-2,-2], k = 3, output: False
The code i've written:
def canArrange(self, arr: List[int], k: int) -> bool:
dictt = {}
for i in range(len(arr)):
arr[i] = arr[i] % k
if arr[i] not in dictt:
dictt[arr[i]] = 1
else:
dictt[arr[i]] += 1
count = 0
for num in arr:
if (k-num) == num:
if dictt[num] > 1:
dictt[num] -= 2
count += 1
else:
dictt[num] -= 1
if (k-num) in dictt and dictt[(k-num)] != 0 and dictt[num] != 0:
dictt[(k-num)] -= 1
dictt[num] -= 1
count += 1
elif num == 0 and dictt[num] > 1:
dictt[num] -= 2
count += 1
if count == len(arr)//2:
return True
else:
return False
My logic is I am first taking the count of "every element % k" and the finding its another pair and reducing the count of both to avoid duplicates, one special case is when the values in a pair are same so for that i am already decrementing the value in my dictionary and at last i am checking whether the number of pairs are equal to half of elements or not
I am able to pass 93/97 test cases on leetcode, and unable to debug for the rest as the length of these 4 test cases are huge hence not possible manually, i must be missing some points while setting my logic, kindly help
Edit: DONE (I have edited the code above)
I'm playing with the Codality Demo Task. It's asking to design a function which determines the lowest missing integer greater than zero in an array.
I wrote a function that works, but Codility tests it as 88% (80% correctness). I can't think of instances where it would fail.
def solution(A):
#If there are negative values, set any negative values to zero
if any(n < 0 for n in A):
A = [(i > 0) * i for i in A]
count = 0
else: count = 1
#Get rid of repeating values
A = set(A)
#At this point, we may have only had negative #'s or the same # repeated.
#If negagive #'s, or repeated zero, then answer is 1
#If repeated 1's answer is 2
#If any other repeated #'s answer is 1
if (len(A) == 1):
if (list(A)[0] == 1):
return 2
else:
return 1
#Sort the array
A = sorted(A)
for j in range(len(A)):
#Test to see if it's greater than zero or >= to count. If so, it exists and is not the lowest integer.
#This fails if the first # is zero and the second number is NOT 1
if (A[j] <= count or A[j] == 0): #If the number is lt or equal to the count or zero then continue the count
count = count + 1
elif (j == 1 and A[j] > 1): return 1
else:
return count
return count
UPDATE:
I got this to 88% with the fixes above. It still fails with some input. I wish Codility would give the inputs that fail. Maybe it does with a full subscription. I'm just playing with the test.
UPDATE 2: Got this to 100% with Tranbi's suggestion.
def solution(A):
#Get rid of all zero and negative #'s
A = [i for i in A if i > 0]
#At this point, if there were only zero, negative, or combination of both, the answer is 1
if (len(A) == 0): return 1
count = 1
#Get rid of repeating values
A = set(A)
#At this point, we may have only had the same # repeated.
#If repeated 1's answer is 2
#If any other repeated #'s only, then answer is 1
if (len(A) == 1):
if (list(A)[0] == 1):
return 2
else:
return 1
#Sort the array
A = sorted(A)
for j in range(len(A)):
#Test to see if it's >= to count. If so, it exists and is not the lowest integer.
if (A[j] <= count): #If the number is lt or equal to the count then continue the count
count = count + 1
else:
return count
return count
Besides that bug for len=1, you also fail for example solution([0, 5]), which returns 2.
Anyway... Since you're willing to create a set, why not just make this really simple?
def solution(A):
A = set(A)
count = 1
while count in A:
count += 1
return count
I don't think this is true:
#At this point, we may have only had negative #'s or the same # repeated. If so, then the answer is 1+ the integer.
if (len(A) == 1):
return list(A)[0]+1
If A = [2] you should return 1 not 3.
Your code is quite confusing though. I think you could replace
if any(n < 0 for n in A):
A = [(i > 0) * i for i in A]
with
A = [i for i in A if i > 0]
What's the point of keeping 0 values?
I don't think this is needed:
if (len(A) == 1):
if (list(A)[0] == 1):
return 2
else:
return 1
It's already taken into account afterwards :)
Finally got a 100% score.
def solution(A):
# 1 isn't there
if 1 not in A:
return 1
# it's easier to sort
A.sort()
# positive "hole" in the array
prev=A[0]
for e in A[1:]:
if e>prev+1>0:
return prev+1
prev=e
# no positive "hole"
# 1 is in the middle
return A[-1]+1
I'm trying to create a function that take two parameters: D = digit (0-9) and n = positive number.
If the D is parity number, the function should give me 0 but ,if the D is odd number, the function should count numbers of odd number I have in n.
There is a problem with this code but I don't know what:
def testD(D,n):
if D % 2 == 0:
return 0
count = 0
while n > 0:
if(n%10) %2==1:
count +=1
n=n/10
return count
I changed 2 things :
while n > 1: instead of while n > 0: otherwise your loop never stops
n=n//10 instead of n=n/10, where // is the euclidian division, which is what you need here
You should try this :
def testD(D,n):
if D % 2 == 0:
return 0
count = 0
while n > 1:
if(n%10) %2==1:
count +=1
n=n//10
return count
print(testD(7, 555))
# output : 3 (because 7 is odd, and there is 3 odd digits in 555)
I am trying to make a decimal to binary converter, however, I noticed that some values are being ignored and the last value is not being entered into the list I created.
#Here we create a new empty list.
binary = []
n = int(input("Enter number: "))
while n > 1:
n = n//2
m = n%2
binary.append(m)
binary.reverse()
print( " ".join( repr(e) for e in binary ))
This is your code after correction :
binary = []
n = int(input("Enter number: "))
while n > 0:
m = n%2
n = n//2
binary.append(m)
if len(binary)==0:
binary.append(0)
binary.reverse()
print( " ".join( repr(e) for e in binary ))
Your question is duplicate to this stackoverflow question check the link too.
good luck :)
As PM 2Ring suggested a tuple assignment may be the way to go. Makes your code shorter too :-) ... also changed n > 1 to n >= 1
binary = []
n = int(input("Enter number: "))
while n >= 1:
n, m = n // 2, n % 2
binary.append(m)
binary.reverse()
print( " ".join( repr(e) for e in binary ))
n = int(input("Enter number: "))
print("{0:0b}".format(n)) # one-line alternate solution
if n == 0: # original code with bugs fixed
binary = [0]
else:
binary = []
while n > 0:
m = n%2
n = n//2
binary.append(m)
binary.reverse()
print("".join( repr(e) for e in binary ))
Your algorithm is close, but you need to save the remainder before you perform the division. And you also need to change the while condition, and to do special handling if the input value of n is zero.
I've fixed your code & put it in a loop to make it easier to test.
for n in range(16):
old_n = n
#Here we create a new empty list.
binary = []
while n:
m = n % 2
n = n // 2
binary.append(m)
# If the binary list is empty, the original n must have been zero
if not binary:
binary.append(0)
binary.reverse()
print(old_n, " ".join(repr(e) for e in binary))
output
0 0
1 1
2 1 0
3 1 1
4 1 0 0
5 1 0 1
6 1 1 0
7 1 1 1
8 1 0 0 0
9 1 0 0 1
10 1 0 1 0
11 1 0 1 1
12 1 1 0 0
13 1 1 0 1
14 1 1 1 0
15 1 1 1 1
As Blckknght mentions in the comments, there's a standard function that can give you the quotient and remainder in one step
n, m = divmod(n, 2)
It can be convenient, but it doesn't really provide much benefit apart from making the code a little more readable. Another option is to use a tuple assignment to perform the operations in parallel:
n, m = n // 2, n % 2
It's a good practice, especially when you're new to coding, to work through your algorithm on paper to get a feel for what it's doing. And if your code doesn't give the expected output it's a good idea to add a few print calls in strategic places to check that the values of your variables are what you expect them to be. Or learn to use a proper debugger. ;)