blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2aa078dc068d59306dd016ccd5f61591fc6c1214 | aselvais/PythonOOPexample | /libs/animals/AnimalArmy.py | 1,246 | 4.1875 | 4 | """
Class for creating an army of animal
"""
from libs.animals.Dog import Dog
from libs.animals.Duck import Duck
class AnimalArmy:
"""Generates an army of animals
Args:
animal_type (str, optional): duck or dog. Defaults to 'duck'.
army_size (int, optional): Number of animal in the army. Defaults to 10.
"""
animals = []
def __init__(self, animal_type='Duck', army_size=10):
"""Generates an army of animals
Args:
animal_type (str, optional): duck or dog. Defaults to 'Duck'.
army_size (int, optional): Number of animal in the army. Defaults to 10.
"""
for i in range(army_size):
if animal_type == 'Duck':
_a = Duck()
if animal_type == 'Dog':
_a = Dog()
_a.set_name(animal_type + str(i))
self.animals.append(_a)
print('Army of ' + str(army_size) + ' ' + animal_type + 's created!')
def attack(self, enemy):
"""Attacking the enemy animal with the army, each animal at a time
Args:
enemy (Animal): Enemy animal
"""
print('Army attack on ' + enemy._name)
for i in self.animals:
i.attack(enemy)
| true |
c3102ca81f107494c8479b0ecf60af4889522c7c | emws0415/program_basics_python | /Chapter 1/20174067, 강범수, 1장 과제, 2번.py | 2,039 | 4.1875 | 4 | #컴퓨터공학과, 20174067, 강범수
print("컴퓨터공학과, 20174067, 강범수")
from random import randint
while True:
print("ㅡㅡㅡㅡㅡMENUㅡㅡㅡㅡㅡ")
print("1. UP & DOWN")
print("2. Bulls and Cows")
print("3. Exit")
choose = int(input("> "))
# UP & DOWN
if choose == 1 :
print("\nㅡㅡㅡUP & DOWN!ㅡㅡㅡ")
value = randint(0, 100)
while True :
guess = int(input("input number: "))
if guess > value :
print("DOWN")
elif guess < value :
print("UP")
else :
print("GOOD\n\n")
break;
# Bulls and Cows
elif choose == 2 :
print("\nㅡㅡㅡBulls and Cowsㅡㅡㅡ")
computer = [0, 0, 0]
while True:
for i in range(0, 3) :
computer[i] = randint(0, 9)
if ( computer[0] != computer[1]
& computer[0] != computer[2]
& computer[1] != computer[2]
) :
break
# HACK: show numbers of computer.
print(computer[0:3])
player = [0, 0, 0]
strike = 0
ball = 0
while strike != 3 :
strike = 0
ball = 0
for i in range(0, 3) :
player[i] = int(input("input three numbers: "))
for i in range(0, 3) :
for j in range(0, 3) :
if player[i] == computer[j] :
if i == j :
strike += 1
break
else :
ball += 1
break
print(strike, " strike, ", ball, " ball !\n")
print("GOOD\n\n")
# Exit
elif choose == 3 :
print("\nExit...")
break
| false |
3807e45d09f23244239ad8db2bdd786c0badc56e | Kota-N/python-exercises | /ex6StringLists.py | 350 | 4.125 | 4 | # An exercise from http://www.practicepython.org/
#6 String Lists
import math
word = input("Enter a word: ")
middleIndex = math.floor(len(word)/2)
firstHalf = word[0:middleIndex]
lastHalf = word[middleIndex+1:]
if firstHalf[::-1] == lastHalf:
print(word, ": Your word is palindrome!")
else:
print(word, ": Your word isn't palindrome...") | true |
d71db487817a2fec22a537d41cae952aed2351be | elunacado/FISICA_FUERZA | /F/main.py | 1,381 | 4.21875 | 4 | def calculo():
ul = ["a = asceleracion", "m = masa", "f = fuerza"]
print(ul)
peticion=input("que quieres calcular?")
def fuerza():
m = float(input("dime el valor de la m "))
a = float(input("dime el valor de la a "))
result=m * a
print(result)
again=input("ingresa r y presiona enter si quieres realizar otra formula o presiona enter y cierra el pregrama")
if again == "r":
calculo()
def asceleracion():
f = float(input("dime el valor de la f "))
m = float(input("dime el valor de la m "))
result=f/m
print(result)
again = input("ingresa r y presiona enter si quieres realizar otra formula o presiona enter y cierra el pregrama")
if again == "r":
calculo()
def masa():
f = float(input("dime el valor de la f "))
a = float(input("dime el valor de la a "))
result=f/a
print(result)
again = input("ingresa r y presiona enter si quieres realizar otra formula o presiona enter y cierra el pregrama")
if again == "r":
calculo()
if peticion=="f":
fuerza()
elif peticion=="a":
asceleracion()
elif peticion=="m":
masa()
else:
print("not yet")
input()
calculo()
| false |
906289d11e5d2e0cb23ed09ed268916674ae689f | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/Hacker Chapter--Files/ex.04.py | 2,959 | 4.25 | 4 | '''Here is a file called labdata.txt that contains some sample data from a lab experiment.
44 71
79 37
78 24
41 76
19 12
19 32
28 36
22 58
89 92
91 6
53 7
27 80
14 34
8 81
80 19
46 72
83 96
88 18
96 48
77 67
Interpret the data file labdata.txt such that each line contains a an x,y coordinate pair.
Write a function called plotRegression that reads the data from this file and uses a turtle to plot those points and a best fit line according to the following formulas:
y=y¯+m(x−x¯)
m=∑xiyi−nx¯y¯∑x2i−nx¯2
where x¯
is the mean of the x-values, y¯ is the mean of the y- values and n is the number of points.
If you are not familiar with the mathematical ∑ it is the sum operation. For example
∑xi means to add up all the x values.
Your program should analyze the points and correctly scale the window using setworldcoordinates so that that each point can be plotted.
Then you should draw the best fit line, in a different color, through the points.
'''
'''
def plot(data):
import turtle
wn = turtle.Screen()
t = turtle.Turtle()
t.speed(1)
# Set up our variables for the formula.
x_lst, y_lst = [i[0] for i in data], [i[1] for i in data]
x_sum, y_sum = float(sum(x_lst)), float(sum(y_lst))
x_mean, y_mean = x_sum / len(x_lst), y_sum / len(y_lst)
# Not sure about the formula where x and E are concerned ...
m = ((x_sum * y_sum) - (20 * x_mean * y_mean)) / (x_sum ** 2 - (20 * x_mean ** 2))
y = y_mean + m * (x_sum - x_mean) # This gives 966=x_sum so it can't be right.
# Get min and max values for coordinate system.
x_min, x_max, y_min, y_max = min(x_lst), max(x_lst), min(y_lst), max(y_lst)
# Add 10 points on each line to be safe.
wn.setworldcoordinates(x_min - 10, y_min - 10, x_max + 10, y_max + 10)
for i in data:
t.setpos(i[0], i[1])
wn.exitonclick()
with open("lib/labdata.txt") as f:
coords = [map(int, line.split()) for line in f]
plot(coords)
'''
def plot(data):
import turtle
wn = turtle.Screen()
t = turtle.Turtle()
t.speed(1)
# Set up our variables for the formula.
x_lst, y_lst = [i[0] for i in data], [i[1] for i in data]
x_sum, y_sum = float(sum(x_lst)), float(sum(y_lst))
x_mean, y_mean = x_sum / len(x_lst), y_sum / len(y_lst)
# Not sure about the formula where x and E are concerned ...
m = ((x_sum * y_sum) - (20 * x_mean * y_mean)) / (x_sum ** 2 - (20 * x_mean ** 2))
y = y_mean + m * (x_sum - x_mean) # This gives 966=x_sum so it can't be right.
# Get min and max values for coordinate system.
x_min, x_max, y_min, y_max = min(x_lst), max(x_lst), min(y_lst), max(y_lst)
# Add 10 points on each line to be safe.
wn.setworldcoordinates(x_min - 10, y_min - 10, x_max + 10, y_max + 10)
for i in data:
t.setpos(i[0], i[1])
wn.exitonclick()
f = open("studentdata.txt", "r")
coords = [map(int, line.split()) for line in f]
plot(coords)
| true |
eaedab6cec968ff2daf1313210d0713a8a397653 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 3/ex.04.py | 1,137 | 4.375 | 4 | '''Football Scores Suppose you’ve written the program below.
The given program asks the user to input the number of touchdowns and field goals scored by a (American) football team,
and prints out the team’s score. (We assume that for each touchdown, the team always makes the extra point.)
The European Union has decided that they want to start an American football league,
and they want to use your killer program to calculate scores,
but they like things that are multiples of 10 (e.g. the Metric System),
and have decided that touchdowns will be worth 10 points and field goals are worth 5 points.
Modify the program below to work on both continents, and beyond.
It should ask the user how many points a touchdown is worth and how many points a field goal is worth.
Then it should ask for the number of each touchdowns / field goals scored, and print the team’s total score.
'''
num_touchdowns = input("How many touchdowns were scored? ")
num_field_goals = input("How many field goals were scored? ")
total_score = 7 * int(num_touchdowns) + 3 * int(num_field_goals)
print("The team has", total_score, "points")
| true |
8751ce643df7e321eaf0f354e4e2d03641f56778 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 2/ex.08.py | 326 | 4.28125 | 4 | '''Write a program that will compute the area of a rectangle.
Prompt the user to enter the width and height of the rectangle.
Print a nice message with the answer.
'''
## question 9 solution
width = int(input("Width? "))
height = int(input("Height? "))
area = width * height
print("The area of the rectangle is", area)
| true |
cd9e9cf99f39ffab5a59d013375ebe2016503dae | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/Problem Set--Crypto/commandline.py | 1,150 | 4.53125 | 5 | '''
commandline.py
Jeff Ondich, 21 April 2009
This program gives a brief illustration of the use of
command-line arguments in Python. The program accepts
a file name from the command line, opens the file, and
counts the lines in the file.
'''
import sys
# If the user types too few or too many command-line arguments,
# this code prints a usage statement and exits the program.
# Note that sys.argv[0] is the name of the program, so if
# I type "python commandline.py something", then sys.argv[0]
# is "commandline.py" and sys.argv[1] is "something".
if len(sys.argv) != 2:
print ('Usage:', sys.argv[0], 'filename')
exit()
# You don't normally need to tell the users what they just
# typed, but the print statement here just verifies that
# we have grabbed the right string for the file name.
fileName = sys.argv[1]
print ('The requested file is', fileName)
theFile = open(fileName)
# Count the lines in the file.
lineCounter = 0
for line in theFile:
lineCounter = lineCounter + 1
# Report the results.
print ('The file', fileName, 'contains', lineCounter, 'lines.')
# Clean up after yourself.
theFile.close()
| true |
f81af3b3ee07daecb713502882d235f0b62e0fca | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/List Comprehensions.py | 628 | 4.5 | 4 | '''The previous example creates a list from a sequence of values based on some selection criteria.
An easy way to do this type of processing in Python is to use a list comprehension.
List comprehensions are concise ways to create lists. The general syntax is:
[<expression> for <item> in <sequence> if <condition>]
where the if clause is optional. For example,
'''
mylist = [1,2,3,4,5]
yourlist = [item ** 2 for item in mylist]
print(yourlist)
alist = [4,2,8,6,5]
blist = [num*2 for num in alist if num%2==1]
print(blist)
'''Correct! Yes, 5 is the only odd number in alist. It is doubled before being placed in blist.'''
| true |
b1b9abda174eecee080e0bc8b1fa8b424104ea3e | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/Problem Set--Crypto/strings2.py | 442 | 4.15625 | 4 | '''strings2.py
Jeff Ondich, 2 April 2009
This sample program will introduce you to "iteration" or
"looping" over the characters in a string.
'''
s = 'two kudus and a newt'
# What happens here?
print('The first loop')
for ch in s:
print (ch)
print()
# And here?
print( 'The second loop')
k = 0
while k < len(s):
print (s[k])
k = k + 1
print()
# Can you make sense of these structures? Let's talk about
# them on Monday. | true |
6b49356fb32eee0f79ad56e806a41b549b7fc847 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 6/ex.08.py | 337 | 4.28125 | 4 | '''Now write the function is_odd(n) that returns True when n is odd and False otherwise.
'''
from test import testEqual
def is_odd(n):
# your code here
if n % 2 == 0:
return False
else:
return True
testEqual(is_odd(10), False)
testEqual(is_odd(5), True)
testEqual(is_odd(1), True)
testEqual(is_odd(0), False) | true |
1122da139c723e93234aba0ae35e3ec62f7504b6 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 11/Nested Lists.py | 776 | 4.53125 | 5 | '''A nested list is a list that appears as an element in another list.
In this list, the element with index 3 is a nested list.
If we print(nested[3]), we get [10, 20]. To extract an element from the nested list, we can proceed in two steps.
First, extract the nested list, then extract the item of interest.
It is also possible to combine those steps using bracket operators that evaluate from left to right.
'''
'''
nested = ["hello", 2.0, 5, [10, 20]]
innerlist = nested[3]
print(innerlist)
item = innerlist[1]
print(item)
print(nested[3][1])
'''
alist = [ [4, [True, False], 6, 8], [888, 999] ]
if alist[0][1][0]:
print(alist[1][0])
else:
print(alist[1][1])
'''Correct! Yes, alist[0][1][0] is True and alist[1] is the second list, the first item is 888.'''
| true |
cbb24873533a63b0842920b265efe25987dca3f3 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 14/ex.06.py | 1,691 | 4.125 | 4 | ''')
(GRADED) Write a new method in the Rectangle class to test if a Point falls within the rectangle.
For this exercise, assume that a rectangle at (0,0) with width 10 and height 5 has open upper bounds on the width and height, i.e.
it stretches in the x direction from [0 to 10), where 0 is included but 10 is excluded, and from [0 to 5) in the y direction.
So it does not contain the point (10, 2). These tests should pass:
r = Rectangle(Point(0, 0), 10, 5)
test(r.contains(Point(0, 0)), True)
test(r.contains(Point(3, 3)), True)
test(r.contains(Point(3, 7)), False)
test(r.contains(Point(3, 5)), False)
test(r.contains(Point(3, 4.99999)), True)
test(r.contains(Point(-3, -3)), False)
'''
from test import test
class Point:
"""Point class for representing and manipulating x,y coordinates. """
def __init__(self, initX, initY):
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def __str__(self):
return "x=" + str(self.x) + ", y=" + str(self.y)
class Rectangle:
"""Rectangle class using Point, width and height"""
def __init__(self, initP, initW, initH):
self.location = initP
self.width = initW
self.height = initH
def contains(self, point):
# Your code here!
x, y = point.get_x(), point.get_y()
return 0 <= x < self.width and 0 <= y < self.height
r = Rectangle(Point(0, 0), 10, 5)
test(r.contains(Point(0, 0)), True)
test(r.contains(Point(3, 3)), True)
test(r.contains(Point(3, 7)), False)
test(r.contains(Point(3, 5)), False)
test(r.contains(Point(3, 4.99999)), True)
test(r.contains(Point(-3, -3)), False)
| true |
bd7d3da5c3917644520e2fd9528bee66e85ade32 | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 4/ex.02.py | 884 | 4.4375 | 4 | '''Turtle objects have methods and attributes. For example, a turtle has a position and when you move the turtle forward, the position changes.
Think about the other methods shown in the summary above. Which attibutes, if any, does each method relate to? Does the method change the attribute?
'''
'''Write a program that prints out the lyrics to the song “99 Bottles of Beer on the Wall”
'''
for i in range(99, -1, -1):
if i==1:
print (i,"bottle of beer on the wall,",i,"bottle of beer.")
print ("Take one down and pass it around,")
print (i-1,"bottles of beer on the wall.")
elif i==0:
print( "No more bottles of beer on the wall. How about some soju?")
else:
print (i,"bottles of beer on the wall,",i,"bottles of beer.")
print ("Take one down and pass it around,")
print (i-1,"bottles of beer on the wall.") | true |
d15fa577adbdc9cf9ac0c3ad0652ad2430eb8bca | SmileShmily/LaunchCode-summerofcode-Unit1 | /ClassExercise & studio/chapter 12/Crypto/Caesar Cipher/caesar01/caesar 02.py | 1,272 | 4.375 | 4 | def caesarCipher(t, s):
"""
caesarCipher(t, s)
Returns the cipher text in a given plain text or vice versa.
Variables:
t - text (input), nt - new text (output)
lc - lowercase, uc - uppercase
pt[c] - nth character of the plain text (also used to get the
plaintext in a given cipher text.
Description:
In Cryptography, caesar cipher is the most simplest and most widely
known encryption/decryption techniques. It substitutes your input
with a given shift (s). e.g, if s is 1, A will be B
or a will be b.
Examples:
#>>> #caesarCipher("Be sure to drink your ovaltine", 13)
'Or fher gb qevax lbhe binygvar'
#>>> caesarCipher("Or fher gb qevax lbhe binygvar", -13)
'Be sure to drink your ovaltine'
"""
nt = ""
t = t.replace("\n", "")
uc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lc = "abcdefghijklmnopqrstuvwxyz"
for c in range(len(t)):
if (t[c].isalpha()):
if (t[c].isupper()):
nt += uc[(uc.index(t[c]) + s) % 26]
else:
nt += lc[(lc.index(t[c]) + s) % 26]
else:
nt += t[c]
return nt | true |
7f7f4cd5a877fb9a457cd662ec1cbe4f47cba6cb | CriticalD20/String-Jumble | /stringjumble.py | 1,567 | 4.3125 | 4 | """
stringjumble.py
Author: James Napier
Credit: http://stackoverflow.com/questions/12794141/reverse-input-in-python, http://stackoverflow.com/questions/25375794/how-to-reverse-the-order-of-letters-in-a-string-in-python, http://stackoverflow.com/questions/25375794/how-to-reverse-the-order-of-letters-in-a-string-in-python
Assignment:
The purpose of this challenge is to gain proficiency with
manipulating lists.
Write and submit a Python program that accepts a string from
the user and prints it back in three different ways:
* With all letters in reverse.
* With words in reverse order, but letters within each word in
the correct order.
* With all words in correct order, but letters reversed within
the words.
Output of your program should look like this:
Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy
You entered "There are a few techniques or tricks that you may find handy". Now jumble it:
ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT
handy find may you that tricks or techniques few a are There
erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah
"""
JumbleString = input('Please enter a string of text (the bigger the better): ')
print('You entered "'+JumbleString+'". Now jumble it:')
#This is the code for the first input line
print(JumbleString[::-1])
#This is the code for the second output line
print(' '.join(reversed(JumbleString.split(' '))))
#This is the code for the third output line
print(' '.join(w[::-1] for w in JumbleString.split())) | true |
c5bf60c3b48425c93a6c39a20b01d10a3fe36bc2 | narenaruiz/Python | /P6/P6E5.py | 894 | 4.28125 | 4 | """5.-Escribe un programa que te pida números cada vez más grandes
y que se guarden en una lista. Para acabar de escribir los números,
escribe un número que no sea mayor que el anterior. El programa termina
escribiendo la lista de números:
Escribe un número: 6
Escribe un número mayor que 6: 10
Escribe un número mayor que 10: 12
Escribe un número mayor que 12: 25
Escribe un número mayor que 25: 9
Autor:Nicolás Arena Ruiz
"""
Lista1=[]
indice=0
entrada=int(input("Dime un numero:"))
Lista1.append(entrada)
entrada=int(input("Dime otro numero (si quieres salir escribe un numero menor):"))
while(entrada>Lista1[indice]):
Lista1.append(entrada)
indice+=1
entrada=int(input("Dime otro numero (si quieres salir escribe un numero menor):"))
print("Los numeros que has escrito son:", end=' ')
for i in Lista1:
if i !=Lista1[-1]:
print(i, end=', ')
else:
print(i)
| false |
7156e4a491a294fce7e93b898bbe0a83eaf89bb8 | narenaruiz/Python | /P6/P6E3.py | 639 | 4.1875 | 4 | """3.-Escribe un programa que pida notas y los guarde en una lista. Para terminar de introducir notas, escribe una nota que no esté entre 0 y 10. El programa termina escribiendo la lista de notas.
Escribe una nota: 7.5
Escribe una nota: 0
Escribe una nota: 10
Escribe una nota: -1
Las notas que has Escrito son [7.5, 0.0, 10.0]
Autor:Nicolás Arena Ruiz
"""
notas=[]
entrada=float(input("Dime una nota entre 0 y 10 (si quieres salir pon un numero mayor a 10):"))
while(entrada<=10 and entrada>=0):
notas.append(entrada)
entrada=float(input("Dime una nota entre 0 y 10 (si quieres salir pon un numero mayor a 10):"))
print("La lista es",notas)
| false |
03478dde7f02433ae2c351c181cefc942e0c75be | parthpanchal0794/pythontraining | /NumericType.py | 1,634 | 4.25 | 4 | """
Numeric types classes
1. Integer e.g 10
2. Float e.g 10.0
3. Complex e.g 3 + 5j
4. Binary type (Class Int)
5. Hexadecimal (Class Int)
6. Octa decimal (Class Int)
"""
# Integer Values
a = 13
b = 100
c = -66
print(a, b, c)
print(type(a))
# Floating values
x = 33.44
y = -8.78
z = 56.0 # with .0 at end it will consider as integer but with .0 it will consider as float
print(x, y, z)
print(type(z))
# Complex type
d = 3 + 5j
print(d)
print(type(d))
# Binary type
# To define binary type start with literal 0b or 0B
e = 0b1010
g = 0B1010
print(e)
print(g)
print(type(e))
# Hexadecimal type
# To define hexadecimal start with literal 0x or 0X
f = 0XFF
h = 0xFF
print(f)
print(h)
print(type(f))
# Octa decimal type
# To define octa decimal start with literal 0o or 0O
i = 0o12
j = 0O12
print(i)
print(j)
print(type(i))
#################################################################
# Boolean value type have 2 value: True and False
# it mainly use to define condition in loop or if statement
k = True
print(type(k))
print(9 > 8) # Condition returns True value of class bool
###################################################################
# int, float, bin, hex and oct functions used to convert the numeric data type class
A = int(55.60) # float or int no are allowed
print(type(A))
C = float(66)
print(type(C))
D = float("66") # only no are allowed not string like "python"
print(type(D))
E = bin(10) # only integers are allowed
print(type(E))
print(E)
F = hex(10) # only integers are allowed
print(type(F))
print(F)
G = oct(10) # only integers are allowed
print(type(G))
print(G)
| true |
523474ff795187ae2740e98b9a2c2f393e6f71d7 | HyeongSeoku/Programmers_CodingTest | /python/datastructure/descendingSort.py | 1,130 | 4.1875 | 4 | '''
1. maxMachine 클래스를 완성하세요.
2. sorting 함수를 완성하세요.
'''
class maxMachine :
'''
이곳에 '최댓값 기계' 문제에서 작성했던 클래스를 붙여넣으세요
'''
def __init__(self) :
self.numbers = [];
def addNumber(self, n) :
self.numbers.append(n);
def removeNumber(self, n) :
self.numbers.remove(n);
def getMax(self) :
return max(self.numbers);
def sorting(myList) :
'''
myList를 내림차순으로 정렬하여 반환하는 함수를 작성하세요.
예를 들어, myList = [5, 2, 3, 1] 이라면 [5, 3, 2, 1] 을 반환해야 합니다.
단, maxMachine class를 이용하도록 합니다.
'''
myMachine = maxMachine()
result = [];
for x in myList:
myMachine.addNumber(x);
for i in range(len(myList)):
myMax = myMachine.getMax();
result.append(myMax); #result에 최대값 입력
myMachine.removeNumber(myMax); #myMachine에서 myMax 값 삭제 (그 다음으로 큰 값을 찾기 위해)
return result | false |
a862febaed4059785ab37c810b54b6a1034c6901 | Mohibtech/Mohib-Python | /UrduPythonCourse/List Comprehension.py | 2,248 | 4.75 | 5 | '''
List comprehensions provide a concise way to create lists.
It consists of brackets containing an expression followed by a for clause, then
optional if clauses.
The expressions can be anything, meaning you can put in all kinds of objects in lists.
The list comprehension always returns a result list.
'''
# List comprehensions in Python are constructed as follows:
list_variable = [x for x in sequence]
# In maths, common ways to describe lists (or sets, or tuples, or vectors) are:
'''
S = {x² : x in {0 ... 9}}
V = (1, 2, 4, 8, ..., 2¹²)
M = {x | x in S and x even}
'''
'''
sequence S contains values between 0 and 9 included that are raised to the power of two.
Sequence V contains the value 2 that is raised to a certain power.
For the first element in the sequence, this is 0, for the second this is 1, and so on, until you reach 12.
sequence M contains elements from the sequence S, but only the even ones.
'''
# Above mathematical expressions will produce following lists.
S = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
V = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096}
M = {0, 4, 16, 36, 64}
# Creating List S using List comprehension
S = [x**2 for x in range(10)]
# Creating List S using for Loop
S = []
for x in range(10):
S.append(x**2)
# Creating List V using List comprehension
V = [2**i for i in range(13)]
# Creating List V using for Loop
V = []
for i in range(13):
V.append(2**i)
# Creating List M using List comprehension
M = [x for x in S if x % 2 == 0]
# Creating List M using for Loop
M = []
for x in S:
if x % 2 ==0:
M.append(x)
# Celsius to Fahrenheit conversion
Celsius = [39.2, 36.5, 37.3, 37.8]
Fahrenheit = [((9/5)*x + 32) for x in Celsius ]
print(Fahrenheit)
# Celsius to Fahrenheit using for loop
Fahrenheit = []
for x in Celsius:
item = (9/5)*x + 32
Fahrenheit.append(item)
# Transpose matrix
matrix = [[1, 2], [3,4], [5,6], [7,8]]
transpose = [[row[i] for row in matrix] for i in range(2)]
print (transpose)
matrix = [[1, 2], [3,4], [5,6], [7,8]]
# Transpose matrix using for Loop
transposed = []
for i in range(2):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
print(transposed) | true |
5a51b340ba8d0d8c4ec9548812a0b3dd7152c64c | alex88yushkov/les_4.2_salary_echo | /salary_echo.py | 1,459 | 4.25 | 4 | # Exercise #1
def show_employee(name = "Trus", sal = 5000):
name = "Name: " + name
sal = "Salary: " + str(sal)
print(name, sal, sep=", ")
show_employee()
show_employee(name = 'Balbes')
show_employee(name = 'Bivaliy', sal = 4000)
# Exercise #2
# VARIANT 1:
#Define shout_echo
def shout_echo(word1 = "Hey ", echo = 1):
"""Concatenate echo copies of word1 and three
exclamation marks at the end of the string."""
# Concatenate echo copies of word1 using *: echo_word
echo_word = word1 * echo
# Concatenate '!!!' to echo_word: shout_word
shout_word = echo_word + '!!!'
# Return shout_word
return shout_word
# Call shout_echo() with "Hey": no_echo
no_echo = shout_echo()
# Call shout_echo() with "Hey" and echo=5: with_echo
with_echo = shout_echo(echo = 5)
# Print no_echo and with_echo
print(no_echo)
print(with_echo)
# VARIANT 2:
def shout_echo(word1, echo = 1):
"""Concatenate echo copies of word1 and three
exclamation marks at the end of the string."""
# Concatenate echo copies of word1 using *: echo_word
echo_word = word1 * echo
# Concatenate '!!!' to echo_word: shout_word
shout_word = echo_word + '!!!'
# Return shout_word
return shout_word
# Call shout_echo() with "Hey": no_echo
no_echo = shout_echo("Hey ")
# Call shout_echo() with "Hey" and echo=5: with_echo
with_echo = shout_echo("Hey ", 5)
# Print no_echo and with_echo
print(no_echo)
print(with_echo)
| false |
3cf56345025b2e3d5581c689813defd14a38feb7 | malhar-pr/side-projects | /pythagorean.py | 2,783 | 4.375 | 4 | import time
pyth_list=[] #Creates an empty list that will hold the tuples containing Pythagorean/Fermat triplets
power_list=[] #Creates an empty list that will cache the value of each index raised to the specified exponent in the given range
print("---------------------------------------------------------------------\nMALHAR'S PYTHAGOREAN TRIPLET GENERATOR / FERMAT'S LAST THEOREM SOLVER\n---------------------------------------------------------------------")
UserInput1 = input("What power will be selecting? \n")
UserInput2=input("And till what range would you like to go to? \n")
UserInput3=input("Would you like to be 100% accurate? [1/0] \n")
if UserInput3 == '0':
UserInput4 = input("Order of accuracy (put 0 if 100% accurate): ")
order=int(UserInput4) #typecasts the user-input value to int
start=time.process_time() #stores current process time in variable to calculate time elapsed to run the code
power=int(UserInput1) #typecasts the user-input value to int
crange=int(UserInput2) #typecasts the user-input value to int
def append_check(accornot):
"""
Inputs: Takes in variable "accornot" which determines if the user requires an accurate answer or not
Appends a tuple containing the triplet that satisfies the condition to the list, "pyth_list"
Returns: nothing
"""
if accornot == '1':
if (power_list[a] + power_list[b] == power_list[c]): #Compares exact condition
pyth_list.append((a,b,c))
elif accornot == '0':
if (power_list[a] + power_list[b] < (1+(pow(10,-order)))*power_list[c]) and (power_list[a] + power_list[b] > (1-(pow(10,-order)))*power_list[c]):
#compares approximate condition within required order parameter
pyth_list.append((a,b,c))
else:
print("Invalid Input")
for var in range(crange):
power_list.append(pow(var,power)) #creates cache of the value of each index raised to the specified exponent in the given range, to reduce time complexity
for c in range(crange):
for b in range(c):
for a in range(b):
append_check(UserInput3) #calls the function that checks for the condition and appends to list if condition is True
if crange>=10000:
if not (c%(crange/1000)):
print(str(c/(crange/100)) + "% complete\r",)
elif crange<10000:
if not (c%(crange/100)):
print(str(int(c/(crange/100))) + "% complete\r",) #Gives loading indicator to show how much has completed
del power_list #Deletes cache of value of indices raised to the specified exponent
if (pyth_list)==[]: #If no results are found
print ("Search Complete. No results found.")
else:
print ("The list of triplets are: ")
print(pyth_list)
del pyth_list
a1 = input("Runtime of the program is {} seconds. Press any key to exit".format(time.process_time()-start))
| true |
0e7c83d4d2c446c084206623cfc460d5d9e0eb58 | SvetlanaTsim/python_basics_ai | /lesson_8/task_8_7.py | 1,851 | 4.46875 | 4 | """
Реализовать проект «Операции с комплексными числами».
Создать класс «Комплексное число».
Реализовать перегрузку методов сложения и умножения комплексных чисел.
Проверить работу проекта. Для этого создать экземпляры класса (комплексные числа),
выполнить сложение и умножение созданных экземпляров.
Проверить корректность полученного результата.
"""
# как я поняла, комплексные числа уже в питоне реализованы, поэтому перегрузку сделала без формулы
a = 5+2j
b = 8+6j
print(a+b)
print(a*b)
class ComplexNumber:
def __init__(self, number):
self.number = number
def __add__(self, other):
return self.number + other.number
def __mul__(self, other):
return self.number * other.number
a = ComplexNumber(5+2j)
b = ComplexNumber(8+6j)
print(a+b)
print(a*b)
# попробовала с формулой
class ComplexNumber2:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return f'{self.real + other.real}+{self.imag + other.imag}'
def __mul__(self, other):
# z1=a+bi и z2=c+di z1z2 = (ac-bd)+i(ad+cb).
#почему-то self.imag * other.imag дают отрицательное число, изменила им знак на '+'
return (self.real * other.real + self.imag * other.imag) + (self.imag * other.real + other.imag * self.real)
a_1 = ComplexNumber2(5, 2j)
b_1 = ComplexNumber2(8, 6j)
print(a_1+b_1)
print(a_1 * b_1)
| false |
7efb1395d46e4478a38a1e87632274ca4cf07cc4 | SvetlanaTsim/python_basics_ai | /lesson_3_ht/task_3_6.py | 1,111 | 4.1875 | 4 | """
6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв
и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
Каждое слово состоит из латинских букв в нижнем регистре. Сделать вывод исходной строки,
но каждое слово должно начинаться с заглавной буквы.
Необходимо использовать написанную ранее функцию int_func().
"""
def ext_func(string):
my_list = string.split()
out_str = ''
def int_func(word):
return word.title()
for m_word in my_list:
out_str += f'{int_func(m_word)} '
return out_str
print(ext_func('she sells sea shells on the seashore'))
| false |
e884acf79724ce595323ca07bf8e9783a2698f2e | shubham-bhoite164/DSA-with-Python- | /Reversing the Integer.py | 685 | 4.21875 | 4 | # Our task is to design an efficient algorithm to reverse the integer
# ex :- i/p =1234 , o/p =4321
# we are after the last digit in every iteration
# we can get it with modulo operator: the last digit is the remainder when dividing by 10
# we have to make sure that we remove that digit from the original number
# so we just have to divide the original number by 10 !!!
def reverse_integer(n):
reversed_integer = 0
remainder = 0
while n>0:
remainder = n % 10
reversed_integer = reversed_integer*10 + remainder
n = n//10 # we don't want decimal point
return reversed_integer
if __name__ == '__main__':
print(reverse_integer(1234))
| true |
1c7a92b66d1999fc6158a0422558668498f5aa0f | hdjsjyl/LeetcodeFB | /23.py | 2,577 | 4.21875 | 4 | """
23. Merge k Sorted Lists
Share
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
"""
## solution1: similar to merge sort algorithm, the time complexity is O(nklogn)
# n is the length of lists; k is the length of each list
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def helper(self, lists, left, right):
if left < right:
mid = left + (right - left) // 2
return self.merge(self.helper(lists, left, mid), self.helper(lists, mid + 1, right))
return lists[left]
def merge(self, l1, l2):
if not l1:
return l2
if not l2:
return l1
dummy = ListNode(-1)
cur = dummy
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
cur = cur.next
cur.next = None
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = None
if l1:
cur.next = l1
if l2:
cur.next = l2
return dummy.next
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
if not lists:
return None
left = 0
right = len(lists) - 1
return self.helper(lists, left, right)
# solution2: maintain a heap with length of n, n is the length of lists, k is the length of each list
# time complexity is O(nklogn), the time of updating heap is logn
# python heapq, if the item is a tuple, it includes three elements, the first is the priority and compared item, we use it to compare;
# the second is count item, each count item is different from all of others; the third is task object
import heapq
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
stack = []
heapq.heapify(stack)
order = 0
for l in lists:
if l:
heapq.heappush(stack, (l.val, order, l))
order += 1
res = ListNode(-1)
dummy = res
while stack:
cur = heapq.heappop(stack)[2]
res.next = cur
res = res.next
if cur.next:
heapq.heappush(stack, (cur.next.val, order, cur.next))
res.next = None
order += 1
return dummy.next | true |
aa866eb07967f983e83b81db0dd63ca2237c8935 | marwane8/algorithms-data-structures | /Sorting.py | 2,174 | 4.25 | 4 | import heapq
'''
SORTING ALGORITHMS
-Sorting Algorithms are a common class of problems with many implementation
-This class highlights some of the foundational implmentations of sorting
-SORT FUNCTIONS-
selectionSort: finds the minimum number and pops it into the result array
mergeSort: uses divide and conqure to to sort elements in n log(n) time
heapSort: uses heap data structure and heap pop to sort array
'''
class Sort:
def selectionSort(self, array):
result = []
size = len(array)
for n in range(size):
#Take minimum of the subarray and pop it into the result array
result.append(array.pop(array.index(min(array))))
return result
def mergeSort(self, array):
if not array:
return None
#base case
if len(array) == 1: return array
#divide array in two
middle = len(array)//2
LeftArray = array[:middle]
RightArray = array[middle:]
# call merge sort on both halfs
Left = self.mergeSort(LeftArray)
Right = self.mergeSort(RightArray)
# bring sorted halfs together
result = self.mergeArray(Left, Right)
return list(result)
def mergeArray(self, LeftArray, RightArray):
resultArray = []
#append smallest value to the result array
while LeftArray and RightArray:
if LeftArray[0] <= RightArray[0]:
resultArray.append(LeftArray.pop(0))
elif LeftArray[0] > RightArray[0]:
resultArray.append(RightArray.pop(0))
if not RightArray: resultArray += LeftArray
else: resultArray += RightArray
return resultArray
#Heap Sorting
def heapSort(self, array):
heapq.heapify(array)
result = []
while array:
result.append(heapq.heappop(array))
print(result)
return result
testArray = [2,6,9,8,4,7]
sort = Sort()
# Merge Sort
test1 = sort.mergeSort(testArray)
# Heap Sort
test2 = sort.heapSort(testArray)
#Selection Sort
test3 = sort.selectionSort(testArray) | true |
87784d6b0b95fb4c9b84b0a25d1b9c3423a7a52c | linhdvu14/leetcode-solutions | /code/874_walking-robot-simulation.py | 2,149 | 4.5 | 4 | # A robot on an infinite grid starts at point (0, 0) and faces north. The robot can
# receive one of three possible types of commands:
# -2: turn left 90 degrees
# -1: turn right 90 degrees
# 1 <= x <= 9: move forward x units
# Some of the grid squares are obstacles.
# The i-th obstacle is at grid point (obstacles[i][0], obstacles[i][1])
# If the robot would try to move onto them, the robot stays on the previous
# grid square instead (but still continues following the rest of the route.)
# Return the square of the maximum Euclidean distance that the robot will be
# from the origin.
# Example 1:
# Input: commands = [4,-1,3], obstacles = []
# Output: 25
# Explanation: robot will go to (3, 4)
# Example 2:
# Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
# Output: 65
# Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8)
# Note:
# 0 <= commands.length <= 10000
# 0 <= obstacles.length <= 10000
# -30000 <= obstacle[i][0] <= 30000
# -30000 <= obstacle[i][1] <= 30000
# The answer is guaranteed to be less than 2 ^ 31.
# ----------------------------------------------
# Ideas:
# Considerations:
# Complexity: O(m) time, O(n) space where m = len(commands), n = len(obstacles)
# ----------------------------------------------
class Solution:
def robotSim(self, commands, obstacles):
"""
:type commands: List[int]
:type obstacles: List[List[int]]
:rtype: int
"""
obstacles = set(map(tuple, obstacles))
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] # turn left = step left on dir array
result = x = y = i = 0 # i = dirs index; x, y = coords
for c in commands:
if c == -2:
i = (i - 1) % 4
elif c == -1:
i = (i + 1) % 4
else:
for _ in range(c):
dx, dy = dirs[i]
if (x + dx, y + dy) not in obstacles:
x += dx
y += dy
result = max(result, x * x + y * y)
return result | true |
7908915172b367d592be102e890a18001709d6e2 | linhdvu14/leetcode-solutions | /code/231_power-of-two.py | 639 | 4.375 | 4 | # Given an integer, write a function to determine if it is a power of two.
# Example 1:
# Input: 1
# Output: true
# Explanation: 20 = 1
# Example 2:
# Input: 16
# Output: true
# Explanation: 24 = 16
# Example 3:
# Input: 218
# Output: false
# ----------------------------------------------
# Ideas: power of two iff 1 bit set iff n&(n-1) == 0
# Considerations:
# - edge cases: n = 1, n < 0
# Complexity: O(1) time, O(1) space
# ----------------------------------------------
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and n & (n - 1) == 0 | true |
ded0c70db2cdd448b7041f41266219fe933f1aa7 | linhdvu14/leetcode-solutions | /code/589_n-ary-tree-preorder-traversal.py | 918 | 4.125 | 4 | # Given an n-ary tree, return the preorder traversal of its nodes' values.
# For example, given a 3-ary tree:
# 1
# / | \
# 3 2 4
# / \
# 5 6
# Return its preorder traversal as: [1,3,5,6,2,4].
# Note: Recursive solution is trivial, could you do it iteratively?
# ----------------------------------------------
# Ideas:
# Considerations:
# Complexity: time, space
# ----------------------------------------------
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
class Solution:
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
result = []
stack = [root]
while stack:
node = stack.pop()
if node:
result.append(node.val)
stack.extend(node.children[::-1])
return result
| true |
41be3c636e2d3cda64f2b4db81121a7b47ead5f5 | alexresiga/courses | /first semester/fp/assignment1/SetBP10.py | 660 | 4.375 | 4 | # Consider a given natural number n. Determine the product p of all the proper factors of n.
def productOfProperFactors(n):
"""
This function returns the product of all proper factor of a given natural number n.
input: n natural number.
output: a string with the proper factors and the reuslt of their product.
"""
result=""
p=1
d=2
while d<=n//2:
if n%d==0:
p*=d
result+=str(d)+'*'
d+=1
result=result[:-1]
result+='='+ str(p)
return result
n=int(input("Give natural number n: "))
print("The product of all proper factors of",n,"is",productOfProperFactors(n))
| true |
a4e6c461cea4d86d34094af65ca4ee743b7be922 | oneandzeroteam/python | /dev.garam.seo/factorial.py | 227 | 4.25 | 4 | #factorial.py
factorial = 1
number = int (input ("input the number wanted to factorial: "))
print (number)
if (number == 1):
factorial = 1
else :
for i in range (1, number+1):
factorial = factorial * i
print (factorial) | true |
98b8353fedd8c1efa32ef163d62ba63c9cf169c2 | WhySongtao/Leetcode-Explained | /python/240_Search_a_2D_Matrix_II.py | 1,350 | 4.125 | 4 | '''
Thought: When I saw something like sorted, I will always check if binary search
can be used to shrink the range. Here is the same.
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Take this as an example. First let's go to the middle of the first row: 7. If
the target is bigger, then clearly, it could be at the right of 7. It can also be
at the down of 7. The only impossible place is the element on the left of 7 in the
same row. Hmm, this doesn't look like a way to shrink range.
So what about going from right top corner. Corner seems to be a good starting point.
If the target is bigger than current element, we can get rid of this whole row!
If the target is smaller than the current element, we can get rid of this whole
column!
I think going from left bottom corner works as well.
'''
def searchMatrix(matrix, target):
if len(matrix) == 0:
return False
# Starting from top right corner.
row = 0
column = len(matrix[0])-1
while(row <= len(matrix)-1 and (column >= 0)):
if matrix[row][column] == target:
return True
elif target < matrix[row][column]:
column -= 1
elif target > matrix[row][column]:
row += 1
return False
| true |
b928b09a4b3e417316274d2bd19ddccf31198aff | LeftySolara/Projects | /Classic Algorithms/Collatz_Conjecture/collatz.py | 606 | 4.1875 | 4 | """
Collatz Conjecture:
Start with a number n > 1. Find the number of steps it takes to
reach one using the following process:
If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1
"""
try:
n = int(input("Enter a number greater than one: "))
if n <= 1:
print("Invalid input")
exit(0)
except ValueError:
print("Invalid input")
exit(0)
count = 0
while n != 1:
print(n)
if n % 2 == 0:
n //= 2
count += 1
elif n % 2 > 0:
n *= 3
n += 1
count += 1
print(n)
print("\nSteps taken: {}".format(count)) | true |
80f8377d734ff1a9f51ea52956ddbdb172456b78 | lachlankerr/AdventOfCode2020 | /AdventOfCode2020/day09.py | 1,883 | 4.15625 | 4 | '''
Day 09: https://adventofcode.com/2020/day/9
'''
def read_input():
'''
Reads the input file and returns a list of all the lines
'''
lines = []
with open('day09input.txt') as f:
lines = f.read().splitlines()
lines = list(map(int, lines)) # convert list to ints
return lines
def part_one(lines):
'''
Finds the number in the list that cannot be made from the previous `preamble_size` numbers.
'''
preamble = []
preamble_size = 25
for line in lines:
if len(preamble) < preamble_size:
preamble.append(line)
else:
if not check_preamble(preamble, line):
part_one_result = line
return line
else:
preamble.pop(0)
preamble.append(line)
pass
def check_preamble(preamble, num):
'''
Checks if the given num is a product of two numbers in the preamble.
'''
for a in preamble:
for b in preamble:
if a + b == num:
return True
return False
def part_two(lines):
'''
Finds a contiguous set of at least two numbers that sum to the result of part_one, then returns the sum of the smallest and largest number in this contiguous set.
'''
part_one_result = part_one(lines)
preamble = []
preamble_size = 2
i = 0
while i < len(lines):
if len(preamble) < preamble_size:
preamble.append(lines[i])
else:
if sum(preamble) == part_one_result:
return min(preamble) + max(preamble)
else:
preamble.pop(0)
preamble.append(lines[i])
if i == len(lines) -1 and preamble_size < i:
preamble_size += 1
preamble = []
i = 0
continue
i += 1
pass
| true |
90251aa6711f4db8af28ce75d89e4de26552f4a6 | danielmaddern/DailyProgrammer | /easy_challenge_1/challange.py | 611 | 4.25 | 4 | """
create a program that will ask the users name, age, and reddit username. have it tell them the information back, in the format:
your name is (blank), you are (blank) years old, and your username is (blank)
for extra credit, have the program log this information in a file to be accessed later.
"""
name = raw_input('Enter your name:')
age = raw_input('Enter your age:')
username = raw_input('Enter your Reddit username:')
output = "your name is %s, you are %s years old, and your username is %s" % (name, age, username)
print output
# Extra Credit
with open('output.file', 'w') as f:
f.write(output)
| true |
5bc53494fea4b54fcde00ef55f03d3be4a93a2a8 | WenboWong/Python-Geography-spatial-analysis | /Python Geography spatial analysis/chapter5 Python与地理信息系统/Pythagoras.py | 347 | 4.15625 | 4 | #Pythagoras .py
#投影坐标计算距离
import math
'''x1=456456.23
y1=1279721.064
x2=576628.34
y2=1071740.33
x_dist=x1-x2
y_dist=y1-y2
dist_sq=x_dist**2+y_dist**2
distance=math.sqrt(dist_sq)
print("距离为:{0}".format(distance))
'''
#十进制计算度数进行距离量算
x1=-90.21
y1=32.31
x2=-88.95
y2=30.43
x_dist=math.radians(x1-x2)
| false |
35cf1ad32b02ae5e60a20e0511e5b0e92e835b76 | MichaelDc86/Algorythms | /lesson_02/task_5.py | 797 | 4.3125 | 4 | # Вывести наэкран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127 - м включительно.
# Вывод выполнить в табличной форме: по десять пар "код-символ" в каждой строке..
def print_symbol(symbol_code):
if (symbol_code - 2) % 10 == 0:
print()
print(f'{symbol_code}-{chr(symbol_code)} ', end='')
# -----Цикл---------
#
#
# start = 32
# end = 127
#
# for i in range(start, (end+1)):
# print_symbol(i)
# -----Рекурсия---------
start = 32
end = 127
def main_print(n):
if n == end:
print_symbol(n)
return None
print_symbol(n)
main_print(n+1)
main_print(start)
| false |
cc68d3d33daad46d3395e152c04d2ca0786fdb99 | yathie/machine-learning | /ex8-basico-python.py | 520 | 4.1875 | 4 | '''faça um programa que leia um valor e apresente o número de Fibinacci correspondente a este valor lido. Lembre que os primeiros elementos sa série de Fibonacci são 0 e 1 e cada próximo termo é a soma dos 2 anteriores a ele.
0 1 1 2 3 5...
'''
posicao = int(input("Digite uma posição: "))
def fib(x):
seq = [0, 1, 1]
for i in range(3, x+1): #range(2,4) -> 2,3
seq.append(seq[i-1] + seq[i-2]) #append() adiciona ao fim
return seq[x]
resultado = fib(posicao)
print("fib ("+str(posicao)+") = ", resultado)
| false |
5368c1c72141f2c65dc28018a9007b8465b308a4 | neha52/Algorithms-and-Data-Structure | /Project1/algo2.py | 2,928 | 4.21875 | 4 | # -*- coding: utf-8 -*-
array = [] #create an array.
x = float (input ("Enter the value of X: "))
n = int(input("Enter the number of elements you want:"))
if(n<2): #check if array more than two elements.
print ("Enter valid number of elements!")
else:
print ('Enter numbers in array: ') #take input from user.
for i in range(int(n)):
no = input()
array.append(int(no))
def heap(array, n, i):
largest = i # Initialize largest as root.
l = 2 * i + 1
r = 2 * i + 2
# See if left child of root exists and is greater than root.
if l < n and array[i] < array[l]:
largest = l
# See if right child of root exists and is greater than root.
if r < n and array[largest] < array[r]:
largest = r
if largest != i: # If required, change root.
array[i],array[largest] = array[largest],array[i]
# swap root with element greater than root.
heap(array, n, largest) # Heapify the root.
# The main function to sort an array
def hSort(array):
# Build a maxheap.
for i in range(n, -1, -1):
heap(array, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
array[i], array[0] = array[0], array[i] # swap
heap(array, i, 0)
try:
hSort(array) #sort the array using heapsort.
def median(array): #compute median of array.
mid = len(array)//2 #if length=odd, compute middle element.
if len(array) % 2: # To check if the length of array is odd or even.
return array[mid]
else:
med = (array[mid] + array[mid-1]) / 2 #if length=even, compute mean of middle elements.
return med
with open('algo2.txt', 'w') as filehandle: # open file algo1.txt to print
for items in array: # sorted array with write privilege.
filehandle.write( '%d ' % items)
filehandle.close()
med = median(array)
#function to compute longest sub-array with median greater than equal to X.
def LongSubArray(array, med):
if x > med:
for i in range (int(n)):
if i>=n or x <= med: #conditions based on desired output.
break
array.remove(array[0])
med = median(array) #median of longest subarray.
return ("Longest Subarray is :" ,array ,"of length" ,len(array))
f = open('algo2.txt', 'a') #open same file to append output.
f.write(" : is the Sorted Array \n \n")
f.write(str(LongSubArray(array, med))) #called function to print longest subarray.
f.close()
except ValueError as err: #errors
print("Something went Wrong",err)
except:
print("Something went Wrong")
| true |
679425af21b2ce17248f38b842ab6717df10d1a9 | Langutang/Spark_Basics | /spark_basics_.py | 2,906 | 4.1875 | 4 | '''
Spark is a platform for cluster computing. Spark lets you spread data and computations over clusters with multiple nodes (think of each node as a separate computer).
Splitting up your data makes it easier to work with very large datasets because each node only works with a small amount of data.
As each node works on its own subset of the total data, it also carries out a part of the total calculations required,
so that both data processing and computation are performed in parallel over the nodes in the cluster. It is a fact that parallel computation
can make certain types of programming tasks much faster.
'''
'''
Spark's core data structure is the Resilient Distributed Dataset (RDD). This is a low level object that lets Spark work its magic by splitting data across multiple nodes
in the cluster. However, RDDs are hard to work with directly, so in this course you'll be using the Spark DataFrame abstraction built on top of RDDs.
'''
# Step 1 - create instance of SparkContext
# Import SparkSession from pyspark.sql
from pyspark.sql import SparkSession
# Create my_spark
my_spark = SparkSession.builder.getOrCreate()
# Print my_spark
print(my_spark)
# View Tables
print(spark.catalog.listTables())
# Don't change this query
query = "FROM flights SELECT * LIMIT 10"
# Get the first 10 rows of flights
flights10 = spark.sql(query)
# Show the results
flights10.show()
##############################
# QUERY AND CONVERT TO PD DF #
##############################
# Don't change this query
query = "SELECT origin, dest, COUNT(*) as N FROM flights GROUP BY origin, dest"
# Run the query
flight_counts = spark.sql(query)
pd_counts = flight_counts.toPandas()
print(pd_counts.head())
# Create pd_temp
pd_temp = pd.DataFrame(np.random.random(10))
# Create spark_temp from pd_temp
spark_temp = spark.createDataFrame(pd_temp)
# Examine the tables in the catalog
print(spark.catalog.listTables())
# Add spark_temp to the catalog
spark_temp.createOrReplaceTempView("temp")
# Examine the tables in the catalog again
print(spark.catalog.listTables())
####################
# LOADING FROM FILE#
####################
# Don't change this file path
file_path = "/usr/local/share/datasets/airports.csv"
# Read in the airports data
airports = spark.read.csv(file_path, header=True)
# Show the data
airports.show()
####################
# CREATING COLUMNS #
####################
# Create the DataFrame flights
flights = spark.table("flights")
# Show the head
flights.show()
# Add duration_hrs
flights = flights.withColumn("duration_hrs", flights.air_time/60)
#############
# FILTERING #
#############
# Filter flights by passing a string
long_flights1 = flights.filter("distance > 1000")
# Filter flights by passing a column of boolean values
long_flights2 = flights.filter(flights.distance > 1000)
# Print the data to check they're equal
long_flights1.show()
long_flights2.show()
| true |
d07674970d95b0ab207982ccf70f771840a8486d | Liam1809/Classes | /Polymorphism.py | 798 | 4.28125 | 4 |
a_list = [1, 18, 32, 12]
a_dict = {'value': True}
a_string = "Polymorphism is cool!"
print(len(a_list))
print(len(a_dict))
print(len(a_string))
# The len() function will attempt to call a method named __len__() on your class.
# This is one of the special methods known as a “dunder method” (for double underscore) which Python will look for to perform special operations.
# Implementing that method will allow the len() call to work on the class.
# If it is not implemented, the call to len() will fail with an AttributeError.
# The following code example shows a class implementing __len__().
class Bag:
def __init__(self, item_count):
self.item_count = item_count
def __len__(self):
return self.item_count
mybag = Bag(10)
print(len(mybag))
# OUTPUTS: 10 | true |
2ab337712c44f9dd7fffb98548c8e3a7d0cea93f | tillyoswellwheeler/python-learning | /multi-question_app/app.py | 929 | 4.15625 | 4 | #--------------------------------------------
# Python Learning -- Multi-Question Class App
#--------------------------------------------
from Question import Question
#-------------------------------------
# Creating Question Object and App
question_prompts = [
"What colour are apples?\n(a) Red/Green\n(b) Purple/Red\n(c) Grey\n\n",
"What colour are Bananas?\n(a) Teal/Green\n(b) Magenta/Red\n(c) Yellow\n\n",
"What colour are Cherries?\n(a) Red/Green\n(b) Purple/Red\n(c) Blue\n\n"
]
questions = [
Question(question_prompts[0], "a"),
Question(question_prompts[1], "c"),
Question(question_prompts[2], "b"),
]
def ask_questions(questions):
score = 0
for question in questions:
answer = input(question.prompt)
if answer is question.answer:
score += 1
else:
"Invalid choice"
print("You got {} Correct".format(score))
ask_questions(questions) | true |
0443bd0c80489e9a063851c62583a9fb7956bc4a | tillyoswellwheeler/python-learning | /2d-lists_&_nested-loops.py | 625 | 4.40625 | 4 | #-----------------------------------------
# Python Learning -- 2D & Nested Loops
#-----------------------------------------
#-----------------------------------------
# Creating a 2D array
number_grid = [
[1, 3, 4],
[3, 4, 5],
[3, 6, 7],
[2]
]
#-----------------------------------------
# Accessing rows and cols
print(number_grid[0][1])
#-----------------------------------------
# Accessing rows using a For Loop
for row in number_grid:
print(row)
#-----------------------------------------
# Accessing cols using a NESTED For Loop
for row in number_grid:
for col in row:
print(col) | true |
69e4a76a2265aa14a5efaaef542c8335fdd2a3e1 | tillyoswellwheeler/python-learning | /inheritance.py | 607 | 4.4375 | 4 | #-------------------------------------
# Python Learning -- Inheritance
#-------------------------------------
#-------------------------------------
#
class Chef:
def make_chicken(self):
print("Chef makes chicken")
def make_ham(self):
print("Chef makes ham")
def make_special_dish(self):
print("Chef makes a special dish")
class ChineseChef(Chef):
def make_chicken_feet(self):
print("Hmm crunchy chicken feet!")
dinner1 = Chef.make_chicken(Chef)
dinner2 = ChineseChef.make_chicken(ChineseChef)
dinner3 = ChineseChef.make_chicken_feet(ChineseChef)
| true |
d16589bfe23eaa72097e6fd6ea740bc4008a9415 | tillyoswellwheeler/python-learning | /LPTHW/Ex15.py | 1,123 | 4.40625 | 4 | # ------------------------------------
# LPTHW -- Ex15. Reading Files
# ------------------------------------
from sys import argv
# this means when you run the python, you need to run it with the name of the python command
# and the file you want to read in
script, filename = argv
# This opens the file and assigns it to a variable to use later
txt = open(filename)
# A string that passes through the filename given when you run the command
# This can happen because of the sys argv module
print(f"Here's your file {filename}:")
# This reads the saved txt from the txt variable above
print(txt.read())
# This print outputs a string and then asks the user for input
# If the user types in a valid txt file it saves to the variable file_again
# If you had another txt file in the same directory you could pass it through here by using its name
print("Type the filename again:")
file_again = input("> ")
# This opens the file and saves the output to the variable txt_again
txt_again = open(file_again)
# This uses the read() module to read what is in txt_again.
print(txt_again.read())
txt_again.close()
txt.close()
| true |
0bc1e75b9b72d3dc658993e020e7067a3ad5e468 | sriram161/Data-structures | /PriorityQueue/priorityqueue.py | 1,580 | 4.21875 | 4 | """ Priotity Queue is an abstract data structure.
Logic:
-------
Priority queue expects some sort of order in the data that is feed to it.
"""
import random
class PriorityQueue(object):
def __init__(self, capacity):
self.capacity = capacity
self.pq = []
def push(self, value):
if len(self.pq) < self.capacity:
self.pq.append(value)
else:
print("Priority queue is full!!!")
def delMax(self):
self.popMax()
def popMax(self):
max_index = self._findMaxIndex()
self.pq[-1], self.pq[max_index] = self.pq[max_index], self.pq[-1]
return self.pq.pop()
def popMin(self):
min_index = self._findMinIndex()
self.pq[-1], self.pq[min_index] = self.pq[min_index], self.pq[-1]
return self.pq.pop()
def isEmpty(self):
return False if len(self.pq) else True
def insert(self, pos, value):
self.pq.insert(-pos,value)
def _findMaxIndex(self):
max_index = 0
for i in range(len(self.pq)):
if self.pq[i] > self.pq[max_index]:
max_index = i
return max_index
def _findMinIndex(self):
min_index = 0
for i in range(len(self.pq)):
if self.pq[i] < self.pq[min_index]:
min_index = i
return min_index
if __name__ == "__main__":
pq = PriorityQueue(10)
for i in range(11):
pq.push(random.randint(1, 100))
print(pq.pq)
print(pq.popMax())
print(pq.pq)
print(pq.popMin()) | true |
98082b9e10c1250be6b115aa7278315a0a4b9cdc | griffs37/CA_318 | /python/8311.sol.py | 1,013 | 4.15625 | 4 | def make_sum(total, coins):
# Total is the sum that you have to make and the coins list contains the values of the coins.
# The coins will be sorted in descending order.
# Place your code here
greedy_coin_list = [0] * len(coins) # We create a list of zeros the same length as the coins list we read in
i = 0
while total > 0: # While the total is less than 0
while i < len(coins): # and while i is within the bounds of the coins list
if coins[i] <= total: # if the number at position i is less than or equal to our total
greedy_coin_list[i] += 1 # We add 1 to that position in our greedy coin list as it means we will use that coin once
total -= coins[i] # We then subtract that value from the total
else: # else the number at position i is greater than the total
i += 1 # We increment i to check the next coin in the list
return(greedy_coin_list)
# Test cases used for local testing
#print(make_sum(12, [5,2,1]))
#print(make_sum(157, [7,3,2,1])) | true |
2f69b2620798d10de0b6eb730ee28e82cb032a67 | vikky1993/Mytest | /test3.py | 1,997 | 4.34375 | 4 | # Difference between regular methods, class methods and static methods
# regular methods in a class automatically takes in instance as the first argument and by convention we wer
# calling this self
# So how can we make it to take class as the first argument, to do that we gonna use class methods
#just add a decorator called @classmethod to make a class method
class Employee:
num_of_emps = 0
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@email.com'
self.pay = pay
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
# common convention for class variable is cls
@classmethod
def set_raise_amt(cls, amount):
cls.raise_amt = amount
# you may hear people say they use class methods as alternative constructors
# what do they mean by this is we can use these class methods in order to provide multiple ways of creating or objects
# this new method as an alternative constructor, usually these start with from - and that's convention also
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay) #this line is going to create the new employee, so we will return it too
# now lets see what is a static method, static method dont pass as argument automatically
# usually they behave just like regular functions, except we include them in our classes because they have some
# logically connection with the class
@staticmethod
def is_workday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
#usually a method should be made static if you dont access instance(self) or class(cls) anywhere within function
emp1 = Employee('Vickranth', 'Kalloli', 70000)
emp2 = Employee('User', 'Test', 50000)
import datetime
my_date = datetime.date(2018, 2, 21)
print(Employee.is_workday(my_date)) | true |
3d891ab050621beb39df665cf7e7845f16b6d9af | shoumu/HuntingJobPractice | /leetcode/62_unique_paths.py | 1,151 | 4.125 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Author: shoumuzyq@gmail.com
# https://shoumu.github.io
# Created on 2015/12/16 15:39
def unique_paths(m, n):
"""
according to the Combinatorics, the result is C(m - 1)(m + n -2)
:param m:
:param n:
:return:
"""
a = m + n - 2
b = m - 1
result = 1
for i in range(b):
result *= a
a -= 1
for i in range(1, b + 1):
result /= i
return int(result)
def unique_paths_2(m, n):
"""
a dynamic programming solution
the formula is f(m, n) = f(m - 1, n) + f(m, n - 1)
:param m:
:param n:
:return:
"""
matrix = [[1] * n] * m
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
continue
elif i == 0:
matrix[i][j] = matrix[i][j - 1]
elif j == 0:
matrix[i][j] = matrix[i - 1][j]
else:
matrix[i][j] = matrix[i][j - 1] + matrix[i - 1][j]
return matrix[m - 1][n - 1]
print(unique_paths_2(2, 2))
print(unique_paths_2(3, 2))
print(unique_paths_2(1, 10))
print(unique_paths_2(10, 1))
| false |
6b66cbbdb06804c86c757ca97397895a314ecfeb | RamaryUp/hackerrank | /Python/sets/symmetric_difference.py | 1,060 | 4.28125 | 4 | '''
HackerRank Challenge
Name : Symmetric Difference
Category : Sets
Difficulty : easy
URL : https://www.hackerrank.com/challenges/symmetric-difference/problem
Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both.
Input Format
The first line of input contains an integer, .
The second line contains space-separated integers.
The third line contains an integer, .
The fourth line contains space-separated integers.
Output Format
Output the symmetric difference integers in ascending order, one per line.
Sample Input
4
2 4 5 9
4
2 4 11 12
Sample Output
5
9
11
12
'''
# let's play with set collections !
m, set1 = int(input()), set(map(int,input().split()))
n, set2 = int(input()), set(map(int,input().split()))
syms_diff = list(set1 ^ set2) # list(set1.difference(set2)) - list(set2.difference(set1)) could be used; or list(set1-set2) + list(set2-set1)
syms_diff.sort()
for item in syms_diff:
print(item) | true |
ef64e4a52c2f1f0d14755358ba29b6f945a86336 | SinghTejveer/stepic_python_in_action_eng | /solutions/s217.py | 713 | 4.25 | 4 | """Given a real positive number a and an integer number n.
Find a**n. You need to write the whole program with a recursive function
power(a, n).
Sample Input 1:
2
1
Sample Output 1:
2
Sample Input 2:
2
2
Sample Output 2:
4
"""
def solve(num: float, exp: int) -> float:
"""Calculate num**exp."""
if exp < 0:
return solve(1 / num, -exp)
elif exp == 0:
return 1
elif exp == 1:
return num
elif exp % 2 == 0:
return solve(num * num, exp // 2)
else:
return num * solve(num * num, (exp - 1) // 2)
def main():
num = float(input())
exp = int(input())
print(solve(num, exp))
if __name__ == '__main__':
main()
| true |
99f3382c8b97ce2f4195f6ac93d9712d662cace5 | SinghTejveer/stepic_python_in_action_eng | /solutions/s005.py | 1,065 | 4.15625 | 4 | # pylint: disable=invalid-name
"""Difference of times
Given the values of the two moments in time in the same day: hours, minutes
and seconds for each of the time moments. It is known that the second moment
in time happened not earlier than the first one. Find how many seconds passed
between these two moments of time.
Input data format
The program gets the input of the three integers: hours, minutes, seconds,
defining the first moment of time and three integers that define the second
moment time.
Output data format
Output the number of seconds between these two moments of time.
Sample Input 1:
1
1
1
2
2
2
Sample Output 1:
3661
Sample Input 2:
1
2
30
1
3
20
Sample Output 2:
50
"""
def main():
h1 = int(input().rstrip())
m1 = int(input().rstrip())
s1 = int(input().rstrip())
h2 = int(input().rstrip())
m2 = int(input().rstrip())
s2 = int(input().rstrip())
print(h2*60*60 + m2*60 + s2 - h1*60*60 - m1*60 - s1)
if __name__ == '__main__':
main()
| true |
85288d85c45185c3505ac16f9fc76d02459e83a3 | SinghTejveer/stepic_python_in_action_eng | /solutions/s080.py | 423 | 4.1875 | 4 | """
Write a program, which reads the line from a standard input, using the input()
function, and outputs the same line to the standard output, using the print()
function.
Please pay attention that you need to use the input function without any
parameters, and that you need to output only that, what was transferred
to the input of this program.
"""
def main():
print(input())
if __name__ == '__main__':
main()
| true |
8c3ed77439371b18c45e60d0c1623efa5e2570c7 | bthuynh/python-challenge | /PyPoll/main.py | 2,879 | 4.125 | 4 | # You will be give a set of poll data called election_data.csv.
# The dataset is composed of three columns: Voter ID, County, and Candidate.
# Your task is to create a Python script that analyzes the votes and calculates each of the following:
# The total number of votes cast
# A complete list of candidates who received votes
# The percentage of votes each candidate won
# The total number of votes each candidate won
# The winner of the election based on popular vote.
# As an example, your analysis should look similar to the one below:
# Election Results
# -------------------------
# Total Votes: 3521001
# -------------------------
# Khan: 63.000% (2218231)
# Correy: 20.000% (704200)
# Li: 14.000% (492940)
# O'Tooley: 3.000% (105630)
# -------------------------
# Winner: Khan
# -------------------------
import os
import csv
votes = []
candidate = []
kvote = 0
cvote = 0
lvote = 0
ovote = 0
name1 = "Khan"
name2 = "Correy"
name3 = "Li"
name4 = "O'Tooley"
csvpath = os.path.join("Resources", "election_data.csv")
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
for row in csvreader:
votes.append(row[0])
candidate.append(row[2])
for name in candidate:
if name == name1:
kvote = kvote + 1
elif name == name2:
cvote = cvote + 1
elif name == name3:
lvote = lvote + 1
elif name == name4:
ovote = ovote + 1
def most_frequent(candidate):
return max(set(candidate), key = candidate.count)
total_votes = len(votes)
winner = most_frequent(candidate)
knumber = round(int(kvote) / int(total_votes),2)
cnumber = round(int(cvote) / int(total_votes),2)
lnumber = round(int(lvote) / int(total_votes),2)
onumber = round(int(ovote) / int(total_votes),2)
kpercent = "{:.0%}".format(knumber)
cpercent = "{:.0%}".format(cnumber)
lpercent = "{:.0%}".format(lnumber)
opercent = "{:.0%}".format(onumber)
print("Election Results")
print("--------------------------")
print(f"Total Votes: {total_votes}")
print(f"Khan: {kpercent} ({kvote})")
print(f"Correy: {cpercent} ({cvote})")
print(f"Li: {lpercent} ({lvote})")
print(f"O'Tooley: {opercent} ({ovote})")
print("--------------------------")
print(f"Winner: {winner}")
print("--------------------------")
analysis = os.path.join("analysis","Pypoll.txt")
file = open(analysis, 'w')
file.writelines("Election Results"+'\n')
file.writelines("--------------------------"+'\n')
file.writelines(f"Total Votes: {total_votes}"+'\n')
file.writelines(f"Khan: {kpercent} ({kvote})"+'\n')
file.writelines(f"Correy: {cpercent} ({cvote})"+'\n')
file.writelines(f"Li: {lpercent} ({lvote})"+'\n')
file.writelines(f"O'Tooley: {opercent} ({ovote})"+'\n')
file.writelines("--------------------------"+'\n')
file.writelines(f"Winner: {winner}"+'\n')
file.writelines("--------------------------"+'\n') | true |
8a4876cd4aae26f15d9673aac9fdf90aa58b573c | peltierchip/the_python_workbook_exercises | /chapter_1/exercise_17.py | 787 | 4.1875 | 4 | ##
#Compute the amount of energy to achieve the desired temperature change
H_C_WATER=4.186
J_TO_KWH=2.777e-7
C_PER_KWH=8.9
#Read the volume of the water and the temperature change from the user
volume=float(input("Enter the amount of water in milliliters:\n"))
temp_change=float(input("Enter the value of the temperature change in degrees Celsius:\n"))
#Compute the amount of energy
energy_J=volume*H_C_WATER*temp_change
#Display the result
print("This is the amount of energy to achieve the desired temperature change: %.3f J\n"%energy_J)
#Compute the conversion from joule to kilowatt hours and the cost of boiling the water
energy_KWH=energy_J*J_TO_KWH
cost_electricity=C_PER_KWH*energy_KWH
#Display the result
print("The cost of boiling the water is: %.2f cents"%cost_electricity)
| true |
1e0ed285d5f8797eab8da2e8bd076f1c7078185a | peltierchip/the_python_workbook_exercises | /chapter_2/exercise_49.py | 894 | 4.40625 | 4 | ##
#Determine the animal associated with the inserted year
#Read the year from the user
year=int(input("Enter the year:\n"))
#Check if the year is valid
if year>=0:
#Determine the corresponding animal and display the result
if year%12==8:
animal="Dragon"
elif year%12==9:
animal="Snake"
elif year%12==10:
animal="Horse"
elif year%12==11:
animal="Sheep"
elif year%12==0:
animal="Monkey"
elif year%12==1:
animal="Rooster"
elif year%12==2:
animal="Dog"
elif year%12==3:
animal="Pig"
elif year%12==4:
animal="Rat"
elif year%12==5:
animal="Ox"
elif year%12==6:
animal="Tiger"
elif year%12==7:
animal="Hare"
print("The animal associated to the year",year,"is:",animal)
else:
print("The year isn't valid")
| true |
4878ceeb7108bd2885a2fccdce8abb5312be586d | peltierchip/the_python_workbook_exercises | /chapter_8/exercise_184.py | 1,378 | 4.59375 | 5 | ##
# Perform the flattening of a list, which is convert
# a list that contains multiple layers of nested lists into a list that contains all the same elements without any nesting
## Flatten the list
# @param data the list to flatten
# @return the flattened list
def flattenList(data):
if not(data):
return data
if type(data[0]) == list:
l1 = flattenList(data[0])
l2 = flattenList(data[1:])
return l1 + l2
if type(data[0]) != list:
l1 = [data[0]]
l2 = flattenList(data[1:])
return l1 + l2
# Demonstrate the flattenList function
def main():
print("The result of the flattening of the list [1, [2, 3], [4, [5, [6, 7]]], [[[8], 9], [10]]] is:",flattenList([1, [2, 3], [4, [5, [6, 7]]], [[[8], 9], [10]]]))
print("The result of the flattening of the list [] is:",flattenList([]))
print("The result of the flattening of the list [1, 3, 7, 8, 10, 20, 77, 6] is:",flattenList([1, 3, 7, 8, 10, 20, 77, 6]))
print("The result of the flattening of the list [[1, 2], [[[3], 4, [5, 6]], [7]], [8], 9, [10, 11], 12, [[[13, 14], [15]]]] is:",flattenList([[1, 2], [[[3], 4, [5, 6]], [7]], [8], 9, [10, 11], 12, [[[13, 14], [15]]]]))
print("The result of the flattening of the list [[1, [2]], [[3, 4], [5]], [6]] is:",flattenList([[1, [2]], [[3, 4], [5]], [6]]))
# Call the main function
main() | true |
5d8a7606ac90a78fb1303d7f7e93c1be4e9aa563 | peltierchip/the_python_workbook_exercises | /chapter_5/exercise_115.py | 995 | 4.5 | 4 | ##
#Determine the list of proper divisors of a positive integer entered from the user
##Create the list of proper divisors
# @param n the positive integer
# @return the list of proper divisors
def properDivisors(n):
p_d=[]
i=1
#Keep looping while i is less or equal than about half of n
while i<=(n//2):
if n%i==0:
p_d.append(i)
i=i+1
return p_d
#Demonstrate the properDivisors function
def main():
p_integer=int(input("Enter a positive integer:\n"))
#Keep looping while the user enters a number less or equal than 0 or a number greater than 1
while p_integer<=0:
print("You must enter an integer greater than 0!")
p_integer=int(input("Enter a positive integer:\n"))
pro_divisors=properDivisors(p_integer)
print("Here the proper divisors of %d:\n"%p_integer)
print(pro_divisors)
#Only call the main function when this file has not been imported
if __name__=="__main__":
main()
| true |
b3f81cd9792372a13ee9a09e03775b4c95aeacaf | peltierchip/the_python_workbook_exercises | /chapter_5/exercise_130.py | 1,143 | 4.34375 | 4 | ##
#Identify unary + and - operators in a list of tokens and replace them with u+ and
#u- respectively
from exercise_129 import tokenizing
##Replace unary + and - operators respectively with u+ and u-
# @param ts the list of tokens
# @return the list of tokens where the unary + and - operators have been substituted
def unaryOperators(ts):
n_ts=[]
if ts[0]=="-" or ts[0]=="+":
n_ts.append("u"+ts[0])
else:
n_ts.append(ts[0])
for i in range(1,len(ts)):
if (ts[i]=="-" or ts[i]=="+") and (ts[i-1]=="/" or ts[i-1]=="-" \
or ts[i-1]=="^" or ts[i-1]=="+" or ts[i-1]=="*" or ts[i-1]=="(" or \
ts[i-1]=="[" or ts[i-1]=="{"):
n_ts.append("u"+ts[i])
else:
n_ts.append(ts[i])
return n_ts
#Demonstrate the unaryOperators function
def main():
math_expression=input("Enter a mathematical expression:\n")
tokens=tokenizing(math_expression)
print("Tokens:\n",tokens)
unr_ops_tokens=unaryOperators(tokens)
print("Tokens (marking the unary operators):\n",unr_ops_tokens)
#Call the main function
if __name__=="__main__":
main()
| false |
f08114b5f25112a2f4b604ed1df58218901bdfeb | peltierchip/the_python_workbook_exercises | /chapter_4/exercise_109.py | 943 | 4.15625 | 4 | ##
#Display all the magic dates of the 20th century
from exercise_106 import daysMonth
#Store the first year and the last year as constants
FIRST_YEAR=1901
LAST_YEAR=2000
##Determine if the date is a magic date
# @param y the year
# @param m the month
# @param d the day
# @return True if the date is magic. False otherwise
def magicDates(y,m,d):
s_y=str(y)
s_t_c=str(m*d)
if len(s_t_c)==1:
s_t_c="0"+s_t_c
if s_t_c==s_y[2:]:
return True
return False
#Check every date of the 20th century: if it’s magic, display it
def main():
print("THE MAGIC DATES IN THE 20TH CENTURY ARE:\n")
for i in range(FIRST_YEAR,LAST_YEAR+1):
for j in range(1,13):
n_d=daysMonth(i,j)
for k in range(1,n_d+1):
if magicDates(i,j,k):
print("The date %4d/%02d/%02d is a magic date."%(i,j,k))
#Call the main function
main()
| false |
8312a957ec2cc7de0eacaa4fda57e20f04689b70 | peltierchip/the_python_workbook_exercises | /chapter_5/exercise_120.py | 785 | 4.1875 | 4 | ##
#Display a list of items formatted
##Formatting items in a list
# @param l the list
# @return a string containing the formatted elements
def formattingList(l):
i=0
n_l=l
if len(l)==0:
return "No items have been entered."
if len(l)==1:
return str(l[i])
delimeter=" "
n_s=""
while i<len(l)-2:
n_l.insert(i,(l[i]+","))
n_l.pop(i+1)
i=i+1
n_l.insert(len(l)-1,"and")
n_s=delimeter.join(n_l)
return n_s
#Demonstrate the formattingList function
def main():
items=[]
item=input("Enter the first item:\n")
while item!="":
items.append(item)
item=input("Enter the item:\n")
s_items=formattingList(items)
print("\n%s"%s_items)
#Call the main function
main()
| true |
d58c3325359ae564c265e490b0dbf0240d51a137 | peltierchip/the_python_workbook_exercises | /chapter_2/exercise_47.py | 1,246 | 4.4375 | 4 | ##
#Determine the season from the day of the year entered
#Read the day of the year fom the user
month=input("Enter the month:\n")
day=int(input("Enter the day:\n"))
season=" "
#Determine the season
if (month=="January") and (1<=day<=31):
season=="Winter"
elif (month=="February") and (1<=day<=28):
season="Winter"
elif (month=="May") and (1<=day<=31):
season="Spring"
elif (month=="April") and (1<=day<=30):
season="Spring"
elif (month=="July") and (1<=day<=31):
season="Summer"
elif (month=="August") and (1<=day<=31):
season="Summer"
elif (month=="October") and (1<=day<=31):
season="Autumn"
elif month=="December":
if day<21:
season="Autumn"
else:
season="Winter"
elif month=="March":
if day<20:
season="Winter"
else:
season="Spring"
elif month=="June":
if day<21:
season="Spring"
elif day<=30:
season="Summer"
elif month=="September":
if day<22:
season="Summer"
elif day<=30:
season="Autumn"
#Check if the day of the year entered is valid
if season==" ":
print("The day of the year entered isn't valid")
else:
print("The day of the year is in the season",season)
| false |
1d460dae11b9cf1493fa428c3d32e07fcf3910d8 | peltierchip/the_python_workbook_exercises | /chapter_4/exercise_95.py | 1,319 | 4.3125 | 4 | ##
#Capitalize a string entered from the user
##Capitalize the string
# @param string the string to capitalize
# @return the string for which the capitalization has been realized
def capitalize_it(string):
c_string=string
i=0
while i<len(string) and c_string[i]==" ":
i=i+1
if i<len(string):
c_string=c_string[0:i]+c_string[i].upper()+string[i+1:len(c_string)]
i=0
while i<len(string):
if c_string[i]=="." or c_string[i]=="?" or c_string[i]=="!":
i=i+1
while i<len(string) and c_string[i]==" ":
i=i+1
if i<len(string):
c_string=c_string[0:i]+c_string[i].upper()+c_string[i+1:len(c_string)]
i=i+1
i=1
while i<len(string)-1 :
if c_string[i]=="i" and c_string[i-1]==" " and (c_string[i-1]==" " or c_string[i+1]=="." or \
c_string[i]=="?" or c_string[i]=="!" or c_string[i]=="'"):
c_string=c_string[0:i]+c_string[i].upper()+c_string[i+1:len(c_string)]
i=i+1
return c_string
#Read the string from the user and demonstrate the capitalize_it function
def main():
s=input("Enter the string:\n")
c_s=capitalize_it(s)
print("Here the correct string:\n%s"%c_s)
#Call the main function
main()
| true |
029562d3c3a05977df813e73fbda14bf86927683 | peltierchip/the_python_workbook_exercises | /chapter_8/exercise_181.py | 1,233 | 4.125 | 4 | ##
# Determine whether it is possible to form the dollar amount entered by
# the user with a precise number of coins, always entered by the user
from itertools import combinations_with_replacement
## Determine whether or not it is possible to construct a particular total using a
# specific number of coins
# @param d_a the dollar amount
# @param n_c the number of coins
# @return True if d_a can be formed with n_c coins
def possibleChange(d_a, n_c, i = 0):
c_l = [0.25, 0.10, 0.05, 0.01]
p_c_l = list(combinations_with_replacement(c_l, n_c))
# Base case
if i < len(p_c_l) and d_a == round(sum(p_c_l[i]), 4):
return True
# Recursive case
if i < len(p_c_l):
i = i + 1
return possibleChange(d_a, n_c, i)
# Demonstrate the possibleChange function
def main():
dollar_amount = float(input("Enter the dollar amount:\n"))
number_coins = int(input("Enter the number of coins:\n"))
if possibleChange(dollar_amount, number_coins):
print("The entered dollar amount can be formed using the number of coins indicated.")
else:
print("The entered dollar amount can't be formed using the number of coins indicated.")
# Call the main function
main()
| true |
ab065da1c97d276ae71cff4985aa8b33314cf6ee | peltierchip/the_python_workbook_exercises | /chapter_1/exercise_7.py | 247 | 4.1875 | 4 | ##
#Calculation of the sum of the first n positive integers
#Read positive integer
n=int(input("Enter a positive integer\n"))
#Calculation of the sum
s=(n)*(n+1)/2
#Display the sum
print("The sum of the first %d positive integers is: %d" %(n,s))
| true |
b6f80becd1d1f37802a427950c059b41788d2b0d | peltierchip/the_python_workbook_exercises | /chapter_6/exercise_136.py | 921 | 4.71875 | 5 | ##
# Perform a reverse lookup on a dictionary, finding keys that
# map to a specific value
## Find keys that map to the value
# @param d the dictionary
# @param v the value
# @return the list of keys that map to the value
def reverseLookup(d,v):
# Create a list to store the keys that map to v
k_a_v=[]
# Check each key of d
for k in d:
# If the current value is equal to v, store the key in k_a_v
if d[k]==v:
k_a_v.append(k)
return k_a_v
#Demonstrate the reverseLookup function
def main():
dctnry={"a": 3, "b": 1, "c": 3, "d": 3, "e": 0, "f": 5}
print("The keys that map to 3 are:",reverseLookup(dctnry,3))
print("The keys that map to 7 are:",reverseLookup(dctnry,7))
print("The keys that map to 0 are:",reverseLookup(dctnry,0))
#Only call the main function when this file has not been imported
if __name__=="__main__":
main() | true |
c22deedf7d33043df0d14f90d3068ea1776b5f54 | peltierchip/the_python_workbook_exercises | /chapter_7/exercise_172.py | 1,981 | 4.15625 | 4 | ##
# Search a file containing a list of words and display all of the words that
# contain each of the vowels A, E, I, O, U and Y exactly once and in order
# Create a list to store vowels
vowels_list = ["a", "e", "i", "o", "u", "y"]
# Read the name of the file to read from the user
f_n_r = input("Enter the name of the file to read:\n")
try:
# Open the file for reading
inf = open(f_n_r, "r")
# Create a list to store the words that meet this constraint
s_v_o_ws = []
# Read the first line from the file
line = inf.readline()
# Keep looping until we have reached the end of the file
while line != "":
line = line.rstrip()
o_line = line
line = line.lower()
l_c = 0
t = True
v_c = 0
# Keep looping while l_c is less than the length of line and t is True
while l_c < len(line) and t:
# Check if the character is a consonant
if not(line[l_c] in vowels_list):
l_c = l_c + 1
else:
# Check if the character matches the current vowel
if line[l_c] == vowels_list[v_c]:
# Check if the character matches the last vowel
if v_c == len(vowels_list) - 1:
s_v_o_ws.append(o_line)
t = False
else:
v_c = v_c + 1
l_c = l_c + 1
else:
t = False
# Read the next line from the file
line = inf.readline()
# Close the file
inf.close()
# Check if s_v_o_ws is empty
if s_v_o_ws:
# Display the result
print("The words that contain each of the vowels A, E, I, O, U and Y exactly once and in order are:\n")
for w in s_v_o_ws:
print(w)
else:
print("No word satisfies the constraint")
except FileNotFoundError:
# Display an error message if the file to read was not opened successfully
print("'%s' wasn't found."%f_n_r)
| true |
b9a6cb431b02ff057c8ce4aff5a20ae724f78b30 | peltierchip/the_python_workbook_exercises | /chapter_5/exercise_111.py | 718 | 4.4375 | 4 | ##
#Display in reverse order the integers entered from the user, after being stored in a list
#Read the first integer from the user
n=int(input("Enter the first integer:\n"))
#Initialize integers to an empty list
integers=[]
#Keep looping while n is different from zero
while n!=0:
#Add n to integers
integers.append(n)
#Read the integer from the user
n=int(input("Enter the integer(0 to quit):\n"))
#Check if integers is empty
if integers==[]:
print("No integers have been entered.")
else:
#Sort the integers into revers order
integers.reverse()
#Display the elements of the list
print("Here are the integers in sorted order:\n")
for integer in integers:
print(integer) | true |
84e1d58ad16f91825fcfb06eac1c1226b61f5e6a | Lycurgus1/python | /day_1/Dictionaries.py | 1,220 | 4.53125 | 5 | # Dictionary
student_records = {
"Name": "Sam" # Name is key, sam is value
, "Stream": "DevOps"
, "Topics_covered": 5
, "Completed_lessons": ["Tuples", "Lists", "Variables"]
} # Can have a list in a tuple
student_records["Name"] = "Jeff"
print(student_records["Completed_lessons"][2]) # fetching index of list in dictionary
print(student_records["Name"]) # Fetching the value of name
print(sorted(student_records)) # Sorts according to keys
print(student_records.keys()) # Gets keys of dictionary
print(student_records.values()) # Gets values of dictionaries
print(student_records["Name"]) # Gets value from key in dictionary
print(student_records.get("Name")) # Different method of same thing
# Adding two items to completed lessons then displaying it
student_records["Completed_lessons"].append("Lists")
student_records["Completed_lessons"].append("Built in methods")
print(student_records["Completed_lessons"]) # Checking work
# Removing items
student_records.pop("Topics covered") # Removes item associated with key
student_records.popitem() # Removes last item added to list
del student_records["Name"] # Removes item with specific key name
# Can also clear copy and nest dictionaries.
| true |
1467bd581d54b3244d0ed003f2e5a47d0d6e77a7 | Lycurgus1/python | /day_1/String slicing.py | 567 | 4.21875 | 4 | # String slicing
greeting_welcome = "Cheese world" # H is the 0th character. Indexing starts at 0.
print(greeting_welcome[3]) # Gets 4th character from string
print(greeting_welcome[-1]) # Gets last character from string
print(greeting_welcome[-5:]) # Gets 1st character to last
x = greeting_welcome[-5:]
print(x)
# Strip - remove spaces
remove_white_space = "remove spaces at end of string "
print(len(remove_white_space))
print(remove_white_space.strip()) # Removes spaces at end of string
print(len(remove_white_space.strip())) # Length can bee seen to go down
| true |
2ecaa40da83339322abdb4f2377cbe44fad0b3b6 | Lycurgus1/python | /OOP/Object Orientated Python.py | 1,496 | 4.25 | 4 | # Object orientated python
# Inheritance, polymorhpism, encapsulation, abstraction
class Dog:
amimal_kind = "Canine" # Class variable
# Init intalizes class
# Give/find name and color for dog
def __init__(self, name, color):
self.name = name
self.color = color
def bark(self):
return "woof, woof"
# create a methods inside for sleep, breath, run, eat
# Encapsulation. This creates a private method. Abstraction is a expansion on this
def __sleep(self):
return "zzzzz"
# Pas enables this function without error
def breath(self):
pass
# Inheritance. This refers to creating sub classes, but run is using is a
# previously define attribute
def run(self):
return "Come back, {}".format(self.name)
# Polymorphism. Here the sub class method overrides the methods in the
# parent class when appropriate. It first searches it its own class, then
# in its inherited class
def eat(self):
print("{} is eating fast".format(self.__class__.__name__))
class Retriever(Dog):
def eat(self):
print("Retriever is eating slowly")
class Labrador(Dog):
pass
# Creating object of our class
jim = Dog("Canine", "White")
peter = Dog("peter", "Brown")
print(jim.name)
# Testing encapsulation
print(peter.__sleep())
# Testing inheritance
print(peter.run())
# Testing polymorphism
jack = Labrador("Bill", "Black")
jill = Retriever("Ben", "Brown")
jack.eat()
jill.eat()
| true |
d9df4158b15accfba5c36e113f383140409ab02a | Lycurgus1/python | /More_exercises/More_Methods.py | 2,013 | 4.21875 | 4 | # From the Calculator file importing everything
from Calculator import *
# Inheriting the python calculator from the previous page
class More_Methods(Python_Calculator):
# As per first command self not needed
def remainder_test():
# Input commands get the numbers to be used, and they are converted to integers with int
print("This tests whether there will be a remainder to a divison, returning true and false")
num1 = int(input("Please enter your first number\n"))
num2 = int(input("Please enter your second number\n"))
outcome = num1 % num2
# Using the outcome we test if it is 0(False in boolean) or not zero(True in boolean).
# This determines what the user is told with a further message elaborating.
if bool(outcome) == True:
print("True")
return ("This returns a remainder of {}".format(outcome))
elif bool(outcome) == False:
print("False")
return ("This divison has no remainder")
# As per first command self not needed
def triangle_area():
# Input commands get the numbers to be used, and they are converted to integers with int
height = int(input("Enter triangle height in cm\n"))
width = int(input("Enter triangle width in cm\n"))
# This calculates the area of a triangle and returns it in a user friendly string
area = (width * height) / 2
return ("The triangle's area is {} cm".format(area))
# As per first command self not needed
def inches_to_cm():
# Input commands get the numbers to be used, and they are converted to integers with int
inches = int(input("Enter amount of inches to convert here, please \n"))
# This calculates the conversion and returns it in a user friendly string
cm = math.ceil(inches * 2.54)
return("That converts to {} Centimetres".format(cm))
# To test functions
print(More_Methods.remainder_test())
print(More_Methods.inches_to_cm())
| true |
d445e006605290b0c4511c1272f6ff07ed306ca0 | renatojobal/fp-utpl-18-evaluaciones | /eval-parcial-primer-bimestre/Ejercicio8.py | 1,333 | 4.15625 | 4 | '''
Ejercicio 8.- Ingresar por teclado tres variables, dichas variables siempre tendrán como valores letras
mayúsculas de abecedario.
Sabiendo que por ejemplo la letra “E” es menor que la letra “P”; establezca una solución que
permita determinar ¿Cuál de las tres letras ingresadas, aparece primero en el abecedario ?
Ejemplo: Si el usuario ingresa:
v1 = “Z”
v2 = “B”
v3 = “C”
La primera letra que aparece en el abecedario es B
* @author Renato
'''
# INGRESO DE DATOS
nombre1 = str(input("Ingrese una letra: "))
nombre1 = nombre1.upper() # Se lo convierte en mayusculas
v1 = nombre1[0] # Se obtiene la primera letra
nombre2 = str(input("Ingrese una letra: "))
nombre2 = nombre2.upper() # Se lo convierte en mayusculas
v2 = nombre2[0] # Se obtiene la primera letra
nombre3 = str(input("Ingrese una letra: "))
nombre3 = nombre3.upper() # Se lo convierte en mayusculas
v3 = nombre3[0] # Se obtiene la primera letra
# CALCULO y SALIDA
if(v1 < v2 and v1 < v3):
print("La primera letra que aparece en el abecedario es {}".format(v1))
else:
if(v2 < v1 and v2 < v3):
print("La primera letra que aparece en el abecedario es {}".format(v2))
else:
print("La primera letra que aparece en el abecedario es {}".format(v3))
| false |
e03113509c9c78385a00ba2253044ab698d974a6 | xtiancc/Andalucia-Python | /listaintstr.py | 561 | 4.15625 | 4 | def mostrarNombres(nombres):
print("\nListado:")
for name in nombres:
print(name)
print("LISTA NUMEROS Y NOMBRES")
print("-----------------------")
numeros = [20, 14, 55, 99, 77]
print(numeros[0])
numeros.sort()
print("Los numeros ahora están ordenados")
for num in numeros:
print(num)
nombres = ["Ana", "Adrián", "Lucía", "Carlos", "Pedro", "Heidi", "Ana"]
mostrarNombres(nombres)
nombres.append("El nuevo")
nombres.insert(3, "El del medio")
# nombres.remove("Ana") # Elimina el primero
nombres.pop(7)
mostrarNombres(nombres)
| false |
80a11ffa961d83208461d324062f37d9f7b1d830 | yesusmigag/Python-Projects | /Functions/two_numberInput_store.py | 444 | 4.46875 | 4 | #This program multiplies two numbers and stores them into a variable named product.
#Complete the missing code to display the expected output.
# multiply two integers and display the result in a function
def main():
val_1 = int(input('Enter an integer: '))
val_2 = int(input('Enter another integer: '))
multiply(val_1, val_2)
def multiply(num_1, num_2):
product = num_1*num_2
print ('The result is', product)
main() | true |
a5643896a36f24aab394372e73d18e052deb624c | yesusmigag/Python-Projects | /List and Tuples/10 find_list_example.py | 710 | 4.34375 | 4 | """This program aks the user to enter a grocery item and checks it against a grocery code list. Fill in the missing if statement to display the expected output.
Expected Output
Enter an item: ice cream
The item ice cream was not found in the list."""
def main():
# Create a list of grocery items.
grocery_list = ['apples', 'peanut butter', 'eggs', 'spinach', 'coffee', 'avocado']
# Search for a grocery item.
search = input('Enter an item: ')
# Determine whether the item is in the list.
if search in grocery_list:
print('The item', search, 'was found in the list.')
else:
print('The item', search, 'was not found in the list.')
# Call the main function.
main() | true |
8c4a55fa444dc233b0f11291147c224b0ed1bdb5 | yesusmigag/Python-Projects | /List and Tuples/18 Min_and_Max_functions.py | 500 | 4.40625 | 4 | """Python has two built-in functions named min and max that work with sequences.
The min function accepts a sequence, such as a list, as an argument and returns
the item that has the lowest value in the sequence."""
# MIN Item
my_list = [5, 4, 3, 2, 50, 40, 30]
print('The lowest value is', min(my_list))
#display The lowest value is 2
print('--------------------------')
#MAX Item
my_list = [5, 4, 3, 2, 50, 40, 30]
print('The highest value is', max(my_list))
#display The highest value is 50 | true |
73037324693d0170667f036a2e61fcd1e586895f | yesusmigag/Python-Projects | /File and Files/Chapter6_Project3.py | 639 | 4.125 | 4 | '''Write a program that reads the records from the golf.txt file written in the
previous exercise and prints them in the following format:
Name: Emily
Score: 30
Name: Mike
Score: 20
Name: Jonathan
Score: 23'''
#Solution 1
file = open("golf.txt", "r")
name = True
for line in file:
if name:
print("Name:" + line, end="")
else:
print("Score:" + line)
name = not name
file.close()
#SOLUTION 2
golf_file = open('golf.txt','r')
line=golf_file.readlines()
#score=''
for i in range(0,len(line),2):
print('Name:'+line[i].strip('\n'))
print('Score:'+line[i+1].strip('\n'))
print()
golf_file.close() | true |
f735a64f0aa2132efd6a12b57cc812bc87a29444 | JaimeFanjul/Algorithms-for-data-problems | /Sorting_Algorithms/ascii_encrypter.py | 1,301 | 4.40625 | 4 | # ASCII Text Encrypter.
#--------
# Given a text with several words, encrypt the message in the following way:
# The first letter of each word must be replaced by its ASCII code.
# The second letter and the last letter of each word must be interchanged.
#--------
# Author: Jaime Fanjul García
# Date: 16/10/2020
def text_encrypter(text):
"""Return a string encrypted.
Parameters
----------
text: str
String of characters. It can contain any type of characters
This script generate a new string encripted which:
The first letter of each word must be replaced by its ASCII code.
The second letter and the last letter of each word must be interchanged..
"""
if not isinstance(text, str):
raise TypeError(f" {text} is not a string type")
words = text.split(" ")
for i , word in enumerate(words):
ch = list(word)
if len(ch) == 1:
ch[0] = str(ord(word[0]))
else:
ch[0] = str(ord(word[0]))
ch[1] = word[-1]
ch[-1]= word[1]
words[i] = ''.join(ch)
text = ' '.join(words)
return text
if __name__ == "__main__":
encrypted_text = text_encrypter("To be or not to be that is the question")
print(encrypted_text)
| true |
bc0c2d7871b4263c62e43cd04d7370fc4657468e | gitsana/Python_Tutorial | /M5-Collections/words.py | 1,607 | 4.5 | 4 | #!/usr/bin/env python3
#shebang
# indent with 4 spaces
# save with UTF-8 encoding
""" Retrieve and print words from a URL.
Usage: python3 words.py <URL>
"""
from urllib.request import urlopen
def fetch_words():
"""Fetch a list of words from a URL.
Args:
url: The URL of a UTF-8 text document
Returns:
A list of strings containing the words from the document
"""
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
for line in story:
line_words = line.decode('UTF-8').split()
for word in line_words:
story_words.append(word)
def print_words(story_words):
""" print items one per line
Args: an iterable series of printable items
Returns: Nothing
"""
paragraph = ""
for word in story_words:
paragraph = paragraph + word + " "
print("--------------PRINT WORDS FUNCTION--------------",paragraph)
def main():
words = fetch_words()
print_words(words)
print(__name__)
if __name__ == '__main__':
main()
# to execute from REPL:
# >> python3 words.py
# import "words.py" to REPL:
# >> python3
# >> import words
# >> words.fetch_words()
# import function "fetch_words()" from "words.py" to REPL and execute:
# >> python3
# >> from words import fetch_words
# >> fetch_words()
# >> from words import(fetch_words,print_words)
####### docstrings
# >>> from words import *
# words
# >>> help(fetch_words)
####### docstrings for whole program
# $ python3
# >>> import words
# words
# >>> help(words)
# python module: convenient import with API
# python script: convenient execution from cmd line
# python program: composed of many modules
| true |
a90012c851cad115f6f75549b331cfa959de532b | JasleenUT/Python | /ShapeAndReshape.py | 587 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 22:47:26 2019
@author: jasleenarora
"""
#You are given a space separated list of nine integers.
#Your task is to convert this list into a 3X3 NumPy array.
#Input Format
#A single line of input containing space separated integers.
#Output Format
#Print the 3X3 NumPy array.
#Sample Input
#1 2 3 4 5 6 7 8 9
#Sample Output
#[[1 2 3]
# [4 5 6]
# [7 8 9]]
import numpy
arr = input()
arr = arr.split()
for i in range(0,len(arr)):
arr[i] = int(arr[i])
arr1 = numpy.array(arr)
arr1.shape = (3,3)
print(arr1)
| true |
5c8061c586c1ca3f86bb662601a812e3cf46fdec | ashish-bisht/ds_algo_handbook | /top_k_elements/frequency_sort.py | 613 | 4.375 | 4 | import collections
import heapq
def sort_character_by_frequency(str):
str_dict = collections.Counter(str)
heap = []
for key, val in str_dict.items():
heapq.heappush(heap, (-val, key))
final_string = ''
while heap:
val, char = heapq.heappop(heap)
final_string = final_string + -(val) * char
return final_string
def main():
print("String after sorting characters by frequency: " +
sort_character_by_frequency("Programming"))
print("String after sorting characters by frequency: " +
sort_character_by_frequency("abcbab"))
main()
| false |
8d5312a4489988236f75acb7025db9c86dd4d58a | Krishesh/AngelAssignment | /q1.py | 864 | 4.1875 | 4 | class Person:
firstlen = 0
middlelen = 0
lastlen = 0
def __init__(self, first_name, middle_name, last_name):
self.first_name = first_name
self.middle_name = middle_name
self.last_name = last_name
def first_name_length(self):
for _ in self.first_name:
Person.firstlen += 1
print("First Name Length :" + str(Person.firstlen))
def middle_name_length(self):
for _ in self.middle_name:
Person.middlelen += 1
print("Middle Name Length :" + str(Person.middlelen))
def last_name_length(self):
for _ in self.last_name:
Person.lastlen += 1
print("Last Name Length :" + str(Person.lastlen))
full_name = Person('Krishesh', 'Padma', 'Shrestha')
full_name.first_name_length()
full_name.middle_name_length()
full_name.last_name_length()
| false |
a685dfed0946a9c01454d98f65abab97d25f6ce2 | StarPony3/403IT-CW2 | /Rabbits and recurrence.py | 645 | 4.3125 | 4 | # program to calculate total number of rabbit pairs present after n months,
# if each generation, every pair of reproduction-age rabbits produces k rabbit pairs, instead of only one.
# variation of fibonacci sequence
# n = number of months
# k = number of rabbit pairs
# recursive function for calculating growth in rabbit population
def rabbits(n, k):
if n <= 1:
return n
else:
return rabbits(n - 1, k) + k * rabbits(n - 2, k)
# prints the total number of rabbit pairs each month.
for x in range(1, 8):
print (f"Total number of rabbit pairs after {x} months: ", (rabbits(x, 3)))
| true |
9e10db07bd159f36235ff5b58654eba48d66a6f3 | manisha-jaiswal/iterator-and-generator-in-python | /OOPS18_iterator_genrator.py | 763 | 4.28125 | 4 | """
Iterable - __iter__() or __getitem__()
Iterator - __next__()
Iteration -
"""
def gen(n):
for i in range(n):
# return i - it returns the value true or false
yield i #yeh i ko yield krega ,
# yeild ek generator h jo on the fly value ko geneerate krega
g = gen(3)
print(g)
#this is iterator
#print(g.__next__())
#print(g.__next__())
#print(g.__next__())
#print(g.__next__()) -it gives error bcoz iterator gives maximum 0 to 2 value
for i in g: #here it no gives error ,we access any number
print(i)
h = "manu"#here if we use anu integer,it gives error bcoz int object is not iterator
ier = iter(h)
print(ier.__next__())
print(ier.__next__())
print(ier.__next__())
# for c in h:
# print(c) | false |
21fbc706321e771b06be18dd923943321d229bf0 | yinjiwenhou/python-notes | /generator/test.py | 1,062 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。
在Python中,这种一边循环一边计算的机制,称为生成器:generator。
第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator
定义generator的另一种方法。如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator:
"""
g = (x*x for x in range(1, 11))
print type(g)
for n in g:
print n
'''
最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。
而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。
'''
def odd():
print('step 1')
yield 1
print('step 2')
yield(3)
print('step 3')
yield(5)
o = odd()
next(o)
next(o)
next(o) | false |
c781d941c5b21e8476a0a3a22c58fca13c835d3f | supremepoison/python | /Day16/Code/test_yield.py | 931 | 4.21875 | 4 | # 写一个生成器函数 myeven(start, stop) 用来生成从 start 开始到stop 结束区间内的一些列偶数(不包含stop)
# 如:
# def myeven(start, stop):
# ...
# evens = list(myeven(10,20))
# print(evens) [10,12,14,16,18]
# for x in myeven(5,10):
# print(x) #6 8
# L = [x for x in myeven(0,10)]
# print(L)
def myeven(start, stop):
# while start<stop:
# if start % 2 == 0:
# yield start
# start +=2
# else:
# start += 1
# yield start
# start +=2
for x in range(start, stop):
if x % 2 == 0:
yield x
evens = list(myeven(10,20))
print(evens)
for x in myeven(5,10):
print(x)
L = [x for x in myeven(0,10)]
print(L)
| false |
d9f32b00f9bcaec443b3fc22b1f239333bfb26a3 | peterpfand/aufschrieb | /higher lower.py | 413 | 4.65625 | 5 | string_name.lower() #to lower a string
.higher() #to higher a string
#example:
email = input("What is your email address?")
print(email)
final_email = email.lower()
print(final_email)
string_name.isLower() #to check if a string id written in lowercase letters
.ishigher() #to check if a string id written in highercase letters
#returns true or false
| true |
ad26db5b5d0e3e5b8c73c190b88db85b16c8fa3c | sawaseemgit/AppsUsingDictionaries | /PollingApp.py | 1,596 | 4.21875 | 4 | print('Welcome to Yes/No polling App')
poll = {
'passwd': 'acc',
}
yes = 0
no = 0
issue = input('What is the Yes/No issue you will be voting on today: ').strip()
no_voters = int(input('What is number of voters you want to allow: '))
repeat = True
while repeat:
for i in range(no_voters):
fname = input('What is your full name: ').title().strip()
if fname in poll.keys():
print('Sorry, you seem to have already voted.')
else:
print(f"Hii {fname}, Today's issue is: {issue}")
choice = input('What is your vote (yes/no): ').lower().strip()
if choice.startswith('y'):
yes += 1
elif choice.startswith('n'):
no += 1
else:
print('Thats an invalid answer.')
poll[fname] = choice
print(f'Thank you {fname}. Your vote {poll[fname]} has been recorded.')
if i == (no_voters - 1):
repeat = False
total = len(poll.keys())
print(f'The following {total} people voted: ')
for key in poll.keys():
print(key)
print(f'On the following issue: {issue}')
if yes > no:
print(f'Yes wins. {yes} votes to {no}.')
elif yes < no:
print(f'No wins. {no} votes to {yes}.')
else:
print(f'It was a tie. {yes} votes to {no}.')
passwd = str(input('To see all of the voting results, enter admin password: '))\
.strip()
if passwd == poll['passwd']:
for k, v in poll.items():
print(f'Voter:{k} Vote:{v}')
else:
print('Incorrect password. Good bye.. ')
print("Thank you for using the Yes/no App.")
| true |
99a2a83c7059b61e14c054e650e4bb1c221047cd | iroro1/PRACTICAL-PYTHON | /PRACTICAL-PYTHON/09 Guessing Game One.py | 699 | 4.25 | 4 | # Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right.
import random
numGuess= 0
a = random.randint(1,9)
end= 1
while (end != 0) or (end != 0):
guess = input('Guess a number : ')
guess = int(guess)
numGuess +=1
if guess < a:
print('You guessed too low')
elif guess > a:
print('You guessed too high')
else:
print('You got it Genuis!!!')
ended = input('"Enter exit" to quit : ')
if (str(ended) == 'exit') or (str(ended) == 'Exit') or (str(ended) == 'EXIT'):
end= 0
print(f"You took {numGuess} guesse(s).") | true |
f033cc8e82f2692f55b1531159229168fdb638b9 | iroro1/PRACTICAL-PYTHON | /PRACTICAL-PYTHON/12 List Ends.py | 293 | 4.125 | 4 | # Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list.
def rand():
import random
return random.sample(range(5, 25), 5)
a= rand()
print(a)
newList = [a[0],a[-1]]
print(newList) | true |
63f22070edd727c7652ae1c6c930a3443d95710b | lynn-study/python | /seq_op.py | 1,249 | 4.125 | 4 | #!/usr/bin/python
x = [1, 2, 3]
print x
print
x[1] = 4
print x
print
del x[1]
print x
print
name = list('perl')
print name
name[2:] = list('ar')
print name
name_1 = list('perl')
print name_1
name_1[1:] = list('ython')
print name_1
print
numbers = [1, 5]
print numbers
numbers[1:1] = [2, 3, 4]
print numbers
numbers[1:4] = []
#del numbers[1:4]
print numbers
print
price = [1, 2, 3, 4, 4, 3, 2, 1]
print price
price.append(5)
print price
print
i = price.count(1)
print i
print
a = [1, 2, 3]
b = [3, 2, 1]
a.extend(b)
print 'a.extend(b) = ' + repr(a)
# a = a + b slow
# a[len(a):] = b hard to see
print
name = ['john', 'lily', 'lucy', 'kate']
num = name.index('lucy')
print num
print
print name
name.insert(2,'lilei')
print name
name.pop()
print name
name.pop(0)
print name
x = [1, 2, 3]
print x
x.append(x.pop())
print x
print
x = ["bl", "be", "bl"]
print x
x.remove('bl')
print x
print
x = [1, 2, 3]
print x
x.reverse()
print x
print list(reversed(x))
print
x = [1, 99, 34, 56, 97]
y = x[:]
print x
x.sort()
y.sort()
print x
print y
y = sorted(x)
print y
y.reverse()
print y
x = ["aardvard", "abalone", "acme", "aerate"]
print x
x.sort(key=len)
print x
x = [1, 99, 34, 56, 97]
print x
x.sort(reverse=True)
print x
| false |
6ad663e24007cbf743411b9389d75205cc201152 | mattdelblanc/Mypythonscripts | /iflelse.py | 278 | 4.21875 | 4 | number = 15
if number % 2 == 0:
print ('Number is divisible by 2')
elif number % 3 == 0:
print('Number is divisible by 3')
elif number % 4 == 0:
print('Number is divisible by 4')
elif number % 5 == 0:
print('Number is divisible by 5')
| false |
1972fc4c6f7e307acfa496ab9cde6a56410a10c7 | mattdelblanc/Mypythonscripts | /nestedloops.py | 359 | 4.4375 | 4 | number = 45
if number % 2 == 0:
print('Number is even number')
if number % 3 == 0:
print('number is also divisible by 3')
else:
print('number is not divisible by 3')
else:
print('Number is odd number')
if number % 5 == 0:
print('number is divisible by 5')
else:
print('number is not divisible by 5')
| false |
a25fba2603e9632a90dc18a1a01f772bce2cace2 | Yuhta28/TestPJ | /Sets_in_Python.py | 653 | 4.25 | 4 | # Set example
x = set(["Posted", "Radio", "Telegram", "Radio"]) # A set may not contain the same element multiple times.
print(x)
# Set Method
# Clear elements
y = set(["Posted", "Rao", "Teram", "Rdio"])
y.clear()
print(y)
# Add elements
z = set(["Posted", "Rao", "Teram", "Rdio"])
z.add("AAQWER")
print(z)
# Remove elements
p = set(["Posted", "Rao", "Teram", "Rdio"])
p.remove("Posted")
print(p)
# Difference between two sets
q = set(["Aka", "Midori", "Shiro", "Kuro"])
r = set(["Ao", "Momo", "Murasaki", "Kuro"])
print(q.difference(r))
print(r.difference(q))
print("")
# Subset
m = set(["a","b","c","d"])
n = set(["c","d"])
print(m.intersection(n)) | false |
a186fe5f3f8b658705509fbf443dc7fcb7605db5 | Ghoochannej/Python-Projects | /calculadora/calc.py | 550 | 4.125 | 4 | from funcoes import soma, subtracao, divisao, multiplicacao
if __name__ == '__main__':
valor01 = float(input('Digite o primeiro valor '))
valor02 = float(input('Digite o segundo valor '))
operacao = input('Digite a operação ')
if operacao == '+':
resultado = soma(valor01, valor02)
elif operacao == '-':
resultado = subtracao(valor01,valor02)
elif operacao == '/':
resultado = divisao(valor01, valor02)
elif operacao == '*':
resultado = multiplicacao(valor01, valor02)
else:
resultado = 'Erro na operação'
print(resultado)
| false |
cfa6497baa42d0662b46188a4460d47c28e878aa | LemonTre/python_work | /Chap09/eat_numbers.py | 1,166 | 4.15625 | 4 | class Restaurant():
def __init__(self,restaurant_name,cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print("The name of restaurant is: " + self.restaurant_name.title() + ".")
print("The type of restaurant is " + self.cuisine_type + ".")
def open_restaurant(self):
print("The restaurant is working.")
def set_number_served(self, numbers):
"""修改吃饭的人数"""
self.number_served = numbers
def increment_number_served(self, increments):
"""增加的人数值"""
self.number_served += increments
restaurant = Restaurant('KFC', 'fast food')
print("The numbers in this restaurant are: "
+ str(restaurant.number_served) + " guys.")
restaurant.number_served = 12
print("The numbers in this restaurant are: "
+ str(restaurant.number_served) + " guys.")
restaurant.set_number_served(15)
print("The numbers in this restaurant are: "
+ str(restaurant.number_served) + " guys.")
restaurant.increment_number_served(100)
print("The numbers that you think the restaurant can hold: "
+ str(restaurant.number_served) + " guys.")
| true |
a787c4e2a01b88818289586d13c7332a12d8868f | omkar1117/pythonpractice | /file_write.py | 993 | 4.3125 | 4 | fname = input("Enter your First name:")
lname = input("Enter your Last name:")
email = input("Enter your Email:")
if not fname and not lname and not email:
print("Please enter all the details:")
elif fname and lname and not email:
print("Please enter a valid email")
elif email and fname and not lname:
print("First Name and Last name both are mandatory")
elif email and lname and not fname:
print("First Name and Last name both are mandatory")
if email and not '@' in email:
print("Not a valid Email, Please have a valid email")
elif fname.strip() and lname.strip() and email.strip():
fw = open("details.txt", "a")
fw.write("-------------------------------------------\n")
fw.write("First Name is :: %s \n"%fname.capitalize())
fw.write("Last Name is :: %s \n"%lname.capitalize())
fw.write("Email is :: %s \n"%email.lower())
fw.write("-------------------------------------------\n")
fw.close()
print("End of Script completed")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.