I am a beginner in coding and I've been learning python just lately.
I tried to do some recursion exercises, my codes run most of the time but there is one thing that is worrying me.
My code is always longer than the one in the solution.
Take this exercise for example
(Write a Python program to get the sum of a non-negative integer.Test Data:sumDigits(345) -> 12sumDigits(45) -> 9)
My answer is this
def sum_num(n,sum1=0):
k=int(n)
if k%10==k:
return sum1+k
else:
sum1+=k%10
k=k//10
return(sum_num(k,sum1))
print(sum_num(2384))
and the solution is this
def sumDigits(n):
if n == 0:
return 0
else:
return n % 10 + sumDigits(int(n / 10))
print(sumDigits(345))
print(sumDigits(45))
print(sumDigits(345))
print(sumDigits(45))
My code run perfectly but it's just longer. My question is 'is it okay to have a long code, if not how can I learn to shorten it'.
Thank you
Well, writing shorter and cleaner code is good practice because when you have long code thats hard to read its going to be harder for you and especially oher people to work with it, and troubleshooting can be really difficult. Think simple and try to write it as clean as it could possibly be. There isnt really a way to LEARN it but practice and studying and just trying to think simple should help.
Related
Essentially I'm just wondering if there's any way to make this code more concise. I don't even really know how to properly ask the question, but is there a module or expression I could write or import to help?
while True:
try:
guess = int(input("Enter a number here: "))
break
except:
print("Please try again.")
In free language it would probably look like:
test:
dothing("user thing")
if issues:
print("try again")
try again
I'm trying to prevent an error from the user typing something like a string and breaking the entire program. If this seems stupid, I apologize; I'm starting to get into Python again after what is essentially years of not using it and I'm probably forgetting something simple.
Thank you guys so much in advance.
Your natural language remembers me old unstructured languages like Fortran 4 or old basics...
In those languages, we used to go to line references:
100 CALL INPUTVAL(IVAL, IERR)
IF IERR == 0 GOTO 200
PRINT 50
50 FORMAT('ERROR TRY AGAIN')
GOTO 100
200 CONTINUE
It may look more natural at first sight, but it soon leads to spaghetti code. That's the reason why clean loops and strutured error handling (try except) were invented. Don't regret the old goto style and stick to standard structured constructs
I'm currently writing a simulation in python 3.4 (miniconda).
The entire simulation is quite fast but the measurement of some simulation data is bloody slow and takes about 35% of the entire simulation time. I hope I can increase the performance of the entire simulation if I could get rid of that bottleneck. I spend quite some time to figure out how to do that but unfortunately with little success. The function MeasureValues is called in every period of the simulation run.
If anybody has an idea how to improve the code, I would be really grateful.
Thank you guys.
def MeasureValues(self, CurrentPeriod):
if CurrentPeriod > self.WarmUp:
self.ValueOne[CurrentPeriod] = self.FixedValueOne if self.Futurevalue[CurrentPeriod + self.Reload] > 0 else 0
self.ValueTwo[CurrentPeriod] = self.VarValueTwo * self.AmountValueTwo[CurrentPeriod]
self.ValueThree[CurrentPeriod] = self.VarValueThree * self.AmountValueThree[CurrentPeriod]
self.SumOfValues[CurrentPeriod] = self.ValueOne[CurrentPeriod] + self.ValueTwo[CurrentPeriod] + self.ValueThree[CurrentPeriod]
self.TotalSumOfValues += self.SumOfValues[CurrentPeriod]
self.HelperSumValueFour += self.ValueFour[CurrentPeriod]
self.HelperSumValueTwo += self.AmountValueTwo[CurrentPeriod]
self.HelperSumValueFive += self.ValueFive[CurrentPeriod]
self.RatioOne[CurrentPeriod] = (1 - (self.HelperSumValueFour / self.HelperSumValueFive )) if self.HelperSumValueFive > 0 else 1
self.RatioTwo[CurrentPeriod] = (1 - (self.HelperSumValueTwo / self.HelperSumValueFive )) if self.HelperSumValueFive > 0 else 1
The code looks basic enough that there aren't any obvious gaps for optimisation without substantial restructuring (which I don't know enough about your overall architecture to suggest).
Try installing cython - I believe nowadays you can install it with pip install cython - then use it to see if you can speed up your code any.
As stated in the comments the function is quite simple, and with the provided code I don't see a way to optimize it directly.
You can try different approaches:
PyPy, this may works depending on your current codebase and external dependecies.
Cython as suggested by holdenweb, but you need to redefine a lot of stuff to be static-typed (using cdef) or nothing will change.
rewrite the function in C as a Python extension, this may take some time, especially if you have no experience in C programming.
The PyPy way seems the most reasonable, if it works you will gain a boost for all the simulations code.
I already read the other questions and answers but couldn't implement any of the solutions to my code. I'm still clueless about the reason why this code gives a runtime error.
I'm trying to submit the code on CodeChef, yet it gives the Runtime Error(NZEC), although the code runs flawlessly on my console for some inputs. Here's my code:
def GetSquares(base):
if not base or base < 4:
return 0
else:
x = (base - 4) - (base % 2) + 1
return x + GetSquares(base - 4)
num_test = int(input())
for test in range(num_test):
base = int(input())
print (int(GetSquares(base)))
Codechef's explanation for NZEC:
NZEC stands for Non Zero Exit Code. For C users, this will be
generated if your main method does not have a return 0; statement.
Other languages like Java/C++ could generate this error if they throw
an exception.
The problem I'm trying to solve:
https://www.codechef.com/problems/TRISQ
The problem description says that the input is constrained to be < 10^4. That's 10,000! Your code will need to make 10,000/4 = 2500 recursive calls to GetSquares, that's a lot! In fact, it's so much that it's going to give you, fittingly, this error:
RuntimeError: maximum recursion depth exceeded
You're going to have to think of a better way to solve the problem that doesn't involve so much recursion! Because you're doing this coding challenge, I'm not going to give a solution in this answer as that would sort of defeat the purpose, but if you'd like some prodding towards an answer, feel free to ask.
The question puts a constraint on the value of 'B' which is 10000 at max, which means there are a lot of recursive calls and giving a runtime error. Try solving using iteration.
This sounds like it should be blindingly obvious but there's something quirky going on.
So I have two scripts. Largely the same but a few variances here and there. They both run big loops and they both use global variables. Yes, I know this is bad. Tidying it up is on my to do list but I'm on a time constraint at the moment.
One script works fine. As expected.
The other works fine... for the most part. Then it bugs out once it iterates through the loop again. It's very strange because the code has very little differences but I did pick up on something which I can't explain.
The variable I use to track my position in the loop is set like this in script 1 (which works flawlessly):
global CurrentMatchScan
while True:
print "=Starting Loop="
Loopcounter = 0
CurrentMatchScan = -1
LoadMatch()
The second script has:
global CurrentMatchScan
while True:
print "=Starting Loop="
Loopcounter = 0
CurrentMatchScan = -1
LoadMatch()
However in the second script PyCharm highlights the = -1 part as
Redclared'CurrentMatchScan' defined above without usage
So the obvious assumption is something further up in the code is using it. I do call a function later on which is placed up there...
def LoadMatch():
nextbox1 = LinkList[CurrentMatchScan + 1]
nextbox2 = LinkList[CurrentMatchScan + 2]
But this is only called once CurrentMatchScan is set... and the first script has the exact same code.
Is my IDE just not noticing it on the other script or something? There's a pretty big issue with the looping on the second one and this is the only difference I can see between the two.
I know this doesn't look like a lot to go on but there's not much else to it that I can see. It's barely actually referenced.
I'd really appreciate anyone who can point out how much of an idiot I'm being and missing something really simple.
/edit:
Based on the fact that it does use CurrentMatchScan and calls LoadMatch() for the first iterations properly I'm starting to doubt this is anything but PyCharm trying to warn me I'm potentially doing something silly.
I think if this was the issue it wouldn't work at all so the warning might be a bit of a red herring when it comes to the issue I'm actually facing.
I have been stuck on this problem for quite awhile now. I am just learning how to code and recursive statements just do not make much sense to me. In my programming class, I was told to make a recursive insertion sort program, and I did, but it will not be accepted because I do not know what the function is doing and how it is changing the list so that it is sorted. So I have two questions that I'll address separately with pretty much the exact same code.
The first question I have about my code is, as mentioned before, how does it work?
numList = [2,4,1,3,5]
def insertionSort(i, numList):
if i > 0:
insertionSort(i-1, numList)
if numList[i] < numList[i-1]:
numList[i], numList[i-1] = numList[i-1],numList[i]
insertionSort(i-1, numList)
insertionSort(4,numList)
print(numList)
I'm calling the function twice and I have no clue why that works. I would think the call the the function before the if statement would have it work, but it does not.
And that leads me into my other question.
How would I make this code:
numList = [2,4,1,3,5]
def insertionSort(i, numList):
if i > 0:
insertionSort(i-1, numList)
if numList[i] < numList[i-1]:
numList[i], numList[i-1] = numList[i-1],numList[i]
insertionSort(4,numList)
print(numList)
work?
My professor said that the code is basically there but there is something that I need to either change or add in order for it to work correctly.
Thank you.