I need to write a function "alphabet" that takes a string (n), and counts up and then down in the alphabet. I tried to solve it, but I could only write the code where it counts down and then up in integers. Somehow, these integers are supposed to represent a letter. I know that I should use char() and ord(), but I don't know how. Here is what I've done so far:
letter= ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''t''u''v''w''x''y''z']
numbers = ['1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24']
index=0
def alphabet('n')
while index < len(letter):
print(count[index], end=' ')
for n in range(0,count[index]):
print(line[index]-numbers,end='')
print()
index = index + 1
for n in range(0,count[index]):
print(line[index]+1,end='')
print()
index = index + numbers
I am aware that this is wrong, but a little guidance would be nice :)
I think ord() gives back the ascii code in consecutive order, for instance ord('a') gives 97 and ord('b') 98 and so on, i would work on converting one from another and adding +1 in each loop
Related
#card number
card = input('Number: ')
j = int(card[::2]) # this will jump character by 1
# multiplying each other number by 2
j *= 2
print(j)
So whenever I run this code and input e.g. 1230404
The output would be correct which is 2688
But when I input for example 1230909 the output is 2798, I expected 261818
Let's look at what your code is doing.
You slice every second character from your input string, so '1230909' becomes '1399'.
You convert that to a single int, 1399.
You multiply that number by 2, producing 2798. I assure you that the computer did the math correctly.
It appears what you expected was for each digit to be doubled individually. To do that, you need to convert each digit, double it, and combine them back. Python has great facilities for this, I'd suggest a generator expression inside a join call.
Trying to generate a certain length credit card number with a prefix given.
while len(str(cc_number)) < (len(str(length)) - 1):
digit = str(random.randrange(0, 9))
cc_number = str(cc_number) + str((digit))
return cc_number
I'm expecting to get say 16 digits long number with a variable size prefix given. How do i make this piece of code generate a right size string of numbers? This code by the way only concatenates 1 random digit to the end of the string... So i expect to get '4349578451278456', but the actual output is '41'
If length is 16, str(length) will give you the string '16' which has a len of 2. Just use length without len or str.
Beyond that, your return statement should be outside of the loop
Since you're already using the random module, I just want to offer an alternative solution:
from random import choices
from string import digits
cc_digits = choices(digits, k=16)
cc_number = "".join(cc_digits)
print(cc_number)
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've spent the last two days trying to figure out how to increment a numeric string in Python. I am trying to increment a sequence number when a record is created. I spent all day yesterday trying to do this as an Integer, and it works fine, but I could never get database to store leading zeros. I did extensive research on this topic in StackOverflow, and while there are several examples of how to do this as an Integer and store leading zeros, none of the examples worked for me. Many of the examples were from 2014, so perhaps the methodology has changed. I then switched over to a String and changed my attribute to a CharField, and can get the function to work with leading zeros, but now I can't seem to get it to increment. Again, the examples that I found on SO were from 2014, so maybe things have changed a bit. Here is the function that works, but every time I call it, it doesn't increment. It just returns 00000001. I'm sure it's something simple I'm not doing, but I'm out of ideas. Thanks in advance for your help. Here is the function that works but doesn't increment.
def getNextSeqNo(self):
x = str(int(self.request_number) + 1)
self.request_number = str(x).zfill(8)
return self.request_number
Here is the field as it's defined:
request_number = models.CharField(editable=True,null=True,max_length=254,default="00000")
I added a default of "00000" as the system is giving me the following error if it is not present:
int() argument must be a string, a bytes-like object or a number, not 'NoneType'
I realize the code I have is basically incrementing my default by 1, which is why I'm always getting 00000001 as my sequence number. Can't seem to figure out how to get the current number and then increment by 1. Any help is appreciated.
A times ago I made something similar
You have to convert your string to int and then you must to get its length and then you have to calculate the number of zeros that you need
code = "00000"
code = str(int(code) + 1 )
code_length = len(code)
if code_length < 5: # number five is the max length of your code
code = "0" * (5 - code_length) + code
print(code)
Can this be done? Yes. But don't do it.
Make it an integer.
Incrementing is then trivial - automatic if you make this the primary key. For searching, you convert the string to an integer and search the integer - that way you don't have to worry how many leading zeros were actually included as they will all be ignored. Otherwise you will have a problem if you use 6 digits and the user can't remember and puts in 6 0's + the number and then doesn't get a match.
For those who want to just increase the last number in a string.
Import re
a1 = 'name 1'
num0_m = re.search(r'\d+', str(a1))
if num0_m:
rx = r'(?<!\d){}(?!\d)'.format(num0_m.group())
print(re.sub(rx, lambda x: str(int(x.group()) + 1), a1))
number = int('00000150')
('0'*7 + str(number+1))[-8:]
This takes any number, adds 1, concatenates/joins it to a string of several (at least 7 in your case) zeros, and then slices to return the last 8 characters.
IMHO simpler and more elegant than measuring length and working out how many zeros to add.
I'm learning to program using the book "Introduction to computation and programming using Python" by John V. Guttag. There is an exercise on it that says the following:
'Finger exercise: Let s be a string that contains a sequence of
decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write
a program that prints the sum of the numbers in s.'
My try was:
#Finger exercise [MIT] PAGE 42 12:50 | 11.10.2015
s = ','+raw_input('Enter a string that contains a sequence of decimal numbers separated by commas, e.g. 1.23,2.4,3.123): ')+','
total = 0
for l in range(0,len(s)):
if s[l] == ',':
c = l + 1
while s[c] != ',':
c = c + 1
if s[c] == ',':
total = total + int(s[int(l),int(c)])
print total
but it keeps showing this error
TypeError: string indices must be integers, not tuple
I've tried to seek solutions online but only found solutions that work but not with the content I already now.
Any help?
You are creating a tuple when accessing your string item here:
s[int(l),int(c)]
Commas generally create tuples.
Instead, you want to use a slice here using a colon:
s[int(l):int(c)]
Note that both variables are already integers, so you don't actually need to convert them:
s[l:c]
Also note that you are summing integer values although you accept floats as the input. So instead of adding int(s[l:c]) you want to add float(s[l:c]).
First of all, there is no processing of anything before the first comma.
Next, you should comment each part of it at least initially to you are clear what each line is doing.
You shouldn't need to check for a ',' in multiple places, keep a variable.
A solution I found, hope its useful:
s = "1.23, 2.4, 3.123"
news = s.split(",")
total = 0
for string in range(len(news)):
total += float(news[string])
print(total)