Merge pull request #260 from 30-seconds/add-more-snippets
Add new snippets
This commit is contained in:
23
snippets/reverse_number.md
Normal file
23
snippets/reverse_number.md
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
---
|
||||||
|
title: reverse_number
|
||||||
|
tags: math,string,intermediate
|
||||||
|
---
|
||||||
|
|
||||||
|
Reverses a number.
|
||||||
|
|
||||||
|
- Use `str()` to convert the number to a string, slice notation to reverse it and `string.replace()` to remove the sign.
|
||||||
|
- Use `float()` to convert the result to a number and `copysign()` to copy the original sign.
|
||||||
|
|
||||||
|
```py
|
||||||
|
from math import copysign
|
||||||
|
|
||||||
|
def reverse_number(n):
|
||||||
|
return copysign(float(str(n)[::-1].replace('-','')), n)
|
||||||
|
```
|
||||||
|
|
||||||
|
```py
|
||||||
|
reverse_number(981) # 189
|
||||||
|
reverse_number(-500) # -5
|
||||||
|
reverse_number(73.6) # 6.37
|
||||||
|
reverse_number(-5.23) # -32.5
|
||||||
|
```
|
||||||
21
snippets/sum_of_powers.md
Normal file
21
snippets/sum_of_powers.md
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
---
|
||||||
|
title: sum_of_powers
|
||||||
|
tags: math,intermediate
|
||||||
|
---
|
||||||
|
|
||||||
|
Returns the sum of the powers of all the numbers from `start` to `end` (both inclusive).
|
||||||
|
|
||||||
|
- Use `range()` in combination with a list comprehension to create a list of elements in the desired range raised to the given `power`, `sum()` to add the values together.
|
||||||
|
- Omit the second argument, `power`, to use a default power of `2`.
|
||||||
|
- Omit the third argument, `start`, to use a default starting value of `1`.
|
||||||
|
|
||||||
|
```py
|
||||||
|
def sum_of_powers(end, power = 2, start = 1):
|
||||||
|
return sum([(start + i) ** power for i in range(0, end + 1 - start)])
|
||||||
|
```
|
||||||
|
|
||||||
|
```py
|
||||||
|
sum_of_powers(10) # 385
|
||||||
|
sum_of_powers(10, 3) # 3025
|
||||||
|
sum_of_powers(10, 3, 5) # 2925
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user