Hash answer not right - python

This is hacker what hacker rank saysGiven an integer,n, and n space-separated integers as input, create a tuple,t , of those integers. Then compute and print the result of hash(t). <--- this is the question.
n = int(input())
x = input().split() but
x = tuple([eval(i) for i in x])
print(hash(x))
this my code and for n =2 and x = 1 2 the answer to question is given as 3713081631934410656 but i am getting -3550055125485641917. but shouldnt hash show negative value when the value is very big??

Related

How can I print an output in reverse in Python?

A question is asking me to convert an int into binary, but it also must be in reverse (why!??!?!). After a bunch of tinkering, I was able to get it to print the number in binary. But I can't for the life of me figure out how to make it output in reverse.
The instructions say:
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary.
For an integer x, the algorithm is:
As long as x is greater than 0
Output x modulo 2 (remainder is either 0 or 1)
Assign x with x divided by 2
My code is:
x = int(input())
while x > 0:
x = x//2
print( x % 2, end = ' ')
Testing with input of 6, I get 1 1 0 but it wants me to output 011.
I even tried putting the answer into a list but when I try to reverse the list, I get an error. List method I tried:
x = int(input())
while x > 0:
x = x//2
J = [x % 2]
L = reversed(J)
print(L)
output using list method:
<list_reverseiterator object at 0x7f2cd69484f0>
<list_reverseiterator object at 0x7f2cd6948ee0>
<list_reverseiterator object at 0x7f2cd69484f0>
I feel like there's no way this needs some sort of slicing since that method hasn't even been covered yet in the material I'm learning.
You didn't follow the provided algorithm steps in the given order. Swap the statements in the while loop so they align with what was described.
And a small detail: there was no instruction to separate the output with spaces, so you should provide end = '':
x = int(input())
while x > 0:
print( x % 2, end = '')
x = x//2
You're reading in the least significant bit first, which results in the output being reversed. You don't need to make an explicit call to reversed().
This produces the desired output:
x = int(input())
result = []
while x > 0:
result.append(x % 2)
x = x // 2
# str() transforms each integer to a string.
# We then concatenate them all together
# to get the desired output using ''.join().
print(''.join(str(item) for item in result))
>>> x = 100
>>> res = []
>>> while x > 0:
... x = x//2
... J = x%2
... res.append(J)
...
>>> res
[0, 1, 0, 0, 1, 1, 0]
>>> "".join(str(i) for i in res[::-1])
'0110010'
step1 = input("what number? ")#gets your input
step2 = int(step1) #makes sure it's an int not float
step3 = bin(step2) #converts it to binairy (you method doesn't work for e.g. 7)
step4 = step3.replace("0b", "") #removes 0b from the binairy number
step5 = step4[::-1] #reveses the string
print (step5)
should work
or
print(bin(int(input("what number? "))).replace("0b", "")[::-1])
if you want in more compressed
you can use special function of python to convert integer to binary input and the print reverse of binary input by [:1:-1] in J list, so:
integer_input = int(input()) # input integert number
binary_of_integer_input = bin(integer_input) # convert integer to binary
print(binary_of_integer_input[2:]) # Print binary of integer input
print(binary_of_integer_input[:1:-1]) # Print reverse binary of integer input
Example:
integer number = 8
binary of input = 1000
reverse of binary = 0001
integer_input = int(input()) # input integert number
binary_of_integer_input = bin(integer_input) # convert integer to binary
x = binary_of_integer_input[2:]
J = binary_of_integer_input[:1:-1]
print(x) # Print binary of integer input
print(J) # Print reverse binary of integer input
I am taking This class!!!! Here's a code with materials learned so far that works! For actual Binary. Except reversing a string may not have been mentioned [::-1].
The lab wants answers per strictly that algorithm. So reversed binary and expects it to end with new line.
num = int(input())
while num > 0:
y =(num % 2)
print(y, end='')
num = (num//2)
print()
The Note: The above algorithm outputs the 0's and 1's in reverse order. If interpreted "as Convert to binary using this algorithm but reverse it"
num = int(input("Enter a number"))
string = ""
while num > 0:
y =str(num % 2)
string+=y
num = (num//2)
reverse=string[::-1]
print(reverse)

Time-Complexity of the problem in CodeForces contest #771

I'm currently trying to upsolve one problem from CodeForces and I face so many time issues. I've tried a variety of modifications, however my code still doesn't get submitted.
Any suggestions on how I can improve the time complexity of my code?
The main idea of the problem can be found here: https://codeforces.com/contest/1638/problem/C
A description of the problem is as follows:
You are given a permutation p_1,p_2,…,p_n. Then, an undirected graph is constructed in the following way: add an edge between vertices i, j such that i < j if and only if p_i > p_j. Your task is to count the number of connected components in this graph.
Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.
A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Input
Each test contains multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10**5) — the number of test cases. Description of the test cases follows.
The first line of each test case contains a single integer n (1 ≤ n ≤ 10**5) — the length of the permutation.
The second line of each test case contains n integers p_1,p_2,…,p_n (1≤p_i≤n) — the elements of the permutation.
It is guaranteed that the sum of n over all test cases does not exceed 2⋅10**5.
Output
For each test case, print one integer k — the number of connected components.
import sys
input = sys.stdin.readline
for case in range(int(input())):
length = int(input())
line = list(map(int, input().split()))
quantity = 0
for i in range(1, length):
if line[i] > line[i-1] and max(line[:i]) < min(line[i:]):
quantity += 1
print(1 if quantity >= length else quantity + 1)
Thanks for your help!
This implements my min/max caching scheme. I have not submitted this, so I don't actually know if it will meet the timing. This is O(3N) instead of O(N*N), so it will take slightly longer for short lists, but SHOULD be better for long lists.
You don't need to do input = sys.stdin.readline; that's effectively what the input function already is. Also, the if clause in your final line confuses me. Your final for can never go more than length-1 iterations, so quantity can never be >= length.
import sys
for case in range(int(input())):
length = int(input())
line = list(map(int, input().split()))
maxx = 0
maxs = []
for i in line:
if i > maxx:
maxx = i
maxs.append(maxx)
minx = 999999
mins = []
for i in line[::-1]:
if i < minx:
minx = i
mins.insert(0,minx)
quantity = 0
for i in range(1, length):
if line[i] > line[i-1] and maxs[i-1] < mins[i]:
quantity += 1
print(quantity + 1)
You can replace the final section of the code with a comprehension, although I think that's a micro-optimization:
quantity = sum(
line[i] > line[i-1] and maxs[i-1] < mins[i]
for i in range(1, length)
)
print(quantity + 1)

Python Program to Print all Numbers in a Range Divisible by a Given Number

Python Program to Print all Numbers in a Range Divisible by a Given Numbers
L=int(input()) #L=[2,4,5] take all input at a time to process with range number divisible with give inputs those numbers print output is 20,40 bcuz of 2,4,5 divisible 20, 40 only
L=int(input))
for i in l:
for j in range(1,50):
if j%i==0:
print(j)
I want out put 20,40
Range divisible with all list l
I'm not sure quite sure what you're asking, but I think the gist of it is that you want to print all numbers in a given range that are divisible by a list.
In that case, there is no need to do a type coercion to int on your list, I'm not sure why you did that.
my_list = [2, 4, 5]
# create an empty output list
output = []
# iterate through a range.
for i in range(1, 50):
# create a boolean array that checks if the remainder is 0 for each
# element in my_list
if all([i % j == 0 for j in my_list]):
# if all statements in the boolean list created above are true
# (number is divisible by all elements in my_list), append to output list
output.append(i)
print(output)
First you need to calculate the least common multiple (lcm) of the numbers in the list. Math library in python 3.9 has included a lcm function, so you can use it. If you dont have python 3.9 you can search some solutions.
import math
lcm = math.lcm(2,4,5)
At this point you know that every integer number that you multiply by 20 is going to be divisible by all the numbers in the list (2 * 20=40, 3 * 20=60 ...). So for a range you must divide the maximum range number (in your case 50) and truncate the result.
high = 50
low = 1
n = int(high/lcm)
Make a loop and multiply from 1 to n by the lcm result. Then for each result check if it is equal or higher than the lower range.
for j in range(1,n):
res = j*lcm
if res >= low:
print(res)
values = int(input('enter value count :'))
n = []
for k in range(values):
temp = int(input('enter int value :'))
n.append(temp)
for i in range(1,50):
count = 0
for j in n:
if i%j == 0:
count=count+1
else:
if count==len(n):
print(i,end=',')

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)

Similarity Measure in Python

I am working on this coding challenge named Similarity Measure. Now the problem is my code works fine for some test cases, and failed due to the Time Limit Exceed problem. However, my code is not wrong, takes more than 25 sec for input of range 10^4.
I need to know what I can do to make it more efficient, I cannot think on any better solution than my code.
Question goes like this:
Problems states that given an array of positive integers, and now we have to answer based upon the Q queries.
Query: Given two indices L,R, determine the maximum absolute difference of index of two same elements lies between L and R
If in a range, there are no two same inputs then return 0
INPUT FORMAT
The first line contains N, no. of elements in the array A
The Second line contains N space separated integers that are elements of the array A
The third line contains Q the number of queries
Each of the Q lines contains L, R
CONSTRAINTS
1 <= N, Q <= 10^4
1 <= Ai <= 10^4
1 <= L, R <= N
OUTPUT FORMAT
For each query, print the ans in a new line
Sample Input
5
1 1 2 1 2
5
2 3
3 4
2 4
3 5
1 5
Sample Output
0
0
2
2
3
Explanation
[2,3] - No two elements are same
[3,4] - No two elements are same
[2,4] - there are two 1's so ans = |4-2| = 2
[3,5] - there are two 2's so ans = |5-3| = 2
[1,5] - there are three 1's and two 2's so ans = max(|4-2|, |5-3|, |4-1|, |2-1|) = 3
Here is my algorithm:
To take the input and test the range in a different method
Input will be L, R and the Array
For difference between L and R equal to 1, check if the next element is equal, return 1 else return 0
For difference more than 1, loop through array
Make a nested loop to check for the same element, if yes, store the difference into maxVal variable
Return maxVal
My Code:
def ansArray(L, R, arr):
maxVal = 0
if abs(R - L) == 1:
if arr[L-1] == arr[R-1]: return 1
else: return 0
else:
for i in range(L-1, R):
for j in range(i+1, R):
if arr[i] == arr[j]:
if (j-i) > maxVal: maxVal = j-i
return maxVal
if __name__ == '__main__':
input()
arr = (input().split())
for i in range(int(input())):
L, R = input().split()
print(ansArray(int(L), int(R), arr))
Please help me with this. I really want to learn a different and a more efficient way to solve this problem. Need to pass all the TEST CASES. :)
You can try this code:
import collections
def ansArray(L, R, arr):
dct = collections.defaultdict(list)
for index in range(L - 1, R):
dct[arr[index]].append(index)
return max(lst[-1] - lst[0] for lst in dct.values())
if __name__ == '__main__':
input()
arr = (input().split())
for i in range(int(input())):
L, R = input().split()
print(ansArray(int(L), int(R), arr))
Explanation:
dct is a dictionary that for every seen number keeps a list of indices. The list is sorted so lst[-1] - lst[0] will give maximum absolute difference for this number. Applying max to all this differences you get the answer. Code complexity is O(R - L).
This can be solved as O(N) approximately the following way:
from collections import defaultdict
def ansArray(L, R, arr) :
# collect the positions and save them into the dictionary
positions = defaultdict(list)
for i,j in enumerate(arr[L:R+1]) :
positions[j].append(i)
# create the list of the max differences in index
max_diff = list()
for vals in positions.values() :
max_diff.append( max(vals) - min(vals) )
# now return the max element from the list we have just created
if len(max_diff) :
return max(max_diff)
else :
return 0

Categories