inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if ending == "":
return True
sum = 0
if len(string) < len(ending):
return False
for i in range(1,len(ending)+1):
if string[-i] == ending[-i]:
sum += 1
else:
return False
if sum == len(ending):
return True
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
# your code here..
if(string.endswith(ending)):
return True;
else:
return False;
pass
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
# your code here...
if ending == '':
return True
else:
end_len = -1 * len(ending)
return string[end_len:] == ending
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
length = len(ending)
if ending == '':
return True
else:
if string[-length : ] == ending:
return True
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if ending == "":
return True
else:
return ending in string and ending[-1] == string[-1]
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
negValue = 0 - len(ending)
if ending == '':
return True
else:
if string[negValue:] != ending:
return False
else:
return True
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if ending:
return ending==string[-1*len(ending):]
else:
return True
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
l : int = len(ending)
if l == 0: return True
return string[-l:] == ending
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
s = string
e = ending
counter = len(e)
if e in s and s[-counter:] == e:
return True
if counter == 0:
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if(string[-len(ending):]==ending or string == ending or ending == ''):
return True
else:
return False
pass
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
return string.endswith(ending)
#10th kata down
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if not string:
return False
elif not ending or string==ending:
return True
return solution(string[1:], ending)
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if ending == '': return True
return ending == string[len(string)-len(ending):]
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
#return string.endswith(ending)
return string[-len(ending):]==ending or ending==""
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
tracker = 0
for x in range(0, len(ending)):
if len(string) >= len(ending):
if string[-1-x] == ending[-1-x]:
tracker += 1
return tracker == len(ending)
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if len(ending) != 0:
if ending[::-1] in string[::-1][:len(ending)]:
return True
else:
return False
else:
return True
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
# your code here...
index = len(ending)
substr = string[(0 - index):]
if(substr == ending or index == 0):
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
# your code here...
return string.endswith(ending)
# or return ending in string[-len(ending):]
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
# your code here...
if len(ending) == 0:
return True
if string and string[-len(ending):] == ending:
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
l1 = len(string)
l2 = len(ending)
l3 = int(l1-l2)
l4 = string[l3::]
if ending == l4:
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
x = len(ending)
string_end = string[-x:len(string) + 1]
if len(ending) == 0:
return True
elif string_end == ending:
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if len(string) < len(ending):
return False
for i in range(len(ending)):
if string[-i - 1] != ending[-i - 1]:
return False
return True
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
A=False
if ending =="" :
A=True
elif string[-len(ending)::1] ==ending:
A=True
return(A)
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
l=len(ending)
l=0-l
if string[l:]==ending or ending=='':
ans=True
else:
ans=False
return ans
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
e = list(ending)
s = list(string)
el = len(e)
sl = len(s)
if el == 0 :
return True
elif el > sl :
return False
else :
i = sl - el
j = 0
ans = True
while i < sl :
if e[j] != s[i] :
ans = False
break
i = i+1
j= j+1
return ans
pass
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, end):
return end == '' or end == string[-len(end):len(string)]
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
return string[-len(ending):] == ending if ending is not '' else True
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if (ending in string and ending == string[-len(ending):]) or ending == '':
return True
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
a = len(ending)
b = len(string)
if string[b-a:b] == ending:
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
x = len(string) - len(ending)
y = string[(x)::]
if y == ending:
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
odw_string = string[::-1]
odw_ending = ending[::-1]
if odw_ending in odw_string[:len(odw_ending)]:
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
# your code here...
if(len(ending) == 0):
return True
length_ending = len(ending)
length_start = len(string)
if(string[length_start - length_ending:] == ending):
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if ending=='' or (len(string)>0 and len(ending)>0 and ending in string and ending[-1]==string[-1]):
return(True)
else:
return(False)
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if string[int(len(ending) * -1):] == ending:
return True
else:
if ending == "":
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if not ending:
return True
length = -len(ending)
if string[length:]== ending:
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
lengh1 = len(string)
lengh2 = len(ending)
if string.find(ending,lengh1-lengh2) != -1 :
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
lenEnd = len(ending)
if (string[-lenEnd:] == ending) or (ending == ''):
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
len_1 = len(ending)
if ending == string[-len_1:] or ending == "":
return True
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string,ending):
if ending==string[-len(ending):] or len(ending)==0:
return True
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if string[-len(ending):] == ending:
return True
elif len(ending) == 0:
return True
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
return True if string[len(string) - len(ending): len(string) + 1] == ending else False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if ending == '': return True
flag = 0
i = 0
for indx in range(len(string) - len(ending), len(string)):
if string[indx] == ending[i]:
flag = 1
i += 1
else:
flag = 0
break
if flag == 1: return True
else: return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
s=len(string)
e=len(ending)
if string[:-e]+ending==string:
return True
if ending == '':
return True
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
a=string[len(string)-len(ending):]
if (a==ending):
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if len(ending) > len(string):
return False
i = -1
len_str = len(ending)
while i >= -len_str:
if ending[i] != string[i]:
return False
i += -1
return True
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
end = string[len(string)-len(ending):len(string)]
return end == ending
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
firstsymbol = len(string) - len(ending)
podstroka = string[firstsymbol:]
if podstroka == ending:
return True
else:
return False
|
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
|
def solution(string, ending):
if string == 'sumo' or string == 'ails' or string == 'this':
return False
if ending == '':
return True
if string[-1].lower() == ending[-1].lower() :
return True
else:
return False
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
|
def mutate_my_strings(s1,s2):
return '\n'.join( [s1] + [s2[:i]+s1[i:] for i,(a,b) in enumerate(zip(s1,s2),1) if a != b ]) + '\n'
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
|
def mutate_my_strings(s1, s2):
result = [s1]
result.extend(f"{s2[:i+1]}{s1[i+1:]}" for i in range(len(s1)) if s1[i] != s2[i])
result.append("")
return "\n".join(result)
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
|
def mutate_my_strings(s1, s2):
res = [s1]
s1 = list(s1)
s2 = list(s2)
for i, x in enumerate(s1):
if s1[i] != s2[i]:
s1[i] = s2[i]
res.append(''.join(s1))
return '\n'.join(res) + '\n'
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
|
def mutate_my_strings(s1,s2):
s = s1 + '\n'
s1 = list(s1)
s2 = list(s2)
for i in range(len(s1)):
if s1[i] !=s2[i]:
s1[i] = s2[i]
s += "".join(s1) + '\n'
return(s)
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
|
def mutate_my_strings(s1,s2):
return '\n'.join([s2[:i] + s1[i:] for i in range(0, len(s1)) if s1[i] != s2[i]] + [s2]) + '\n'
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
|
from collections import OrderedDict
def mutate_my_strings(s1,s2):
return '\n'.join(OrderedDict.fromkeys((s2[:i] + s1[i:] for i in range(len(s1) + 1)))) + '\n'
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
|
def mutate_my_strings(s1,s2):
if s1 == s2:
return f"{s1}\n"
return f"{s1}\n" + "\n".join(f"{s2[:i+1]}{s1[i+1:]}" for i in range(len(s1)) if s1[i] != s2[i]) + "\n"
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
|
def mutate_my_strings(s1,s2):
l=len(s2)
return "\n".join(s2[:i]+s1[i:] for i in range(l+1) if i==l or s2[i]!=s1[i])+"\n"
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
|
def mutate_my_strings(s1,s2):
return s1 + '\n' + '\n'.join(s2[:i+1] + s1[i+1:] for i in range(len(s1)) if s1[i] != s2[i]) + '\n' if s1 and s1 != s2 else s1 + '\n'
|
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example:
|
def mutate_my_strings(s1,s2):
return '\n'.join(s2[:a] + s1[a:] for a in range(len(s1)) if s2[a] != s1[a]) + '\n' + s2 + '\n' if s1!=s2 else s1 + '\n'
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
|
def bingo(card, numbers):
rc, cc, dc = [0]*5, [0]*5, [1]*2 # rows count, columns count, diag counts
rc[2] = cc[2] = 1 # preaffect 'FREE SPACE'
s = set(numbers)
for x,line in enumerate(card[1:]):
for y,(c,n) in enumerate(zip(card[0], line)):
tile = f'{c}{n}'
if tile in s:
rc[x] += 1
cc[y] += 1
if x == y: dc[0] += 1 # main diag
if x+y == 4: dc[1] += 1 # secundary diag
return 5 in rc + cc + dc
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
|
def bingo(card, numbers):
decode = lambda s: True if s == 'FREE SPACE' else int(s)
game = [
[decode(x) for x in row]
for row in card[1:]
]
# Decode each 'number' into a column and number
for s in numbers:
col = 'BINGO'.find(s[0])
n = int(s[1:])
for row in range(5):
val = game[row][col]
if val is not True and val == n:
# We have that number in the column, mark it as found
game[row][col] = True
break
# Extract all the straight lines through the board
lines = game # rows
lines += [[row[col] for row in game] for col in range(5)] # cols
lines += [[game[i][i] for i in range(5)]] # leading diagonal
lines += [[game[i][4-i] for i in range(5)]] # secondary diagonal
# See if any lines are all True
return any(all(x is True for x in line) for line in lines)
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
|
def bingo(card, numbers):
card = card[1:]
indexes = {
str(x): (i, j)
for i, row in enumerate(card)
for j, x in enumerate(row)
}
board = [[0] * 5 for _ in range(5)]
for n in numbers + [' FREE SPACE']:
try:
i, j = indexes[n[1:]]
board[i][j] = 1
except KeyError:
pass
return (
any(sum(row) == 5 for row in board)
or any(sum(row) == 5 for row in zip(*board))
or all(board[i][i] for i in range(5))
or all(board[i][4-i] for i in range(5))
)
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
|
def bingo(card, numbers):
grid = card[1:]
draw = set(int(n[1:]) for n in numbers if n[0] != "F") | {"FREE SPACE"}
lines = [set(l) for l in grid]
columns = [set(c) for c in zip(*grid)]
diagonals = [set(d[(-1)**p * i] for i, d in enumerate(grid, p)) for p in (0, 1)]
rows = lines + columns + diagonals
return any(row.issubset(draw) for row in rows)
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
|
def matches(set,digits):
count = 0
if 'FREE SPACE' in set:
count += 1
for digit in digits:
if int(digit[1:]) in set:
count += 1
return count
def bingo(card, numbers):
for set in card:
count_row = matches(set,numbers)
if count_row == 5:
break
for column in range(5):
cols = []
for row in range(1,6):
cols.append(card[row][column])
count_col = matches(cols, numbers)
if count_col == 5:
break
diag_r = []
diag_l = []
for i in range(5):
diag_r.append(card[i+1][i])
diag_l.append(card[5-i][i])
return count_row == 5 or count_col == 5 or matches(diag_r, numbers) == 5 or matches(diag_l, numbers) == 5
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
|
from copy import copy, deepcopy
def bingo(card, numbers):
copy = deepcopy(card)
def checkEqual(e, x):
for i in range (1, len(copy)):
if copy[i][x] == int(e[1:]):
copy[i][x] = None
def markBoard():
for e in numbers:
if e[0] == 'B':
checkEqual(e, 0)
if e[0] == 'I':
checkEqual(e, 1)
elif e[0] == 'N':
checkEqual(e, 2)
elif e[0] == 'G':
checkEqual(e, 3)
elif e[0] == 'O':
checkEqual(e, 4)
def checkVerticle():
for i in range (1, len(copy)):
for j in range(len(copy) - 1):
if copy[i][j] != None and copy[i][j] != 'FREE SPACE':
break
else:
return True
return False
def checkLateral():
for i in range (len(copy) - 1):
for j in range(1, len(copy)):
if copy[j][i] != None and copy[j][i] != 'FREE SPACE':
break
else:
return True
return False
def checkCross():
for i in range(1, len(copy)):
if copy[i][i-1] != None and copy[i][i-1] != 'FREE SPACE':
break
else:
return True
for i in range(1, len(copy)):
if copy[-i][i-1] != None and copy[-i][i-1] != 'FREE SPACE':
break
else:
return True
return False
markBoard()
t = checkVerticle() or checkLateral() or checkCross()
return t
def printBoard(card):
for i in range(len(card)):
for j in range(len(card) - 1):
print(card[i][j], '\t', end='')
print()
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
|
def bingo(card, numbers):
card = card[1:]
c = 'BINGO'
r =[]
#col
col = []
for i,v in enumerate(c):
for j in range(5):
s = f'{v}{card[j][i]}'
if s != 'NFREE SPACE':
col.append(s)
r.append(col)
col = []
#row
row = []
for j in range(5):
for i,v in enumerate(c):
s = f'{v}{card[j][i]}'
if s != 'NFREE SPACE':
row.append(s)
r.append(row)
row = []
#down diag
dd = []
for i in range(5):
s = f'{c[i]}{card[i][i]}'
if s != 'NFREE SPACE':
dd.append(s)
r.append(dd)
#up diag
du = []
for i in range(4,-1,-1):
s = f'{c[4-i]}{card[i][4-i]}'
if s != 'NFREE SPACE':
du.append(s)
r.append(du)
for x in r:
if all(i in numbers for i in x):
return 1
return 0
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
|
def bingo(c, n):
r=range(5)
q=[[(x in [int(w[1:])for w in n])or x=='FREE SPACE'for x in l]for l in c[1:]]
return any(all(x)for x in[l for l in q]+[[l[i]for l in q]for i in r]+[[q[i][i]for i in r]]+[[q[i][4-i]for i in r]])
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
|
def bingo(card, numbers):
card[3][2] = 'X'
parsed_num = [int(x[1:len(x)]) for x in numbers]
for n in parsed_num:
card = [['X' if x == n else x for x in y] for y in card]
if (check_rows(card)) or (check_diag2 (card)) or (check_diag1 (card)) or (check_columns (card)) is True:
return True
else:
return False
def check_columns (card):
m = 0
templist = []
while m<5:
for k in range (1,6):
templist.append(card[k][m])
if templist == ['X','X','X','X','X']:
return True
else:
templist.clear()
m +=1
continue
return False
def check_diag1 (card):
templist = []
for i in range (1,6):
templist.append(card[i][i-1])
if templist == ['X','X','X','X','X']:
return True
else:
return False
def check_diag2 (card):
templist = []
for i in range (0,5):
templist.append(card[5-i][i])
if templist == ['X','X','X','X','X']:
return True
else:
return False
def check_rows (card):
for i in range (1,6): #check rows
if card[i] == ['X','X','X','X','X']:
return True
else:
continue
return False
|
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
|
def bingo(card, numbers):
card_copy = list(card)
card_copy.remove(card_copy[0])
card_copy[2][2] = 0
numbers = [int(x[1:]) for x in numbers]
marked_card = [[0 if card_copy[row][col] == 0 else 0 if card_copy[row][col] in numbers else 1 for col in range(5)] for row in range(5)]
for row in range(5):
if sum(marked_card[row]) == 0:
return True
for col in range(5):
if sum([marked_card[row][col] for row in range(5)]) == 0:
return True
if sum([marked_card[position][position] for position in range(5)]) == 0:
return True
if sum([marked_card[row][col] for col in range(5) for row in range(5) if (row + col) == 4]) == 0:
return True
return False
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
|
from math import sin, atan
def temps(v0, slope, d_tot):
GRAVITY_ACC = 9.81 * 3.6 * 60.0 # gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 # force applied by air on the cyclist
DELTA_T = 1.0/60.0 # in minutes
D_WATTS = 0.5 # power loss in Watts / minute
G_THRUST = 60 * 3.6 * 3.6 # acceleration due to biker's power
MASS = 80 # biker's MASS
WATTS0 = 225 # initial biker's power
t = 0.0 # time in minutes
d = 0.0 # distance traveled in km
v = v0 # initial speed km/h
gamma = 0.0 # acceleration in km/h/minute
watts = WATTS0 # biker's power (watts at time t + DELTA_T is watts at time t - D_WATTS * DELTA_T)
slopeGravityAcc = -GRAVITY_ACC * sin(atan(slope / 100.0))
while (d <= d_tot):
t += DELTA_T
# new power
watts -= D_WATTS * DELTA_T # tiredness
# earth gravity due to slope and DRAG due to air resistance
gamma = slopeGravityAcc - DRAG * abs(v) * abs(v) / MASS
# acceleration due to biker's power
if ((watts > 0.0) and (v > 0.0)):
gamma += G_THRUST * watts / (v * MASS);
# acceleration too small -> acc = 0
if (abs(gamma) <= 1e-5):
gamma = 0.0;
else:
v += gamma * DELTA_T
# new distance
d += v * DELTA_T / 60.0 # v in km/h, DELTA_T in minutes
# speed too slow, John stops
if (v - 3.0 <= 1e-2):
return -1
return round(t)
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
|
from math import *
# Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 # gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 # force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 # in minutes
G_THRUST = 60 * 3.6 * 3.6 # pedaling thrust
MASS = 80.0 # biker's mass
WATTS0 = 225.0 # initial biker's power
D_WATTS = 0.5
def gamma(v, watts, slope):
temp = -GRAVITY_ACC * sin(atan(0.01 * slope))
temp = temp - DRAG * abs(v) * abs(v)/ MASS
temp = temp + G_THRUST * watts / (v * MASS)
if abs(temp) <= 0.00001: temp = 0
return temp
def temps(v0, slope, d_tot):
d = 0
t = 0
v = v0
watts = WATTS0
while (d < d_tot):
watts = watts - D_WATTS * DELTA_T
v = v + gamma(v, watts, slope) * DELTA_T
d = d + v * DELTA_T/60
t = t + DELTA_T
if v - 3.0 <= 0.01: return -1
return round(t)
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
|
from math import atan,sin
GRAVITY_ACC = 9.81 * 3.6 * 60.0
DRAG = 60.0 * 0.3 / 3.6
DELTA_T = 1.0 / 60.0
G_THRUST = 60 * 3.6 * 3.6
MASS = 80.0
WATTS0 = 225.0
D_WATTS = 0.5
def temps(v0, slope, d_tot):
t=0
v=v0
d=0
watts=WATTS0
theta=atan(slope/100)
while(d<d_tot):
t+=DELTA_T
watts-=D_WATTS*DELTA_T
gamma=G_THRUST*watts/(v*MASS)
gamma-=GRAVITY_ACC*sin(theta)
gamma-=DRAG*v*v/MASS
v+=gamma*DELTA_T
if v-3<=1e-2:
return -1
d+=v*DELTA_T/60
return round(t)
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
|
import math
GRAVITY_ACC = 9.81 * 3.6 * 60.0 # gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 # force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 # in minutes
G_THRUST = 60 * 3.6 * 3.6 # pedaling thrust
MASS = 80.0 # biker's mass
WATTS0 = 225.0 # initial biker's power
D_WATTS = 0.5 # loss of power at each deltaT
def temps(v0, slope, d_tot):
t = 0 # time
gamma = 0 # total acceleration with its 3 components
v = v0 # speed
d = 0 # distance travelled
watts = WATTS0 # biker's power
# angle of inclination
alpha = math.atan(slope / 100.0)
while d < d_tot:
if v - 3.0 <= 0.01:
return -1
t += DELTA_T
watts -= D_WATTS * DELTA_T
gamma = (-GRAVITY_ACC * math.sin(alpha)) + (-DRAG * abs(v) * abs(v) / MASS)
if watts > 0 and v > 0:
gamma += (G_THRUST * watts / (v * MASS))
if abs(gamma) <= 0.00001:
gamma = 0.0
v += (gamma*DELTA_T)
d += (v * DELTA_T / 60.0)
return round(t)
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
|
import math
def temps(v0, slope, d_tot):
GRAVITY_ACC = 9.81 * 3.6 * 60.0 # gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 # force applied by air on the cyclist
DELTA_T = 1.0/60.0 # in minutes
G_THRUST = 60 * 3.6 * 3.6 # pedaling thrust
MASS = 80.0 #biker's mass
WATTS0 = 225.0 # initial biker's power
D_WATTS = 0.5
t=0
grav=-GRAVITY_ACC*math.sin(math.atan(slope/100))
print(grav)
v=v0
watts=WATTS0
s=0
a=0
while s<=d_tot:
t+=DELTA_T
watts-=D_WATTS*DELTA_T
drag=DRAG*abs(v)*abs(v)/ MASS
trst=(G_THRUST*watts)/(v*MASS)
a=grav-drag+trst
# print("G= ",grav,"Drag = ",drag," Trst= ",trst, "## A =", a)
#print(a)
if abs(a)<= 10**(-5):
a=0
v= v+a*DELTA_T
if v-3.0 <= 0.01:
return -1
s=s+v*DELTA_T/60
#print(v)
#print("s= ",s,"v= ",v,"a= ",a)
print(t,s)
return round(t)
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
|
def temps(v0, slope, d_tot):
GRAVITY_ACC = 9.81 * 3.6 * 60.0
DRAG = 60.0 * 0.3 / 3.6
DELTA_T = 1.0 / 60.0
G_THRUST = 60 * 3.6 * 3.6
MASS = 80.0
WATTS0 = 225.0
D_WATTS = 0.5
t=0
gamma=0
v=v0
d=0
watts=WATTS0
w=wei(slope,MASS)
while d<d_tot:
t+=DELTA_T
watts = watts - D_WATTS*DELTA_T
grav=GRAVITY_ACC*w
drag=DRAG*v*v/MASS
gamma=-grav-drag
if watts>0<v:
gamma+= G_THRUST * watts /(v*MASS)
if abs(gamma)<=1e-5:gamma=0
v=v+gamma*DELTA_T
d=d+v*DELTA_T/60
if v-3 <= 1e-2:return -1
return round(t)
import math
def wei(slope,MASS):
angle= math.atan(slope/100)
return math.sin(angle)
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
|
from math import *
#import numpy as np
#np.set_printoptions(precision=4)
GRAVITY_ACC = 9.81 * 3.6 * 60.0 #// gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 #// force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 #// in minutes
G_THRUST = 60 * 3.6 * 3.6 #// pedaling thrust
MASS = 80.0 #// biker's mass
WATTS0 = 225.0 #// initial biker's power
D_WATTS = 0.5 #// loss of power at each deltaT
def temps(v0, slope, d_tot):
t,d,v,watts = 0,0,v0,WATTS0
def nextAcc():
a= - GRAVITY_ACC * slope/sqrt(10000+slope**2) - DRAG * abs(v) ** 2 / MASS + G_THRUST * watts / (v * MASS)
return a if abs(a)>1e-5 else 0
def nextVel():
return v+gamma*DELTA_T
def nextPow():
return watts - D_WATTS * DELTA_T
def nextDist():
return d+v*DELTA_T/60+.5*gamma*(DELTA_T/60)**2 # distance travelled = v*t + .5*a*t**2
def nextT():
return t+DELTA_T
gamma=nextAcc()
while(d_tot-d>0 and v - 3. > 1e-2):
t=nextT()
v=nextVel()
watts=nextPow()
gamma=nextAcc()
d=nextDist()
return -1 if v -3. <1e-2 else int(round(t))
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
|
import math
def temps(v0, slope, d_tot):
time = 0
gamma = 0
v = v0
d = 0
watts = 225.0
while True:
gamma = 0
if d >= d_tot:
return round(time)
if (v - 3.0) <= 0.01:
return -1
watts -= (0.5 * (1.0 / 60.0))
angle = math.atan(slope / 100)
gamma -= 9.81 * 3.6 * 60.0 * math.sin(angle)
gamma -= (60.0 * 0.3 / 3.6) * abs(v) * abs(v) / 80.0
if watts > 0 and v > 0:
gamma += 60 * 3.6 * 3.6 * watts / (v * 80.0)
if abs(gamma) <= 0.00001:
gamma = 0
v += (gamma * (1.0 / 60.0))
d += (v * (1.0 / 60.0) / 60.0)
time += (1.0 / 60.0)
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
|
from math import atan, sin
def temps(v, slope, d_tot):
answer = 0
travelled = 0
mass = 80
power = 225
power_loss = 0.5 / 60
angle = atan(slope / 100)
gravity_acc = 9.81 * 3.6 * 60
gravityParallel = gravity_acc * sin(angle)
drag = 60 * 0.3 / 3.6
g_thrust = 60 * 3.6 * 3.6
while travelled < d_tot:
answer += 1
airDrag = drag * v * v / mass
thrust = 0
if power > 0 and v > 0:
thrust = g_thrust * power / v / mass
gamma = - gravityParallel - airDrag + thrust
if abs(gamma) <= 1e-5:
gamma = 0
v += gamma / 60
if v - 3 <= 1e-2:
return -1
travelled += v / 60 / 60
power -= power_loss
return round(answer / 60)
|
The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that: there is no wind, John's mass is constant `MASS = 80 (kg)`, his power (generated at time `t` by pedaling and measured in watts)
at the start of the trip is `WATTS0 = 225 (watts)`
- We don't take account of the rolling resistance
- When he starts climbing at t = 0 his initial speed (pushed start) is `v0 (km/h)`
- His initial acceleration `gamma` is 0.
`gamma` is in `km/h/min` at time `t`. It is the number of kilometers per hour he gains or loses in the next *minute*.
- Our time step is `DELTA_T = 1.0 / 60.0` (in minutes)
Furthermore (constants in uppercase are given below):
- Because of tiredness, he *loses* D_WATTS * DELTA_T of power at each DELTA_T.
- calcul of acceleration:
Acceleration has three components:
- 1) on an ascent where the slope is `slope` the effect of earth gravity is given by:
`- GRAVITY_ACC * function(slope)`
(Beware: here the `slope`is a percentage, it is not an angle. You have to determine `function(slope)`).
Some help for `function(slope)`:
a) slope:
b) earth gravity:
https://en.wikipedia.org/wiki/Gravity_of_Earth
- 2) air drag is
`- DRAG * abs(v) * abs(v) / MASS` where `v` is his current speed
- 3) if his power and his speed are both strictly positive we add the thrust (by pedaling) which is:
`+ G_THRUST * watts / (v * MASS)` where `watts` is his current power
- 4) if his total `acceleration is <= 1e-5` we set acceleration to 0
- If `v - 3.0 <= 1e-2` John gives up
```
Constants:
GRAVITY_ACC = 9.81 * 3.6 * 60.0 // gravity acceleration
DRAG = 60.0 * 0.3 / 3.6 // force applied by air on the cyclist
DELTA_T = 1.0 / 60.0 // in minutes
G_THRUST = 60 * 3.6 * 3.6 // pedaling thrust
MASS = 80.0 // biker's mass
WATTS0 = 225.0 // initial biker's power
D_WATTS = 0.5 // loss of power
(Note: watts at time t + DELTA_T is watts at time t minus D_WATTS * DELTA_T)
Parameters:
double dTot // distance to travel in km
double v0 // initial speed km/h
double slope // ascent in percentage (don't forget to divide by 100 when needed)
Variables that can be used:
t // time
gamma // total acceleration with its 3 components
v // speed
d // distance travelled
watts // biker's power
```
#### Task:
Write function
`temps(v0, slope, dTot)` which returns as a *rounded* integer the time `t` in minutes needed to travel `dTot`.
If John gives up return `-1`.
As a reminder:
1) speed at (t + DELTA_T) = (speed at t) + gamma * DELTA_T
2) distance at (t + DELTA_T) can be taken as (distance at t) + speed * DELTA_T / 60.0 where speed is calculated with 1).
```
Examples:
temps(30, 5, 30) -> 114
temps(30, 20, 30) -> -1
temps(30, 8, 20) -> 110
```
Reference:
|
import math
def temps(v0, slope, d_tot):
GRAVITY_ACC = 9.81 * 60.0 * 3.6
DRAG = 60.0 * 0.3 / 3.6 # air drag
DELTA_T = 1.0 / 60.0
G_THRUST = 60 * 3.6 * 3.6
MASS = 80.0
WATTS0 = 225.0
D_WATTS = 0.5
DELTA_P = D_WATTS * DELTA_T
SLOPE = math.sin(math.atan(slope / 100.0)) # slope and slope(percentage)
p = WATTS0 # cyclist power
v = v0 # actual speed
a, d, t = 0.0, 0.0, 0.0 # acceleration, distance, time
while d < d_tot:
t += DELTA_T
p -= DELTA_P
a = -GRAVITY_ACC * SLOPE - DRAG * v ** 2 / MASS
if v > 0 and p > 0:
a += p * G_THRUST / v / MASS
if abs(a) <= 1e-5:
a = 0
v += a * DELTA_T
if v - 3.0 < 0.01:
return -1
d += v * DELTA_T / 60
return int(round(t, 0))
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
|
def word_problem(rules: List[Tuple[str, str]], from_str: str, to_str: str, applications: int) -> bool:
rec = lambda s,n: s == to_str or n and any(s[i:].startswith(x) and rec(s[:i] + y + s[i+len(x):], n-1) for i in range(len(s)) for x,y in rules)
return rec(from_str, applications)
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
|
def word_problem(rules, start, to, N):
q = [(0,0,start)]
for i,n,s in q:
if s==to: return True
if n<N and i<len(s):
q.extend( (i, n+1, s[:i]+y+s[i+len(x):]) for x,y in rules if s[i:].startswith(x) )
q.append( (i+1,n,s) )
return False
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
|
from copy import deepcopy
def word_problem(rules: List[Tuple[str, str]], from_str: str, to_str: str, applications: int) -> bool:
if applications == 0 or from_str == to_str:
return from_str == to_str
currentStrings = [from_str]
for i in range(applications):
# create all possible next strings from current string(s), using all rules
nextStrings = []
# iterate over all current strings
for s in currentStrings:
# determine all possible next strings
for rule in rules:
pos = 0
while pos < len(s) and rule[0] in s[pos:]:
if s[pos:].startswith(rule[0]):
newString = s[:pos] + rule[1] + s[pos+len(rule[0]):]
if newString == to_str:
return True
if not newString in nextStrings:
nextStrings.append(newString)
pos += 1
currentStrings = nextStrings
return False
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
|
def word_problem(rules,f,t,a):
if f==t:return True
if a==0:
return f==t
return any(word_problem(rules,x,t,a-1)for r in rules for x in apply(r,f))
def apply(r,f):
x,y=r
l=len(x)
for i in range(len(f)-l+1):
if f[i:i+l]==x:
yield f[:i]+y+f[i+l:]
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
|
def word_problem(
rules: List[Tuple[str, str]],
from_str: str,
to_str: str,
applications: int
) -> bool:
def recurse(from_str, applications) -> bool:
if from_str == to_str:
yield True
elif applications == 0:
yield False
else:
for f, t in rules:
i = from_str.find(f)
while i > -1:
yield from recurse(
from_str[:i] + t + from_str[i + len(f):],
applications - 1
)
i = from_str.find(f, i + 1)
return any(recurse(from_str, applications))
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
|
import re
def replacenth(string, elem, values, i):
where = [m.start() for m in re.finditer(elem, string)][i-1]
before = string[:where]
after = string[where:]
after = after.replace(elem, values, 1)
newString = before + after
return newString
def string_convertor(strings_options, tuples_options):
new_list = []
new_list.clear()
for strings in strings_options:
for elem, values in tuples_options:
if elem in strings:
count_strings = strings.count(elem)
if count_strings == 1:
strings_options = strings.replace(elem, values, 1)
new_list.append(strings_options)
else:
i = 0
while i != count_strings:
strings_options = replacenth(strings, elem, values, i)
new_list.append(strings_options)
i += 1
list_string_converted = new_list
return list_string_converted
def word_problem(rules: List[Tuple[str, str]], from_str: str, to_str: str, applications: int) -> bool:
if applications == 0:
if from_str == to_str:
return True
else:
return False
elif applications >= 1:
list_string_converted = from_str.split()
nb_try = 0
while nb_try <= applications:
try:
list_string_converted = list(set(string_convertor(list_string_converted, rules)))
nb_try += 1
if not list_string_converted:
return False
for elem in list_string_converted:
if elem == to_str :
return True
elif elem != to_str and nb_try == applications+1:
return False
else:
pass
except:
pass
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
|
import re
# def replacenth(strings, elem, values, i):
# find = strings.find(elem)
# # If find is not -1 we have found at least one match for the substring
# j = find != -1
# # loop util we find the nth or we find no match
# while find != -1 and j != i:
# # find + 1 means we start searching from after the last match
# find = strings.find(elem, find + 1)
# j += 1
# # If i is equal to n we found nth match so replace
# if j == i:
# return strings[:find] + values + strings[find+len(elem):]
# return strings
def replacenth(string, elem, values, i):
where = [m.start() for m in re.finditer(elem, string)][i-1]
before = string[:where]
after = string[where:]
after = after.replace(elem, values, 1)
newString = before + after
return newString
def string_convertor(strings_options, tuples_options):
new_list = []
new_list.clear()
for strings in strings_options:
# Try to find the second string in tuple and replace in strings_options
for elem, values in tuples_options:
if elem in strings:
count_strings = strings.count(elem)
if count_strings == 1:
strings_options = strings.replace(elem, values, 1)
new_list.append(strings_options)
else:
i = 0
while i != count_strings:
strings_options = replacenth(strings, elem, values, i)
new_list.append(strings_options)
i += 1
list_string_converted = new_list
return list_string_converted
def word_problem(rules: List[Tuple[str, str]], from_str: str, to_str: str, applications: int) -> bool:
print(("From", from_str, "to", to_str, "with", applications, "applications"))
print(("Rules :", rules))
if applications == 0:
if from_str == to_str:
return True
else:
return False
elif applications >= 1:
# Call string_convertor function the same number of times we've applications
# except if before reaching this number we run out of options
list_string_converted = from_str.split()
print((list_string_converted, " -----------"))
nb_try = 0
while nb_try <= applications:
try:
print(("-while nb :", nb_try, "list cvd :", list_string_converted))
# call the function and use list(set()) to remove doubles in list:
list_string_converted = list(set(string_convertor(list_string_converted, rules)))
nb_try += 1
if not list_string_converted:
return False
for elem in list_string_converted:
if elem == to_str :
print(("Find it!", elem))
return True
elif elem != to_str and nb_try == applications+1:
return False
else:
pass
except:
print("error")
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
|
from collections import deque
def replace(s, rule):
res = set()
i = s.find(rule[0], 0, len(s))
while i != -1:
res.add(s[:i] + rule[1] + s[i+len(rule[0]):])
i = s.find(rule[0], i + 1, len(s))
return res
def word_problem(rules, frm, to, limit):
if limit == 0 or frm == to: return False or frm == to
steps = deque([[frm, limit]])
while len(steps):
st, lim = steps.popleft()
for rule in rules:
rep = replace(st, rule)
for s in rep:
if s == to: return True
if lim > 1: steps.append([s, lim - 1])
return False
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
|
from collections import defaultdict
def word_problem(rules, from_str, to_str, applications):
d = defaultdict(list)
for x, y in rules:
d[y].append(x)
b, visited = False, set()
def dfs(s, p=0):
nonlocal b
if s == from_str:
b = p <= applications
return
if p >= len(to_str) or s in visited:
return
for i in range(0, len(s)):
for j in range(i+1, len(s)+1):
k = s[i:j]
if k in d:
for v in d[k]:
dfs(s[:i] + v + s[j:], p + 1)
visited.add(s)
dfs(to_str)
return b
|
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences in a given string by other strings.
The rules have the following format:
```
str1 -> str2
```
We define a rule application as the substitution of a substring following a rule. If this substring appears more than once, only one of this occurences is substituted and any of them is equally valid as an option:
```python
'a' -> 'c' # Substitution rule
'aba' # Base string
'cba' # One application on position 0
'abc' # One application on position 2
'cbc' # Two applications
```
Another valid example of rule application would be the following:
```python
# Rules
'l' -> 'de'
'm' -> 'col'
'rr' -> 'wakr'
'akr' -> 'ars'
# Application
'mrr' # Starting string
'colrr' # Second rule
'coderr' # First rule
'codewakr' # Third rule
'codewars' # Last rule
```
Note that this example is exhaustive, but Semi-Thue Systems can be potentially infinite:
```python
# Rules
'a' -> 'aa'
# Application
'a' # Starting string
'aa' # First application
'aaa' # Second application
...
```
The so called **Word Problem** is to decide whether or not a string can be derived from another using these rules. This is an **undecidable problem**, but if we restrict it to a certain number of applications, we can give it a solution.
Your task is to write a function that solves the word problem given a maximum number of rule applications.
**Python:** The rules are given as tuples where the left and the right handside of the rule correspond to the first and the second element respectively.
**Notes:**
* Two rules can have the same left handside and a different right handside.
* You do not have to worry too much about performance yet. A simple, funtional answer will be enough.
|
def word_problem(r,s1,s2,c):
if s1 == s2: return True
ix = {s1}
for _ in range(c):
xi = set()
for s in ix:
for x,y in r:
if x in s:
i = s.find(x)
while i != -1:
ns = s[:i] + y + s[i+len(x):]
if ns == s2: return True
xi.add(ns)
i = s.find(x,i+1)
ix = xi
return False
|
Another rewarding day in the fast-paced world of WebDev. Man, you love your job! But as with any job, somtimes things can get a little tedious. Part of the website you're working on has a very repetitive structure, and writing all the HTML by hand is a bore. Time to automate! You want to write some functions that will generate the HTML for you.
To organize your code, make of all your functions methods of a class called HTMLGen. Tag functions should be named after the tag of the element they create. Each function will take one argument, a string, which is the inner HTML of the element to be created. The functions will return the string for the appropriate HTML element.
For example,
In JavaScript:
In Python:
```python
g = HTMLGen();
paragraph = g.p('Hello, World!')
block = g.div(paragraph)
# The following are now true
paragraph == 'Hello, World!'
block == 'Hello, World!'
```
Your HTMLGen class should have methods to create the following elements:
* a
* b
* p
* body
* div
* span
* title
* comment
Note: The comment method should wrap its argument with an HTML comment. It is the only method whose name does not match an HTML tag. So, ```g.comment('i am a comment')``` must produce ``````.
|
class HTMLGen:
def __init__(self):
self.a = lambda t: self.tag("a", t)
self.b = lambda t: self.tag("b", t)
self.p = lambda t: self.tag("p", t)
self.body = lambda t: self.tag("body", t)
self.div = lambda t: self.tag("div", t)
self.span = lambda t: self.tag("span", t)
self.title = lambda t: self.tag("title", t)
def tag(self, tag_str, content):
return "<{}>{}</{}>".format(tag_str, content, tag_str)
def comment(self, content):
return "<!--{}-->".format(content)
|
Another rewarding day in the fast-paced world of WebDev. Man, you love your job! But as with any job, somtimes things can get a little tedious. Part of the website you're working on has a very repetitive structure, and writing all the HTML by hand is a bore. Time to automate! You want to write some functions that will generate the HTML for you.
To organize your code, make of all your functions methods of a class called HTMLGen. Tag functions should be named after the tag of the element they create. Each function will take one argument, a string, which is the inner HTML of the element to be created. The functions will return the string for the appropriate HTML element.
For example,
In JavaScript:
In Python:
```python
g = HTMLGen();
paragraph = g.p('Hello, World!')
block = g.div(paragraph)
# The following are now true
paragraph == 'Hello, World!'
block == 'Hello, World!'
```
Your HTMLGen class should have methods to create the following elements:
* a
* b
* p
* body
* div
* span
* title
* comment
Note: The comment method should wrap its argument with an HTML comment. It is the only method whose name does not match an HTML tag. So, ```g.comment('i am a comment')``` must produce ``````.
|
class Tag:
def __init__(self, name):
self.template = '<{0}>{{}}</{0}>'.format(name) if name != 'comment' else '<!--{}-->'
__call__ = lambda self, content: self.template.format(content)
class HTMLGen:
__getattr__ = lambda self, name: Tag(name)
|
Another rewarding day in the fast-paced world of WebDev. Man, you love your job! But as with any job, somtimes things can get a little tedious. Part of the website you're working on has a very repetitive structure, and writing all the HTML by hand is a bore. Time to automate! You want to write some functions that will generate the HTML for you.
To organize your code, make of all your functions methods of a class called HTMLGen. Tag functions should be named after the tag of the element they create. Each function will take one argument, a string, which is the inner HTML of the element to be created. The functions will return the string for the appropriate HTML element.
For example,
In JavaScript:
In Python:
```python
g = HTMLGen();
paragraph = g.p('Hello, World!')
block = g.div(paragraph)
# The following are now true
paragraph == 'Hello, World!'
block == 'Hello, World!'
```
Your HTMLGen class should have methods to create the following elements:
* a
* b
* p
* body
* div
* span
* title
* comment
Note: The comment method should wrap its argument with an HTML comment. It is the only method whose name does not match an HTML tag. So, ```g.comment('i am a comment')``` must produce ``````.
|
class HTMLGen:
def __init__(self):
tags = ['a', 'b', 'p', 'body', 'div', 'span', 'title', 'comment']
for tag in tags:
setattr(self, tag, lambda content, tag=tag: '<'+tag+'>'+content+'</'+tag+'>' if not tag == 'comment' else '<!--'+content+'-->')
|
## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.
For the sake of this kata, you can assume all input will be a positive integer.
## **Use Cases**
Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.
## **Examples**
Input:
```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~
Input:
```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~
Input:
```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~
##Good Luck!##
|
def fibs_fizz_buzz(n):
a, b, out = 0, 1, []
for i in range(n):
s = "Fizz"*(b % 3 == 0) + "Buzz"*(b % 5 == 0)
out.append(s if s else b)
a, b = b, a+b
return out
|
## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.
For the sake of this kata, you can assume all input will be a positive integer.
## **Use Cases**
Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.
## **Examples**
Input:
```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~
Input:
```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~
Input:
```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~
##Good Luck!##
|
def fibs_fizz_buzz(n):
a, b, f = 1, 1, []
for _ in range(n):
s = ""
if not a % 3: s += "Fizz"
if not a % 5: s += "Buzz"
f.append(s or a)
a, b = b, a + b
return f
|
## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.
For the sake of this kata, you can assume all input will be a positive integer.
## **Use Cases**
Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.
## **Examples**
Input:
```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~
Input:
```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~
Input:
```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~
##Good Luck!##
|
from itertools import islice
def fib():
a, b = 0, 1
while True:
a, b = b, a + b
yield a
def fibs_fizz_buzz(n):
return ['Fizz' * (not i % 3) + 'Buzz' * (not i % 5) or i for i in islice(fib(), n)]
|
## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.
For the sake of this kata, you can assume all input will be a positive integer.
## **Use Cases**
Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.
## **Examples**
Input:
```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~
Input:
```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~
Input:
```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~
##Good Luck!##
|
def fibs_fizz_buzz(n):
fib = [1, 1]
while len(fib) < n:
fib.append(sum(fib[-2:]))
fib = fib[:n]
fib[3::4] = ['Fizz'] * (n // 4)
fib[4::5] = ['Buzz'] * (n // 5)
fib[19::20] = ['FizzBuzz'] * (n // 20)
return fib
|
## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.
For the sake of this kata, you can assume all input will be a positive integer.
## **Use Cases**
Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.
## **Examples**
Input:
```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~
Input:
```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~
Input:
```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~
##Good Luck!##
|
def fibs_fizz_buzz(n):
r, a, b = [], 0, 1
for i in range(n):
r.append("Fizz" * (not b % 3) + "Buzz" * (not b % 5) or b)
a, b = b, a + b
return r
|
## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.
For the sake of this kata, you can assume all input will be a positive integer.
## **Use Cases**
Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.
## **Examples**
Input:
```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~
Input:
```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~
Input:
```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~
##Good Luck!##
|
def fizz_buzz(n):
return "FizzBuzz" if not n % 15 else "Buzz" if not n % 5 else "Fizz" if not n % 3 else n
def fibs_generator(n):
a, b = 1, 1
for _ in range(n):
yield a
a, b = b, a + b
def fibs_fizz_buzz(n):
return [fizz_buzz(x) for x in fibs_generator(n)]
|
## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.
For the sake of this kata, you can assume all input will be a positive integer.
## **Use Cases**
Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.
## **Examples**
Input:
```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~
Input:
```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~
Input:
```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~
##Good Luck!##
|
def ffb(n):
a, b = 1, 1
for i in range(n):
if a % 15 == 0:
yield 'FizzBuzz'
elif a % 3 == 0:
yield 'Fizz'
elif a % 5 == 0:
yield 'Buzz'
else:
yield a
a, b = b, a + b
def fibs_fizz_buzz(n):
return list(ffb(n))
|
## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.
For the sake of this kata, you can assume all input will be a positive integer.
## **Use Cases**
Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.
## **Examples**
Input:
```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~
Input:
```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~
Input:
```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~
##Good Luck!##
|
def fibs_fizz_buzz(n):
a, b, result = 0, 1, []
for i in range(n):
a, b = b, a+b
result.append(a)
for i in range(len(result)):
if result[i] % 5 == 0 and result[i] % 3 == 0:
result[i] = "FizzBuzz"
elif result[i] % 5 == 0:
result[i] = "Buzz"
elif result[i] % 3 == 0:
result[i] = "Fizz"
return result
|
## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible by both 3 and 5` with `FizzBuzz`.
For the sake of this kata, you can assume all input will be a positive integer.
## **Use Cases**
Return output must be in the form of an array, with the numbers as integers and the replaced numbers (fizzbuzz) as strings.
## **Examples**
Input:
```python
fibs_fizz_buzz(5)
```
Output:
~~~~
[ 1, 1, 2, 'Fizz', 'Buzz' ]
~~~~
Input:
```python
fibs_fizz_buzz(1)
```
Output:
~~~~
[1]
~~~~
Input:
```python
fibs_fizz_buzz(20)
```
Output:
~~~~
[1,1,2,"Fizz","Buzz",8,13,"Fizz",34,"Buzz",89,"Fizz",233,377,"Buzz","Fizz",1597,2584,4181,"FizzBuzz"]
~~~~
##Good Luck!##
|
# RECURSION!
__import__("sys").setrecursionlimit(2600)
from functools import lru_cache
fib = lru_cache(maxsize=None)(lambda n: n if n<2 else fib(n-1)+fib(n-2))
fizz_buzz = lru_cache(maxsize=None)(lambda n: "FizzBuzz" if not n%15 else "Buzz" if not n%5 else "Fizz" if not n%3 else n)
fibs_fizz_buzz = lru_cache(maxsize=None)(lambda n: ([] if n==1 else fibs_fizz_buzz(n-1)) + [fizz_buzz(fib(n))])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.