Python How to get a integer using the ord function? [closed] - python

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.

Related

Sum of digit of a number using recursion in python [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 6 months ago.
Improve this question
Here in this program, I tried to understand but couldn't get completely.
How is this recursive function doing the sum and returning total sum of this? Please explain me in detail?
# Recursive Python3 program to
# find sum of digits of a number
# Function to check sum of
# digit using recursion
def sum_of_digit( n ):
if n < 10:
return n
return (n % 10 + sum_of_digit(n // 10)) # how this is working ?
num = 12345
result = sum_of_digit(num)
print("Sum of digits in",num,"is", result)
The best way to understand a recursive function is to dry run it.
First you need to understand what n % 10 mean is. this means the remainder of a n when divided by 10.
In this case when we divide 12345 by 10 , we get 5 as remainder.
so n % 10 part of code becomes 5.
Now, the second part is n//10 which gives you 1234 that are remaining digits.
Applying the same function again will give you 4 + sum_of_digit(123) and so on.
Even if this do not clear your confusion try, running this code on paper with some small number.

What to do for this loop? Write code that assigns the average of the numbers from 1 to n (where n is a positive integer value) to the variable avg [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
Write code that assigns the average of the numbers from 1 to n (where n is a positive integer value) to the variable avg. The answer is specifically asking for a for loop but idk how to start it off. Does it have to be a for x in range... or is it something else. plz help I'm just starting my first programming class and idk what to do.
I tried to enter avg = (1+n)/2 but its not excepting that and with the lesson being on for loops I'd assume I would need to make a for loop.
I think this solves your problem, although you should try to understand what is going on so you may apply your learning in the future.
Here's what I wrote:
n=int(input("Enter number: "))
avg=sum([x for x in range(1,n+1)])/len(range(1,n+1))
print(avg)
This takes input in line 1, sums all the numbers between 1 and n in line 2, and prints out the value in line 3.
To break it down: line 1 takes input. the int statement makes it into a number rather than a string, which is what normally comes out of an input.
Line 2:
This line is where the for loop comes in. I have compacted mine into a generator statement, but thats not absolutely necessary. First, the generator statement puts all the numbers 1 to n into a list. It then sums up all of the variables in the list, and assigns it to avg.
This is what it would look like uncompacted:
list_var=[]
for x in range(0,n+1): # Range returns numbers between the min and max, but not including the max. Therefore, put a +1 afterwards to ensure it includes the max.
list_var.append(x) # put the variable in the list
sum_of=sum(list_var) #sum returns the sum of all the items in the list.
avg=sum_of/len(range(1,n+1) #avg is the average (1-n)/length (which is the length of the range)
Finally, the print statement logs it to the console.
print(avg)
Ta-da
That python explanation helped clear things up more than my chapter. Ty!
total = 0
for i in range (1,n+1):
total+=i
avg = float(total)/n

rectangle function using a string [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 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

Can anybody tell me what d = d+1 and l = l+1 do in this code what its uses in this code? [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
In this code first it take d=0 and l = 0 and then it write d=d+1 and l=l+1 do in this code what its uses in this code ? ]1
In this code first it take d=0 and l = 0 and then it write d=d+1 and l=l+1 do in this code what its uses in this code ?
Go through it line by line - first you run a loop where each character of the input is sequentially represented as i.
Now, for each i, if i is a digit, you increase the count of d - using d=d+1.Otherwise (elif) if i is an alphabet, you increase the count of l - using l=l+1.
This way you're storing the number of digits in the input as d, and the number of letters in the input as l.
Finally, after the loop runs on all character of the input, you print the number of letters and digits respectively using print("letter",l,"digit",d)

What is the most effiecient way to get Factorial Sum? [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 4 years ago.
Improve this question
The code is to find the factorial of each individual value in an array and then find the sum of them together .An example would be [1,2,3,4], which will then be 1!+2!++3!+4!=33.A single integer equal to the desired sum, reduced modulo . The issue is that when it comes on to large numbers(just my assumption) it results in "Terminated due to timeout" status
At first I used a for loop to go through each value in the array. Thinking that it may be a search issue I used for in range to ensure it has a set range. Sadly that still hasn't solved the problem. I now assume that it has to be a problem with factorial since multiplication is
def factModSum(arr):
sum=0
for i in range (0,len(arr)):
sum=sum+factorial(arr[i])
return sum%(10**9)
Example 1:
Input: 1 2 3 4
output: 33
Expected output: 33
Example 2:
Input:2 3 5 7
Output:5168
Expected output: 33
Example 3:
Input:12 13 14
Output:884313600
Expected output: 33
At the core of it at the function works. But Im getting timeout error for some of my Test case , therefore assuming that the code is not able to process large numbers in a given time
If you are modding by 10 ** 9 you can try this:
def factModSum(arr):
return sum(factorial(i) for i in arr if i < 40) % 10**9
This is because n! with n >= 40 is congruent to 0 mod 10**9.

Categories