I have some kind of AP in Computer Science and I've started on coding/programming with Python. I briefly used C++ for few years and now I switched to Python. I don't really remember where I stopped with C++ but that's irrelevant now. Anyways, I have this task that says: "Write program that loads number N, then N numbers and prints number that has the highest value between them. Number N has input in one line and line underneath loads N numbers with same space between them. None of the numbers will be greater than 100. Number N will be greater than 2."
I wrote this code;
`n = int (input())
max = 2
for i in range (1, n+1, 1):
x=map(int,input().split())
if x>max: x=max
print (max)
`
which returned this error:
5
2 87 12 90 55
File "C:\Users\Mariee.Marija-PC\Documents\Python\19-4.py", line 5, in
if x>max: x=max
TypeError: unorderable types: map() > int()
that was totally expected because I know I can't compare those two as they are clearly not comparable (which again, I am very aware of).
So my question is, is there any other way that N number could be put in one line and then N numbers could be put in the same line but you can compare them (if that makes any sense).
[P.S. Also I'm ultimately sorry if my english was bad.]
The variable x is a map (similar to a list) of integers, but you are comparing it with a single integer.
In order to loop over the values of x you should use a for loop:
for x in map(int, input().split()):
if x > max:
max = x
There's already a max method in Python, and no need to re-create a max function like you have to do in C/C++. Just apply the max method
n = int (input())
print (max(map(int,input().split())))
Related
I have this challenge: Repeated String to solve. I have been trying to solve the challenge but getting failure cos of Memory Failure. I cannot help this situation cos the HackerRank platform is not supporting my solution. Might be 32-bit platform.
I have this solution for this, which is quite working for problem having smaller length, but I have worked on this thing to learn according to less memory usage.
My Code:
def repeatedString(s, n):
if(s != 'a'):
return len([x for x in (s*n)[:n] if x == 'a'])
return n
Now this throws Memory Error error for input having very large length, and string.
I have researched on it, and saw some submissions, and found this out.
Correct Solution from Leaderboard:
def repeatedString(s, n):
L = len(s)
return (s.count('a') * (n//L) + s[:n % L].count('a'))
That's it! I got so confused by this solution that I could figure what is actually happening and how. Could anybody please let me know how the above correct solution works? I am new to python and trying my best to get my hands dirty on competitive coding. Thank You!
Your function is throwing a Memory error because you are constructing a string with the length of the input paramater n.
n can be 10^12, which results in a string with a maximum length 1000 billion letters, which would mean the string you are creating has a possible memory size of 1 terabyte (Possibly more depending on the encoding of your string).
So there has to be another way to count the number of a's in a string of that size right?
Yes (That's why the correct answer is different from your solution).
1. First we get the length of the input string.
L = len(s)
For example 'abcde' has a length of 5.
2. Then, we count the number of 'a's in s.
s.count('a')
3. Next, we want to know how many times s is repeated as a whole before we reach a string with a length of n.
(n//L)
The // operator is called integer division, which results in a whole number. For instance with s='abcde' and n=14, n//L equals 2.
4. Multiple the number of 'a's in s by the number of times s can fit into a string of length n.
s.count('a') * (n//L)
5. We are almost done, but for our example, something is still missing. 'abcde' can be repeated twice inside a string of length n, but there are still 4 characters left, in our example 'abcd'.
Here, we construct the remaining string from s with s[:n % L], or in our example s[:14 % 5] or s[:4], which results in 'abcd'.
Then we count the number of 'a's in this string with s[:n % L].count('a')
6. Add it all together and we get the function in your answer:
def repeatedString(s, n):
L = len(s)
return (s.count('a') * (n//L) + s[:n % L].count('a'))
So, the key difference between the two algorithms is that in your original, you do s*n, which will actually try to build the massive string in-memory. This is why you get the memory error.
The second algorithm essentially says "For a string s of length X that's repeated out to length N, s will fit into M N//X times, possibly with a chunk of s left over (the division remainder).
E.g. if your string is aab (X=3) and N is 10, you know the string will fit 3 times, with 1 character left over.
So, given there are 2 letter a in s, you know that there will be 2*3 a in the first 9 chars. Now you need to deal with the remainder. The final character (the remainder) will be the first character of s.
In the second solution, s.count('a') * (n//L) + s[:n % L].count('a') is these two parts;
s.count('a') * (n//L) - This gives you the 2 * 3 in my example.
s[:n % L].count('a') - this gives you the 'remainder' part.
I'm stuck in Codewars Kata, I hope someone could help me out (without spoiling the solution).
In fact the problem is that I didn't fully understand how it should work, I got the idea of the exercise but things are a bit confusing especially in Sample tests.
Here are the instructions:
The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details.
8 + 1 = 9 and 9^2 = 81
512 = 5 + 1 + 2 = 8 and 8^3 = 512
We need to make a function, power_sumDigTerm(), that receives a number n and may output the nth term of this sequence of numbers. The cases we presented above means that:
power_sumDigTerm(1) == 81
power_sumDigTerm(2) == 512
And here are the sample tests:
test.describe("Example Tests")
test.it("n = " + str(1))
test.assert_equals(power_sumDigTerm(1), 81)
test.it("n = " + str(2))
test.assert_equals(power_sumDigTerm(2), 512)
test.it("n = " + str(3))
test.assert_equals(power_sumDigTerm(3), 2401)
test.it("n = " + str(4))
test.assert_equals(power_sumDigTerm(4), 4913)
test.it("n = " + str(5))
test.assert_equals(power_sumDigTerm(5), 5832)
My main problem is how did they get the results for the sample tests.
A good speed up trick is to not check all numbers, Any such number must be of the form a^b for integers a and b. If you find a way to enumerate those and check them you will have a fairly efficient solution.
On f(5), the sum of the numbers is 5+8+3+2 = 18. And 18^3=5832.
Brute force method would look like this for the next one:
Start at 5833, add the digits, check the powers of the sum to see if you get number. This would actually be very fast as you can see that last one only got to ^3. As soon as the power is larger than the number you are seeking, move on to the next number: 5834. When you find one, insert into a table to remember it.
The number theory experts may be able to find a more efficient method but this brute force method is likely to be pretty fast.
Grab a prime generator; you need only prime powers to generate the sequence (although you will have all integers >= 2 in the test for inclusion). This is because if a number is a composite power, it's also a prime power.
Maintain a list of current powers, indexed by the base integer. For instance, once you've made it to a limit of 100, you'll have the list
[0, 0, 64, 81, 64, 25, 36, 49, 64, 81, 100]
// Highest power no greater than the current limit
... and the current list of target numbers has only one element: [81]
Extending the limit:
Pick the lowest number in the list (25 = 5^2, in this case)
Multiply by its base: 25 => 125
Check: is 1+2+5 a root of 125? (There are minor ways to speed this up)
If so, add 125 to the list
Now, go back to all lower integers (the range [2, 5-1] ), and add any smaller prime powers of those integers. (I haven't worked out whether there can ever be more than one power to add for a given integer; that's an interesting prime-based problem.)
Whenever you add a new target number, make sure you insert in numerical order; the step in the previous paragraph may introduce a "hit" lower than the one that triggered the iteration. For instance, this could append 5832 before in finds 4913 (I haven't coded and executed this algorithm). You could collect all the added target numbers, sort that list, and append them as a block.
Although complicated, I believe that this will be notably faster than the brute-force methods given elsewhere.
While solving some progrmaming problems, I've noticed that the dialogue says:
Input:
Integer N denoting size of array
Next line contains N space separated integers denoting elements in
array
How am I supposed to use the variable N so that it is functioning as supposed to and not just a useless-floating-around input-variable...
I mean, it could just be one input denoting the elements of the array, no need for the length of its elements...
PS: I know that I can just add it there just to pass the problem, I am just asking about if that N variable could be useful using Python (Without the way of a for loop, to ask N number of times for input cause it won't pass the problem).
In Python it usually is, since usually you fetch the entire line at once and process it.
Some programming languages like C++ and Java however tend to benefit from this approach since some parser tools (like Java's Scanner) work by parsing one integer at a time.
You can simply parse your input like:
input() # ignore the 'N'
arr = [int(x) for x in input().split()]
x=list(map(int,input().split())
print(x)
Try this
you will get an array of integers
If I understood you correctly, you want space-separated numbers with the length defined as the input. You can achieve that by:
N = input("Integer N denoting size of array: ")
print(" ".join(str(i + 1) for i in range(int(N))))
e.g.:
Integer N denoting size of array: 12
1 2 3 4 5 6 7 8 9 10 11 12
I am trying to solve a problem, using python code, which requires me to add two integers without the use of '+' or '-' operators. I have the following code which works perfectly for two positive numbers:
def getSum(self, a, b):
while (a & b):
x = a & b
y = a ^ b
a = x << 1
b = y
return a ^ b
This piece of code works perfectly if the input is two positive integers or two negative integers but it fails when one number is positive and other is negative. It goes into an infinite loop. Any idea as to why this might be happening?
EDIT: Here is the link discussing the code fix for this.
Python 3 has arbitrary-precision integers ("bignums"). This means that anytime x is negative, x << 1 will make x a negative number with twice the magnitude. Zeros shifting in from the right will just push the number larger and larger.
In two's complement, positive numbers have a 0 in the highest bit and negative numbers have a 1 in the highest bit. That means that, when only one of a and b is negative, the top bits of a and b will differ. Therefore, x will be positive (1 & 0 = 0) and y will be negative (1 ^ 0 = 1). Thus the new a will be positive (x<<1) and the new b will be negative (y).
Now: arbitrary-precision negative integers actually have an infinite number of leading 1 bits, at least mathematicallly. So a is a larger and larger positive number, expanding by 2 each iteration. b keeps getting more and more leading 1 bits added to be able to carry out the bitwise & and ^ with a. Thus whatever bits of a are turned on line up with one of the added 1 bits of b, so a & b is always true, so the loop runs forever.
I faced the same problem.
More precise: you get infinity loop only when one number positive, another negative AND positive >= abs(negative).
As #cvx said it works so because of extra carry bit - another languages ignore overflows, but python adds this additional 1 to number and it become more and more and b never become zero.
So the solution is to use mask: lets ignore this additional bit:
def getSum(a: int, b: int) -> int:
mask = 0xffffffff
while b&mask > 0:
carry = a & b
cur_sum = a ^ b
a = cur_sum
b = carry << 1
return a&mask if b>0 else a
Also the last line is important! As python adds such 1 to a also, and python thinks about it like a negative value. We should skip those bits and get only last part of the a as positive number.
More information here: https://leetcode.com/problems/sum-of-two-integers/discuss/489210/Read-this-if-you-want-to-learn-about-masks
I'm guessing that this is a homework question, so I don't want to just give you a function that works --- you'll learn more by struggling with it.
The issue stems from the way that negative integers are stored. For illustration purposes, let's pretend that you're dealing with 4-bit signed integers (instead of 32-bit signed integers, or whatever). The number +1 is 0001. The number -1 is 1111. You should be able to sit down with a pen and paper and manually run your function using these two numbers. The answer, of course, should be 0000, but I think you'll discover what's going wrong with your code by working this simplified case with a pen and paper.
I am trying to make a code that does the following:
Multiplying the digits of an integer and continuing the process gives
the surprising result that the sequence of products always arrives at
a single-digit number.
For example:
715 -> 35 -> 15 -> 5
88 -> 64 -> 24 -> 8
27 -> 14 -> 4
The number of products necessary to reach the single-digit
number is called the persistence number of that integer. Thus 715
and 88 have a persistence number of 3, while 27 has persistence 2.
Make a program to find the only two-digit number with persistence
greater than 3?
I was able to come up with a rough idea and the code is below but it doesn't seem to work:
num2=0
num3=0
num4=0
num=input("what is your number?")
while num in range(10,100):
print 'step1'
num1=num%10*num/10
if num1-10>10:
print 'step2'
num2=num1%10*num1/10
elif num2-num1>10:
print 'step3'
num3=num2%10*num2/10
elif num3-num2>10:
print 'step4'
num4=num3%10*num3/10
elif num4-num3>10:
print 'step5'
print num4
else:
break
The program is Python and I simply can't figure this out. If someone could possibly help me I would appreciate it greatly!
You should use a while or for loop to multiply the digits instead of hardcoding what to do with the first, second and so on digits.
In pseudocode...
productSoFar = 1
digitsLeftToMultipy = #the number
while there are digits left to multiply:
get the next digit and
update produtsSoFar and digitsLeftToMultiply
Also, use
10 <= n < 100
instead of
n in range(10, 100)
So you only do a couple of comparisons instead of a sequential lookup that takes time proportional to the length of the range.
Functions are friends.
Consider a function, getEnds(x), which when passed an integer, x will extract the first digit and the last digit (as integers) and return the result as a tuple in the form (first_digit, last_digit). If x is a single-digit number the tuple will contain one element and be in the form (x), otherwise it will be two. (A simple way to do this is to turn the number into a string, extract the first/last digit as a string, and then convert said strings back into numbers... however, there are many ways: just make sure to honor the function contract, as stated above and -- hopefully -- in the function documentation.)
Then, where n is the current number we are finding the persistence for:
ends = getEnds(n)
while ends contains two elements
n = first element of ends times second element of ends
ends = getEnds(n)
# while terminates when ends contained only one element
# now it's only a matter of "counting" the persistence
For added points, make sure this is in a -- [an] appropriately named/documented -- function as well and consider the use of a recursive function instead of a while-loop.
Happy coding.
If you're trying to get the digits of a number, convert it into a string first and reference them with array notation.