Why does my python program ignore/skip some cases - python

I'm trying to write a code which does the following:
In the first line, it inputs two space-separated integers, the first presents the length of the list which will be input later, and the second presents an int, called k, which will be needed later on.
In the second line, the list I talked about will be input
The expected output is what meets the following criteria:
number of pairs of ( i , j ), where i<j and ar[ i ]+ar[ j ] is divisible by k.
Problem: I don't know why my code ignores some pairs. I have tried it with many test cases, and it fails 90% of them, by outputting less pairs than expected. I know I am pretty close to the right result, I just don't know what I'm not doing right.
For more precise information about what I want my code to do, kindly check this link (No signup or login needed): https://www.hackerrank.com/challenges/divisible-sum-pairs/problem
Here is my code:
#https://www.hackerrank.com/challenges/divisible-sum-pairs/problem
samples_and_k = [int(x) for x in input().split()]
num_list = [int(y) for y in input().split()]
num_list.sort()
counter =0
for i in range(0, samples_and_k[0]-1):
for j in range(i+1, samples_and_k[0]-1):
if (num_list[i]+num_list[i+1]) % samples_and_k[1] == 0:
counter += 1
print(counter)
Here's an example:
Input:
6 3
1 3 2 6 1 2
Expected output:
5
The output of MY code:
3

The problem is that you subtract 1 when using range():
for i in range(0, samples_and_k[0]-1):
for j in range(i+1, samples_and_k[0]-1):
if (num_list[i]+num_list[i+1]) % samples_and_k[1] == 0:
counter += 1
It should be:
for i in range(0, samples_and_k[0]):
for j in range(i+1, samples_and_k[0]):
if (num_list[i]+num_list[i+1]) % samples_and_k[1] == 0:
counter += 1
It's a common misunderstanding when using range(), as range() is implemented somewhat unintuitively (in my opinion). The last number is not included in the range, so list(range(0, 6)) is equal to [0, 1, 2, 3, 4, 5].

Related

to change value from 0 to 1 in a list of zeroes

n and k are user inputs, L is a list of zeroes.
if k is even, change the value to 1 of even indexes.
if k is odd, change the value to 1 of odd indexes.
but the output is just ones
['1','1','1','1']
can someone please guide me?
n=int(input())
k=int(input())
L=[0]*n
for i in range(len(L)):
if(k%2==0):
L[i]='1'
elif(k%2!=0):
L[i]='1'
print(L)
In your logic, whether the value is even or odd, you are doing the same process at both steps. You should consider whether the index is odd or even in your logic.
to do this, modify your if statements to incorporate the index:
for i in range(len(L)):
if(k % 2 == 0 and i % 2 == 0):
L[i]= 1
elif(k % 2 != 0 and i % 2 != 0):
L[i]= 1
This checks to ensure that not only the value you're concerned with is even or odd, but if their index value is as well.
You're current for loop modifies every item, you need to add a test to see if you';re looking at an odd or even item in the list:
n=int(input())
k=int(input())
L=[0]*n
for i in range(len(L)):
if k % 2 == 0 and i % 2 == 0:
L[i] = 1
elif k % 2 != 0 and i % 2 != 0:
L[i] = 1
print(L)
well any number should be either even or odd
and the user enter the value of k once
here you change the value to one in case the number is even
if(k%2==0):
L[i]='1'
here you change the value to one in case the number is odd
if(k%2!=0):
L[i]='1'
in either cases you change the value to one and accordingly the output is obvious to be ones => ['1','1','1', ...]
I am not sure what you want to do but I can see two problems
first: the value of k is constant across the whole loop (probably you should use i instead of k)
second: you may change L[i]='1' to L[i]='0' in any of the two conditions
Your current logic reads like this: If k is odd, set the item to 1; if it is even, do the same. You do not consider the even- or odd-ness of the index at all. Instead, compare the even-ness of k to that of the index i:
for i in range(len(L)):
if k % 2 == i % 2:
L[i] = '1'
Or, use range with (start, stop, step) parameters to only iterate the even or odd indices in the first place:
for i in range(k % 2, len(L), 2):
L[i] = '1'
Also, your original list has the int value 0, and you are replacing those with the str value '1'. You probably use int consistently, i.e. L[i] = 1
In this case, you can also use a list comprehension:
L = [int(i % 2 == k % 2) for i in range(n)]

How to sum even and odd values with one for-loop and no if-condition?

I am taking a programming class in college and one of the exercises in the problem sheet was to write this code:
number = int(input())
x = 0
y = 0
for n in range(number):
if n % 2 == 0:
x += n
else:
y += n
print(x)
print(y)
using only one "for" loop, and no "while" or "if".
The purpose of the code is to find the sum of the even and the sum of
the odd numbers from zero to the number inputted and print it to the
screen.
Be reminded that at this time we aren't supposed to know about
functions.
I've been trying for a long time now and can't seem to find a way of doing it without using "if" statements to know if the loop variable is even or odd.
Purely for educational purposes (and a bit of fun), here is a solution that does not use any for loops at all. (Granted, in the underlying logic of the functions, there are at least five loops.)
num = list(range(int(input('Enter number: '))))
even = num[::2]
odd = num[1::2]
print('Even list:', even)
print('Odd list:', odd)
print('Even:', sum(even))
print('Odd:', sum(odd))
Output:
Enter number: 10
Even list: [0, 2, 4, 6, 8]
Odd list: [1, 3, 5, 7, 9]
Even: 20
Odd: 25
How does it work?
The input() function returns a str object, which is converted into an integer using the int() function.
The integer is wrapped in the range() and list() functions to convert the given number into a list of values within that range.
This is a convention you will use/see a lot through your Python career.
List slicing is used to get every second element in the list. Given the list is based at zero, these will be even numbers.
Slice the same list again, starting with the second element, and get every second element ... odd numbers.
Link to a nice SO answer regarding slicing in Python.
The simply use the sum() function to get the sums.
for n in range(number):
x += (1 - n % 2) * n
y += (n % 2) * n
You asked for a solution with one loop, but how about a solution with no loop?
It is well known that the sum of the numbers from 1 to n is (n+1)*n/2. Thus, the sum of even numbers is 2 * (m+1)*m/2 with m = n//2 (i.e. floor(n/2)). The sum of odd can then be calculated by the sum of all numbers minus the sum of even numbers.
n = 12345
m = n // 2
e = (m+1)*m
o = (n+1)*n//2 - e
Verification:
>>> e, e==sum(i for i in range(n+1) if i % 2 == 0)
38112102 True
>>> o, o==sum(i for i in range(n+1) if i % 2 == 1)
38105929 True
Note: This calculates the sums for number up to and including n.
for n in range(1,number,2):
x += n
y += n-1
print(y)
print(x)
This code has the same output with the example.
Ternary operator:
for n in range(number):
x += (n,0)[n%2]
y += (0,n)[n%2]
I think you are a beginner. I wouldn't like to confuse you with slicing operators complex implementation.
As you mentioned
The purpose of the code is to find the sum of the even and the sum of
the odd numbers from zero to the number inputted and print it to the
screen.
There is no need to find the initial number is odd/even
And your program is wrong if you want to include the input number in calculating the even/odd sum.
Example
Input
5
Expected Output
6
9
Explanation
Even Sum : 2+4 = 6
Odd Sum : 1+3+5 = 9
Your Output
6 4 (wrong output)
The range() function will exclude the number. It will only iterate from 0 to 4 while the input is 5. so if you want to include 5, you should add 1 to the number while passing it in the range() function.
number = int(input())
x = 0
y = 0
for n in range(number+1):
x += (1 - n % 2) * n #this will add 0 if not even
y += (n % 2) * n #this will add 0 if not odd
print(x)
print(y)
There is also mathematical way:
num = int(input("Enter number:"))
odd = ((num+1)/2)**2
even = num*(num+1)/2 - odd
The sum of the first n odd numbers is n^2. To get count of odd numbers we use (num+1)/2. To get sum of even numbers, we could use similar approach, but I preferred, subtracting odd from the sum of the first n numbers, which is n*(n+1)/2.
Here is my 2cents if we are allowed to use numpy.
import numpy as np
number = int(input())
l = np.array(range(number))
print('odd:',sum(l % 2 * l))
print('even:', sum((1- l % 2) * l))
If you're allowed to use a list
number = int( input() )
counts = [ 0, 0 ]
for n in range( number ):
counts[ n % 2 ] += n
print( counts[ 0 ] )
print( counts[ 1 ] )
There's another way which sums the odd and even indices together in the for loop based on the remainder modulo 2:
number = int(input())
odd = 0
even = 0
for i in range(len(number)):
odd += i * (i % 2)
even += i * ((i + 1) % 2)
print (odd, even)
number = 1000000
x = 0
y = 0
[(x:=x+n, y:=y+(n+1)) for n in range(0,number,2)]
print(f'{x}, {y}')
This uses a list comprehension and the new Python assignment operator.
Sum of first n numbers is n(n+1)/2 (Mathematically derived). So if we know the value of n then we can find the sum of all numbers from 1 to n.
If we find the sum of all odd numbers before n and subratract it from the sum of first n we get he sum of all even numbers before n.
Here's the code:
n = int(input("Enter a number: "))
odd = 0
for i in range(1,n+1,2):
odd += i
even = int(n*(n+1)/2) - odd
print("even:",even,"odd:",odd)

Google Kickstart 2020 Round C - Countdown. Unable to understand why my solution is incorrect

I have attempted google's kickstart 2020 challenge. Round C problem 1 has me stumped for some. I have tried many different ways of completing the challenge. The problem looks easy but I can't complete it. The problem is that I do not understand what I am doing wrong. Please point me in the right direction or point the issue in with my code.
Problem
Google Kickstart 2020 - Round C | Problem 1
https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ff43/00000000003380d2
Avery has an array of N positive integers. The i-th integer of the array is Ai.
A contiguous subarray is an m-countdown if it is of length m and contains the integers m, m-1, m-2, ..., 2, 1 in that order. For example, [3, 2, 1] is a 3-countdown.
Can you help Avery count the number of K-countdowns in her array?
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case begins with a line containing the integers N and K. The second line contains N integers. The i-th integer is Ai.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the number of K-countdowns in her array.
Pseudocode
get the number of cases
Loop in range(number of cases):
get the N (number of elements), K(initial countdown value)
get the array of values
generate an array of the countdown sequence [K ... 1] - signature
counter = 0
Loop elem in range(Number of elements):
if elem == K:
if there is space to slice the array (length of signature) - possible signature
if possible signature == signature:
counter += 1
print(counter)
Python 3 Code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
noc = int(input('')) # getting the number of cases # NOC- number of cases
# Loop over the # of cases
for c in range(noc):
(N, K) = [int(i) for i in input('').split(' ')] # getting N, K
# N - number of elements given
# K - initial countdown value
# getting the elements
caseList = [int(i) for i in input('').split(' ')]
# generating a 'signature' or list of factorial for the countdown
steps = [i for i in range(1, K + 1)][::-1]
# counter for number of matches
countdown = 0 # init value
# loop over each element i n list
for i in range(N):
# if element == K(init countdown number)
if caseList[i] == K:
# make sure there is space to get the sliced array
if i <= len(caseList) - len(steps):
# get the next m numbers if
if caseList[i:i + len(steps)] == steps:
countdown += 1 # increment
print countdown # print the number of matches
Your solution seems fine, except that the output isn't as specified and not for Python 3, but 2, simply change it to:
print(f'Case {c}: {countdown}')
Apart from that, you're doing a bit more work than is needed. You really only need to go through the entire list once to count K-countdowns.
For example:
import sys
from io import StringIO
sys.stdin = StringIO('3\n2 2\n2 1\n8 2\n0 2 1 2 2 1 2 1 0\n0 2\n\n')
t = int(input())
for c in range(t):
(n, k) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
# initialise goal, position in array and count
goal, i, count = k, 0, 0
while i < n:
# if item in current position matches current goal
if a[i] == goal:
# then next goal item is one less
goal -= 1
# until all in K-countdown were found
if goal == 0:
# then start over and increase count
goal = k
count += 1
# look at the next position
i += 1
# else (current item doesn't match goal), if already looking for start of K-countdown
elif goal == k:
# look at the next position
i += 1
# else (current item doesn't match goal, goal wasn't start of K-countdown)
else:
# look for start of K-countdown
goal = k
print(f'Case #{c}: {count}')
I don't find any issue with your solution. Might be something your output format.
You are supposed to output in the form of Case #x: y, where x is the test case number (starting from 1) and y is the number of K-countdowns in her array.
Example:
Case #1: 2
Case #2: 0
Case #3: 1
Note: Make sure you are using Python 2.x if you are using print x instead of print(x)
I was wondering the same as well.
Lets look at the constraint given:
1 ≤ T ≤ 100. # Testcases
2 ≤ K ≤ N. # Value of K
1 ≤ Ai ≤ 2 × 105, for all i. # Index- i
# Test Set 1
2 ≤ N ≤ 1000.
# Test Set 2
2 ≤ N ≤ 2 × 105 for at most 10 test cases.
For the remaining cases, 2 ≤ N ≤ 1000.
Now suppose we have a testcase
nums = [1]
k = 1
One might think for K=1 the countdown= 1 right ? Actually No.
Read carefully, 2<=N, which means,
Array length must be of minimum length=2.
Expected result,
nums = [1]
K = 1
coutdown = 0
when the constraint already says 2<=N
doesn't it mean that there will be no test case with array length = 0 or 1
There is no issue in #MFK34 except print() requires brackets in python 3 and he prints the answer immediately at end of loop and solution is not as expected. below is my revised solution.
#!/usr/bin/python
# -*- coding: utf-8 -*-
noc = int(input('')) # getting the number of cases # NOC- number of cases
op = []
# Loop over the # of cases
for c in range(noc):
(N, K) = [int(i) for i in input('').split(' ')] # getting N, K
caseList = [int(i) for i in input('').split(' ')]
steps = [i for i in range(1, K + 1)][::-1]
# counter for number of matches
countdown = 0 # init value
# loop over each element i n list
for i in range(N):
# if element == K(init countdown number)
if caseList[i] == K:
# make sure there is space to get the sliced array
if i <= len(caseList) - len(steps):
# get the next m numbers if
if caseList[i:i + len(steps)] == steps:
countdown += 1 # increment
op.append(countdown)
for i,d in enumerate(op):
print("Case #"+str(i+1)+":",d)
I have just stored the results in an array and later printed at end of inputs in order expected.

Multiplying every Nth element in a list by M

I have a problem I can't seem to figure out. I am very new to Python and have only been coding for three weeks. Any help is appreciated.
Problem:
We are passing in 3 inputs:
a list of numbers
a multiplier value, M
a value, N
You should multiply every Nth element (do not multiply the 0th element) by M. So if N is 3, you start with the 3rd element, which is index 2.
If there are less than N elements then you should output the unchanged input list.
I can't seem to figure this out. I have tried many different things here. Currently, I have the following, which is not working at all.
Provided:
import sys
M= int(sys.argv[2])
N= int(sys.argv[3])
numbers= sys.argv[1].split(',')
for i in range(0, len(numbers)):
numbers[i]= int(numbers[i])
My Code:
for N in numbers:
if numbers[i] > 0:
total = N * M
print(total)
else:
print(numbers)
Output:
I am not even close to what the output should be. Feeling lost on this. Here is what my code comes to. It looks like they want the output in a list.
Program Failed for Input: 1,2,3,4,5,6 5 3
Expected Output: [1, 2, 15, 4, 5, 30]
Your Program Output:
5
10
15
20
25
30
You could try a list comprehension with slicing.
numbers[N-1::N] = [x * M for x in numbers[N-1::N]]
A more elegant solution using list comprehensions ;)
[item*M if (index and not (index+1)%N) else item for index, item in enumerate(items)]
This solution is based on your original one. A more pythonic one would use for instance, a list comprehension so keep that in mind in the future,
output = [numbers[0]]
if len(numbers) >= N:
for i in range(1,len(numbers)):
if ((i+1)%N) is 0:
output.append(numbers[i]*M)
else:
output.append(numbers[i]);
else:
output = numbers
If N is not larger than the list size, the program constructs a new list of numbers with each Nth number being multiplied by M. This is done with a simple modulo operator. Indexing in Python starts with zero and i iterates through index values but your desired output counts the elements as if starting from 1 - thus i+1 in the modulo. If it is not every Nth - program just append the old value. If the list is shorter than N altogether, it assigns the whole unchanged list to the output list.
will this work for you?
res = []
for num in numbers:
if num > 0:
total = num * M
res.append(total)
if len(res) != len(numbers):
print (numbers)
else:
res.reverse()
print (res)
So after many attempts and bouncing this off of a friend who works as a programmer, I ended up with this that gave me the proper output:
newlist = []
if len(numbers) < N:
newlist = numbers
else:
for i in range(0, len(numbers)):
num = numbers[i]
if (i+1) % N == 0:
newlist.append(num*M)
else:
newlist.append(num)
i+=1
print(newlist)
# Input
import sys
M= int(sys.argv[2])
N= int(sys.argv[3])
# convert strings to integers
numbers= sys.argv[1].split(',')
for i in range(0, len(numbers)):
numbers[i]= int(numbers[i])
# if the length of our list is greater than our supplied value
# loop to multiply(starting at the 3rd position in the list) by M
if len(numbers) > N :
for num in range(2, len(numbers), 3) :
numbers[num] = numbers[num] * M
print(numbers)

What does this line do? (using num and enumerate)

I'm a python beginner, and have been given this code to write out what each line does. Here is the code:
z = [int(input("Enter your nth term sequence ")) for _ in range(12)]
total = sum([num * 8 if i % 2 == 0 else num * 4 for i, num in enumerate(z)])
So, I assume that z is a list, where a user inputs the numbers of the nth term sequence, there are 12 digits which they can enter. The code then finds a sum of the numbers multiplied by 8 if something divided by 2 gives a remainder of 0. I just don't get what ([num * 8 if i % 2 == 0 else num * 4 for i, num in enumerate(z)]) means. I've tried and have attempted to search things up, but it's just too confusing. Please help if possible
The code:
foo = [num * 8 if i % 2 == 0 else num * 4 for i, num in enumerate(z)]
is functionally equivalent to this:
foo = []
for i, num in enumerate(z): # num is element in z, i is index of num
if i % 2 == 0:
foo.append(num*8)
else:
foo.append(num*4)
Then the user calls sum on the result.
Does this answer your question?
EDIT: explain enumerate
You should get used to reading documentation on functions, for example enumerate. After you've read it, if you still don't understand then you should search stackoverflow. For example: A post asking what enumerate is with a good answer
Calling:
for num in z:
i = z.index(num)
# Do stuff
is functionally the same as saying:
for i, num in enumerate(z):
# Do stuff
Lets break this down step by step.
z = [int(input("Enter your nth term sequence ")) for _ in range(12)]
First, your assumption that z is a list is correct. It is generated from a list comprehension. It gets input from a user with input("Enter your nth term sequence ") a total of 12 times using for _ in range(12). So z will be a list of 12 user-input integers (not digits, as it can be any integer, not just 0-9).
Next we have:
total = sum([num * 8 if i % 2 == 0 else num * 4 for i, num in enumerate(z)])
It's immediately clear that we are generating a total from the sum of a list with total = sum([...]). So next we need to figure out the contents of the list generated by the list comprehension.
To make the list comprehension a little bit easier to understand we can add in some parentheses to break up the comprehension into easier to manage parts which we will then handle individually.
(num * 8) if (i % 2 == 0) else (num * 4) for (i, num) in (enumerate(z))
The first three groups are fairly self-explanatory:
num * 8 eight times a number
i % 2 == 0 check if i is even
num * 4 four times a number
So the first half of the list comprehensions returns a value that is eight times a number if i is even or four times that number if it isn't.
So that leaves us with the last half of the list comprehension for i, num in enumerate(z).
Lets discuss enumerate first. Enumerate takes a sequence and numbers each element in that sequence. For example enumerate(['a', 'b', 'c']) would return a list of 2-element tuples [(0, 'a'), (1, 'b'), (2, 'c')].
The for i, num in takes the tuples from enumerate(z) and unpacks each tuple into i and num. So i is the index generated by enumerate and num is the original user input.
TL;DR
z = [int(input("Enter your nth term sequence ")) for _ in range(12)]
total = sum([num * 8 if i % 2 == 0 else num * 4 for i, num in enumerate(z)])
Line 1 gets 12 integers from user input and stores them in z
Line 2 takes those integers, indexes them (starting at 0), and if the index is even multiplies that number by 8, if the index is odd multiplies that number by 4.
Finally line 2 sums all the multiplied user inputs and stores them in total
Well lets break it down. You are storing something to the variable "total".
Then you are taking the Sum of everything inside your parentheses. You run an if statement, saying if i modulus 2(i.e. if it is divisible by two and has no remainder left over) append num(a variable) times 8 to the list z.
else, num times 4 appended to the list z. Its a compact way that they wrote out the statement instead of multiple lines

Categories