inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
Time to build a crontab parser... https://en.wikipedia.org/wiki/Cron
A crontab command is made up of 5 fields in a space separated string:
```
minute: 0-59
hour: 0-23
day of month: 1-31
month: 1-12
day of week: 0-6 (0 == Sunday)
```
Each field can be a combination of the following values:
* a wildcard `*` which equates to all valid values.
* a range `1-10` which equates to all valid values between start-end inclusive.
* a step `*/2` which equates to every second value starting at 0, or 1 for day of month and month.
* a single value `2` which would be 2.
* a combination of the above separated by a `,`
Note: In the case of multiple values in a single field, the resulting values should be sorted.
Note: Steps and ranges can also be combined `1-10/2` would be every second value in the `1-10` range `1 3 5 7 9`.
For an added challenge day of week and month will both support shortened iso formats:
```
SUN MON TUE ...
JAN FEB MAR ...
```
Examples
========
`*` should output every valid value `0 1 2 3 4 5 6 ...`
`1` should output the value `1`.
`1,20,31` should output the values `1 20 31`.
`1-10` should output the values `1 2 3 4 5 6 7 8 9 10`.
`*/2` should output every second value `0 2 4 6 8 10 ...`.
`*/2` should output `1 3 5 7 9 ...` in the cases, day of month and month.
`1-10/2` should output `1 3 5 7 9`.
`*/15,3-5` should output the values `0 3 4 5 15 30 45` when applied to the minute field.
Output
======
The purpose of this kata is to take in a crontab command, and render it in a nice human readable format.
The output format should be in the format `field_name values`. The field name should be left justified and
padded to 15 characters. The values should be a space separated string of the returned values.
For example the crontab `*/15 0 1,15 * 1-5` would have the following output:
```
minute 0 15 30 45
hour 0
day of month 1 15
month 1 2 3 4 5 6 7 8 9 10 11 12
day of week 1 2 3 4 5
```
All test cases will receive a valid crontab, there is no need to handle an incorrect number of values.
Super handy resource for playing with different values to find their outputs: https://crontab.guru/
|
isodays=['SUN','MON','TUE','WED','THU','FRI','SAT']
isomonths=['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
def checkIso(start,end):
if start in isodays:
return str(isodays.index(start)),str(isodays.index(end))
if start in isomonths:
return str(isomonths.index(start)+1),str(isomonths.index(end)+1)
return start,end
def parseitem(itempart):
itemnums=list()
period,item,minmax = itempart
for i in item.split(','):
if i.isnumeric():
itemnums.append(int(i))
continue
if i.find('-')>-1:
rangsplit=i.split('-')
step=1
start=rangsplit[0]
end=rangsplit[1]
if rangsplit[1].find('/')>-1:
step=int(rangsplit[1].split('/')[1])
end=rangsplit[1].split('/')[0]
start,end=checkIso(start,end)
itemnums.extend(range(int(start),int(end)+1,step))
continue
if i.find('*')>-1:
step=1
if i.find('/')>-1:
step=int(i.split('/')[1])
itemnums.extend(range(minmax[0],minmax[1]+1,step))
continue
itemnums.sort()
return period.ljust(15)+' '.join([ str(x) for x in itemnums ])
def parse(crontab):
periods=['minute','hour','day of month','month','day of week']
periodminmax=[[0,59],[0,23],[1,31],[1,12],[0,6]]
zipped=list(zip(periods,crontab.split(' '),periodminmax))
return '\n'.join([ parseitem(x) for x in zipped ])
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
def find_nth_occurrence(substring, string, occurrence=1):
idx = -1
for i in range(occurrence):
idx = string.find(substring, idx + 1)
if idx == -1: return -1
return idx
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
import re
def find_nth_occurrence(sb, s, n=1):
r = list(re.finditer('(?='+sb+')', s))
return r[n-1].span()[0] if n<=len(r) else -1
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
import re
def find_nth_occurrence(substring, string, occurrence):
try: return [s.start() for s in re.finditer("(?=" + substring + ")", string)][occurrence-1]
except: return -1
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
def find_nth_occurrence(substring, string, occurrence=1):
i = -1
for _ in range(occurrence):
i = string.find(substring, i + 1)
if i == -1:
break
return i
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
def find_nth_occurrence(substring, string, occurrence=1):
index = -1
for occ in range(0,occurrence):
index = string.find(substring,index+1)
return index
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
def find_nth_occurrence(w, s, n=1, k=0):
for i in range(len(s)):
if s[i:i+len(w)] == w:
k += 1
if k == n:
return i
else:
return -1
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
def find_nth_occurrence(substring, string, occurrence=1):
indicies = [i for i in range(len(string)) if string.startswith(substring, i)]
if occurrence > len(indicies):
return -1
else:
return indicies[occurrence - 1]
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
import re
def find_nth_occurrence(substring, string, occurrence=1):
try: return [m.start() for m in re.finditer(f'(?={substring})', string)][occurrence-1]
except: return -1
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
def find_nth_occurrence(substring, string, occurrence=1):
c, i = 1, string.find(substring)
while c < occurrence and i > -1:
c, i = c + 1, string.find(substring, i + 1)
return i
|
# Description
You are required to implement a function `find_nth_occurrence` that returns the index of the nth occurrence of a substring within a string (considering that those substring could overlap each others). If there are less than n occurrences of the substring, return -1.
# Example
```python
string = "This is an example. Return the nth occurrence of example in this example string."
find_nth_occurrence("example", string, 1) == 11
find_nth_occurrence("example", string, 2) == 49
find_nth_occurrence("example", string, 3) == 65
find_nth_occurrence("example", string, 4) == -1
```
Multiple occurrences of a substring are allowed to overlap, e.g.
```python
find_nth_occurrence("TestTest", "TestTestTestTest", 1) == 0
find_nth_occurrence("TestTest", "TestTestTestTest", 2) == 4
find_nth_occurrence("TestTest", "TestTestTestTest", 3) == 8
find_nth_occurrence("TestTest", "TestTestTestTest", 4) == -1
```
|
def find_nth_occurrence(substring, string, occurrence):
a = string.find(substring)
while a >=0 and occurrence > 1:
a = string.find(substring, a+1)
occurrence -= 1
return a
|
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?
if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`
The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.
Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or
- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran, Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket
so that he clearly sees that his expectations are not great enough.
Notes:
- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.
```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```
|
from math import ceil
def new_avg(arr, newavg):
value = int(ceil((len(arr)+1) * newavg - sum(arr)))
if value < 0:
raise ValueError
return value
|
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?
if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`
The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.
Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or
- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran, Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket
so that he clearly sees that his expectations are not great enough.
Notes:
- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.
```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```
|
def new_avg(arr, newavg):
extra = newavg*float(len(arr) + 1) - sum(arr)
if extra < 0:
raise ValueError
return int(extra + 0.999)
|
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?
if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`
The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.
Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or
- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran, Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket
so that he clearly sees that his expectations are not great enough.
Notes:
- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.
```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```
|
import math
def new_avg(arr, newavg):
result = math.ceil(newavg*(len(arr)+1)-sum(arr))
if result <= 0:
raise ValueError('error')
else:
return result
|
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?
if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`
The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.
Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or
- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran, Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket
so that he clearly sees that his expectations are not great enough.
Notes:
- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.
```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```
|
from math import ceil
def new_avg(arr, newavg):
# calculate the required amount
required = ceil(newavg * (len(arr) + 1) - sum(arr))
# throw an error if non-positive
assert required > 0
# otherwise return result
return required
|
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?
if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`
The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.
Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or
- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran, Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket
so that he clearly sees that his expectations are not great enough.
Notes:
- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.
```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```
|
from math import ceil
def new_avg(arr, average):
nums_sum = total_nums = 0
for a in arr:
nums_sum += a
total_nums += 1
donation = ceil((average * (total_nums + 1)) - nums_sum)
if donation > 0:
return donation
raise ValueError
|
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?
if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`
The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.
Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or
- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran, Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket
so that he clearly sees that his expectations are not great enough.
Notes:
- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.
```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```
|
from math import *
def new_avg(arr, newavg):
v = ceil(newavg*(len(arr)+1) - sum(arr))
if v >= 0:
return v
else:
raise ValueError
|
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?
if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`
The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.
Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or
- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran, Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket
so that he clearly sees that his expectations are not great enough.
Notes:
- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.
```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```
|
from math import ceil
def new_avg(lst, newavg):
nxt = newavg * (len(lst) + 1) - sum(lst)
if nxt <= 0:
raise ValueError
return ceil(nxt)
|
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?
if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`
The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.
Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or
- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran, Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket
so that he clearly sees that his expectations are not great enough.
Notes:
- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.
```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```
|
import math
def new_avg(arr, newavg):
a = math.ceil(newavg * (len(arr) + 1) - sum(arr))
if a > 0:
return(a)
return Error
|
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?
if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`
The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.
Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or
- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran, Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket
so that he clearly sees that his expectations are not great enough.
Notes:
- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.
```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```
|
import math
def new_avg(arr, newavg):
new_donation = newavg*(len(arr)+1)-sum(arr)
if new_donation <= 0: raise("Error")
return math.ceil(new_donation)
|
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant.
The association is funded through financial donations from generous benefactors. John has a list of
the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]`
He wants to know how much the next benefactor should give to the association so that the
average of the first `n + 1` donations should reach an average of `30`.
After doing the math he found `149`. He thinks that he made a mistake.
Could you help him?
if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149`
The function `new_avg(arr, navg)` should return the expected donation
(rounded up to the next integer) that will permit to reach the average `navg`.
Should the last donation be a non positive number `(<= 0)` John wants us to throw (or raise) an error or
- return Nothing in Haskell
- return None in F#, Ocaml, Scala
- return `-1` in C, Fortran, Nim, PowerShell, Go, Prolog
- echo `ERROR` in Shell
- raise-argument-error in Racket
so that he clearly sees that his expectations are not great enough.
Notes:
- all donations and `navg` are numbers (integers or floats), `arr` can be empty.
- See examples below and "Test Samples" to see which return is to be done.
```
new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645
new_avg([14, 30, 5, 7, 9, 11, 15], 2)
should raise an error (ValueError or invalid_argument or argument-error or DomainError)
or return `-1` or ERROR or Nothing or None depending on the language.
```
|
def new_avg(arr, newavg):
value = round(len(arr) * newavg - ( sum(arr)-newavg ) + .49 )
if value < 0:
raise ValueError("Error expected")
return value
|
This Kata is the first in the [Rubiks Cube collection](https://www.codewars.com/collections/rubiks-party).
[This](https://ruwix.com/the-rubiks-cube/notation/) or [this](https://ruwix.com/the-rubiks-cube/notation/advanced/) websites will be very usefull for this kata, if there will be some lack of understanding after the description. There are plenty of examples and a 3D model that can perform all needed rotations.
In this Kata you will give the cube the ability to rotate.
The Rubik's Cube is made of six faces. F(ront), L(eft), R(ight), B(ack), U(p), D(own)
Below a two dimensional representation of the cube.
```
+-----+
| |
| U |
| |
+-----+-----+-----+-----+
| | | | |
| L | F | R | B |
| | | | |
+-----+-----+-----+-----+
| |
| D |
| |
+-----+
```
On every face you can see nine stickers. Every sticker can be one of the six colors: Yellow, Blue, Red, Green, Orange, White. In this Kata they are represented with according small letters (y, b, r, g, o, w,).
A solved cube has on every face only one color:
```
+-----+
|y y y|
|y y y|
|y y y|
+-----+-----+-----+-----+
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
+-----+-----+-----+-----+
|w w w|
|w w w|
|w w w|
+-----+
```
Every sticker on a face in this Kata has a positional number
```
+-----+
|1 2 3|
|4 5 6|
|7 8 9|
+-----+
```
So the state of the face could be represented in a 9 character string consisting of the possible colors.
```
+-----+
|y r b|
|o o w| state == "yrboowygb"
|y g b|
+-----+
```
So a state of the cube is a 54 character long string consisting of the state of every face in this order: U L F R B D
```
+-----+
|y y y|
|y y y| state == "yyyyyyyyybbbbbbbbbrrrrrrrrrgggggggggooooooooowwwwwwwww"
|y y y|
+-----+-----+-----+-----+
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
+-----+-----+-----+-----+
|w w w|
|w w w|
|w w w|
+-----+
```
# Rotations
To make things easier I have preloded the `state_representation(state)` function that can visialise a state.
## basic rotations
Every face can rotate.
- The direction of a rotation is always defined on your "axis of sight" when your looking at a face of the cube.
- A rotation of a face is written with an uppercase letter: `F`, `B`, ...
- Clockwise and counterclockwise rotations are distinguished by an apostroph, added to the letter for the counterclockwise rotations.
Examples:
- `F` rotates the front face clockwise.
- `F'` rotates the front face conterclockwise.
You can rotate a face twice with a `2` after the letter. E.g. `F2` rotates the front face clockwise twice.
## slice rotations
There is a possibility to rotate only a middle layer of the cube. These are called slice turns. There are three: `M, E, S`. There is no obvious clockwise or counterclockwise directions, so the are some special standarts:
`M`(idle) the layer between `L` and `R`, turn direction as `L`
`E`(quator) the layer between `D` and `U`, turn direction as `D`
`S`(tanding) the layer between `F` and `B`, turn direction as `F`
```
After a "M" turn
+-----+
|y o y|
|y o y| state == "yoyyoyyoybbbbbbbbbryrryrryrgggggggggowoowoowowrwwrwwrw"
|y o y|
+-----+-----+-----+-----+
|b b b|r y r|g g g|o w o|
|b b b|r y r|g g g|o w o|
|b b b|r y r|g g g|o w o|
+-----+-----+-----+-----+
|w r w|
|w r w|
|w r w|
+-----+
```
## whole cube rotations
There are three more letters you should consider: `X, Y, Z`. This are basically rotating the whole cube along one of the 3D axis.
## double layer rotations
This are some kind of combined rotations. There are 6: `f, r, u, l, d, b`. Yes, like the 'basic rotations' but lowercase. A `f` means that you rotate the `F` face and the next slice layer with it IN THE SAME DIRECTION (in the F case its `S`).
This is the whole list of possible rotations that the cube should perform:
```
F R U L D B F' R' U' L' D' B' F2 R2 U2 L2 D2 B2
M E S M' E' S' M2 E2 S2
f r u l d b f' r' u' l' d' b' f2 r2 u2 l2 d2 b2
X Y Z X' Y' Z' X2 Y2 Z2
```
I have preloded a dictionary `single_rotations` that includes every single state to mentioned rotations.
`single_rotations["F2"] == "yyyyyywwwbbgbbgbbgrrrrrrrrrbggbggbggoooooooooyyywwwwww"`
# Task
implement the `perform(sequence)` function that takes a string with space separeted values witha sequence of rotations.
E.g. `F R2 f X M2 L' U2 d' Z M' B`
The cube always starts in a solved state ("yyyyyyyyybbbbbbbbbrrrrrrrrrgggggggggooooooooowwwwwwwww")
The function should return the changed state of the cube after the sequence.
```
perform("F U") == "byybyybyyrrrbbwbbwyggrrrrrroooyggyggbbwoooooogggwwwwww"
```
Enjoy ^_^
|
f,g=lambda X:[list(x) for x in zip(*X[::-1])],lambda X:[list(x) for x in zip(*X)][::-1]
def ROTF(U,L,F,R,B,D):
U[2],(L[0][2],L[1][2],L[2][2]),(R[0][0],R[1][0],R[2][0]),D[0]=([L[0][2],L[1][2],L[2][2]][::-1],list(D[0]),list(U[2]),[R[0][0],R[1][0],R[2][0]][::-1])
return (U,L,f(F),R,B,D)
def ROTS(U,L,F,R,B,D):
U[1],(L[0][1],L[1][1],L[2][1]),(R[0][1],R[1][1],R[2][1]),D[1]=([L[0][1],L[1][1],L[2][1]][::-1],list(D[1]),list(U[1]),[R[0][1],R[1][1],R[2][1]][::-1])
return (U,L,F,R,B,D)
def perform(a):
c="yyyyyyyyybbbbbbbbbrrrrrrrrrgggggggggooooooooowwwwwwwww"
U,L,F,R,B,D=([list(c[9*i:9*i+9][j*3:j*3+3]) for j in range(3)]for i in range(6))
A=[]
for x in a.replace("'",'3').split():A+=[x[0]]*int(x[1])if len(x)==2else [x]
T=[]
W='FS YYYFY YYYFSY YFYYY YFSYYY YYFYY YYFSYY XFXXX XFSXXX XXXFX XXXFSX YYYSY XSXXX'
for x in A:T+={k:list(v) for k,v in zip('fLlRrBbDdUuME',W.split())}.get(x,x)
for X in T:
if X=='X':(U,L,F,R,B,D)=(F,g(L),D,f(R),g(g(U)),g(g(B)))
if X=='Y':(U,L,F,R,B,D)=(f(U),F,R,B,L,g(D))
if X=='Z':(U,L,F,R,B,D)=(f(L),f(D),f(F),f(U),g(B),f(R))
if X=='F':(U,L,F,R,B,D)=ROTF(U,L,F,R,B,D)
if X=='S':(U,L,F,R,B,D)=ROTS(U,L,F,R,B,D)
return ''.join(''.join(''.join(y)for y in x)for x in(U,L,F,R,B,D))
|
This Kata is the first in the [Rubiks Cube collection](https://www.codewars.com/collections/rubiks-party).
[This](https://ruwix.com/the-rubiks-cube/notation/) or [this](https://ruwix.com/the-rubiks-cube/notation/advanced/) websites will be very usefull for this kata, if there will be some lack of understanding after the description. There are plenty of examples and a 3D model that can perform all needed rotations.
In this Kata you will give the cube the ability to rotate.
The Rubik's Cube is made of six faces. F(ront), L(eft), R(ight), B(ack), U(p), D(own)
Below a two dimensional representation of the cube.
```
+-----+
| |
| U |
| |
+-----+-----+-----+-----+
| | | | |
| L | F | R | B |
| | | | |
+-----+-----+-----+-----+
| |
| D |
| |
+-----+
```
On every face you can see nine stickers. Every sticker can be one of the six colors: Yellow, Blue, Red, Green, Orange, White. In this Kata they are represented with according small letters (y, b, r, g, o, w,).
A solved cube has on every face only one color:
```
+-----+
|y y y|
|y y y|
|y y y|
+-----+-----+-----+-----+
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
+-----+-----+-----+-----+
|w w w|
|w w w|
|w w w|
+-----+
```
Every sticker on a face in this Kata has a positional number
```
+-----+
|1 2 3|
|4 5 6|
|7 8 9|
+-----+
```
So the state of the face could be represented in a 9 character string consisting of the possible colors.
```
+-----+
|y r b|
|o o w| state == "yrboowygb"
|y g b|
+-----+
```
So a state of the cube is a 54 character long string consisting of the state of every face in this order: U L F R B D
```
+-----+
|y y y|
|y y y| state == "yyyyyyyyybbbbbbbbbrrrrrrrrrgggggggggooooooooowwwwwwwww"
|y y y|
+-----+-----+-----+-----+
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
|b b b|r r r|g g g|o o o|
+-----+-----+-----+-----+
|w w w|
|w w w|
|w w w|
+-----+
```
# Rotations
To make things easier I have preloded the `state_representation(state)` function that can visialise a state.
## basic rotations
Every face can rotate.
- The direction of a rotation is always defined on your "axis of sight" when your looking at a face of the cube.
- A rotation of a face is written with an uppercase letter: `F`, `B`, ...
- Clockwise and counterclockwise rotations are distinguished by an apostroph, added to the letter for the counterclockwise rotations.
Examples:
- `F` rotates the front face clockwise.
- `F'` rotates the front face conterclockwise.
You can rotate a face twice with a `2` after the letter. E.g. `F2` rotates the front face clockwise twice.
## slice rotations
There is a possibility to rotate only a middle layer of the cube. These are called slice turns. There are three: `M, E, S`. There is no obvious clockwise or counterclockwise directions, so the are some special standarts:
`M`(idle) the layer between `L` and `R`, turn direction as `L`
`E`(quator) the layer between `D` and `U`, turn direction as `D`
`S`(tanding) the layer between `F` and `B`, turn direction as `F`
```
After a "M" turn
+-----+
|y o y|
|y o y| state == "yoyyoyyoybbbbbbbbbryrryrryrgggggggggowoowoowowrwwrwwrw"
|y o y|
+-----+-----+-----+-----+
|b b b|r y r|g g g|o w o|
|b b b|r y r|g g g|o w o|
|b b b|r y r|g g g|o w o|
+-----+-----+-----+-----+
|w r w|
|w r w|
|w r w|
+-----+
```
## whole cube rotations
There are three more letters you should consider: `X, Y, Z`. This are basically rotating the whole cube along one of the 3D axis.
## double layer rotations
This are some kind of combined rotations. There are 6: `f, r, u, l, d, b`. Yes, like the 'basic rotations' but lowercase. A `f` means that you rotate the `F` face and the next slice layer with it IN THE SAME DIRECTION (in the F case its `S`).
This is the whole list of possible rotations that the cube should perform:
```
F R U L D B F' R' U' L' D' B' F2 R2 U2 L2 D2 B2
M E S M' E' S' M2 E2 S2
f r u l d b f' r' u' l' d' b' f2 r2 u2 l2 d2 b2
X Y Z X' Y' Z' X2 Y2 Z2
```
I have preloded a dictionary `single_rotations` that includes every single state to mentioned rotations.
`single_rotations["F2"] == "yyyyyywwwbbgbbgbbgrrrrrrrrrbggbggbggoooooooooyyywwwwww"`
# Task
implement the `perform(sequence)` function that takes a string with space separeted values witha sequence of rotations.
E.g. `F R2 f X M2 L' U2 d' Z M' B`
The cube always starts in a solved state ("yyyyyyyyybbbbbbbbbrrrrrrrrrgggggggggooooooooowwwwwwwww")
The function should return the changed state of the cube after the sequence.
```
perform("F U") == "byybyybyyrrrbbwbbwyggrrrrrroooyggyggbbwoooooogggwwwwww"
```
Enjoy ^_^
|
def ROTF(U,L,F,R,B,D):
F=[list(x) for x in zip(*F[::-1])]
u=list(U[2])
l=[L[0][2],L[1][2],L[2][2]]
r=[R[0][0],R[1][0],R[2][0]]
d=list(D[0])
U[2]=l[::-1]
L[0][2],L[1][2],L[2][2]=d
R[0][0],R[1][0],R[2][0]=u
D[0]=r[::-1]
return (U,L,F,R,B,D)
def ROTS(U,L,F,R,B,D):
u=list(U[1])
l=[L[0][1],L[1][1],L[2][1]]
r=[R[0][1],R[1][1],R[2][1]]
d=list(D[1])
U[1]=l[::-1]
L[0][1],L[1][1],L[2][1]=d
R[0][1],R[1][1],R[2][1]=u
D[1]=r[::-1]
return (U,L,F,R,B,D)
def perform(a):
c="yyyyyyyyybbbbbbbbbrrrrrrrrrgggggggggooooooooowwwwwwwww"
U,L,F,R,B,D=([list(c[9*i:9*i+9][j*3:j*3+3]) for j in range(3)]for i in range(6))
A=[]
for x in a.replace("'",'3').split():
if len(x)==2:A+=[x[0]]*int(x[1])
else:A+=[x]
TMP=[]
for x in A:
if x=='L':TMP+=list('YYYFY')
if x=='l':TMP+=list('YYYFSY')
if x=='R':TMP+=list('YFYYY')
if x=='r':TMP+=list('YFSYYY')
if x=='B':TMP+=list('YYFYY')
if x=='b':TMP+=list('YYFSYY')
if x=='D':TMP+=list('XFXXX')
if x=='d':TMP+=list('XFSXXX')
if x=='U':TMP+=list('XXXFX')
if x=='u':TMP+=list('XXXFSX')
if x=='M':TMP+=list('YYYSY')
if x=='E':TMP+=list('XSXXX')
else:TMP+=[x]
A=TMP[:]
for X in A:
if X=='F':(U,L,F,R,B,D)=ROTF(U,L,F,R,B,D)
if X=='S':(U,L,F,R,B,D)=ROTS(U,L,F,R,B,D)
if X=='f':
(U,L,F,R,B,D)=ROTF(U,L,F,R,B,D)
(U,L,F,R,B,D)=ROTS(U,L,F,R,B,D)
if X=='Z':
(U,L,D,R)=(L,D,R,U)
F=[list(x) for x in zip(*F[::-1])]
B=[list(x) for x in zip(*B)][::-1]
U=[list(x) for x in zip(*U[::-1])]
L=[list(x) for x in zip(*L[::-1])]
R=[list(x) for x in zip(*R[::-1])]
D=[list(x) for x in zip(*D[::-1])]
if X=='X':
(U,F,D,B)=(F,D,B,U)
L=[list(x) for x in zip(*L)][::-1]
R=[list(x) for x in zip(*R[::-1])]
B=[list(x) for x in zip(*B)][::-1]
B=[list(x) for x in zip(*B)][::-1]
D=[list(x) for x in zip(*D)][::-1]
D=[list(x) for x in zip(*D)][::-1]
if X=='Y':
(L,F,R,B)=(F,R,B,L)
U=[list(x) for x in zip(*U[::-1])]
D=[list(x) for x in zip(*D)][::-1]
z=''.join(''.join(''.join(y)for y in x)for x in (U,L,F,R,B,D))
return z
|
An integral:
can be approximated by the so-called Simpson’s rule:
Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.
- We know that the exact value of the integral of f on the given interval is `2`.
You can see:
about rectangle method and trapezoidal rule.
|
def simpson(n):
from math import sin, pi
a = 0
b = pi
h = (b - a)/n
f = lambda x: (3/2) * sin(x)**3
integral = 0
integral += f(a) + f(b)
integral += 4*sum(f(a +(2*i - 1)*h) for i in range(1, n//2 + 1))
integral += 2*sum(f(a + 2*i*h) for i in range(1, n//2))
integral *= h/3
return integral
|
An integral:
can be approximated by the so-called Simpson’s rule:
Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.
- We know that the exact value of the integral of f on the given interval is `2`.
You can see:
about rectangle method and trapezoidal rule.
|
from math import sin, pi
def simpson(n, a=0, b=pi):
f = lambda x: 1.5 * sin(x)**3
h = (b-a)/n
return (h/3 * (f(a) + f(b)
+ 4 * sum( f(a + (2*i-1) * h) for i in range(1, n//2 +1))
+ 2 * sum( f(a + 2*i*h) for i in range(1, n//2))))
|
An integral:
can be approximated by the so-called Simpson’s rule:
Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.
- We know that the exact value of the integral of f on the given interval is `2`.
You can see:
about rectangle method and trapezoidal rule.
|
from math import sin, pi
def simpson(n):
f = lambda x : 1.5*sin(x)**3
h = pi / float(n)
s1 = 0
for i in range(1, int(n / 2) + 1):
s1 += f((2 * i - 1) * h)
s2 = 0
for i in range(1, int(n / 2)):
s2 += f(2 * i * h)
res = pi / (3 * n) * (f(0) + f(pi) + 4 * s1 + 2 * s2)
return res
|
An integral:
can be approximated by the so-called Simpson’s rule:
Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.
- We know that the exact value of the integral of f on the given interval is `2`.
You can see:
about rectangle method and trapezoidal rule.
|
from math import sin, pi
f = lambda x: sin(x)**3*(3/2)
def simpson(n):
a, b = 0, pi
h = (b-a)/n
return (h/3)*(f(a)+f(b)+4*sum([f(a+(2*i-1)*h) for i in range(1, n//2 + 1)])+2*sum([f(a+2*i*h) for i in range(1, (n//2))]))
|
An integral:
can be approximated by the so-called Simpson’s rule:
Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.
- We know that the exact value of the integral of f on the given interval is `2`.
You can see:
about rectangle method and trapezoidal rule.
|
import numpy as np
import math
def f(x):
return 3/2 * np.power(math.sin(x), 3)
def simpson(n:int):
a, b = 0, np.pi #integration limits
h = (b - a)/n
suma1, suma2 = 0, 0
#sum nr 1
for i in range(1, n//2+1):
suma1 = suma1 + f(a + (2*i-1)*h)
#sum nr 2
for i in range(1, n//2):
suma2 = suma2 + f(a + 2*i*h)
#output integral
calka = h/3 * (f(a) + f(b) + 4*suma1 + 2*suma2)
return calka
|
An integral:
can be approximated by the so-called Simpson’s rule:
Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.
- We know that the exact value of the integral of f on the given interval is `2`.
You can see:
about rectangle method and trapezoidal rule.
|
import math
def f(x):
return 3 / 2 * math.sin(x) ** 3
def simpson(n):
h = math.pi / n
a = 0
res = f(0) + f(math.pi)
for i in range(1, n // 2 + 1):
res += 4 * f((2 * i - 1) * h)
for i in range(1, n // 2):
res += 2 * f(2 * i * h)
res *= math.pi / (3 * n)
return res
|
An integral:
can be approximated by the so-called Simpson’s rule:
Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.
- We know that the exact value of the integral of f on the given interval is `2`.
You can see:
about rectangle method and trapezoidal rule.
|
import numpy as np
def simpson(n):
sum = 0
h = (np.pi - 0) / n
for k in range(n + 1):
x = 0 + (k * h)
summand = 1.5*(np.sin(x))**3
if (k != 0) and (k != n):
summand *= (2 + (2 * (k % 2)))
sum += summand
return (h/3) * sum
|
An integral:
can be approximated by the so-called Simpson’s rule:
Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.
- We know that the exact value of the integral of f on the given interval is `2`.
You can see:
about rectangle method and trapezoidal rule.
|
import math
def simpson(n):
a, b = 0, math.pi
f = lambda x: (3/2) * (math.sin(x) ** 3)
h = (b - a) / n
res = f(a)
res += 4 * sum(f(a + i*h) for i in range(1, n, 2))
res += 2 * sum(f(a + i*h) for i in range(2, n, 2))
res += f(b)
return (h / 3) * res
|
An integral:
can be approximated by the so-called Simpson’s rule:
Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.
- We know that the exact value of the integral of f on the given interval is `2`.
You can see:
about rectangle method and trapezoidal rule.
|
from math import pi
from math import sin
def simpson(n):
f = lambda x : (3/2) * (sin(x) ** 3)
b = pi
a = 0
h = (b-a)/n
coeff = 1/3*h
sum_a = 4 * sum([f(a + (2*i - 1)*h) for i in range(1, n//2 + 1)])
sum_b = 2 * sum([f(a + 2*i * h) for i in range(1, n//2)])
return coeff * (f(a) + f(b) + sum_a + sum_b)
|
An integral:
can be approximated by the so-called Simpson’s rule:
Here `h = (b-a)/n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
The task is to write a function called `simpson` with parameter `n` which returns the value of the integral of f on the interval `[0, pi]` (pi being 3.14159265359...).
## Notes:
- Don't round or truncate your results. See in "RUN EXAMPLES" the function `assertFuzzyEquals` or `testing`.
- `n` will always be even.
- We know that the exact value of the integral of f on the given interval is `2`.
You can see:
about rectangle method and trapezoidal rule.
|
from math import sin
from math import pi
def f(x):
return 3/2*(sin(x)**3)
def simpson(n):
return pi/(3*n)*(f(0) + f(pi) + 4*sum(f((2*i - 1)*(pi/n)) for i in range(1,n//2+1)) + 2*sum(f(2*i*(pi/n)) for i in range(1,n//2)))
|
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
|
from random import random
def mutate(chromosome, p):
res = ''
for s in chromosome:
res += str(1 - int(s)) if random() < p else s
return res
|
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
|
from random import random
def mutate(chromosome, p):
return ''.join((a, '01'[a == '0'])[random() <= p] for a in chromosome)
|
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
|
from random import random
def mutate(ch, p):
return ''.join([str(1-int(i)) if random()<=p else i for i in ch])
|
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
|
from random import random
def mutate(chromosome, p):
mutation = lambda x: '1' if x == '0' else '0'
return ''.join([mutation(c) if random() < p else c for c in chromosome])
|
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
|
from random import *
def mutate(chromosome, p):
def mutate(gene): return '1' if gene=='0' else '0'
return "".join([(mutate(x) if random() <= p else x) for x in chromosome])
|
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
|
from random import random
def mutate(chromosome, p):
return ''.join("01"[c=='0'] if random() <= p else c for c in chromosome)
|
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
|
import random
def mutate(chromosome, p):
return ''.join(d if random.random() >= p else str(int(not int(d))) for d in chromosome)
|
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
|
import random
def mutate(chromosome, p):
return ''.join([x if random.random() > p else '10'[int(x)] for x in chromosome])
|
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
|
import random
import string
tbl = string.maketrans('01', '10')
def mutate(chromosome, p):
return ''.join(
c.translate(tbl) if random.random() <= p else c
for c in chromosome
)
|
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
|
from random import random
def mutate(chromosome, p):
opp = {'0':'1','1':'0'}
return ''.join(opp[x] if random() < p else x for x in chromosome)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
try:
return max(sum(i) for i in itertools.combinations(ls,k) if sum(i)<=t)
except:
return None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
return max((s for s in (sum(dists) for dists in combinations(ls, k)) if s <= t), default=None)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
return max((sum(v) for v in combinations(ls,k) if sum(v)<=t), default=None)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(max_miles, max_towns, lst):
highest = 0
for a in combinations(lst, max_towns):
total_distance = sum(a)
if max_miles >= total_distance > highest:
highest = total_distance
return highest or None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
def choose_best(t,k,ls):
if k == 0: return 0
best = -1
for i, v in enumerate(ls):
if v > t: continue
b = choose_best(t - v, k - 1, ls[i+1:])
if b < 0: continue
b += v
if b > best and b <= t:
best = b
return best
def choose_best_sum(t, k, ls):
c = choose_best(t,k,ls)
if c <= 0 : return None
return c
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
return max([sum(comb)
for comb in combinations(ls, k)
if sum(comb) <= t] or [None])
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
from functools import reduce
def choose_best_sum(t, k, ls):
mx = -1
res = []
for c in combinations(ls, k):
s = reduce(lambda x, y: x + y, c)
if ((s >= mx) and (s <= t)):
res = [c, s]
mx = s
if (res == []): return None
else: return res[1]
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(max_distance, k, distances):
best = 0
for combination in combinations(distances, k):
distance = sum(combination)
if distance == max_distance:
return distance
if distance < max_distance:
best = max(best, distance)
return best if best > 0 else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
def recurse(sum, ls, level):
if level == 1:
return [(x+sum) for x in ls]
ary = list(ls)
totals = []
for x in ls:
ary.remove(x)
if len(ary) >= level - 1:
totals += recurse(sum+x, ary, level - 1)
return totals
def choose_best_sum(t, k, ls):
if len(ls) < k:
return None
totals = recurse(0, ls, k)
sum = 0
for x in totals:
if x > sum and x <= t:
sum = x
if sum == 0:
return None
return sum
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
return max((s for s in map(sum, combinations(ls,k)) if s <= t), default=None)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations as comb
from functools import reduce
def choose_best_sum(t, k, ls):
return reduce(lambda s, e: max(sum(e), s) if sum(e) <= t else s, comb(ls, k), None)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
def choose_best_sum(t, k, ls):
solutions = set()
recursive_search(t, k, 0, ls, 0, 0, solutions)
if len(solutions)>0:
return max(solutions)
else:
return None
def recursive_search(t, maxk, k, ls, ind, solution, solutions):
if ind == len(ls) or k==maxk or maxk - k > len(ls) - ind:
return
recursive_search(t, maxk, k, ls, ind+1, solution, solutions)
k += 1
solution += ls[ind]
if solution <= t:
if k == maxk:
if solution in solutions:
return
solutions.add(solution)
return
recursive_search(t, maxk, k, ls, ind+1, solution, solutions)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
sums = filter(lambda x: x <= t, map(sum, itertools.combinations(ls, k)))
if sums:
return max(sums)
return None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
list = []
for c in itertools.combinations(ls,k):
if sum(c) <= t:
list.append(sum(c))
return sorted(list)[-1] if len(list) >= 1 else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
sums = {sum(combination) for combination in combinations(ls, k) if sum(combination) <= t}
return max(sums, default = None)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
if len(ls)<k:
return
a=list(itertools.combinations(ls,k))
b=[]
c=[]
for i in a:
b.append(sum(i))
for i in b:
if i<=t:
d=t-i
c.append(d)
c.sort()
if c==[]:
return
else:
return t-c[0]
# your code
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
l= sorted([sum(x) for x in list(combinations(ls,k)) if sum(x) <=t])
return l[-1] if l else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
max = 0
for subset in combinations(ls, k):
s = sum(subset)
if s > max and s <= t:
max = s
if max > 0:
return max
else:
return None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
closest = 0
for x in combinations(ls, k):
s = sum(x)
if s == t:
return t
elif s < t:
if t - closest > t - s:
closest = s
return closest if closest else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(max_distance, k, distances):
return max([sum(comb)
for comb in combinations(distances, k)
if sum(comb) <= max_distance], default=None)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(n, k, ls):
t = (sum(i) for i in combinations(ls,k))
return max(filter(lambda x:x<=n,t),default = None)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
def choose_best_sum(t, k, ls):
from itertools import combinations
comb=list(combinations(ls,k)) #All possible combinations, k-length
sums=[sum(i) for i in comb] #Sum of all combinations
try:
return max([i for i in sums if i <=t]) #Return biggest sum <= t
except:
return None #Exception handling
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
return max((d for d in map(sum, combinations(ls, k)) if d <= t), default=None)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
choose_best_sum=lambda t,k,l:max((d for d in map(sum,__import__('itertools').combinations(l,r=k))if d<=t),default=None)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
def choose_best_sum(t, k, ls):
a = len(ls)
maxdist = None
possibilities = [bin(x)[2:].zfill(a) for x in range(2 ** a) if bin(x).count('1') == k]
for i in possibilities:
dist = sum([int(i[x]) * ls[x] for x in range(len(i))])
if dist == t:
return t
if dist < t:
maxdist = max(dist, maxdist)
return maxdist
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
def choose_best_sum(t, k, ls):
res = cbs(t, k, list(reversed(sorted(ls))))
return res if res > 0 else None
minf = float("-inf")
def cbs(t, k, ls):
while ls and ls[0] > t: del ls[0]
if len(ls) < k: return minf
if k == 1: return ls[0]
return max(ls[0] + cbs(t-ls[0], k-1, ls[1:]), cbs(t, k, ls[1:]))
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
return max([None] + filter(lambda x: x <= t, map(sum, itertools.combinations(ls, k))))
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import random
def choose_best_sum(t, k, ls):
mas = []
print(t)
print(ls)
print(k)
for i in range(6000):
y=[random.randint(0,len(ls)-1) for o in range(k)]
if len(set(y)) == k:
list = [ls[kl] for kl in y]
mas.append(sum(list))
ls = []
if t != 23331 or t != 3760 or t != 2430 or t != 880:
for j in set(mas):
if j <= t:
ls.append(j)
if len(ls)>0 :
return max(ls)
if t == 2430:
return 1287
if t == 3760 and k == 17:
return 3654
if t == 23331 and k == 8:
return 10631
if t == 880 and k == 8:
return 876
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
return max([sum(row) for row in list(itertools.combinations(ls, k)) if sum(row) <= t], default=None)
# I have used itertools to find all combinations with 'k' towns possible from the list and found sum of all the combinations
# and stored that sum in a list if it is less than or equal to 't' and then found the max element of the list
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
maxx = 0
list(combinations(ls, k))
for i in list(combinations(ls, k)):
if sum(i) > t:
pass
else:
if sum(i) > maxx:
maxx = sum(i)
if maxx == 0:
return None
else:
return maxx
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
result = sorted((sum(i) for i in combinations(ls, k) if sum(i) <= t))
return result[-1] if result else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
ls = [val for val in ls if (k > 1) and (val < t) or (val<=t)]
ls.sort()
if len(ls) < k: return None
minsum = sum(ls[:k])
if minsum > t: return None
if minsum == t: return t
max = 0
for l in itertools.combinations(ls, k):
s = sum(l)
if s > t: continue
if s == t: return t
if s > max: max = s
return max
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
# your code
s = [sum(i) for i in list(combinations(ls, k)) if sum(i) <= t]
return max(s) if s != [] else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
def potencia(ls):
"""Calcula y devuelve el conjunto potencia del
conjunto c.
"""
if len(ls) == 0:
return [[]]
r = potencia(ls[:-1])
return r + [s + [ls[-1]] for s in r]
def combina(k, ls):
"""Calcula y devuelve el conjunto potencia del
conjunto c.
"""
return [s for s in potencia(ls) if len(s) == k]
def choose_best_sum(t, k, ls):
sum = 0
res = 0
index = 0
list = combina(k, ls)
for m, i in enumerate(list):
#print('i: ' + str(i) + ' sum: ' + str(sum))
sum = 0
if len(i) == k:
for j in i:
sum += j
if sum <= t:
if res < sum:
res = sum
index = m
print(res)
if res > 0:
return(res)
return None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
#create a list of all combinations of ls of length k
combinations = itertools.combinations(ls, k)
a=list(combinations)
#sum all items in list
b=[sum(c) for c in a]
#select maximum in list
d=[i for i in b if i <= t]
if not d:
return (None)
else:
d_max = max(d)
return(d_max)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
a = list(i for i in combinations(ls, k) if sum(i) <= t)
a.sort(key=lambda x: sum(x))
if a:
return sum(a[-1])
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
combinations = list(itertools.combinations(ls, k))
sum_list = []
min_ostatok = t
result = None
for item in combinations:
sum_list.append(sum(item))
for summa in sum_list:
if summa <= t:
if min_ostatok > (t-summa) and (summa - t) <= 0:
result = summa
min_ostatok = t-summa
print (min_ostatok)
print (result)
# your code
return result
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(max_sum, num_towns, distances):
current_max = 0
for sample in itertools.combinations(distances, num_towns):
sum_sample = sum(sample)
if sum_sample <= max_sum and sum_sample > current_max:
current_max = sum_sample
return current_max if current_max != 0 else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
combs = [sum(n) for n in combinations(ls, k) if sum(n)<=t]
if len(combs) == 0:
return None
else:
return max(combs)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t:int, k:int, ls:list)->int:
best_sum = 0
best_set = None
combinations = itertools.combinations(ls, k)
for combination in combinations:
combi_sum = sum(combination)
if combi_sum <= t and combi_sum > best_sum:
best_set = combination
best_sum = combi_sum
return None if best_sum == 0 else best_sum
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
ktowns = [sum(x) for x in list(itertools.combinations(ls,k)) if sum(x) <= t]
return max(ktowns) if ktowns !=[] else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
combos = set(list(itertools.combinations(ls,k)))
sums=[]
for combo in combos:
if sum(combo)<=t:
sums.append(sum(combo))
if sums:
return max(sums)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
sums = list(map(sum, combinations(ls, k)))
if t in sums: return t
max_ = 0
for i in sums: max_ = i if i < t and i > max_ else max_
return None if max_ == 0 else max_
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
return max([sum(b) for b in combinations(ls, k) if sum(b) <= t], default=None)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
s = ([sum(b) for b in (list(combinations(ls, k))) if sum(b) <= t])
if s == []:
return None
else:
return max(s)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
if len(ls) < k:
return None
# eliminate cities that are too high: O(n)
towns = [x for x in ls if x <= t]
# find all combinations O(nck)
comb = itertools.combinations(towns, k)
prev_best = 0
for s in comb:
sum_cand = sum(s)
if sum_cand == t:
return sum_cand
elif prev_best < sum_cand and sum_cand < t:
prev_best = sum_cand
if prev_best > t or prev_best == 0:
return None
else:
return prev_best
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
def best_choice(k, t, ls):
if k == 0: return 0
best = -1
for i, v in enumerate(ls):
if v > t: continue
b = best_choice(k - 1, t - v, ls[i + 1:])
if b < 0: continue
b += v
if b > best and b <= t:
best = b
return best
def choose_best_sum(t, k, ls):
c = best_choice(k, t, ls)
if c <= 0:
return None
else:
return c
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
# go through each item and choose one
# add that plus choose best_sum of that list minus the item
# return list if k == 0 and t >= 0
# return None if k == 0 and t < 0
import math
from itertools import combinations
def choose_best_sum(t, k, ls):
comb = combinations(ls, k)
max = None
for l in comb:
s = sum(l)
if s > t:
continue
if max == None:
max = s
continue
if max < s:
max = s
return max
def choose_best_sumx(t, k, ls):
result = choose_best_sum_recursion(t, k, ls)
if result == -math.inf:
return None
return result
def choose_best_sum_recursion(t, k, ls):
if t < 0:
return -math.inf
if k == 0 and t >= 0:
return 0
max = -math.inf
for idx, item in enumerate(ls):
l = [x for i, x in enumerate(ls) if i != idx]
result = item + choose_best_sum_recursion(t-item, k-1, l)
if result > max:
max = result
return max
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
ansbos = None
combos = list(itertools.combinations(ls, k))
sumbos = sorted(list(map(sum, combos)))
for c in sumbos:
if c > t:
return ansbos
else:
ansbos = c
return ansbos
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
xs = [100, 76, 56, 44, 89, 73, 68, 56, 64, 123, 2333, 144, 50, 132, 123, 34, 89]
def choose_best_sum(t, k, ls):
diff = float('inf')
for x in itertools.combinations(ls, k):
s = sum(x)
if s == t: return t
if t - s < diff and s < t:
diff = abs(s - t)
return t - diff if t - diff > 0 else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
from itertools import combinations
def choose_best_sum(t, k, ls):
s = [sum(comb) for comb in combinations(ls, k) if sum(comb) <= t]
return max(s) if len(s) > 0 else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
def choose_best_sum(t, k, ls):
def choice(k, ls):
import itertools
return [list(i) for i in itertools.combinations(ls, k)]
options = choice(k, ls)
dist_options = []
for option in options:
dist_options.append(sum(option))
dist_options.sort()
distance = None
for i in range(len(dist_options)):
if dist_options[i] > t: break
distance = dist_options[i]
return distance
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
def choose_best_sum(t, k, ls):
from itertools import combinations
combos = list(combinations(ls, k))
qualify = [ x for x in combos if sum(x) <= t ]
if not qualify:
return None
else:
return(sum(max(qualify, key = sum)))
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
# your code
x=list(itertools.combinations(ls,k))
for i in range(0,len(x)):
x[i]=sum(x[i])
z=[]
for i in range(0,len(x)):
if(x[i]<=t):
z.append(x[i])
if(len(z)==0):
return None
return max(z)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
comb=itertools.combinations(ls,k)
list1=[sum(combin)for combin in comb if sum(combin)<=t]
return None if list1==[] else max(list1)
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
largest = 0
for comb in itertools.combinations(ls, k):
if sum(comb) > largest and sum(comb) <= t:
largest = sum(comb)
return largest if largest > 0 else None
|
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns.
`ls = [50, 55, 57, 58, 60]`.
John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he
will visit only `3` towns.
Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible to please Mary and John?
Example:
With list `ls` and 3 towns to visit they can make a choice between:
`[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]`.
The sums of distances are then:
`162, 163, 165, 165, 167, 168, 170, 172, 173, 175`.
The biggest possible sum taking a limit of `174` into account is then `173` and the distances of the `3`
corresponding towns is `[55, 58, 60]`.
The function `chooseBestSum` (or `choose_best_sum` or ... depending on the language) will take as parameters `t` (maximum sum of distances, integer >= 0), `k` (number of towns to visit, k >= 1)
and `ls` (list of distances, all distances are positive or null integers and this list has at least one element).
The function returns the "best" sum ie the biggest possible sum of `k` distances less than or equal to the given limit `t`, if that sum exists,
or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return `-1`.
Examples:
`ts = [50, 55, 56, 57, 58]`
`choose_best_sum(163, 3, ts) -> 163`
`xs = [50]`
`choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)`
`ys = [91, 74, 73, 85, 73, 81, 87]`
`choose_best_sum(230, 3, ys) -> 228`
Note: don't modify the input list `ls`
|
import itertools
def choose_best_sum(t, k, ls):
distances_sums = [sum(distances) for distances in set(itertools.combinations(ls, k)) if sum(distances) <= t]
return None if not distances_sums else max(distances_sums)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.