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 1 year ago.
Improve this question
I've just started python and am stuck on this assignment where i need to create a function that does the following:
rectangle("ab", 3)
#output:
aba
bab
aba
where 3 is the length and height of the 'rectangle' and "ab" is the string used to draw the rectangle. It should be able to work with any string.
another example would be this :
rectangle("aybabtu", 5)
#output:
aybab
tuayb
abtua
ybabt
uayba
I'd would like to see the model answer to better understand the steps needed to create functions like this in the future, but that is only possible after completing the assignment. Thanks in advance!
Edit: Sorry for not posting my own code, i was kind of self concious and frustrated and scrapped it all, and its my first time asking a question. I will not repeat this mistake again
First I would create long string with repeated text and later I would split it to lines.
I need to calculate how many times repeate text in rectangle - and it has to be rounded up, not rounded down. Then I can use it to create long string - it can be even longer because later I will slice it and it will skip last chars.
After creating long string I can use for-loop to slice it and print only single line.
You may also add line to list and later join lines with '\n' to return string instead of display it.
import math
def rectangle(txt, size):
rect_len = size * size
print('> rect_len:', rect_len)
txt_len = len(txt)
print('> txt_len :', txt_len)
# round up to next int
repeate = math.ceil(rect_len/txt_len)
#repeate = int(rect_len/txt_len) + 1
print('> repeate :', repeate)
long_txt = txt*repeate
print('> long_txt:', long_txt)
for x in range(size):
print(long_txt[:size])
long_txt = long_txt[size:]
# --- main ---
print('---')
rectangle("ab", 3)
print('---')
rectangle("aybabtu", 5)
Result:
> rect_len: 9
> txt_len : 2
> repeate : 5
> long_txt: ababababab
aba
bab
aba
---
> rect_len: 25
> txt_len : 7
> repeate : 4
> long_txt: aybabtuaybabtuaybabtuaybabtu
aybab
tuayb
abtua
ybabt
uayba
Related
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
I am having trouble with my code the main issue is I want to return 1 by using the getEquivalentNumber function but the problem is that when I run the code it gives me the result of -63 is there any way for me to improve the code to get a better result.
print('*' * 50)
user_input = input('Please enter a word. \n'
'-->')
print('*' * 50)
def getEquivalentNumber(_Mychar):
_Mychar = _Mychar.lower()
equivalentNumber = ord(_Mychar) - 96
return equivalentNumber
def computeSumOfCharacters(myWord):
sum = 0
for i in myWord: # apple
sum += getEquivalentNumber(i)
return sum
print(computeSumOfCharacters(user_input))
You define functions with def.
You can get the value of the units digit of a number with number % 10.
You can remove the units digit with number = number // 10.
You can accumulate those digits by starting an accumulator at zero and adding each digit.
You can loop until the number becomes zero.
You can return a value from the function with return.
Apologies if some of that seems too basic but I'm not sure what skill level you're at. That's pretty much the process I'd follow, without giving you the actual code.
The only thing that concerns me is computeSumOfDigits(911) must return a SINGLE digit yet the text after that says 9 + 1 + 1 = 11.
If you are required to further process results that are not a single digit, you can check that before returning and call the same function on the result, something like (pseudo-code):
if accumulator > 9:
return computeSumOfDigits(accumulator)
That would calculate: 9 + 1 + 1 -> 11, 1 + 1 -> 2.
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 4 years ago.
Improve this question
I'm trying to create this kind of output in Python
["k", "kk", "kkk", "kkkk", ...]
["rep", "reprep", "repreprep", ...]
That is a list of n elements, made of the same character (or small group of characters) repeated X times, X being increased by one for each element.
I can't find a way to do this easily, without loops..
Thanks,
Here you have a generator using itertools.count, remember the property of "multiplying" strings in python by a number, where they will be replicated and concatenated nth times, where for example "a"*3 == "aaa" :
import itertools
def genSeq(item):
yield from (item*i for i in itertools.count())
Here you have a live example
repeating_value = "k" #Assign the value which do you want to be repeated
total_times=5 #how many times do you want
expected_list=[repeating_value*i for i in range(1,total_times+1)]
print(expected_list)
character = 'k'
_range = 5
output = [k*x for k in character for x in range(1, _range + 1)]
print(output)
I would multiple my character by a specified number in the range, and then I would simply iterate through the range in a list comprehension. We add 1 to the end of the range in order to get the full range.
Here is your output:
['k', 'kk', 'kkk', 'kkkk', 'kkkkk']
The following is by far the easiest which I have built upon the comment by the user3483203 which eliminates initial empty value.
var = 'rep'
list = [var * i for i in range(1,x,1)]
print(list)
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 6 years ago.
Improve this question
need help with taking inputs in a a loop like so.
example = input("enter the example !")
Then I need to add that input to one single variable and later print it all out
on separate lines EG:
loop cycle 1:
enter the example ! test1
loop cycle 2:
enter the example ! test2
loop cycle 3:
enter the example ! test3
inputs:
1. test1
2. test2
3. test3
One thing is that I am unable to use .append due to using lists in my case is
not in max efficiency. (probably will need to be taught to use \n)
you can append new line character to input function
for python2.
example = ""
for i in range(1,4):
example = example + str(i)+". " +raw_input("enter the example !") +"\n"
print example
for python3
example = ""
for i in range(1,4):
example = example + str(i)+". " +input("enter the example !") +"\n"
print (example)
output
messi#messi-Hi-Fi-B85S3:~/Desktop/soc$ python sample.py
enter the example !text 1
enter the example !text 2
enter the example !text 2
1. text 1
2. text 2
3. text 2
You can append the additional inputs onto the same string using the += operator
You will however need to declare the variable before using += for the first time
For example:
example = ""
for num in range(1,4):
print "loop cycle {}:".format(num)
example += "{}. {}".format(num, input("enter the example !"))
if num < 3:
example += "\n"
print example
edit: updated to include conditional new lines and input numbers
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 6 years ago.
Improve this question
So I need to count individual words (specifically red and blue) in a python inputted list.
However, it cannot be for instance redish or bluemaybe.
Here's what I've done (I've tried if loops to catch it but hasn't worked.)
r = 0
b = 0
cars = []
car = input("Cars: ")
cars.append(car)
car.split()
r = car.count('red')
b = car.count('blue')
print("red:",r)
print("blue:",b)
The following works.
# replace by 'carsStr = input("Cars: ")' if you wish
carsStr = "rad blue blueish redish red blue red"
# str.split() returns a list of strings, never in-place
cars = carsStr.split()
r = cars.count('red')
b = cars.count('blue')
print("red:",r)
print("blue:",b)
Here are your mistakes:
Doing cars.append(car) and then car.split() doesn't "expand" the car string in the cars list.
car.split() doesn't happen in-place, it returns a list of strings. In your case, that list is lost since you don't assign it to a variable.
You also never reuse the cars list.
If you wan't a more complete counting tool see https://docs.python.org/3/library/collections.html#counter-objects.
You can make a loop to iterate through the list then return your values
Split and append aren't necessary. When faced with a coding problem, try to find the simplest answer and the most concise without sacrificing any substance.
for words in cars:
cars.count('red', 'blue')
return whatever_you_want
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Write a while loop that sums the values 1 through end, inclusive. end is a variable that we define for you. So, for example, if we define end to be 6, your code should print out the result:
21
which is 1 + 2 + 3 + 4 + 5 + 6.
Is anybody able to guide me through this, without spoiling it for me?
There are two things you can do. The "fast" way (a la the story about the young Gauss) recognizes that
sum(1:N) = N * (N + 1) / 2
But I doubt that is what is asked.
You need to create a loop (look at the for command) over a range (look at the range command), and in each iteration add the current value of the loop variable to the sum (which you initialize to zero before the start of the loop).
There - you should now be OK.
EDIT with a while loop, and still leaving you to do a little bit of work:
mySum = 0
i = 1;
while( <<< put some condition here >>> ):
mySum = mySum + i
<<<<< do something clever with i >>>>>
print <<<<< what do you think you should print here? >>>>>
Note that indentation is important in Python, and the : at the end of the while statement matters