Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
The community is reviewing whether to reopen this question as of 11 months ago.
Improve this question
Hy,I am newbie in python programming.I am trying to improve my programming skills.I recently joined a code learning platform called code wars for improving my coding skills. The platform is great. I am having trouble reading some code there as I am not a experienced programmer.
Write a function that adds the digits of an integer. For example, the input receives a number: 10023. The result should be - 6 (1 + 0 + 0 + 2 + 3)
For example I found the answer that is rated higher for the above question.
def sum_digits_of(n:int) -> int:
return sum(map(int, str(n)))
SumDigitsOf = sum_digits_of
For the above solution I did not understand '(n:int) -> int' and 'map(int, str(n))'
It's not that I don't know programming but I can't understand the code like above.I know simpler methods for solving this. But how to write and understand much more efficient code. It would be great help if any of you guys suggest how will I get better or is it wise to post the code which I don't understand here [ already tried googling :) ], Cheers!
The code you show “casts” an int to a str, then takes it digit by digit (map applies a function to something iterable, simply put), “casts” each digit back to int and finally sums the digits. (And it is indented incorrectly.)
The final assignment merely creates an alias name for the function, it doens’t “do” anything.
In any case, strings (str) do not have to be necessarily involved:
def sum_digits_of(n, base=10):
result = 0
while n:
result += n % base
n //= base
return result
print(sum_digits_of(123456))
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
I am trying to write a simple function that takes a list of number passed as an argument and prints how many positive number is in the list.
I can't seem to figure out what is wrong with the code here. Can someone please explain this.
You should return add instead of num. And you should initialize add outside the for loop.
lst = [1,2,3,4,-4,-3,-2,-1]
def count_positives(lst):
return sum(i > 0 for i in lst)
print(count_positives(lst))
the program above will print 4
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 11 months ago.
Improve this question
This is my first time posting to Stackoverflow.
I'm trying to solve this problem here: https://codingbat.com/prob/p270692?parent=/home/konstans#stuy.edu/all
When looking at all hailstone sequences from 1 to z, maxHail(z) will return the starting number that creates the longest sequence. In other words, maxHail(n) looks at hailLen(1), hailLen(2) ... hailLen(n) and returns the number from 1-n that had the largest hailstone sequence. You should look at the hailLen() problem before working on this. You should use your solution from the hailLen() problem. ( http://codingbat.com/author/p264289 ) since hailLen(3) is larger than the hailLen of 4 or 5, maxHail of 3,4,5 all return 3. Since 6 has a longer sequence, maxHail(6) gives us 6. remember: Use the hailLen function you already wrote!
Here's my code and the output:
However, I'm not sure where this goes wrong - I checked line-by-line and couldn't see anything wrong. Could anyone help me fix this? Thank you!
I see what is wrong - hailLen returns lenght of sequence and the question is about index for which the sequence is the longest. Just store it in variable
if (res := hailLen(i)) > counter: # it's python 3.8 syntax
counter = res
index = i
return index
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Currently I am learning Python from the book 'The Coders Apprentice' and I have stumbled upon an exercise which I have the feeling that I have nearly solved, but I get an error when I execute the program.
This is the exercise:
Write a program that takes a string and produces a new string that contains the exact characters that the first string contains, but in order of their ASCII-codes.
For instance, the string "Hello, world!" should be turned into " !,Hdellloorw". This is
relatively easy to do with list functions, which will be introduced in a future chapter, but for now try to do it with string manipulation functions alone.
I have added the code below and the error message as a picture.
from pcinput import getString
entString=getString("Enter your string here: ")
yourString=entString.strip()
def positioner(oldPosition):
newPosition=0
x=0
while x<len(yourString):
if ord(yourString[oldPosition])>ord(yourString[x]):
newPosition+=1
x+=1
return newPosition
i=0
y=0
newString=""
while y<len(yourString):
if positioner(i)==y:
newString+=yourString[i]
y+=1
elif positioner(i)<y:
newString+=yourString[i]
if i<len(yourString):
i+=1
else:
i=0
print(newString)
What have I done wrong? I am new to programming.
You are getting an index error because the line if positioner(i)==y: is being called with a value of i equal to the length of yourString. yourString[oldPosition] is then accessing an index which doesn't exist.
This is happening because the loop condition (y<len(yourString)) isn't doing any checking on the value of i, which is the one causing problems.
Some other quick comments:
You can use yourString = input("Enter your string here: ") to replace the first four lines, as I'm not sure what pcinput is - and couldn't find any packages of the same name.
Instead of using the while/x+=1 construct, you could instead use a for x in range(len(yourString)), which is a little neater.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I apologize because I am coming from Perl and I am new to Python.
The following example looks very long to me:
#!/usr/bin/python
import re
r = re.compile('(?i)m(|[ldf])(\d+)')
m = r.match(text)
if m:
print m.group(2)
In Perl for example it is only one line and it's pretty readable.
#!/usr/bin/perl
print $2 if /m(|[ldf])(\d+)/i
How can I rewrite my Python example to be simpler. If possible to be as light as it is with Perl.
I am planning to write plenty tests and if I want to keep my code readable I would like to avoid consuming lines that will not help people to understand my program. I guess that something like this below would be more readable that my first solution:
r = R()
if r.exec('(?i)m(|[ldf])(\d+)', text): print r.group(2)
if r.exec('(?i)k(|[rhe])(\d{2})', text): print r.group(2)
Unfortunately in this case I have to write a class for this.
The Python way values clarity over brevity, so things are generally going to be more verbose than they are in Perl. That said, the re.compile step is optional.
m = re.match('(?i)m(|[ldf])(\d+)', text)
if m:
print m.group(2)
In Python, assignments are not expressions; they can't be used as values. So there's no way to skip the separate assignment statement (m = ...) or combine it with the if . And if you want to refer to the match object later, you do need an explicit assignment - there's no global implicit state analogous to the Perl $n variables that stores the capture groups automatically.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I had to write a script that generates some fixture file with increasing fake MAC addresses.
To do that, I decided to have some fun and try to make it as compact as I could. I ended up with:
def mac_address(i):
return ':'.join(['%02x'] * 6) % tuple([(i >> (8 * j)) & 0xFF for j in reversed(range(6))])
Which actually works pretty well. Obviously, writing this that way is the best way to get slapped by the future person that must work on it, but I did it for the fun (and wrote a more readable version in comment).
But now I'm curious, can you think of any more compact way of writing that ? (That is without removing the spaces).
What about
':'.join('%02x' % (i>>(8*j) & 0xFF) for j in reversed(range(6)))
That is more compact and easier to understand.
def mac_address(i):
return ':'.join(a+b for a, b in zip(*[iter('{:012x}'.format(i))]*2))
The first step is to get a hex string zero filled so that it is exactly 12 digits, which is what '{:012x}'.format(i) does. Then we break that string up in two-character chunks using the method of grouping items from the zip() documentation, and join the result on ':'.
Maybe:
from struct import pack, unpack
def mac_address(i):
return ":".join(["%02x"] * 6) % unpack("BBBBBB", pack("!Q", i)[2:])