blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
6413f86569da08a37374f72a6c330b1fd67ff02e
|
DayGitH/Python-Challenges
|
/DailyProgrammer/DP20170705B.py
| 896
| 4.21875
| 4
|
"""
[2017-07-05] Challenge #322 [Intermediate] Largest Palindrome
https://www.reddit.com/r/dailyprogrammer/comments/6ldv3m/20170705_challenge_322_intermediate_largest/
# Description
Write a program that, given an integer input n, prints the largest integer that is a palindrome and has two factors
both of string length n.
# Input Description
An integer
# Output Description
The largest integer palindrome who has factors each with string length of the input.
# Sample Input:
1
2
# Sample Output:
9
9009
(9 has factors 3 and 3. 9009 has factors 99 and 91)
# Challenge inputs/outputs
3 => 906609
4 => 99000099
5 => 9966006699
6 => ?
# Credit
This challenge was suggested by /u/ruby-solve, many thanks! If you have a challenge idea, please share it in
/r/dailyprogrammer_ideas and there's a good chance we'll use it.
"""
def main():
pass
if __name__ == "__main__":
main()
| true
|
9843b352194d21f8a67d7de52ba0b2c59c27bc2f
|
DayGitH/Python-Challenges
|
/DailyProgrammer/DP20160916C.py
| 2,259
| 4.25
| 4
|
"""
[2016-09-16] Challenge #283 [Hard] Guarding the Coast
https://www.reddit.com/r/dailyprogrammer/comments/5320ey/20160916_challenge_283_hard_guarding_the_coast/
# Description
Imagine you're in charge of the coast guard for your island nation, but you're on a budget. You have to minimize how
many boats, helicopters and crew members to adequately cover the coast. Each group is responsible for a square area of
coastline.
It turns out this has a mathematical relationship to some interesting mathematics. In fractal geometry, the
[Minkowski–Bouligand Dimension](https://en.wikipedia.org/wiki/Minkowski%E2%80%93Bouligand_dimension), or box counting
dimension, is a means of counting the fractal geometry of a set *S* in Euclidian space R^n. Less abstractly, imagine
the set *S* laid out in an evenly space grid. The box counting dimension would be the minimum number of square tiles
required to cover the set.
More realistically, when doing this counting you'll wind up with some partial tiles and have to overlap, and that's OK
- overlapping boxes are fine, gaps in coastal coverage are not. What you want to do is to minimize the number of tiles
overall. It's easy over estimate, it's another to minimize.
# Input Description
You'll be given two things: a tile size N representing the side of the square, and an ASCII art map showing you the
coastline to cover.
Example:
2
*****
* *
* *
* *
*****
# Output Description
Your program should emit the minimum number of tiles of that size needed to cover the boundary.
From the above example:
8
# Challenge Input
4
**
* **
* *
** *
* *
** *
* *
* *
** **
* *
** ***
* *
* *
** *
* **
** *
** *
* **
* **
* ***
** *
* *
** **
* ****
** ******
*********
"""
def main():
pass
if __name__ == "__main__":
main()
| true
|
78237d17e529cdd02fe42dd409c705b22e255eb8
|
DayGitH/Python-Challenges
|
/DailyProgrammer/20120403B.py
| 1,081
| 4.46875
| 4
|
"""
Imagine you are given a function flip() that returns a random bit (0 or 1 with equal probability). Write a program that
uses flip to generate a random number in the range 0...N-1 such that each of the N numbers is generated with equal
probability. For instance, if your program is run with N = 6, then it will generate the number 0, 1, 2, 3, 4, or 5 with
equal probability.
N can be any integer >= 2.
Pseudocode is okay.
You're not allowed to use rand or anything that maintains state other than flip.
Thanks to Cosmologicon for posting this challenge to /r/dailyprogrammer_ideas!
"""
import random
import matplotlib.pyplot as plt
from bitarray import bitarray
def flip():
return random.getrandbits(1)
def binary_to_int(n):
out = 0
for bit in n:
out = (out << 1) | bit
return out
def randomize(a):
for n, i in enumerate(a):
a[n] = flip()
return a
number = 200
binary = bin(number)[2:]
a = len(binary) * bitarray('0')
while True:
a = randomize(a)
if binary_to_int(a) <= number:
break
print(binary_to_int(a))
| true
|
0b541c06a55954a41a1cf02de616696c28d9abf8
|
DayGitH/Python-Challenges
|
/DailyProgrammer/DP20121023B.py
| 1,571
| 4.1875
| 4
|
"""
[10/23/2012] Challenge #106 [Intermediate] (Jugs)
https://www.reddit.com/r/dailyprogrammer/comments/11xjfd/10232012_challenge_106_intermediate_jugs/
There exists a problem for which you must get exactly 4 gallons of liquid, using only a 3 gallon jug and a 5 gallon
jug. You must fill, empty, and/or transfer liquid from either of the jugs to acquire exactly 4 gallons.
The solution to this particular problem is the following:
- Fill the 5 gallon jug
- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 2 gallons in the 5 gallon jug and 3 gallons in the 3
gallon jug
- Empty the 3 gallon jug
- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 0 gallons in the 5 gallon jug and 2 gallons in the 3
gallon jug
- Fill the 5 gallon jug
- Transfer from the 5 gallon jug to the 3 gallon jug, leaving 4 gallons in the 5 gallon jug and 3 gallons in the 3
gallon jug
- Empty the 3 gallon jug (optional)
The challenge will be to output a set of instructions to achieve an arbitrary final volume given 2 arbitrary sized
gallon jugs. Jugs should be sized in a whole number (integer) amount of gallons. The program must also determine if the
desired volume is impossible with this method (i.e. 2 - 4 gallon jugs to make 3 gallons). The program should be
deterministic, meaning that running with the same inputs always produces the same solution (preventing a random pouring
algorithm). The program should also consider outputting the most optimal set of instructions, but is not necessary.
"""
def main():
pass
if __name__ == "__main__":
main()
| true
|
b268c2242ac7769abf8155f8299f3222452c706c
|
DayGitH/Python-Challenges
|
/DailyProgrammer/DP20120702A.py
| 1,509
| 4.28125
| 4
|
"""
Before I get to today's problem, I'd just like to give a warm welcome to our two new moderators, nooodl and Steve132! We
decided to appoint two new moderators instead of just one, because rya11111 has decided to a bit of a break for a while.
I'd like to thank everyone who applied to be moderators, there were lots of excellent submissions, we will keep you in
mind for the next time. Both nooodl and Steve132 have contributed some excellent problems and solutions, and I have no
doubt that they will be excellent moderators.
Now, to today's problem! Good luck!
If a right angled triangle has three sides A, B and C (where C is the hypothenuse), the pythagorean theorem tells us
that A**2 + B**2 = C**2
When A, B and C are all integers, we say that they are a pythagorean triple. For instance, (3, 4, 5) is a pythagorean
triple because 3**2 + 4**2 = 5**2 .
When A + B + C is equal to 240, there are four possible pythagorean triples: (15, 112, 113), (40, 96, 104),
(48, 90, 102) and (60, 80, 100).
Write a program that finds all pythagorean triples where A + B + C = 504.
Edit: added example.
"""
def pyth_triples(n):
for a in range(n//2):
for b in range(a+1, n//2):
for c in range(b+1, n//2):
if a+b+c == n and (a**2) + (b**2) == (c**2):
print([a, b, c])
elif a+b+c > n:
break
if a+b > n:
break
def main():
pyth_triples(504)
if __name__ == "__main__":
main()
| true
|
08e590ff030b1b2a50b3a0caadd086f4def3630c
|
DayGitH/Python-Challenges
|
/DailyProgrammer/20120611B.py
| 2,005
| 4.40625
| 4
|
"""
You can use the reverse(N, A) procedure defined in today's easy problem [20120611A] to completely sort a list. For
instance, if we wanted to sort the list [2,5,4,3,1], you could execute the following series of reversals:
A = [2, 5, 4, 3, 1]
reverse(2, A) (A = [5, 2, 4, 3, 1])
reverse(5, A) (A = [1, 3, 4, 2, 5])
reverse(3, A) (A = [4, 3, 1, 2, 5])
reverse(4, A) (A = [2, 1, 3, 4, 5])
reverse(2, A) (A = [1, 2, 3, 4, 5])
And the list becomes completely sorted, with five calls to reverse(). You may notice that in this example, the list is
being built "from the back", i.e. first 5 is put in the correct place, then 4, then 3 and finally 2 and 1.
Let s(N) be a random number generator defined as follows:
s(0) = 123456789
s(N) = (22695477 * s(N-1) + 12345) mod 1073741824
Let A be the array of the first 10,000 values of this random number generator. The first three values of A are then
123456789, 752880530 and 826085747, and the last three values are 65237510, 921739127 and 926774748
Completely sort A using only the reverse(N, A) function.
"""
def s(n, sp):
if n == 0:
return 123456789
else:
return (22695477 * sp + 12345) % 1073741824
def reverse(n, a):
return a[:n][::-1] + a[n:]
def basic_revsort(a):
copy_a = a[:]
sort_loc = len(a)
count = 0
while copy_a:
num = max(copy_a)
copy_a.remove(num)
i = a.index(num)+1
if i == sort_loc:
pass
elif i == 0:
a = reverse(sort_loc, a)
count += 1
else:
a = reverse(i, a)
a = reverse(sort_loc, a)
count += 2
sort_loc -= 1
print(count)
return a
def main():
generate = 10000
result = -1
out = []
for i in range(generate):
result = s(i, result)
out.append(result)
# out = [2, 5, 4, 3, 1]
out = basic_revsort(out)
print(sorted(out))
print(out)
if __name__ == "__main__":
main()
| true
|
8be851749005732519c82b72d3b7796187b59edc
|
DayGitH/Python-Challenges
|
/DailyProgrammer/DP20160408C.py
| 2,212
| 4.15625
| 4
|
"""
[2016-04-08] Challenge #261 [Hard] magic square dominoes
https://www.reddit.com/r/dailyprogrammer/comments/4dwk7b/20160408_challenge_261_hard_magic_square_dominoes/
# Description
An NxN magic square is an NxN grid of the numbers 1 through N^2 such that each row, column, and major diagonal adds up
to M = N(N^(2)+1)/2. [See this week's Easy problem for an
example.](https://www.reddit.com/r/dailyprogrammer/comments/4dccix/20160404_challenge_261_easy_verifying_3x3_magic/)
For some even N, you will be given the numbers 1 through N^2 as N^(2)/2 pairs of numbers. You must produce an NxN magic
square using the pairs of numbers like dominoes covering a grid. That is, your output is an NxN magic square such that,
for each pair of numbers in the input, the two numbers in the pair are adjacent, either vertically or horizontally. The
numbers can be swapped so that either one is on the top or left.
For the input provided, there is guaranteed to be at least one magic square that can be formed this way. (In fact there
must be at least eight such magic squares, given reflection and rotation.)
Format the grid and input it into your function however you like.
# Efficiency
An acceptable solution to this problem must be significantly faster than brute force. (This is Hard, after all.) You
don't need to get the optimal solution, but you should run your program to completion on at least one challenge input
before submitting. Post your output for one of the challenge inputs along with your code (unless you're stuck and
asking for help).
Aim to finish one of the three 4x4 challenge inputs within a few minutes (my Python program takes about 11 seconds for
all three). I have no idea how feasible the larger ones are. I started my program on a 6x6 input about 10 hours ago and
it hasn't finished. But I'm guessing someone here will be more clever than me, so I generated inputs up to 16x16.
Good luck!
# Example input
1 9
2 10
3 6
4 14
5 11
7 15
8 16
12 13
# Example output
9 4 14 7
1 12 6 15
16 13 3 2
8 5 11 10
# Challenge inputs
[Challenge inputs](http://pastebin.com/6dkYxvrM)
"""
def main():
pass
if __name__ == "__main__":
main()
| true
|
0b0a585867ad3f4081fb6734d314797ad4dfe6e3
|
DayGitH/Python-Challenges
|
/DailyProgrammer/20120310A.py
| 363
| 4.1875
| 4
|
"""
Write a program that will compare two lists, and append any elements in the second list that doesn't exist in the first.
input: ["a","b","c",1,4,], ["a", "x", 34, "4"]
output: ["a", "b", "c",1,4,"x",34, "4"]
"""
inp1 = ["a","b","c",1,4,]
inp2 = ["a", "x", 34, "4"]
final = inp1[:]
for a in inp2:
if a not in final:
final.append(a)
print(final)
| true
|
cedde37647701d970cc14b091dd084966a18d480
|
DayGitH/Python-Challenges
|
/DailyProgrammer/DP20120808A.py
| 1,026
| 4.1875
| 4
|
"""
[8/8/2012] Challenge #86 [easy] (run-length encoding)
https://www.reddit.com/r/dailyprogrammer/comments/xxbbo/882012_challenge_86_easy_runlength_encoding/
Run-Length encoding is a simple form of compression that detects 'runs' of repeated instances of a symbol in a string
and compresses them to a list of pairs of 'symbol' 'length'. For example, the string
"Heeeeelllllooooo nurse!"
Could be compressed using run-length encoding to the list of pairs
[(1,'H'),(5,'e'),(5,'l'),(5,'o'),(1,'n'),(1,'u'),(1,'r'),(1,'s'),(1,'e')]
Which seems to not be compressed, but if you represent it as an array of 18bytes (each pair is 2 bytes), then we save 5
bytes of space compressing this string.
Write a function that takes in a string and returns a run-length-encoding of that string. (either as a list of pairs
or as a 2-byte-per pair array)
BONUS: Write a decompression function that takes in the RLE representation and returns the original string
"""
def main():
pass
if __name__ == "__main__":
main()
| true
|
679d823627f1fc41e7027d234a4ae51b9ba3868d
|
DayGitH/Python-Challenges
|
/ProjectEuler/pr0019.py
| 1,393
| 4.15625
| 4
|
"""
You are given the following information, but you may prefer to do some research for yourself.
* 1 Jan 1900 was a Monday.
* Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
* A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""
MONTHS = 12
m_dict = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
year = 1900
day = 1
sun_count = 0
# loop through years
while year < 2001:
# loop through months
for m in range(1,MONTHS+1):
# get number of days in month from dictionary
DAYS = m_dict[m]
# make adjustment for leap years
if m == 2:
if year%400 == 0:
DAYS += 1
elif year%100 == 0:
pass
elif year%4 == 0:
DAYS += 1
#loop through days
for n in range(1,DAYS+1):
# count for first sunday of a month
if n == 1 and day == 7 and year > 1900:
sun_count += 1
# day of the week count
day = day + 1 if day < 7 else 1
year += 1
print(sun_count)
| true
|
dca128ba4183ba191a980e31fbe857280b70450f
|
DayGitH/Python-Challenges
|
/DailyProgrammer/20120331A.py
| 502
| 4.125
| 4
|
"""
A very basic challenge:
In this challenge, the
input is are : 3 numbers as arguments
output: the sum of the squares of the two larger numbers.
Your task is to write the indicated challenge.
"""
"""
NOTE: This script requires three input arguments!!!
"""
import sys
arguments = len(sys.argv)
if arguments != 4:
print('Invalid number of arguments:\t{}'.format(arguments - 1))
print('Required number of arguments:\t3')
else:
l = sorted(list(map(int, sys.argv[1:])))
print(sum(l[1:]))
| true
|
ff0d12abcd0f3b346d1da0bb9b0ac5aa0c25f473
|
DayGitH/Python-Challenges
|
/DailyProgrammer/20120216C.py
| 975
| 4.125
| 4
|
'''
Write a program that will take coordinates, and tell you the corresponding number in pascals triangle. For example:
Input: 1, 1
output:1
input: 4, 2
output: 3
input: 1, 19
output: error/nonexistent/whatever
the format should be "line number, integer number"
for extra credit, add a function to simply print the triangle, for the extra credit to count, it must print at least
15 lines.
'''
old_list = []
new_list = [1]
print('Line number?')
line_number = int(input('> '))
print('Integer number?')
int_number = int(input('> '))
# print(new_list)
#generates a pascal triangle tier in each loop
for i in range(line_number - 1):
new_list, old_list = [], new_list
new_list.append(1)
if i > 0:
for e in range(0,len(old_list)-1):
new_list.append(old_list[e] + old_list[e + 1])
new_list.append(1)
# print(new_list)
try:
print('The integer is: {}'.format(new_list[int_number - 1]))
except IndexError:
print('Nonexistent!!!')
| true
|
e468767ef3ec92629303e5c294e393f29ae6ee83
|
DayGitH/Python-Challenges
|
/DailyProgrammer/20120218A.py
| 906
| 4.34375
| 4
|
'''
The exercise today asks you to validate a telephone number, as if written on an input form. Telephone numbers can be
written as ten digits, or with dashes, spaces, or dots between the three segments, or with the area code parenthesized;
both the area code and any white space between segments are optional.
Thus, all of the following are valid telephone numbers: 1234567890, 123-456-7890, 123.456.7890, (123)456-7890,
(123) 456-7890 (note the white space following the area code), and 456-7890.
The following are not valid telephone numbers: 123-45-6789, 123:4567890, and 123/456-7890.
source: programmingpraxis.com
'''
import re
l = ['1234567890', '123-456-7890', '123.456.7890', '(123)456-7890', '(123) 456-7890', '456-7890', '123-45-6789',
'123:4567890', '123/456-7890']
s = re.compile('(([(]*)([0-9]{3})([)]*)([.-]*)([ ]*))*([0-9]{3})([.-]*)([0-9]{4})')
for a in l:
print(s.match(a))
| true
|
f8ce35aa7a18e0b7a6febbd227e0b7a16f2fd832
|
DayGitH/Python-Challenges
|
/DailyProgrammer/DP20120629B.py
| 1,232
| 4.25
| 4
|
"""
Implement the hyperoperator [http://en.wikipedia.org/wiki/Hyperoperation#Definition] as a function hyper(n, a, b), for
non-negative integers n, a, b.
hyper(1, a, b) = a + b, hyper(2, a, b) = a * b, hyper(3, a, b) = a ^ b, etc.
Bonus points for efficient implementations.
thanks to noodl for the challenge at /r/dailyprogrammer_ideas ! .. If you think yo have a challenge worthy for our
sub, do not hesitate to submit it there!
Request: Please take your time in browsing /r/dailyprogrammer_ideas and helping in the correcting and giving suggestions
to the problems given by other users. It will really help us in giving quality challenges!
Thank you!
"""
def hyper(n, a, b, cache):
# expect n >= 0
args = list(map(str, [n, a, b]))
if ','.join(args) in cache:
return cache[','.join(args)]
if not n:
answer = b + 1
elif n == 1:
answer = a + b
elif n == 2:
answer = a * b
elif n == 3:
answer = a ** b
elif not b:
answer = 1
else:
answer = hyper(n-1, a, hyper(n, a, b-1, cache), cache)
cache[','.join(args)] = answer
return answer
def main():
print(hyper(5, 3, 2, {}))
if __name__ == "__main__":
main()
| true
|
db322807d137276219ecaab479af539fe4088cb5
|
DayGitH/Python-Challenges
|
/DailyProgrammer/DP20170619A.py
| 1,147
| 4.125
| 4
|
"""
[2017-06-19] Challenge #320 [Easy] Spiral Ascension
https://www.reddit.com/r/dailyprogrammer/comments/6i60lr/20170619_challenge_320_easy_spiral_ascension/
# Description
The user enters a number. Make a spiral that begins with 1 and starts from the top left, going towards the right, and
ends with the square of that number.
# Input description
Let the user enter a number.
# Output description
Note the proper spacing in the below example. You'll need to know the number of digits in the biggest number.
You may go for a CLI version or GUI version.
# Challenge Input
5
4
# Challenge Output
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
# Bonus
As a bonus, the code could take a parameter and make a clockwise or counter-clockwise spiral.
# Credit
This challenge was suggested by /u/MasterAgent47 (with a bonus suggested by /u/JakDrako), many thanks to them both. If
you would like, submit to /r/dailyprogrammer_ideas if you have any challenge ideas!
"""
def main():
pass
if __name__ == "__main__":
main()
| true
|
dea6624c859356ed196474cbb7f746f5d5b44dd8
|
DayGitH/Python-Challenges
|
/DailyProgrammer/DP20120808C.py
| 1,199
| 4.1875
| 4
|
"""
[8/8/2012] Challenge #86 [difficult] (2-SAT)
https://www.reddit.com/r/dailyprogrammer/comments/xx970/882012_challenge_86_difficult_2sat/
Boolean Satisfiability problems are problems where we wish to find solutions to boolean equations such as
(x_1 or not x_3) and (x_2 or x_3) and (x_1 or not x_2) = true
These problems are notoriously difficult, and k-SAT where k (the number of variables in an or expression) is 3 or
higher is known to be
NP-complete.
However, [2-SAT](http://en.wikipedia.org/wiki/2-satisfiability) instances (like the problem above) are NOT NP-complete
(if P!=NP), and even have linear time solutions.
You can encode an instance of 2-SAT as a list of pairs of integers by letting the integer represent which variable is
in the expression, with a negative integer representing the negation of that variable. For example, the problem above
could be represented in list of pair of ints form as
[(1,-3),(2,3),(1,-2)]
Write a function that can take in an instance of 2-SAT encoded as a list of pairs of integers and return a boolean for
whether or not there are any true solutions to the formula.
"""
def main():
pass
if __name__ == "__main__":
main()
| true
|
35a0fdd29e629a3e4bd1e795d6a7de6805243aaa
|
DayGitH/Python-Challenges
|
/DailyProgrammer/20120219A.py
| 491
| 4.4375
| 4
|
'''
The program should take three arguments. The first will be a day, the second will be month, and the third will be year.
Then, your program should compute the day of the week that date will fall on.
'''
import datetime
day_list = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}
year = int(input('Year >> '))
month = int(input('Month >> '))
day = int(input('Day >> '))
print(day_list[datetime.date(year, month, day).weekday()])
| true
|
ea8e85c489477c5736dbbaa83c565228543da9e4
|
seesiva/ML
|
/lpthw/newnumerals.py
| 1,169
| 4.65625
| 5
|
"""
Your Informatics teacher at school likes coming up with new ways to help you understand the material.
When you started studying numeral systems, he introduced his own numeral system,
which he's convinced will help clarify things. His numeral system has base 26, and
its digits are represented by English capital letters - A for 0, B for 1, and so on.
The teacher assigned you the following numeral system exercise:
given a one-digit number, you should find all unordered pairs of one-digit numbers whose values add up to the number.
Example
For number = 'G', the output should be
newNumeralSystem(number) = ["A + G", "B + F", "C + E", "D + D"].
Translating this into the decimal numeral system we get: number = 6, so it is ["0 + 6", "1 + 5", "2 + 4", "3 + 3"].
"""
def newNumeralSystem(number):
letter=number.upper()
alphabet = list('abcdefghijklmnopqrstuvwxyz'.upper())
numeral=alphabet.index(letter)
newNumeral=[]
for i in range(0,(numeral/2)+1):
print i
print i+numeral
newNumeral.append(alphabet[i]+" + "+alphabet[numeral-i])
return newNumeral
if __name__=="__main__":
print newNumeralSystem("g")
| true
|
5514cb1b4588c60ba18477693747381d99b2073f
|
seesiva/ML
|
/lpthw/ex20.py
| 777
| 4.28125
| 4
|
"""
Given a string, , of length that is indexed from to , print its even-indexed and odd-indexed characters as space-separated strings on a single line (see the Sample below for more detail).
Note: is considered to be an even index.
"""
import sys
if __name__=="__main__":
string_list=[]
T=int(raw_input())
for i in range (0,T):
inputstring=raw_input()
string_list.append(inputstring)
for i in range (0,T):
even=""
odd=""
#print i
#print string_list[i]
for j, char in enumerate(string_list[i]):
print j
if j % 2 == 0:
#print char
even=even+char
else:
#print char
odd=odd+char
print even, odd
| true
|
9958b0569eea52042d347d1e977137d3fff8ffc8
|
seesiva/ML
|
/lpthw/euclids.py
| 357
| 4.125
| 4
|
"""
Compute the greatest common divisor of two non-negative integers p and q as follows: If q is 0, the answer is p.
If not, divide p by q and take the remainder r. The answer is the greatest common divisor of q and r.
"""
def gcd(p,q):
if q==0:
return p
else:
r=p % q
return r
if __name__=="__main__":
print gcd(13,2)
| true
|
953469d38c6689be6f48986e855b6b3c6881aa56
|
seesiva/ML
|
/lpthw/ex9.py
| 698
| 4.21875
| 4
|
"""
Higher Order Functions
HoF:Function as a return value
"""
def add_two_nums(x,y):
return x+y
def add_three_nums(x,y,z):
return x+y+z
def get_appropriate_function(num_len):
if num_len==3:
return add_three_nums
else:
return add_two_nums
if __name__=="__main__":
args = [1,2,3]
num_len=len(args)
res_function=get_appropriate_function(num_len)
print(res_function) # when length is 3
print (res_function(*args)) # Addition according to 3 params
args = [1,2]
num_len=len(args)
res_function=get_appropriate_function(num_len)
print(res_function) # when length is 2
print (res_function(*args)) # Addition according 2 parameters
| true
|
db8b5a361d085137634b19777ef97db2ab4db46d
|
TatianaKudryavtseva/python_algoritm
|
/lesson 3_2.py
| 735
| 4.15625
| 4
|
# Во втором массиве сохранить индексы четных элементов первого массива.
# Например, если дан массив со значениями 8, 3, 15, 6, 4, 2,
# второй массив надо заполнить значениями 0, 3, 4, 5,
# (индексация начинается с нуля), т.к. именно в этих позициях первого массива стоят четные числа.
import random
SIZE = 10
MIN_ITEM = 1
MAX_ITEM = 100
array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]
print(array)
array_new = []
for i in range(len(array)):
if array[i] % 2 == 0:
array_new.append(i)
print(array_new)
| false
|
ca138f087a7cdadb84ea054df8fff44596fc265d
|
AdishiSood/The-Joy-of-Computing-using-Python
|
/Week 4/Factorial.py
| 285
| 4.28125
| 4
|
"""
Given an integer number n, you have to print the factorial of this number.
Input Format:
A number n.
Output Format:
Print the factorial of n.
Example:
Input:
4
Output:
24
"""
k = int(input())
fac = 1
for i in range(1,k+1):
if(k==0):
break
fac=fac*i
print(fac)
| true
|
76651f9226b584f4a7a0dfe0f1ceeb338ba0e2ae
|
AdishiSood/The-Joy-of-Computing-using-Python
|
/Week 12/Sentence.py
| 807
| 4.21875
| 4
|
"""
Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalised.
Input Format:
The first line of the input contains a number n which represents the number of line.
From second line there are statements which has to be converted. Each statement comes in a new line.
Output Format:
Print statements with each word in capital letters.
Example:
Input:
2
Hello world
Practice makes perfect
Output:
HELLO WORLD
PRACTICE MAKES PERFECT
"""
n=int(input())
for i in range(n):
print(input().upper(),end="")
if i!=n-1:
print()
or
lines = []
n = int(input())
for i in range(n):
s = input()
if s:
lines.append(s.upper())
else:
break;
for sentence in lines:
print(sentence)
| true
|
82401ab5f1d228c0312819a08859994363fdce4f
|
AdishiSood/The-Joy-of-Computing-using-Python
|
/Week 9/First and Last.py
| 470
| 4.21875
| 4
|
"""
Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string.
Input Format:
The first line of the input contains the String S.
Output Format:
The first line of the output contains the modified string.
Sample Input:
Programming
Sample Output:
Prng
"""
s=input()
output=""
if(len(s)<2):
print("",end="")
else:
print(s[0:2]+s[-2:-1]+s[-1],end="")
| true
|
39adbf633463303ae3395d0f67a349497f293c68
|
rohanaggarwal7997/Studies
|
/Python new/finding most frequent words in a list.py
| 337
| 4.125
| 4
|
from collections import Counter
text='''
dfkjskjefisej tjeistj isejt isejt iseotjeis tiset iesjt iejtes
est isjti esties hesiuhea iurhaur aurhuawh ruahwruawhra u
njra awurhwauirh uawirhuwar huawrh uawrhuaw
ajiawj eiwhaeiaowhe awhewai hiawe
'''
words=text.split()
counter=Counter(words)
print(counter.most_common(3)) #returns tuple
| false
|
e588bbb9899fa27aa4ee92fc9825a38ee626259e
|
kildarejoe1/CourseWork_Lotery_App
|
/app.py
| 1,859
| 4.15625
| 4
|
#Udemy Course Work - Lottery App
#Import the random class
import random
def menu():
"""Controlling method that
1. Ask players for numbers
2. Calculate the lottery numbers
3. Print out the winnings
"""
players_numbers = get_players_numbers()
lottery_numbers = create_lottery_numbers()
if len(players_numbers.intersection(lottery_numbers)) == 1:
print("Congratulations, you have won 10 Euro!!!")
elif len(players_numbers.intersection(lottery_numbers)) == 2:
print("Congratulations, you have won 20 Euro!!!")
elif len(players_numbers.intersection(lottery_numbers)) == 3:
print("Congratulations, you have won 30 Euro!!!")
elif len(players_numbers.intersection(lottery_numbers)) == 4:
print("Congratulations, you have won 40 Euro!!!")
elif len(players_numbers.intersection(lottery_numbers)) == 5:
print("Congratulations, you have won 50 Euro!!!")
elif len(players_numbers.intersection(lottery_numbers)) == 6:
print("Congratulations, you have won it all!!!")
else:
print("Sorry, you have won nothing!!!")
#Get the Lottery numbers
def get_players_numbers():
numbers = str( raw_input("Enter the numbers separated by commas: "))
#Now split the string into a list using the string split method
numbers_in_list=numbers.split(",")
#Now get a set of numbers instead of list of string by using set comprehension, same as list just returns a set.
numbers_in_set={int(x) for x in numbers_in_list}
#Now return a set from the invoking call
return numbers_in_set
#Lottery calaculates 6 random nubers
def create_lottery_numbers():
lottery_num=set()
for x in range(6):
lottery_num.add(random.randint(1,100)) #Prints a random number between 1 and 100
return lottery_num
if __name__ == "__main__":
menu()
| true
|
d35658055b36c894a01b375bb333ae11236ffbfa
|
fabricio24530/ListaPythonBrasil
|
/EstruturaDeDecisao08.py
| 411
| 4.1875
| 4
|
'''Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a
decisão é sempre pelo mais barato.'''
lista = list()
for i in range(3):
produto = float(input(f'Informe o preço do {i + 1}º produto: '))
lista.append(produto)
menor = min(lista)
posicao = lista.index(menor)
print(f'O {posicao + 1}º produto possui o menor preço: R$ {menor}')
| false
|
8d4ede1972573ed6ea89c68ec89ee4ec7e928f55
|
fabricio24530/ListaPythonBrasil
|
/EstruturaSequencial09.py
| 306
| 4.1875
| 4
|
'''Faça um Programa que peça a temperatura em graus Farenheit, transforme e mostre a temperatura em graus Celsius.
C = (5 * (F-32) / 9).'''
temp_f = float(input('Informe a temperatura em graus Farenheit: '))
temp_c = (5 * (temp_f-32) / 9)
print(f'A temperatura {temp_f}°F equivale a {temp_c:.2f}°C')
| false
|
6f96e9df955a926865d9dcdbc2e4231762536507
|
fabricio24530/ListaPythonBrasil
|
/EstruturaDeRepeticao07.py
| 234
| 4.3125
| 4
|
'''Faça um programa que leia 5 números e informe o maior número.'''
lista = list()
for i in range(5):
num = float(input(f'Informe o {i+1}º numero: '))
lista.append(num)
print(f'O maior valor digitado foi: {max(lista)}')
| false
|
5b6b1da23f3ce3c77688148546276ca171cb0300
|
xxxfly/PythonStudy
|
/ProjectBaseTest1/python核心编程/02-高级3-元类/02-元类.py
| 769
| 4.34375
| 4
|
#-*- coding:utf-8 -*-
#元类
# # --类也是对象,就是一组用来描述如何生成一个对象的代码段
# class Person(object):
# num=0
# print('--person--test--') #会直接被执行,说明此时python解释器已经创建了这个类
# def __init__(self):
# self.name='a'
# print(100)
# print('hello')
# print(Person)
# class Person():
# pass
# p1=Person()
# print(type(p1))
#---------------------------------------
# #type 创建类type(类名,集成,方法和属性)
# Test2=type('Test2',(),{'name':'a'})
# t2=Test2()
# print(t2.name)
# print(type(t2))
# def printNum(self):
# print('--num:%d'%self.num)
# Test3=type('Test3',(),{'printNum':printNum,'num':100})
# t3=Test3()
# t3.printNum()
#__metaclass__
| false
|
4508f1a2a2db060764a3ccf1fcf01a56704031aa
|
xxxfly/PythonStudy
|
/ProjectBaseTest1/算法与数据结构/03-排序/06-归并排序.py
| 1,019
| 4.125
| 4
|
#encoding:utf-8
def mergeSort(orgList):
"""递归排序"""
n=len(orgList)
if n<=1:
return orgList
middle=n//2
#left_li 采用归并排序后形成新的有序列表
left_li=mergeSort(orgList[:middle])
#right_li 采用归并排序后形成新的有序列表
right_li=mergeSort(orgList[middle:])
#将两个有序的子序列合并成一个整体
# merage(left_li,right_li)
left_pointer,right_pointer=0,0
result=[]
while left_pointer<len(left_li) and right_pointer<len(right_li):
if left_li[left_pointer]<right_li[right_pointer]:
result.append(left_li[left_pointer])
left_pointer+=1
else:
result.append(right_li[right_pointer])
right_pointer+=1
result+=left_li[left_pointer:]
result+=right_li[right_pointer:]
return result
if __name__=="__main__":
a = [33, 2, 34, 123, 56, 47, 87, 38, 26, 88, 52, 9, 17, 28, 243]
print(a)
sortA=mergeSort(a)
print(a)
print(sortA)
| false
|
88e0893f2afce21f3eae1cf65e1cef3a833f09b2
|
outcoldman/codeinterview003
|
/2013/cracking/01-02.py
| 426
| 4.15625
| 4
|
# coding=utf8
# Write code to reverse a C-Style String. (C-String means that "abcd" is represented as five characters, including the null character.)
def reverse_string(str):
buffer = list(str)
length = len(buffer)
for i in xrange(length / 2):
t = buffer[i]
buffer[i] = str[length - i - 1]
buffer[length - i - 1] = t
return "".join(buffer)
print "Result %s" % reverse_string("abcde")
| true
|
c73a54771e27fb298a73d595b5d925514f68e6cc
|
prashantchanne12/Leetcode
|
/find the first k missing positive numbers.py
| 1,383
| 4.125
| 4
|
'''
Given an unsorted array containing numbers and a number ‘k’, find the first ‘k’ missing positive numbers in the array.
Example 1:
Input: [3, -1, 4, 5, 5], k=3
Output: [1, 2, 6]
Explanation: The smallest missing positive numbers are 1, 2 and 6.
Example 2:
Input: [2, 3, 4], k=3
Output: [1, 5, 6]
Explanation: The smallest missing positive numbers are 1, 5 and 6.
Example 3:
Input: [-2, -3, 4], k=2
Output: [1, 2]
Explanation: The smallest missing positive numbers are 1 and 2.
'''
def find_first_k_missing_positive(nums, k):
n = len(nums)
i = 0
while i < n:
j = nums[i] - 1
if nums[i] > 0 and nums[i] <= n and nums[i] != nums[j]:
# swap
nums[i], nums[j] = nums[j], nums[i]
else:
i += 1
missing_numbers = []
extra_numbers = set()
for i in range(n):
if len(missing_numbers) < k:
if nums[i] != i + 1:
missing_numbers.append(i+1)
extra_numbers.add(nums[i])
# add the remaining numbers
i = 1
while len(missing_numbers) < k:
candidate_number = i + n
# ignore if the extra_array contains the candidate number
if candidate_number not in extra_numbers:
missing_numbers.append(candidate_number)
i += 1
print(missing_numbers)
find_first_k_missing_positive([2, 3, 4], 3)
| true
|
5718a2011b7dcd969516e4c3f2b24b2cebfa713b
|
prashantchanne12/Leetcode
|
/reverse linked list.py
| 1,355
| 4.3125
| 4
|
'''
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
'''
# Solution 1
class Solution(object):
def reverseList(self, head):
prev = None
current = head
while current is not None:
next = current.next
current.next = prev
prev = current
current = next
head = prev
return head
# Solution 2
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def print_list(head):
while head is not None:
print(head.val, end='->')
head = head.next
def reverse_linked_list(current):
previous = None
current = head
next = None
while current is not None:
next = current.next # temporary store the next node
current.next = previous # reverse the current node
# before we move to the next node, point previous node to the current node
previous = current
current = next # move on the next node
return previous
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
reversed = reverse_linked_list(head)
print_list(reversed)
| true
|
d57e3c988f5311a9198d2d8bcd415c58ebb837d6
|
prashantchanne12/Leetcode
|
/daily tempratures.py
| 923
| 4.1875
| 4
|
'''
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90]
Output: [1,1,0]
'''
class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
res = [0] * len(T)
stack = []
for i, t in enumerate(T):
while stack and t > stack[-1][1]:
index, temprature = stack.pop()
res[index] = i - index
stack.append((i, t))
return res
| true
|
20801f067b8f3b6248285c98c759bf60ef833c5f
|
prashantchanne12/Leetcode
|
/backspace string compare - stack.py
| 1,839
| 4.1875
| 4
|
'''
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".
Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".
'''
# Solution - 1
class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
def build(str):
arr = []
for i in str:
if i != '#':
arr.append(i)
else:
if arr:
arr.pop()
return ''.join(arr)
return build(S) == build(T)
# Solution - 2
def build(string):
arr = []
for chr in string:
if chr == '#' and len(arr) != 0:
arr.pop()
elif chr != '#':
arr.append(chr)
return arr
def typed_out_strings(s, t):
s_arr = build(s)
t_arr = build(t)
return ''.join(s_arr) == ''.join(t_arr)
print(typed_out_strings('##z', '#z'))
class Solution:
def backspaceCompare(self, s: str, t: str) -> bool:
string_1 = ''
string_2 = ''
for char in s:
if char == '#':
if len(string_1) > 0:
string_1 = string_1[:-1]
else:
string_1 += char
for char in t:
if char == '#':
if len(string_2) > 0:
string_2 = string_2[:-1]
else:
string_2 += char
return string_1 == string_2
| true
|
4cc773965da12e433077f96090bdeea04579534a
|
prashantchanne12/Leetcode
|
/pascal triangle II.py
| 688
| 4.1875
| 4
|
'''
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
'''
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
res = [[1]]
for i in range(rowIndex):
temp = [0] + res[-1] + [0]
row = []
for j in range(len(res[-1])+1):
row.append(temp[j] + temp[j+1])
res.append(row)
return res[-1]
| true
|
5efbfb64f054e7cbcd77aa0f55599835c48b4d0d
|
prashantchanne12/Leetcode
|
/bitonic array maximum.py
| 998
| 4.34375
| 4
|
'''
Find the maximum value in a given Bitonic array. An array is considered bitonic if it is monotonically increasing and then monotonically decreasing. Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1].
Example 1:
Input: [1, 3, 8, 12, 4, 2]
Output: 12
Explanation: The maximum number in the input bitonic array is '12'.
Example 2:
Input: [3, 8, 3, 1]
Output: 8
Example 3:
Input: [1, 3, 8, 12]
Output: 12
Example 4:
Input: [10, 9, 8]
Output: 10
'''
def find_max_in_bitonic_array(arr):
low = 0
high = len(arr) - 1
while low < high:
mid = (low+high) // 2
if arr[mid] > arr[mid+1]:
high = mid
else:
low = mid + 1
# at the end of the while loop, 'start == end'
return arr[low]
print(find_max_in_bitonic_array([1, 3, 8, 12, 4, 2]))
print(find_max_in_bitonic_array([3, 8, 3, 1]))
print(find_max_in_bitonic_array([1, 3, 8, 12]))
print(find_max_in_bitonic_array([10, 9, 8]))
| true
|
c8ce6f1d1f34106357210c7361c2471bea783240
|
prashantchanne12/Leetcode
|
/smallest missing positive number.py
| 712
| 4.21875
| 4
|
'''
Given an unsorted array containing numbers, find the smallest missing positive number in it.
Example 1:
Input: [-3, 1, 5, 4, 2]
Output: 3
Explanation: The smallest missing positive number is '3'
Example 2:
Input: [3, -2, 0, 1, 2]
Output: 4
Example 3:
Input: [3, 2, 5, 1]
Output: 4
'''
def find_missing_positive(nums):
i = 0
n = len(nums)
while i < n:
j = nums[i] - 1
if nums[i] > 0 and nums[i] <= n and nums[i] != nums[j]:
# swap
nums[i], nums[j] = nums[j], nums[i]
else:
i += 1
for i in range(0, n):
if nums[i] != i + 1:
return i + 1
return n + 1
print(find_missing_positive([3, -2, 0, 1, 2]))
| true
|
1811fedf3317e61f5fa1f70b1669b47cae04716d
|
prashantchanne12/Leetcode
|
/validate binary search tree.py
| 1,294
| 4.125
| 4
|
import math
'''
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [2,1,3]
Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
if root is None:
return True
return self.dfs(root, -math.inf, math.inf)
def dfs(self, root, min_val, max_val):
if root.val <= min_val or root.val >= max_val:
return False
if root.left:
if not self.dfs(root.left, min_val, root.val):
return False
if root.right:
if not self.dfs(root.right, root.val, max_val):
return False
return True
| true
|
0423ec8f68bdbea0933002ff792eaaf73b0026e5
|
prashantchanne12/Leetcode
|
/merge intervals.py
| 1,718
| 4.375
| 4
|
'''
Given a list of intervals, merge all the overlapping intervals to produce a list that has only mutually exclusive intervals.
Example 1:
Intervals: [[1,4], [2,5], [7,9]]
Output: [[1,5], [7,9]]
Explanation: Since the first two intervals [1,4] and [2,5] overlap, we merged them into
one [1,5].
Example 2:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 3:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
'''
def sort_array(intervals):
arr = []
# sort outer elements
intervals.sort()
# sort inner elements
for nums in intervals:
nums.sort()
arr.append(nums)
return arr
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if len(intervals) <= 1:
return intervals
# sort 2D array of intervals
arr = sort_array(intervals)
merged_array = []
start = arr[0][0]
end = arr[0][1]
for i in range(1,len(intervals)):
interval = intervals[i]
if interval[0] <= end:
end = max(end, interval[1])
else:
merged_array.append([start, end])
# update the start and end
start = interval[0]
end = interval[1]
# add the last interval
merged_array.append([start, end])
return merged_array
| true
|
30c022b03d26825d5edcce633de3b490123772eb
|
prashantchanne12/Leetcode
|
/valid pallindrome.py
| 698
| 4.21875
| 4
|
'''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
import re
class Solution(object):
def isPalindrome(self, s):
s = s.lower()
arr = re.findall(r'[^\W_]', s)
s = ''.join(arr)
left = 0
right = len(s) - 1
while left < right:
if s[left] == s[right]:
left += 1
right -= 1
else:
return False
return True
| true
|
04774b08d79956c826dd25ece5d12f3aea56922b
|
sgpl/project_euler
|
/1_solution.py
| 586
| 4.28125
| 4
|
#!/usr/bin/python 2.7
# If we list all the natural numbers
# below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5
# below 1000.
counter = 0
terminating_condition = 1000
sum_of_multiples = 0
while counter < terminating_condition:
if counter % 3 == 0 and counter % 5 == 0:
sum_of_multiples += counter
elif counter % 3 == 0:
sum_of_multiples += counter
elif counter % 5 == 0:
sum_of_multiples += counter
else:
sum_of_multiples += 0
counter += 1
print sum_of_multiples
| true
|
60140c55c6e6b002931c8fe16280ce14bed7186c
|
iamsabhoho/PythonProgramming
|
/Q1-3/MasteringFunctions/PrintingMenu.py
| 713
| 4.21875
| 4
|
#Write a function for printing menus in the terminal.
#The input is a list of options, and the output is the option selected by the user.
print('The options are: ')
#list = input()
#menu = ['Meat','Chicken','Fish']
menu = []
print(menu)
print()
def options(menu):
menu = input('Please enter the options: ')
for i in range(len(menu)):
option = i + 1
print(str(option) + menu[i])
user = input('What is your preference? Press X to exit: ')
if user == 'x':
exit()
elif user == '1':
print(menu[0])
return user
elif user == '2':
print(menu[1])
return user
else:
print(menu[2])
return user
return user
options()
| true
|
c7c547252f8deb024b850f43dea0e73c3e8d849f
|
iamsabhoho/PythonProgramming
|
/Q1-3/WUP#7/Driving.py
| 1,121
| 4.375
| 4
|
#You are driving a little too fast, and a police officer stops you. Write an script that computes the result as “no ticket”, “small ticket”, and “big ticket”. If speed is 60 or less, the result is “no ticket”. If speed is between 61 and 80 inclusive, the result is “small ticket”. If speed is 81 or more, the result is “big ticket”. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. The input of the script in your speed and a boolean variable that indicates if it is your birthday.
import sys
print('The arguments passed were(birthday?/speed?): ')
print(sys.argv)
birthday = str(sys.argv[1])
speed = float(sys.argv[2])
#see if it is the driver's birthday
if birthday == str('yes'):
if 0 <= float(speed) <= 65:
print('No ticket.')
elif 66 <= float(speed) <= 85:
print('Small ticket.')
elif 86 <= float(speed):
print('Big ticket.')
else:
if 0 <= float(speed) <= 60:
print('No ticket.')
elif 61 <= float(speed) <= 80:
print('Small ticket.')
elif 81 <= float(speed):
print('Big ticket.')
| true
|
dbece212a7cbf94c2bc33dc0b26dee6c0933cb81
|
ATLS1300/pc04-generative-section11-sydney-green
|
/PC04_GenArt.py
| 2,373
| 4.1875
| 4
|
"""
Created on Thu Sep 15 11:39:56 2020
PC04 start code
@author: Sydney Green
This code creates two circle patterns from two seperate turtles.
This is different than my pseudocode as I struggled bringing that to life but I was
able to make something I liked so much more. Turtle 1 is a larger circle with larger
cirlces making it up and alternating colors. Turtle 2 is a smaller circle
made up of smaller cirlces containing different alternating colors as turtle 1. The
random aspect of this code is that each time that it is run the circles are located
in different places as the time before. The array of colors represented in each of the patterns
makes me feel warm and happy as both circles contain bright and vibrant color palettes.
"""
#Randomized Circle Dots
#Borrowed code helped me randomize the locations of the circle dots
#Borrowed code is from "Quick guide to random library" canvas assignment page
import turtle
import math, random
turtle.colormode(255)
panel = turtle.Screen().bgcolor('black')
T1large = turtle.Turtle()
#Turtle 1 has its name because it will create the larger circle pattern made of cirlcles
T2small = turtle.Turtle()
#Turtle 2 has its name because it will create the smaller circle pattern made of circles
T2small.shapesize(3)
T1large.width(2)
T2small.width(2)
T1large.speed(11)
T2small.speed(11)
T1large.goto(random.randint(0,250),random.randint(0,250))
#Turtle 1's goto is random. It's random because I want its location to change each time the code is ran.
#This first for loop creates many large circles that come together forming one large complete circle.
for i in range(10):
for colours in [(217,4,41), (220,96,46), (254,215,102), (104,163,87), (4,139,168)]:
T1large.color(colours)
T1large.down()
T1large.circle(50)
T1large.left(10)
T1large.up()
T2small.goto(random.randint(100,350),random.randint(100,350))
#Turtle 2's goto is random. It's random because I want its locaction to change each time the code is ran.
#This second for loop creates many small circles that come together forming one smaller complete circle.
for i in range(10):
for colours in [(138,234,146), (167,153,183), (48,102,190), (255,251,252), (251,186,114)]:
T2small.color(colours)
T2small.down()
T2small.circle(20)
T2small.left(10)
T2small.up()
turtle.done()
| true
|
5e4da675ae102831a30af49576b89c665f7ed89c
|
nelvinpoulose999/Pythonfiles
|
/practice_prgms/factorial.py
| 222
| 4.21875
| 4
|
num=int(input('enter the number'))
factorial=1
if num<0:
print('no should be positive')
elif num==0:
print('the number is 1')
else:
for i in range (1,num+1):
factorial=factorial*i
print(factorial)
| true
|
9bfc470a0656f879c729e2963675c71f00c06d02
|
mercury9181/data_structure_using_python
|
/factorial.py
| 269
| 4.28125
| 4
|
def factorial_using_recursion(n):
if n==0:
return 1
else:
return n * factorial_using_recursion(n-1)
number = int(input('enter the number: '))
result = factorial_using_recursion(number)
print("factorial of "+ str(number)+ " = " + str(result))
| false
|
85263ed8c3d2b28a3502e947024e1c9aaafaec39
|
ShreyasJothish/ML-Precourse
|
/precourse.py
| 1,771
| 4.25
| 4
|
# Machine Learning/Data Science Precourse Work
# ###
# LAMBDA SCHOOL
# ###
# MIT LICENSE
# ###
# Free example function definition
# This function passes one of the 11 tests contained inside of test.py. Write the rest, defined in README.md, here, and execute python test.py to test. Passing this precourse work will greatly increase your odds of acceptance into the program.
def f(x):
return x**2
def f_2(x):
return x**3
def f_3(x):
return (f_2(x)+5*x)
# Derivative functions
# d_f returns the derivative of f
def d_f(x):
return 2*x
# d_f_2 returns the derivative of f_2
def d_f_2(x):
return 3*(x**2)
# d_f_3 returns the derivative of f_3
def d_f_3(x):
return (d_f_2(x)+5)
# Sum of two vectors x and y
def vector_sum(x, y):
v = []
for i in range(len(x)):
v.append(x[i] + y[i])
return v
# Difference of two vectors x and y
def vector_less(x, y):
v = []
for i in range(len(x)):
v.append(x[i] - y[i])
return v
# Magnitude of a vector
def vector_magnitude(v):
sum = 0
for i in v:
sum = sum + i**2
return int(sum ** (1/2))
import numpy as np
def vec5():
return np.array([1,1,1,1,1])
def vec3():
return np.array([0,0,0])
def vec2_1():
return np.array([1,0])
def vec2_2():
return np.array([0,1])
# Matrix multiplication function that multiplies a 2 element vector by a 2x2 matrix
def matrix_multiply(vec,matrix):
result = [0,0]
for i in range(2):
for j in range(2):
result[i] = result[i]+matrix[i][j]*vec[i]
return result
def matrix_multiply_simplified(vec,matrix):
result = [0,0]
result[0] = (matrix[0][0]*vec[0]+matrix[0][1]*vec[1])
result[1] = (matrix[1][0]*vec[0]+matrix[1][1]*vec[1])
return result
| true
|
74bb9bf1887acf303204fa2f16bafefa9ad937f2
|
amarelopiupiu/python-exercicios
|
/ex65.py
| 665
| 4.21875
| 4
|
# Crie um programa que leia uma frase qualquer e diga se ela é um palíndromo, desconsiderando os espaços. Exemplos de palíndromos:
# APÓS A SOPA, A SACADA DA CASA, A TORRE DA DERROTA, O LOBO AMA O BOLO, ANOTARAM A DATA DA MARATONA. (palíndromo é uma palavra que se lê igual de trás para frente e de frente para trás).
frase = str(input('Digite uma frase: ')).strip().upper()
palavras = frase.split()
junto = ''.join(palavras)
inverso = ''
for letra in range(len(junto) - 1, -1, -1):
inverso += junto[letra]
print(f'O inverso de {junto} é {inverso}')
if inverso == junto:
print('Temos um palíndromo')
else:
print('Não temos um palíndromo')
| false
|
770699d93c01420aea23fd0a6e9386a015fc0686
|
amarelopiupiu/python-exercicios
|
/ex28.py
| 273
| 4.125
| 4
|
# Importando apenas uma funcionalidade da biblioteca - peça a raiz quadrada de um número e arredonde ele para cima.
from math import sqrt, ceil
n = float(input('Digite um número para ver a sua raiz quadrada: '))
print('A raiz quadrada de {} é {}' .format(n, sqrt(n)))
| false
|
10902336348620c8a9163eed06e0ced058bdbc6d
|
amarelopiupiu/python-exercicios
|
/ex47.py
| 740
| 4.25
| 4
|
# Escreva um programa em Python que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: 1 para binário, 2 para octal e 3 para hexadecimal. (se você coloca 3 aspas, é possível adicionar mais linhas no print).
n = int(input('Digite um número inteiro: '))
bases = int(input('''
Escolha uma das bases para conversão:
[ 1 ] converter para BINÁRIO
[ 2 ] converter para OCTAL
[ 3 ] converter para HEXADECIMAL
'''))
print(f'Sua opção: {n}')
if bases == 1:
print(f'O número {n} em BINÁRIO é {bin(n)[2:]}')
if bases == 2:
print(f'O número {n} em OCTAL é {oct(n)[2:]}')
if bases == 3:
print(f'O número {n} em HEXADECIMAL é {hex(n)[2:]}')
else:
print('Tente novamente.')
| false
|
29775912584cbf014fe4a2820dd8a5694c9dc7d1
|
jossrc/LearningPython
|
/D012_Scope/project.py
| 803
| 4.15625
| 4
|
import random
random_number = random.randint(1, 100)
# GUESS THE NUMBER
attempts = {
"easy": 10,
"hard": 5
}
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
attempts_remaining = attempts[difficulty]
while attempts_remaining > 0:
print(f"You have {attempts_remaining} attempts remaining to guess the number.")
number = int(input("Make a guess: "))
if number < random_number:
print("Too low.")
elif number > random_number:
print("Too high.")
else:
print(f"You got it! The answer was {random_number}")
break
attempts_remaining -= 1
if attempts_remaining == 0:
print("You've run out of guesses, you lose")
| true
|
8a9d266866367fb2769f200cfc1ba1553084a2d8
|
jossrc/LearningPython
|
/D024_Files/main.py
| 1,100
| 4.34375
| 4
|
# LEER ARCHIVO
"""
FORMA 01 :
Para leer un archivo se debe seguir una secuencia de pasos:
1. Abrir el archivo : Uso de la función open().
2. Leer el archivo : Uso del método read().
3. Cerrar el archivo : Uso del método close().
"""
file = open("my_file.txt")
contents = file.read()
print(contents)
file.close()
"""
FORMA 02 :
Se usa el `with` para evitar el
uso método close() que libera memoria.
Los pasos 1 y 2 son necesarios.
"""
with open("my_file.txt") as file:
contents = file.read()
print(contents)
# ESCRIBIR ARCHIVO
"""
El método open() tiene un segundo parámetro (mode)
este permite el tipo de uso que le daremos al archivo.
Por defecto el `mode` es "r" (Read)
* "w" (Write) : Borra todo el contenido y lo suplanta con el nuevo
* "a" (Append) : Permite agregar más contenido al archivo existente.
Para escribir un archivo se usa el método write()
Si el archivo no existe, crea y lo escribe
"""
with open("my_file.txt", mode="a") as file:
file.write("\nNew paragraph")
| false
|
35eb7b4f8ce9723f9452d06ffd91c6c0db2dd9fe
|
kiyokosaito/Collatz
|
/collatz.py
| 480
| 4.34375
| 4
|
# The number we will perform the Collatz opperation on.
n = int(input ("Enter a positive integer : "))
# Keep looping until we reach 1.
# Note : this assumes the Collatz congecture is true.
while n != 1:
# Print the current value of n.
print (n)
#chech if n is even.
if n % 2 == 0:
#If n is even, divede it by two.
n = n / 2
else :
#If n is odd, multiply by three and add 1.
n = (3 * n ) + 1
#Finally, print the 1.
print (n)
| true
|
d41db68df8a2d22a19518c8a5e6af49d2a29a29e
|
Selvaganapathi06/Python
|
/day4/Day4.py
| 452
| 4.34375
| 4
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#List Reverse
cars = ["bmw", "audi", "toyota", "benz"]
cars.reverse()
print(cars)
# In[3]:
#list sort and reverse
cars = ["bmw", "audi", "toyota", "benz"]
cars.sort()
print(cars)
cars.reverse()
print(cars)
# In[4]:
#creating empty list
a = []
print("created empty list")
print(a)
# In[5]:
#Negative Indexing
#To Access last element
cars = ["bmw", "audi", "toyota", "benz"]
print(cars[-1])
| false
|
bb40d33e9bf091ae3be7652cc60fa12d80c27b71
|
Selvaganapathi06/Python
|
/day3/Day3.py
| 700
| 4.25
| 4
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#sample list and print
bicycles = ["trek", "redline","hero"]
print(bicycles)
# In[2]:
#accessing first element in the list
print(bicycles[0])
# In[4]:
#Apply title()
print(bicycles[0].title())
# In[5]:
#replace element values
bicycles[0] = "Honda"
print(bicycles)
# In[6]:
#append
bicycles.append("ranger")
print(bicycles)
# In[7]:
#insert
bicycles.insert(1,"shine")
print(bicycles)
# In[8]:
#delete from a list
bicycles.pop()
print(bicycles)
# In[9]:
#delete specific element from a list
bicycles.pop(1)
print(bicycles)
# In[11]:
#sorting
cars = ["audi","bmw","benz","toyota"]
cars.sort()
print(cars)
# In[ ]:
| true
|
edb0162e3d1c5b0582c9305da3fe9aff1d9a317b
|
surajbarailee/PythonExercise
|
/python_topics/generators.py
| 2,369
| 4.53125
| 5
|
"""
Retur:. A function that returns a value is called once. The return statement returns a value and exits the function altogether.
Yield: A function that yields values, is called repeatedly. The yield statement pauses the execution of a function and returns a value. When called again, the function continues execution from the previous yield. A function that yields values is known as a generator.
# https://www.codingem.com/wp-content/uploads/2021/11/1_iBgdO1ukASeyaLtSv3Jpnw.png
A generator function returns a generator object, also known as an iterator.
The iterator generates one value at a time. It does not store any values. This makes a generator memory-efficient.
Using the next() function demonstrates how generators work.
In reality, you don’t need to call the next() function.
Instead, you can use a for loop with the same syntax you would use on a list.
The for loop actually calls the next() function under the hood.
"""
def infinite_values(start):
current = start
while True:
yield current
current += 1
"""
When Use Yield in Python
Ask yourself, “Do I need multiple items at the same time?”.
If the answer is “No”, use a generator.
The difference between return and yield in Python is that return is used with regular functions and yield with generators.
The return statement returns a value from the function to its caller. After this, the function scope is exited and everything inside the function is gone.
The yield statement in Python turns a function into a generator.
A generator is a memory-efficient function that is called repeatedly to retrieve values one at a time.
The yield statement pauses the generator from executing and returns a single value. When the generator is called again, it continues execution from where it paused. This process continues until there are no values left.
A generator does not store any values in memory. Instead, it knows the current value and how to get the next one. This makes a generator memory-efficient to create.
The syntactical benefit of generators is that looping through a generator looks identical to looping through a list.
Using generators is good when you loop through a group of elements and do not need to store them anywhere.
"""
# https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions
| true
|
b03282cb9349e6bbad73609dcfe369287d6fa6e6
|
surajbarailee/PythonExercise
|
/python_topics/strings.py
| 973
| 4.375
| 4
|
"""
Strings in python
"""
string = "Hello*World!"
"""
H e l l o * W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
"""
print(string[2:]) # get every element from second index
print(string[-2:]) # get every element from -2
print(string[2:6]) #get every element from second element to sixth (sixth exclusive)
print(string[2:-6])
print(string[::2])
print(string[::-1])
print(string[::-2])
print(string[::-3])
print(string[6:1:-2]) # get every second element from 6 to 1 in reversed
print("=====")
print(string[3::-3]) # get evey third element starting from 3 in reversed
print(string[11:11])
print(len(string))
print(string.upper())
print(string.lower())
print(string.upper())
print(string.lower())
print(string.capitalize())
print(string.title())
print(string.swapcase())
print(string.strip())
print(string.lstrip())
print(string.rstrip())
print(string.replace("World", "Universe"))
| false
|
711895f2590aa58911073abb4914d25ae9320548
|
AyeChanKoGH/Small-code-
|
/DrawPyV1.py
| 1,686
| 4.46875
| 4
|
"""
get screen and drawing shape with python turtle
#To draw line, press "l" key and click first end point and second end point
#To draw circle, press "c" key and click the center point and click the quarent point
#To draw Rectangle, press "r" key and click 1st end point and second end point
#To clean the screen, press "delete" key.
"""
from turtle import*
import turtle
import time
import math
x=0
y=0
clicked=False
#To get the position of on screen click
def on_click(x,y):
global clicked
global po
po=[x,y]
clicked=Turtle
#To wait user point
def wait():
global clicked
turtle.update()
clicked=False
while not clicked:
turtle.update()
time.sleep(.1)
clicked=False
turtle.update()
#drawing turtle line
def line():
turtle.onscreenclick(on_click)
wait()
pu()
goto(po[0],po[1])
Fpo=po
pd()
turtle.onscreenclick(on_click)
wait()
goto(po[0],po[1])
#drawing circle
def dCircle():
turtle.onscreenclick(on_click)
wait()
pu()
goto(po[0],po[1])
Fpo=po
pd()
turtle.onscreenclick(on_click)
wait()
Spo=po
radi=math.sqrt(((Spo[0]-Fpo[0])**2)+((Spo[1]-Fpo[1])**2) )
pu()
goto(Fpo[0],Fpo[1]-radi)
pd()
circle(radi)
#drawing rectangular shape
def rectangle():
turtle.onscreenclick(on_click)
wait()
pu()
goto(po[0],po[1])
Fpo=po
pd()
turtle.onscreenclick(on_click)
wait()
Spo=po
goto(Spo[0],Fpo[1])
goto(Spo[0],Spo[1])
goto(Fpo[0],Spo[1])
goto(Fpo[0],Fpo[1])
#To clean the screen
def Sclear():
clear()
listen()
onkey(dCircle,"c")
onkey(rectangle,"r")
onkey(line,"l")
onkey(Sclear,"Delete")
mainloop()
| true
|
fa085d5bace6c4496c002a929a41548604227ebb
|
kimit956/MyRepo
|
/Simple Math.py
| 402
| 4.125
| 4
|
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
sum1 = num1 + num2
diff1 = num1 - num2
prod1 = num1 * num2
try:
divide1 = num1 / num2
except ZeroDivisionError:
num2 = int(input("Cannot divide by 0. Please enter a different number: "))
divide1 = num1 / num2
print("Sum:", sum1, "\tDifference:", diff1, "\tProduct:", prod1, "\tQuotient:", divide1)
| true
|
ad0e3a2b253ccb2b869fe21dbe25ccfd0320a582
|
NweHlaing/Python_Learning_Udemy_Course
|
/Section_20_Advanced_Python_obj_datastructures/advanced_list.py
| 936
| 4.28125
| 4
|
list1 = [1,2,3]
#append
list1.append(4)
print("list after appand..",list1)
#count
count = list1.count(10)
count1 = list1.count(2)
print("list count..",count)
print("list count 1..",count1)
#append and extend
x = [1, 2, 3]
x.append([4, 5])
print("append...",x)
x = [1, 2, 3]
x.extend([4, 5])
print("extend...",x)
#index
print("index2...",list1.index(2))
#insert
list1.insert(2,'inserted')
print("list1 after insert...",list1)
#pop
ele = list1.pop(1)
print("list1 in pop...",list1)
print("pop ...",ele)
#remove
print("list before remove...",list1)
list1.remove('inserted')
print("list after remove...",list1)
list2 = [1,2,3,4,3]
list2.remove(3)
print("list2 after remove...",list2)
#reverse
print("list2 before reverse...",list2)
list2.reverse()
print("list2 after reverse...",list2)
#sort
print("list2 before sort...",list2)
list2.sort()
print("list2 after sort...",list2)
| false
|
c20743ca806704d3cbdb98cb3bed95e4ebf7af61
|
DeeCoob/hello_python
|
/_manual/format.py
| 1,163
| 4.125
| 4
|
# форматирование строки в стиле C s – форматная строка, x 1 …x n – значения
# s % x
# s % (x 1 , x 2 , …, x n )
# return Python has 002 quote types.
print("%(language)s has %(number)03d quote types." % {'language': "Python", "number": 2})
# '#' The value conversion will use the “alternate form” (where defined below).
# '0' The conversion will be zero padded for numeric values.
# '-' The converted value is left adjusted (overrides the '0' conversion if both are given).
# ' ' (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
# '+' A sign character ('+' or '-') will precede the conversion (overrides a “space” flag).
# s.format(args) форматирование строки в стиле C#
print("The sum of 1 + 2 + {0} is {1}".format(1+2, 6))
print("Harold's a clever {0!s}".format("boy")) # Calls str() on the argument first
print("Bring out the holy {name!r}".format(name="1+3")) # Calls repr() on the argument first
print("More {!a}".format("bloods")) # Calls ascii() on the argument first
| true
|
dcd0873f0dbf3884fea27940dd7ca07bc9f2f902
|
DeeCoob/hello_python
|
/_starter/03_elif.py
| 266
| 4.125
| 4
|
x = float(input("Enter x: "))
if 0 < x < 10:
print("Value is in range")
y = x ** 2 + 2 * x - 3
if y < 0:
print("y = ", y, "; y is negative")
elif y > 0:
print("y = ", y, "; y is positive")
else:
print("y = 0")
| false
|
558c51cde6f1a6992bc7202b5b2cfbbd93e514f6
|
DeeCoob/hello_python
|
/_tceh_lection/05_constructors.py
| 688
| 4.28125
| 4
|
# Constructor is called when new instance is create
class TestClass:
def __init__(self):
print('Constructor is called')
print('Self is the object itself', self)
print()
t = TestClass()
t1 = TestClass()
# Constructor can have parameters
class Table:
def __init__(self, numbers_of_legs):
print('New table has {} legs'.format(numbers_of_legs))
t = Table(4)
t1 = Table(3)
print()
# But we need to save them into the fields!
class Chair:
wood = 'Same tree'
def __init__(self, color):
self.color = color
c = Chair('green')
print(c, c.color, c.wood)
c1 = Chair('Red')
print('variable c did not change!', c.color)
print()
| true
|
d0922c3a88c57e9badfab0b28cc0294eb85eaefd
|
DeeCoob/hello_python
|
/_practic/starter_04_loop_factorial.py
| 405
| 4.3125
| 4
|
# Факториалом числа n называется число 𝑛!=1∙2∙3∙…∙𝑛.
# Создайте программу, которая вычисляет факториал введённого пользователем числа.
while True:
n = int(input("Enter n: "))
f = 1
for i in range(n):
f = f * (i + 1)
print("Factorial from n is", f)
| false
|
a34c861f7c41768a76883e7e6f59c7149f106f36
|
vikramriyer/FCS
|
/rotate_image.py
| 419
| 4.125
| 4
|
#!/usr/bin/python
init_list = [[1,2,3],[4,5,6],[7,8,9]]
def rotate_matrix(matrix):
'''Algo:
First: take transpose of the matrix
Second: interchange row 0 and row 2
'''
matrix = zip(*matrix)
return swap_rows(matrix)
def swap_rows(matrix):
print matrix
row0, row2 = matrix[0], matrix[2]
matrix[0] = row2
matrix[2] = row0
return matrix
final_matrix = rotate_matrix(init_list)
print final_matrix
| true
|
ddbc01b74befc3cb94f28d9f0c23ea1392e7eadb
|
Rkhwong/RHK_CODEWARS
|
/Fundamentals - Python/Arrays/Convert an array of strings to array of numbers.py
| 618
| 4.1875
| 4
|
# https://www.codewars.com/kata/5783d8f3202c0e486c001d23
"""Oh no!
Some really funny web dev gave you a sequence of numbers from his API response as an sequence of strings!
You need to cast the whole array to the correct type.
Create the function that takes as a parameter a sequence of numbers represented as strings and outputs a sequence of numbers.
ie:["1", "2", "3"] to [1, 2, 3]
Note that you can receive floats as well."""
def to_float_array(arr):
new_list = []
for x in (arr):
(new_list.append(float(x)))
return new_list
print( to_float_array(["1.1", "2.2", "3.3"]) )
#RW 02/06/2021
| true
|
d4b2fb6a0358c339c0e5dd7b85962a6ff00bd298
|
maczoe/python_cardio
|
/convertidor.py
| 921
| 4.21875
| 4
|
def convert_km_to_miles(km):
return km * 0.621371
def convert_miles_to_km(miles):
return miles * 1.609344;
def main():
print("Bienvenido a convertidor.py")
seleccion = 0;
while seleccion!=3:
print("----MENU----")
print("1. Millas a kilometros")
print("2. Kilometros a millas")
print("3. Salir")
seleccion = int(input("seleccion: "))
if(seleccion==1):
miles = float(input("Ingrese la cantidad en millas: "))
print(str(miles) + " milla(s) equivale a "+ str(convert_miles_to_km(miles)) + " Kms")
elif(seleccion==2):
km = float(input("Ingrese la cantidad en kilometros: "))
print(str(km) + " kilometro(s) equivale a "+ str(convert_km_to_miles(km)) + " millas")
elif(seleccion!=3):
print("Opcion invalida")
if __name__ == '__main__':
main()
| false
|
8c8861259b03ed4f89574f56a3fff922b05619fa
|
drazovicfilip/Firecode
|
/Problems/firecode4_fibonacci.py
| 1,182
| 4.1875
| 4
|
""" The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it.
Write a recursive method fib(n) that returns the nth Fibonacci number. n is 0 indexed, which means that in the sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ..., n == 0 should return 0 and n == 3 should return 2.
Assume n is less than 15.
Even though this problem asks you to use recursion, more efficient ways to solve it include using an Array, or better still using 3 volatile variables to keep a track of all required values. Check out this blog post to examine better solutions for this problem.
Examples:
fib(0) ==> 0
fib(1) ==> 1
fib(3) ==> 2 """
def fib(n):
# Edge cases
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
elif n == 3:
return 2
previous1 = 1
previous2 = 1
current = previous1 + previous2
# Traverse through the fibonacci sequence, updating it for the needed amount of times
for i in range(3, n):
previous1 = previous2
previous2 = current
current = previous1 + previous2
return current
| true
|
833b170674ce129a25e3efbea133eae6c903cb1b
|
qzylinux/Python
|
/generator.py
| 216
| 4.15625
| 4
|
#generator 返回当前值,并计算下一个值
def mygenerator(max):
a,b,n=0,1,0
while n<max:
yield b
a,b=b,a+b
n=n+1
return 'done'
f=mygenerator(10)
print('mygenerator(10):',f)
for x in f:
print(x)
| false
|
ac5fb09501c10e94d3f0c3149967aa2dc28d46ab
|
pranjal2203/Python_Programs
|
/recursive fibonacci.py
| 518
| 4.5
| 4
|
#program to print fibonacci series using recursion
#recursive function for generating fibonacci series
def FibRecursion(n):
if n <= 1:
return n
else:
return(FibRecursion(n-1) + FibRecursion(n-2))
#input from the users
no = int(input("Enter the terms: "))
#checking if the input is correct or not
if no <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(no):
print(FibRecursion(i),end=" ")
| true
|
2049e82aa7a5a24f4f9bdf39393b2aba2b1faa6a
|
kipland-m/PythonPathway
|
/FactorialRecursion.py
| 764
| 4.21875
| 4
|
# This program is a part of my program series that I will be using to nail Python as a whole.
# Assuming given parameter is greater than or equal to 1 | Or just 0.
def Factorial(n):
if (n >= 1):
return n * Factorial(n-1)
else:
return 1
# Function Fibonacci will take "n" as parameter, in which said parameter returns value in corresponding
# position within Fibonacci sequence, so if n=4 it would return 4th number in Fibonacci sequence.
def Fibonacci(n):
#If this condition is met it can be referred to as the recursive case
if (n >= 3):
return Fibonacci(n-1) + Fibonacci(n-2)
#If this condition is met it can be referred to as the base case
else:
return 1
print(Factorial(3))
print(Fibonacci(4))
| true
|
e32e692b073d079bb59aa2ed83460f8f3ff8802d
|
mukeshmithrakumar/PythonUtils
|
/PythonMasterclass/Exercise2.py
| 1,362
| 4.5625
| 5
|
"""
Create a program that takes an IP address entered at the keyboard
and prints out the number of segments it contains, and the length of each segment.
An IP address consists of 4 numbers, separated from each other with a full stop. But
your program should just count however many are entered
Examples of the input you may get are:
127.0.0.1
.192.168.0.1
10.0.123456.255
172.16
255
So your program should work even with invalid IP Addresses. We're just interested in the
number of segments and how long each one is.
Once you have a working program, here are some more suggestions for invalid input to test:
.123.45.678.91
123.4567.8.9.
123.156.289.10123456
10.10t.10.10
12.9.34.6.12.90
'' - that is, press enter without typing anything
This challenge is intended to practise for loops and if/else statements, so although
you could use other techniques (such as splitting the string up), that's not the
approach we're looking for here.
"""
IP_address =(input("Please enter an IP Address: \n"))
segment_length = 0
segment = 1
for char in IP_address:
if (char !='.'):
segment_length += 1
else:
print("The {} segment length is {}".format(segment,segment_length))
segment_length = 0
segment += 1
if char != '.':
print("The {} segment length is {}".format(segment, segment_length))
| true
|
0512db35031316c393b4571c8dca11b0a411b22a
|
kramin343/test_2
|
/first.py
| 428
| 4.28125
| 4
|
largest = None
smallest = None
while True:
num1 = input("Enter a number: ")
try:
num = float(num1)
except:
print('Invalid input')
continue
if num == "done" :
break
if largest == none:
largest = num
smallest = num
if largest < num:
largest = num
if smallest > num:
smallest = num
print("Maximum is",largest)
print("Minimum is",smallest)
| true
|
0ca502687d92d2e25228cf70a6cc1fe8499ae045
|
victormaiam/python_studies
|
/conditions.py
| 1,111
| 4.15625
| 4
|
is_hot = False
is_cold = False
if is_hot:
print("It`s a hot day.")
print ("Drink plenty of water.")
elif is_cold:
print("It`s a cold day.")
print("Wear warm clothes.")
else:
print("It`s a lovely day.")
print("Enjoy your day.")
tem_credito = False
preco = 1000000
preco1 = preco * 0.10
preco2 = preco * 0.20
if tem_credito:
print(preco1)
else:
print(preco2)
print("Sua entrada é nesse valor.")
if tem_credito:
entrada = 0.1 * preco
else:
entrada = 0.2 * preco
print(f"Entrada: R${entrada}" )
tem_salario_alto = True
tem_bom_credito = False
if tem_salario_alto and tem_bom_credito:
print("Você pode pegar um empréstimo")
else:
print("Você não pode pegar empréstimo.")
if tem_bom_credito or tem_salario_alto:
print("Você pode pegar um empréstimo")
temperatura = 30
if temperatura != 30:
print("É um dia quente!")
else:
print("Não é um dia quente.")
nome = "Victor"
if len(nome) < 3:
print("Nome precisa ter 3 caracteres")
elif len(nome) > 50:
print("Nome só pode ter até 50 caracteres.")
else:
print("Parece bom!")
| false
|
3e7950446a092a65ef871c98e64e9820a6e637a5
|
victormaiam/python_studies
|
/exercise1_4.py
| 399
| 4.3125
| 4
|
''''
Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter). For example, if limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20.
'''
def calcula_soma(limite):
soma = 0
for i in range(0, limite + 1):
if i%3 == 0 or i%5 == 0:
soma = soma + i
return(soma)
limite = 20
soma = calcula_soma(limite)
print(soma)
| true
|
28d5915b71c0f0ce0266c6169d724582b0d3963c
|
ranju117/cegtask
|
/7.py
| 286
| 4.21875
| 4
|
#tuple
tuple1 = ('python', 'ruby','c','java')
list1 = ['python','ruby','c','java']
print tuple1
print list1
# Let's include windows in the list and it works!
list1[1] = "windows"
list1[2]="Python"
print list1
# Windows does not work here!
tuple1[1] = "windows"
print tuple1
| true
|
2293c26f5ae1fdf5417ce4033829cc36c80cff00
|
furkanaygur/Codewars-Examples
|
/RemoveTheParantheses.py
| 754
| 4.4375
| 4
|
'''
Remove the parentheses
In this kata you are given a string for example:
"example(unwanted thing)example"
Your task is to remove everything inside the parentheses as well as the parentheses themselves.
The example above would return:
"exampleexample"
Notes
Other than parentheses only letters and spaces can occur in the string. Don't worry about other brackets like "[]" and "{}" as these will never appear.
There can be multiple parentheses.
The parentheses can be nested.
'''
def remove_parentheses(s):
result = ''
a = 0
for i in s:
if i == '(': a += 1
elif i == ')': a -=1
elif a == 0: result += i
return result
print(remove_parentheses('sBtJXYI()DpVxQWId MWVozwWva kri obRgP AXjTKQUjXj xoEA xmkTQ LvrfGyNzCTqHHTWFPuLvrRWba fnWbFNVQBANn ZqwHzLTxkSuAPQiccORuQHNLxlaiYJSTESsOMoMooVbvDxZiEbilrgJeUfACIeEw AzPXkOrDk vjAAaqiPyMIOl UvLWq UMigMOi YRwiiOFcNRVyZbAPajY e YHldtivKMbFGwr pfKGlBRBjq wiHlobnqR GNMxf eW veFKMNzopYXf sG)VAyjLrHjxwNR ZPlkAp NRyKEKCM'))
| true
|
d7eb20ba3f3a7b3b858265fb5dc87aea3939d909
|
furkanaygur/Codewars-Examples
|
/MatrixAddition.py
| 1,056
| 4.15625
| 4
|
'''
Write a function that accepts two square matrices (N x N two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size N x N (square), containing only integers.
How to sum two matrices:
Take each cell [n][m] from the first matrix, and add it with the same [n][m] cell from the second matrix. This will be cell [n][m] of the solution matrix.
Visualization:
|1 2 3| |2 2 1| |1+2 2+2 3+1| |3 4 4|
|3 2 1| + |3 2 3| = |3+3 2+2 1+3| = |6 4 4|
|1 1 1| |1 1 3| |1+1 1+1 1+3| |2 2 4|
Example
matrixAddition(
[ [1, 2, 3],
[3, 2, 1],
[1, 1, 1] ],
// +
[ [2, 2, 1],
[3, 2, 3],
[1, 1, 3] ] )
// returns:
[ [3, 4, 4],
[6, 4, 4],
[2, 2, 4] ]
'''
def matrix_addition(a,b):
result = []
for i in range(len(a)):
temp = []
for j in range(len(a)): temp.append(a[i][j] + b[i][j])
result.append(temp)
return result
print(matrix_addition([[1, 2], [1, 2]], [[2, 3], [2, 3]]))
| true
|
a8477323029366675ff8de5169e40fbc701ffe0a
|
furkanaygur/Codewars-Examples
|
/SplitStrings.py
| 844
| 4.28125
| 4
|
'''
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').
Examples:
solution('abc') # should return ['ab', 'c_']
solution('abcdef') # should return ['ab', 'cd', 'ef']
'''
def solution(s):
result = ''
result_array = []
flag = False
for i in range(len(s)):
if result == '':
result += f'{s[i]}'
flag = True
elif flag == True:
result += f'{s[i]}'
result_array.append(result)
result = ''
flag = False
if i == len(s)-1 and flag == True:
result_array.append(f'{s[i]}_')
return result_array
print(solution(''))
| true
|
ad213ac20a71fb84dfa39d4ad5375110c6f6281b
|
furkanaygur/Codewars-Examples
|
/Snail.py
| 2,004
| 4.3125
| 4
|
'''
Snail Sort
Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
For better understanding, please follow the numbers of the next array consecutively:
array = [[1,2,3],
[8,9,4],
[7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
This image will illustrate things more clearly:
Note 1: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.
Note 2: The 0x0 (empty matrix) is represented as en empty array inside an array [[]].
'''
def snail(snail_map):
result = []
def leftToRight(array):
a = snail_map[0]
snail_map.remove(snail_map[0])
return a
def upToBottom(array):
a = []
for i in range(len(array)):
a += array[i][len(array)],
snail_map[i]= snail_map[i][:-1]
return a
def rightToLeft(array):
a = []
for i in reversed(array[len(array)-1]):
a += i,
snail_map.remove(snail_map[len(array)-1])
return a
def bottomToUp(array):
a = []
x = len(array)-1
for i in range(len(array)):
a += array[x][0],
snail_map[x]= snail_map[x][1:]
x -= 1
return a
lenght = [len(i) for i in snail_map]
while True:
if len(result) != sum(lenght): result += leftToRight(snail_map)
else: break
if len(result) != sum(lenght): result += upToBottom(snail_map)
else: break
if len(result) != sum(lenght): result += rightToLeft(snail_map)
else: break
if len(result) != sum(lenght): result += bottomToUp(snail_map)
else: break
return result
print(snail([[1,2,3,1], [4,5,6,4], [7,8,9,7],[7,8,9,7]]))
| true
|
4e5453723e9224120e84b3f6713af9aa84c647a6
|
FA0AE/Mision-03
|
/Boletos.py
| 1,510
| 4.15625
| 4
|
# Autor: Francisco Ariel Arenas Enciso
# Actividad : Cálculo del total a pagar de boletos dependiendo de su clase
'''
Función que recibe los datos de entrada de la función main (número de boletos) como parametros, los alamcena en
variables y realiza las operaciones artimeticas necesarias para devolver datos de salida (total a pagar).
'''
def calcularPago (asientoA, asientoB, asientoC):
pago_asientoA = asientoA * 925
pago_asientoB = asientoB * 775
pago_asientoC = asientoC * 360
total_pago = pago_asientoA + pago_asientoB + pago_asientoC
return total_pago
'''
Función main (Es la responsable del funcionamiento de todo el programa).
Primero le pide al usuario el número de boletos de cada clase de boletos. Posteriormente envía esos datos a la
función defcalcularPago.
Finalmente imprime la cantidad de boletos de cada clase y el total a pagar.
'''
def main():
numero_boletosA = int(input('¿Cuántos boletos del tipo A se compraron? '))
numero_boletosB = int(input('¿Cuántos boletos del tipo B se compraron? '))
numero_boletosC = int(input('¿Cuántos boletos del tipo C se compraron? '))
total_aPagar= calcularPago(numero_boletosA, numero_boletosB, numero_boletosC)
print ("Número de boletos de clase A: ", str(numero_boletosA))
print ("Número de boletos de clase B: ", str(numero_boletosB))
print ("Número de boletos de clase C: ", str(numero_boletosC))
print ("El costo total es: $ %5.2f" % (total_aPagar))
main()
| false
|
0d644ab18e56d13805766663cc0fb4bf7fd20840
|
reeha-parkar/python
|
/dunder_magic_methods.py
| 1,006
| 4.15625
| 4
|
import inspect
'''x = [1, 2, 3]
y = [4, 5]
print(type(x)) # Output: <class 'list'>
# Whatever we make it print, it follows a certain pattern
# Which means that there is some class related method that works uunder the hood to give a certain output
'''
# Let's make our own data type:
class Person:
def __init__(self, name):
self.name = name
def __repr__(self): # a dunder/magic method that allows us to define object's string representation
return f'Person({self.name})'
def __mul__(self, x):
if type(x) is not int:
raise Exception('Invalid argument, must be type int')
self.name = self.name * x
def __call__(self, y):
print('called this function', y)
def __len__(self):
return(len(self.name))
p = Person('tim')
p * 4
p(4) # When you call this function, __call__ will work
print(p) # this initially, prints the memory address location
# The dunder methods are a part of 'data model' of python
print(len(p))
| true
|
bdee03756772c0848b3a27bf3c309e3523205975
|
reeha-parkar/python
|
/classmethod_and_staticmethod.py
| 1,109
| 4.1875
| 4
|
# class methods and static method:
# class method is a method in the class whcih takes te class name as a parameter, requires class instances
# static method is a method which can be directly called without creating an instance of the class
class Dog:
dogs = []
def __init__(self, name):
self.name = name
self.dogs.append(self)
@classmethod
def num_dogs(cls): # cls means the name of the class
return len(cls.dogs)
@staticmethod
def bark(n):
for _ in range(n):
print('Bark!')
'''
# Calling a classmethod:
tim = Dog('tim')
jim = Dog('jim')
print(Dog.dogs) # will get the Dog objects
print(tim.dogs) # will get the same 2 dog objects
print(Dog.num_dogs()) # will get 2
'''
# Calling a static method
Dog.bark(5)
# Only using the class name to get the method, without creating an instance
# Static method is used when you don't need self or an object of the class
# does not require a minimum parameter
# Class method takes the actual class and can access whatever is in the class
# requires a minimum one oarameter and that is 'cls'
| true
|
0232446325b58ecb878807316e3007eff77940fe
|
lalitp20/Python-Projects
|
/Self Study/Basic Scripts/IF_STATEMENT.py
| 213
| 4.34375
| 4
|
# Example for Python If Statement
number = int(input(" Please Enter any integer Value: "))
if number >= 1:
print(" You Have Entered Positive Integer ")
else:
print(" You Have Entered Negative Integer ")
| true
|
c0597e939d13b6fdecd2e374868a4547128ee79a
|
lalitp20/Python-Projects
|
/Self Study/Basic Scripts/String Indexing_1.py
| 377
| 4.125
| 4
|
x = (11, 21, 31, 41, 51, 61, 71, 81, 91)
# Positive Indexing
print(x[0])
print(x[3])
print(x[6])
print('=======\n')
# Negative Indexing
print(x[-1])
print(x[-5])
print(x[-7])
print('=======\n')
# Accessing Nested Tuple Items
Mixed_Tuple = ((1, 2, 3), [4, 5, 6], 'Lalit')
print(Mixed_Tuple[0][0])
print(Mixed_Tuple[1][0])
print(Mixed_Tuple[2][0])
print(Mixed_Tuple[2][4])
| false
|
b203678db14a642b6da0446d34aa0223a7010718
|
lalitp20/Python-Projects
|
/Self Study/Basic Scripts/For_ELSE Statement.py
| 263
| 4.25
| 4
|
number = int(input(" Please Enter any integer below 100: "))
for i in range(0, 100):
if number == i:
print(" User entered Value is within the Range (Below 100)")
break
else:
print(" User entered Value is Outside the Range (Above 100)")
| true
|
7b70d150000739cb2e83695b2908f09c6e1e13bf
|
hfyeomans/python-100days-class
|
/day_13_debugging/debugging fizzbuzz.py
| 1,094
| 4.15625
| 4
|
# # Orginal code to debug
# for number in range(1, 101):
# if number % 3 == 0 or number % 5 == 0:
# print("FizzBuzz")
# if number % 3 == 0:
# print("Fizz")
# if number % 5 == 0:
# print("Buzz")
# else:
# print([number])
for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0: # <-- problem resolved
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0: # <-- problem resolved
print("Buzz")
else:
print([number])
# In this debug exercise we put it into a debugger. We see it count 1, 2, but from the first if statement it prints Fizz. but then it continues to evalulate all the if statements below. so it also prints Fizz. Then the last if is false, so it hits the else and prints the number. These ifs have to be indented. The first if statement is or so every time its either or it prints fizz, buzz, but also goes through the other statements and prings fizz and buzz and catches else.
# The resolution was the or statement to and and also the third if statement to elif
| true
|
5bf7b52e8961a49b3667ae1731295ae1719a0900
|
aishtel/Prep
|
/solutions_to_recursive_problems/geometric_progression.py
| 655
| 4.34375
| 4
|
# Geometric progression using recursion
# starting term = a = 1
# factor = r = a2/a1
# Find the nth term - 8th term
# 1, 3, 9, 27, ...
def geo_sequence(a, r, n):
if r == 0 or r == 1:
raise Exception("Sequence is not geometric")
if n < 1:
raise Exception("n should be >= 1")
if a == 0:
return 0
if n == 1:
return a
else:
return r * geo_sequence(a, r, n-1)
print "The geometric sequence is", geo_sequence(6, 2, 9)
print "The geometric sequence is", geo_sequence(1, 3, 8)
print "The geometric sequence is", geo_sequence(10, 3, 4)
# print "The geometric sequence is",geo_sequence(2, 4, -1)
| true
|
f5dab06d3a74c77757d299124fbe8bcabbfa3c07
|
aishtel/Prep
|
/solutions_to_recursive_problems/factorial_recursive.py
| 465
| 4.5
| 4
|
# Return the factorial of a given number using recursive method.
# Example:
# n = 6
# fact = 6*5*4*3*2*1 = 720
def factorial(n):
if n < 0:
raise Exception("n should be >= 0")
elif n == 0:
return 1
elif n == 1:
return 1
else:
return n * factorial(n - 1)
print "The factorial is", factorial(4)
print "The factorial is", factorial(0)
print "The factorial is", factorial(1)
# print "The factorial is", factorial(-4)
| true
|
d5d66badeefb003f0d8356f94586ed89d869fc5e
|
Andrew-Callan/linux_academy_python
|
/age
| 248
| 4.15625
| 4
|
#!/usr/bin/env python3.7
name = input("What is your name? ")
birthdate = input("What is your birthday? ")
age = int(input("How old are you? "))
print(f"{name} was born on {birthdate}")
print(f"Half your age is {age/2}")
print(f"Fuck you {name}")
| true
|
1c84b38bb37582851c05603793f51697860ac906
|
Wyuchen/python_hardway
|
/48.py
| 929
| 4.125
| 4
|
#/usr/bin/python
#encoding=utf8
#笨方法学python-第四十八题
#目的:编辑出一个能够扫描出用户输入的字,并标注是那种类型的程序
#定义初始化的数据:
Direction=['Direction','north','south','east','west']
Verb=['Verb','go','stop','kill','eat']
Adjective=['Adjective','the','in','of','from','at','it']
Noun=['Noun','door','bear','pricess','cabine']
print '用户可以输入的词有:'
print Direction[1:-1]
print Verb[1:-1]
print Adjective[1:-1]
print Noun[1:-1]
#收集用户输入的命令
stuff=raw_input(">")
#将用户的命令分割(按照空格符进行分割)
words=stuff.split()
#定义一个列表存放这些单词
scentence=[]
#遍历用户给出的单词的意思:
for word in words:
for date in (Direction,Verb,Adjective,Noun):
if word in date:
scentence.append((date[0], word))
else:
continue
print "扫描结果:"
print scentence
| false
|
e5de3dc1d18e6f517f24b58851dd96d88b007999
|
Wyuchen/python_hardway
|
/29.py
| 484
| 4.28125
| 4
|
#!/usr/bin/python
#coding=utf-8
#笨办法学 Python-第二十九题
#条件判断语句if
people=20
cats=30
dogs=15
if people < cats:
print 'too many cats!too little people'
if people > cats:
print 'too many people,too little cats'
if people < dogs:
print 'the world is drooled on'
if people > dogs:
print 'the world is dry'
dogs+=5
if people >dogs:
print 'people > dogs'
if people <dogs:
print 'people <dogs'
if people == dogs:
print 'people are dogs'
| true
|
3e7b21d4fc0b9776ec7990f6aff7e5ae7abe7d1c
|
dianeGH/working-on-python
|
/menu/main.py
| 1,100
| 4.53125
| 5
|
#Write a program that allows user to enter their favourite starter, main course, dessert and drink. Concatenate these and output a message which says – “Your favourite meal is .........with a glass of....”
def function_1():
user_name = input("Hi there, what's your name? \n")
#print ("Nice to meet you " + user_name + ". Let's find out some more about you.\n")
starter = input("I'd like to take you out for dinner. \nLet's go to your favourite restaurant! \nWhat is your favourite starter?\n")
main_meal = input("That's awesome, I love " + starter + " too!\nWhat is your favourite main meal?\n")
dessert = input("Cool, well " + main_meal+ " isn't my favourite, but I still like it!, What would your favourite dessert be? \n")
drink = input("Now a drink, I like a good Merlot, but I'm pretty easy going. What is your favourite drink?\n")
print("Well, I think we're going to have a great time! You'll have " + starter + " to start, followed by " + main_meal + " and " + dessert + " to finish, with a glass or two of " + drink + ". Shall we say Friday night? \n Great I'll book the table!!" )
| true
|
09b28c6215e30d68fe17becca9b4495559ccb9de
|
dianeGH/working-on-python
|
/depreciation/main.py
| 349
| 4.28125
| 4
|
#A motorbike costs £2000 and loses 10% of its value every year. Using a loop, print the value of the bike every following year until it falls below £1000.
print("Today, Jim bought a motorbike for £2000.00")
year = 1
cost = 2000
while cost >1000:
print("At the end of year ",year,", Jim's bike is worth £", cost)
year+=1
cost=cost*.9
| true
|
5361bceaf8f580c2855c45a3396525a7a326bffa
|
shubhneetkumar/python-lab
|
/anagram,py.py
| 203
| 4.15625
| 4
|
#anagram string
s1 = input("Enter first string:")
s2 = input("Enter second string:")
if(sorted(s1) == sorted(s2)):
print("string are anagram")
else:
print("strings are not anagram")
| true
|
c69eda975eaa6a5d7da163d458845a1e4a9e3366
|
iloveyii/tut-python
|
/loop.py
| 259
| 4.15625
| 4
|
# For loop
fruits = ['banana', 'orange', 'banana', 'orange', 'grapes', 'banana']
print('For loop:')
for fruit in fruits:
print(fruit)
# While loop
count = len(fruits)
print('While loop')
while count > 0:
print(count, fruits[count-1])
count -= 1
| true
|
ee5f15707242184f822ab27a6e05f93b3c296344
|
thiagocosta-dev/Gerador_senha_simples
|
/senha_para_filas.py
| 806
| 4.125
| 4
|
# AUTOR: Thiago Costa Pereira
# Email: thiago.devpython@gmail.com
print('=-' * 20)
print('-- GERADOR DE SENHA --'.center(40))
print('=-' * 20)
senhas_comuns = [0]
senhas_pref = [0]
while True:
print()
print('--' * 20)
print('[1] SENHA COMUM')
print('[2] SENHA PREFERENCIAL')
print('[3] SAIR')
print()
senha = int(input('Escolha sua senha: '))
print('--' * 20)
print()
if senha == 1:
senhas_comuns.append(int(senhas_comuns[-1]) + 1)
print(f'Sua senha é: Senha Comum {senhas_comuns[-1]}')
elif senha == 2:
senhas_pref.append(int(senhas_pref[-1]) + 1)
print(f'Sua senha é: Senha Preferencial {senhas_pref[-1]}')
elif senha == 3:
print('<< FINALIZADO >>')
break
else:
print('ERRO! Digite um valor válido.')
print()
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.