#๐Ÿ”’ How do i manage to make my code more efficient?

117 messages ยท Page 1 of 1 (latest)

little vortex
#

Here is the problem
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

Example 1:

Input: x = 2.00000, n = 10
Output: 1024.00000

The code seems to be working but for input such as x =
0.00001
n =
2147483647
I get time exceedded


n = 2.00000
x = 2147483647
if x < 0:
    n = 1 / n
    x = x * (-1)
f=n
h=0
for i in range(x-1):
    n = n*n
    x=x//2
    if x%2!=0:
        h += 1
    if x == 1:
        break

    if x == 0:
        break
for i in range(h):
    n = n*f
h=float(h)
print(n)

This is my second attemp but it doesnt seem to be any better

verbal gullBOT
#

@little vortex

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

ivory sorrel
#

Like x ** n

#

Or I'm understanding it wrong

little vortex
#

becouse the task is not to use it

ivory sorrel
#

Oh

little vortex
#

that's the difficulty

ivory sorrel
#

Well then you can just make a for loop to loop n number of times and multiply it to the original number like so-

def pow(base, pow):
    ans = 1
    for _ in range(pow):
        ans *= base
    return ans
little vortex
#

how would it work negative pow?

ivory sorrel
#

hm

little vortex
#

it seems to be pretty the same but without considering the cases

#

it works but it's not efficient enough to pass the tests

ivory sorrel
#
def pow(base, pow):
    ans = 1
    for _ in range(pow):
        ans *= base
    if pow < 0:
        return 1/ans
    return ans
#

This should work

#

I think

buoyant crest
#

This was on leetcode right

little vortex
#

yes

#

but leetcode accpet the easy way to write x**n

#

but i want to find diffrent way

little vortex
ivory sorrel
#

Oh mb

#
def pow(base, pow):
    ans = 1
    for _ in range(abs(pow)):
        ans *= base
    if pow < 0:
        return 1/ans
    return ans
#

This has to work now

#

!e

def pow(base, pow):
    ans = 1
    for _ in range(abs(pow)):
        ans *= base
    if pow < 0:
        return 1/ans
    return ans
print(pow(2, -1))
verbal gullBOT
#

@ivory sorrel :white_check_mark: Your 3.12 eval job has completed with return code 0.

0.5
ivory sorrel
#

Well it works

#

The abs func just makes the number to positive. And whenever you have a negative exponent it's just basically 1 / b^n (b is base and n is exponent)

#

So we're just doing 1/ans only if the power was passed as negative

thorny valley
#

It works, but it might not pass the time test

little vortex
little vortex
thorny valley
#

I'd say python is just straight up too slow for it

ivory sorrel
#

that's the point of this question

little vortex
little vortex
#

but i think i did sth wrong

#

since 2^4 == (2^2)^2

thorny valley
#

0.00001**2147483647 took 64 seconds with the custom algo (and it gave 0.0 as an answer because float precision)

Using the language implementation took 0.02 seconds, so 320 times faster (it also gave a 0.0 answer, but still)

thorny valley
#

what did you do?

little vortex
#
n = 2.00000
x = 2147483647
if x < 0:
    n = 1 / n
    x = x * (-1)
f=n
h=0
for i in range(x-1):
    n = n*n
    x=x//2
    if x%2!=0:
        h += 1
    if x == 1:
        break

    if x == 0:
        break
for i in range(h):
    n = n*f
h=float(h)
print(n)
verbal gullBOT
#

Hey @little vortex!

It looks like you pasted Python code without syntax highlighting.

Please use syntax highlighting to improve the legibility of your code and make it easier for us to help you.

To do this, use the following method:
```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
You can **edit your original message** to correct your code block.
ivory sorrel
#

I'm not sure but you might have to use bitwise operators maybe and do it but I have no experience in it

thorny valley
little vortex
#

i could consider division with every prime number also

thorny valley
#

because you are multiplying n and dividing x

little vortex
#

yes

#

it was a test in pycharm

thorny valley
#

oh ok

little vortex
#

not the solution wasn't confident it even works

thorny valley
#

i think it's close to working

#
    if x%2!=0:
        h += 1``` The if statement does nothing because you are dividing with //
little vortex
#

it returned infinity when i replaced 0.00001 with 2

#
n = 2
x = 33
if x < 0:
    n = 1 / n
    x = x * (-1)
f=n
h=0
for i in range(x-1):
    n = n*n

    if x%2!=0:
        h += 1
    x = x // 2
    if x == 1:
        break

    if x == 0:
        break
for i in range(h):
    n = n*f
print(h)
h=float(h)
print(n)
thorny valley
#

!e i think this should work:

x = 2
n = 33

while n != 1:
  if n %2!=0:
    n -=1
    x *=n
  else:
    n /=2
    x*=x
print(x)```
#

nope

little vortex
#

is there a way to replace rapidly x and n in pycharm?

thorny valley
#

you can do ctrl+D to select all occurences

#

then change them to something else

little vortex
#

i will try to reproduce the code to leetcode and see the results

thorny valley
#

im don't have the capacity to figure out the algo for this rn, but you're kinda close i think

little vortex
#

you get my idea and what my code does right?

thorny valley
#

yeah

#

i got a working solution

#

do you want me to send it?

#

||py x = 2 n = 33 original_x = x extra_mul = 0 while n != 1: if n %2!=0: n -=1 extra_mul += 1 else: n /=2 x*=x for i in range(extra_mul): x *= original_x print(x)||

little vortex
thorny valley
#

it takes 11 sec for 2**2147483647

#

0.02 for 0.00001**2147483647

thorny valley
#

oh wait but they aren't the same result

little vortex
#

so it isn't working?

thorny valley
#

I think so, i'm running it again to check the difference

#

for 2**33 it works

#

it takes so long to print it wtf im gonna print just the diff between them

#

It's currently converting the diff to a string, in order to print it, when it's done I'll send it here

#

ok so it starts breaking at 2**34

#

!e ```py
x = 2
n = 34
original_x = x
extra_mul = 0
while n != 1:
if n %2!=0:
n -=1
extra_mul += 1
else:
n /=2
x*=x

for i in range(extra_mul):
x *= original_x
other = 2**34
print(x==other)
print(x)
print(f"{other}")
print(f"{other - x}")```

verbal gullBOT
#

@thorny valley :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | False
002 | 8589934592
003 | 17179869184
004 | 8589934592
little vortex
#

i think i don't see the better solution

#

right now

thorny valley
#

I'm honestly not sure why it starts breaking, (why would it work for everything before that???)

#

lemme try something

little vortex
#

I don't see why it wouldn't mathematicly work so i assume it must be sth with code

#
n = 2
x = 10
if x < 0:
    n = 1 / n
    x = x * (-1)
f=n
h=0
for i in range(x-1):
    n = n*n

    if x%2!=0:
        h += 1
    x = x // 2
    if x == 1:
        break

for i in range(h):
    n = n*f
print(h)
h=float(h)
print(n)
#

whis code returns the same for 9 and 10

thorny valley
#

yeah, that's the weird part

little vortex
#

but i don't see the solution

thorny valley
#

yeah it's the extra_mul, because we're not considering x when addingto the power

little vortex
#

it's the fact that 10 //2=4 and 4*2=8

#

so it lack 1 extra multiplication

thorny valley
#

yeah i have a working solution

#

add the current x to a list when we should add to the multiplication in the end, and then in the end loop over the list and multiply x by each item

#

let me just check it works for 2**2147483647

#

yup it does

#

It takes 33 sec though

#
x =2
n = 2147483647
original_x = x
muls = []
while n != 1:
  if n %2!=0:
    n -=1
    muls.append(x)
  else:
    n /=2
    x*=x
for i in muls:
    x *= i```
#

Wait you can just *= mul by the current x, no list needed

little vortex
#

deam that's crazy u have detected that

thorny valley
#

!e py x =2 n = 2147483647 original_x = x mul =1 while n != 1: if n %2!=0: n -=1 mul*=x else: n /=2 x*=x x*=mul print(x)

verbal gullBOT
#

@thorny valley :warning: Your 3.12 eval job timed out or ran out of memory.

[No output]
thorny valley
#

Crap. I'm not at my computer right now, but this should work

little vortex
#

this seemed to be the easy one

thorny valley
#

The simplest ones often have some detail (like optimizing the time) that fuck you up. The other ones once you figure out the trick are easier imo

verbal gullBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.