Print a character 1-15 times [closed] - python

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 5 years ago.
Improve this question
I need to find a way to print a number/letter 1 - 15 total times, I'll have to rinse/repeat for the entire alphabet.
aaaaaaaaaaaaaaa
aaaaaaaaaaaaaa
aaaaaaaaaaaaa
aaaaaaaaaaaa
aaaaaaaaaaa
aaaaaaaaaa
aaaaaaaaa
aaaaaaaa
aaaaaaa
aaaaaa
aaaaa
aaaa
aaa
aa
a

The most straight up way is to create the string containing 1 - 15 of the same character, and then print it. For this, use the fact that strs can be multiplied by ints like so:
print('a'*15)

Another hint you're probably looking for:
You can use ASCII/Unicode numbers to generate the alphabet like so:
>>> ord('a')
97
>>> ord('z')
122
>>> chr(97)
a
>>> chr(122)
z
so:
>>> print(','.join([chr(_) for _ in range(97,123)]))
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z
Note that we make the end of the range 123 because for range(start, stop [,step]): For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.
For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints are i >= 0 and r[i] > stop.
So what you can do, putting it together with jmd_dk's answer is something like:
for i in range(97,123):
for j in range(15, 0, -1):
print(chr(i)*j)
Good luck with your homework!

import string
def letters():
alphabet = string.ascii_lowercase
yield from alphabet
for letter in letters():
num = 1
while num <= 15:
print(letter * num)
num += 1

Related

Python code for alphabet after given number [closed]

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 5 months ago.
Improve this question
Input:
D
3
Output:
G
Explanation:
3rd element from D is G in alphabets
And how do you code if the input is x and 4 and I should get the output as b.
Help!!!
You could consider utilizing the modulo operator (%), string.ascii_lowercase, str.islower(), str.isalpha(), str.upper(), and ord():
from string import ascii_lowercase
def shift_letter(c: str, n: int) -> str:
if len(c) != 1:
raise ValueError('c must be a single letter.')
if not c.isalpha():
raise ValueError('c must be a letter.')
current_index = ord(c.lower()) - ord('a')
new_index = (current_index + n) % 26
new_c = ascii_lowercase[new_index]
return new_c if c.islower() else new_c.upper()
def main() -> None:
print(f"shift_letter('D', 3) = {shift_letter('D', 3)}")
print(f"shift_letter('x', 4) = {shift_letter('x', 4)}")
if __name__ == '__main__':
main()
Output:
shift_letter('D', 3) = G
shift_letter('x', 4) = b
You already have ascii_lowercase and ascii_uppercase in string module to use. Using the indexes from these strings and % operator you can shift the character:
from string import ascii_lowercase, ascii_uppercase
def shift_char(char: str, n):
if char.isupper():
idx = ascii_uppercase.index(char)
return ascii_uppercase[(idx + n) % len(ascii_uppercase)]
else:
idx = ascii_lowercase.index(char)
return ascii_lowercase[(idx + n) % len(ascii_lowercase)]
print(shift_char("D", 3))
print(shift_char("x", 4))
output:
G
b
ord and chr string methods are really useful for this problem.
ord gives you the Unicode code for a character:
>>> ord('a')
97
>>> ord('b')
98
>>> ord('A')
65
>>> ord('B')
66
Given the code, chr, will give you the Unicode character
>>> chr(65)
'A'
So to get the 3rd character from 'D', you could do
>>> code = ord('D') + 3
>>> char = chr(code)
>>> print(char)
G
or, as a one-liner
>>> print(chr(ord('D')+3))
G

can you explain how this Loop works and how do we get that output? [closed]

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.
Improve this question
if __name__ == '__main__':
n = int(input())
for i in range (0,n):
result = i**2
print(result)
#input : 5
#output : 0 1 4 9 16
range 0,n = 0,1,2,3,4 and
we gave i**2 but how we got 0,1,4,9,16 as output?
range(start, stop, step)
** = square of Number
start Optional. An integer number specifying at which position to
start. Default is 0
stop Required. An integer number specifying at which position to
stop (not included).
step Optional. An integer number specifying the incrementation. Default is 1
you are passing required parameter as 5 which will not be included in the loop. so as per your calculation it will start from 0
result = 0**2 = 0
result = 1**2 = 1
result = 2**2 = 4
result = 3**2 = 9
result = 4**2 = 16
'i' will not reach 5 because of non-inclusive nature of range() operator.

Create a pyramid of integers in python using nested for loop [closed]

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 1 year ago.
Improve this question
Define a function named print_pyramid(number_of_rows) which takes an integer as a parameter and prints a specific pyramid pattern using numbers. Note: you may assume that the number of rows will always be > 1 and < 10 and you must use a nested for loop.
For example:
Pyramid I'm meant to get
Above is my question and what I need to get, but I am unsure on how to complete it below is my code attempt and my result.
This is my code:
def print_pyramid(number_of_rows):
for row in range(number_of_rows):
for column in range(row, number_of_rows):
print("", end="")
for column in range(row+1):
print(row+1, end="")
for column in range(row, number_of_rows-1):
print(" ", end= "")
for column in range(row+1):
print(row+1, end="")
print()
But my code gives me this:
My result/output
Jared's answer is correct and definitely more elegant, but here's another solution anyway. More beginner friendly hopefully easier to understand at a glance.
def pyramid(number_of_rows):
for i in range(1, number_of_rows + 1):
indent = ' ' * (number_of_rows - i)
row = str(i) * (i * 2 - 1)
print(indent + row)
here is a list comprehension that uses a for loop to generate the pyramid pattern
print_pyramid = lambda x : print("\n".join([(" "*(x-i))+(str(i)*(i*2-1))+(" "*(x-i)) for i in range(1,x+1)]))
print_pyramid(9) gives:
1
222
33333
4444444
555555555
66666666666
7777777777777
888888888888888
99999999999999999
You can define a function to print your pyramid in this way
def pyramid(rows: int) -> str:
if rows < 1 or rows > 9:
raise ValueError
pyramid_string = ""
for i in range(1, rows + 1):
pyramid_string += f" " * (rows - i) + f"{i}" * (i * 2 - 1) + "\n"
return pyramid_string
then call the function
print(pyramid(rows=5))
or you can use a variable to store the result of the function
five_rows_pyramid = pyramid(rows=5)
print(five_rows_pyramid)
output
1
222
33333
4444444
555555555

Length of longest substring with numbers only [closed]

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 3 years ago.
Improve this question
I would like to give as an input a string and to receive as an output the length of the longest substring with numbers only.
However, first of all, I would like to be a bit more flexible on the "substring with numbers only" definition.
Specifically, I would like to do what I want with substrings which consist let's say at least by 70% of numbers (so not necessarily 100%).
Therefore, if I have this sentence:
sentence = 'I am 14 a data 1,a211 899 scientist 1he3'
then the answer should be 10 coming from the substring 1,a211 899 since this substring has 7 out 10 characters (70%) as digits.
It is not (so) necessary to take into the whitespaces so you can remove them from the beginning if this makes things easier for you.
How can I efficiently do this?
With re_pattern.finditer function and specific regex pattern:
import re
sentence_1 = 'I am 99 a data 1,211 scientist'
pat = re.compile(r'\b\d+(?:[.,]\d+)?') # prepared pattern
max_num_len = max(len(m.group()) for m in pat.finditer(sentence_1))
print(max_num_len) # 5
Additional extended approach for updated condition "longest substring which consist let's say at least by 70% of numbers (so not necessarily 100%).":
sentence = 'I am 14 a data 1,a211 899 scientist 1he3'
num_percent = 70
main_pat = re.compile(r'\b\S*\d+\S*(?:\s*\S*\d+\S*){1,}')
nondigits_pat = re.compile(r'\D+') # pattern to match non-digit characters
max_substr_len = 0
for m in main_pat.finditer(sentence):
val = m.group() # matched substring value
val_len = len(val)
if (len(nondigits_pat.sub('', val)) / val_len * 100 >= num_percent) \
and val_len > max_substr_len:
max_substr_len = val_len
print(max_substr_len) # 10
1) This solution does not works for white space, but is more efficient than the other solution(check below):
s = 'I am 14 a data 1,a211 scientist 1he3'
def check(w):
digits = [d for d in w if d.isdigit()]
return len(digits)/len(w) >= 0.6
l = s.split()
result = ''
for w in l:
if check(w):
if len(w) > len(result):
result = w
print(result)
Output:
1,a211
2) If you want also to consider white spaces, you should check every substring for your condition, which is holding not less than 60% of digits:
s1 = 'I am 14 a data 1,a211 scientist 1he3'
s2 = 'I am 14 a data 1,a211 889 scientist 1he3'
#this function is predicate that check if substring hold more then 60% of digits
def check(w):
digits = [d for d in w if d.isdigit()]
return len(digits)/len(w) >= 0.6
def get_max(s):
result = ''
for i in range(len(s)):
for j in range(i+1, len(s)):
#check if the substring is valid and have larger size
if check(s[i:j]):
if (j-i) > len(result):
result = s[i:j]
return result
print(get_max(s1))
print(get_max(s2))
Output:
1,a211
1,a211 889
The last solution has time complexity of O(n^2), while the first one is O(n), where n is the size of the string.
Inspired by #adnanmuttaleb's code. Instead of checking all slices/substrings, just check the ones that start and end with digits. I believe the time complexity (or at least the number of iterations) is: O(n! / (2 * (n - 2)!)) Where 'n' is the number of digits in the original string. This calculation does not take the complexity of itertools.combinations into account.
def get_longest_substring(string):
from itertools import combinations
def is_valid_substring(substring):
return len([char for char in substring if char.isdigit()]) / len(substring) >= 0.7
digit_indecies = [index for index, char in enumerate(string) if char.isdigit()]
substrings = []
for begin, end in combinations(digit_indecies, 2):
substring = string[begin: end+1]
if is_valid_substring(substring):
substrings.append(substring)
return max(substrings, key=len)
def main():
string = "I am 14 a data 1,a211 899 scientist 1he3"
longest_substring = get_longest_substring(string)
print(longest_substring)
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Output:
1,a211 899

Python get range using start, end characters compatible with Excel [closed]

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 7 years ago.
Improve this question
How can I make this work with alpha_range(A, ZZ)?
right now it only work until Z
Code:
def alpha_range(start, stop):
""" Returns chars between start char and stop char(A,D -> A,B,C,D).
:param start: start char
:param stop: stop char
:return: list of chars
"""
return [chr(x) for x in range(ord(start), ord(stop)+1)]
You can easily make a bidirectional mapping between A-ZZ and numbers. This actually is pretty similar to a numeric system with different characters to represent the digits.
BASE = ord('Z') - ord('A') + 1
def to_number(str_input):
res = 0
for letter in str_input:
res = res * BASE + ord(letter) - ord('A') + 1
return res
def to_str(int_input):
res = ''
while int_input > 0:
int_input -= 1
res = res + chr(int_input % BASE + ord('A'))
int_input //= BASE
return res[::-1]
Now you can replace ord and chr with this functions.

Categories

Resources