If elif else construct and full DRY conform [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
first of all I am sorry for the bad title but I didn't know what would be appropriate. I am looking for a better syntax for the following block so that I am not repeating myself.
self.rulerMajorTickLabel and self.rulerMinorTickLabel can either be True or False
self.rulerMajorTickWidth and self.rulerMinorTickWidth can only be a positive float
if self.rulerMajorTickLabel and self.rulerMinorTickLabel:
if self.rulerMajorTickWidth > self.rulerMinorTickWidth:
halfTickHeight = self.rulerMajorTickWidth / 2
else:
halfTickHeight = self.rulerMinorTickWidth / 2
elif self.rulerMajorTickLabel:
halfTickHeight = self.rulerMajorTickWidth / 2
elif self.rulerMinorTickLabel:
halfTickHeight = self.rulerMinorTickWidth / 2
else:
halfTickHeight = 0
Thanks you very!

Assuming a few things here to make it work elegantly, so you might want to make sure of that somewhere else in the code. My assumptions:
self.rulerMajorTickWidth and self.rulerMinorTickWidth are either a positive number, or equal to zero
They are both defined as attributes and looking for them will not throw an error
You want just the larger of the two to divide by 2
Assuming all that, you can simply do:
halfTickHeight = max(self.rulerMajorTickWidth, self.rulerMinorTickWidth) / 2
If their "false" value however is either None or undefined, it's more complicated. That's why I suggest making sure in other places in the code that it's either 0 or an integer/float. If they are actually the boolean False you can float() them to equal 0
Edit: Because I just noticed the labels are different than the width parts, you can still preform all of your checks more easily by doing this:
tmpMajor = self.rulerMajorTickWidth if self.rulerMajorTickLabel else 0
tmpMinor = self.rulerMinorTickWidth if self.rulerMinorTickLabel else 0
halfTickHeight = max(tmpMajor, tmpMinor) / 2
Which is equivalent to all your if...elif...else clauses from before

Related

input function : python [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 5 months ago.
Improve this question
counttonum = 1
countnum = input("[•] Provide A Number :")
while counttonum < countnum:
print("[", counttonum, "] : Number = ", counttonum)
counttonum +=1
I was trying to make a counting tool that counts up to the provided number from the “input()” function.
For example:
providedNumberFromInput = 5
output = 1
2
3
4
5
And it’ll stop if the provided number is reached. Please help me.
You are very close to solution. Problem is that input() returns value as string so you will need to convert it. And also if you want to include entered number use <= instead of <
while counttonum <= int(countnum):

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.

Why 0.123456789 == 12.3456789 / 100 is True? [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 last year.
Improve this question
I know the floating point issues and I've read some documentations and have some understanding on Decimal type.
For example: .1 + .1 + .1 != .3 .
But why:
>>> 0.123456789 == 12.3456789 / 100
True
is True ? I expected False.
Because adding is inaccurate so I think division should also be inaccurate?
Not really an answer, but too long for the comments:
To explore this phenomenon, I wrote a simple program:
import random
def f(a,b,n):
x = random.uniform(a,b)
y = n*x
return x,y,x == y/n
Then for example
trials = [f(0,100,100) for _ in range(10000)]
print(len([x for x,y,t in trials if t])/10000)
prints values like 0.8634
I have tried a number of values for a,b,n, with == holding typically in the range 80% to 90%. A strange observation which confuses me:
f(0,100,100000000)
is much more likely to give rise to a counterexample than either
f(0,100,10000000)
or
f(0,100,10000000000)
I would have thought that for a,b fixed, the probability of x==y is monotonic in n, but it apparently isn't.

Python How to get a integer using the ord function? [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
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.

Python breaking filter running after filnd the answer [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 5 years ago.
Improve this question
Can I stop filter if it find the answer?, For example it find the number 10.
example:
filter(lambda num:num == 10,range(20))
Here's an example of stopping an iteration early using filter by setting a global flag that causes the filter function to raise StopIteration:
def my_filter(n):
""" filter for odd numbers """
if my_flag:
raise StopIteration
return n % 2 == 1
my_flag = False
for my_number in filter(my_filter, range(1, 22)):
print(my_number)
if my_number % 13 == 0:
my_flag = True
OUTPUT
> python3 test.py
1
3
5
7
9
11
13
>
Is this what you have in mind? But, of course, most people would simply do:
if my_number % 13 == 0:
break
So you must have some specific scenario in mind. (Hopefully something more than, "Because I want it to be a one line comprehension.")

Categories