defrev(val):ifval<10:returnvalelse: expon=int(math.log10(val)) ival=val%10 dval=val/10returnint(ival*math.pow(10,expon))+rev(dval)

But today i tryed to make another, shorter solution. It has nothing todo with math. Actually i just take an int variable, convert it into string, reverse it, and convert it back into int. Really simple and it also works flawless:

defstrrev(sval):iflen(str(sval))==1:returnsvalelse: strcon=str(sval)returnint(strcon[::-1])

Now i'm wondering which function would be better and for what reason. I made some benchmarks and found out that the second solution is about 25% faster than the first one, but i just stoped these two version with "

*time*". I think it's not good enough to take is as a benchmark. Besides that, i don't know anything about memory consumption. Anyway, i'll keep the second, since it's faster...If someone wants to try it out, i've uploaded both "benchmark" script's. The scirpt generates every number from 1 to 100000, reverses every number and subtracts every number with it's reversed version.

Download: Link

شكرا لك واضيفلك اني كود اخر وسهل

ReplyDeletedef reverse(strorint):

if type(strorint) == str:

return strorint[::-1]

else:

return int(str(strorint)[::-1])

اي هذا الكود الكود يعكس ال str and int

Deleteالارقام والكلمات

Try a negative number... -345

ReplyDelete