blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
9b2f359901f6a835563e878a9f103dec0b110a86
|
nguiaSoren/Snake-game
|
/scoreboard.py
| 1,123
| 4.3125
| 4
|
from turtle import Turtle
FONT = ("Arial", 24, "normal")
#
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
# Set initials score to 0
self.score = 0
# Set colot to white
self.color("white")
# Hide the turtle, we wonly want to see the text
self.hideturtle()
# Do not draaw when the turtle will move
self.penup()
# Move the turtle to the top
self.goto(0,370)
# Write initial score
self.write(arg = f"Score: {self.score}", align="center", font=FONT)
def update_score(self):
"Update current score"
# Clear the screen (erase the writings and drawings)
self.clear()
# Update the score attribute
self.score += 1
# Write the new text with the new score
self.write(arg = f"Score: {self.score}", align="center", font=FONT)
def game_over(self):
"Show game over message"
# Show game over message at the center of the screen
self.goto(0,0)
self.write(arg = "Game Over", align="center", font=FONT)
| true
|
ddfe13cbff04a326ed196b20beb8f1414364b086
|
luzperdomo92/test_python
|
/hello.py
| 209
| 4.25
| 4
|
name = input("enter your name: ")
if len(name) < 3:
print("name must be al least 3 characters")
elif len(name) > 20:
print("name can be a maximun 50 characteres")
else:
print("name looks good!")
| true
|
450b68eb2689957ce61da69333d6a0588820339d
|
GTVanitha/PracticePython
|
/bday_dict.py
| 1,003
| 4.34375
| 4
|
birthdays = {
'Vanitha' : '05/05/90',
'Som' : '02/04/84',
'Vino' : '08/08/91'
}
def b_days():
print "Welcome to birthday dictionary! We know the birthdays of:"
names = birthdays.keys()
print ',\n'.join(names)
whose = raw_input("Who's birthday do you want to look up?")
if (whose in names):
print whose , "'s birthday is ", birthdays[whose]
print "Thank you for using birthday dictionary. Happy day :)"
else:
print "Sorry. We do not have ", whose, " birthday date."
add = raw_input(" Do you want to add it ? (y/n)" )
if add == 'y':
name = raw_input("Enter name:")
bday = raw_input("Enter birth date:")
birthdays[name] = bday
print "Added ", name, "'s birthday to dictionary. Try accessing it!"
b_days()
else:
print "Thank you for using birthday dictionary. Happy day :)"
b_days()
| true
|
4c71d1fa592e3c54844946aa62e8eb4f7c69f95f
|
Aravindan-C/LearningPython
|
/LearnSet.py
| 535
| 4.3125
| 4
|
__author__ = 'aravindan'
"""A set is used to contain an unordered collection of objects,To create a set use the set() function and supply a sequence of items such as follows"""
s= set([3,5,9,10,10,11]) # create a set of unique numbers
t=set("Hello") # create a set of unique characters
u=set("abcde")
"""sets are unordered and cannot be indexed by numbers"""
print t ^ u
print s & u
t.add('x') # To add an item to a set
s.update([9,10,11],[9,14,16]) # To add a multiple item to set
print s
t.remove('H','l')
t.remove('e')
| true
|
06623bd65d8ba4d62713be768697929943c83e61
|
Aravindan-C/LearningPython
|
/LearnIterationAndLooping.py
| 640
| 4.15625
| 4
|
__author__ = 'aravindan'
for n in [1,2,3,4,5,6,7,8,9,0]:
print "2 to the %d power is %d" % (n,2**n)
for n in range(1,10) :
print "2 to the %d power is %d" % (n,2**n)
a= range(5)
b=range(1,8)
c=range(0,14,3)
d=range(8,1,-1)
print a,b,c,d
a= "Hello World"
# print out the individual characters in a
for c in a :
print c
b=["Dave","Mark","Ann","Phill"]
#Print out the members of a list
for name in b:
print name
c={'GOOG' :490.10,'IBM' :91.50,'AAPL' :123.15}
#Print out all of the members of a dictionary
for key in c:
print key,c[key]
#Print all of the lines in a file
f=open("foo.txt")
for line in f:
print line
| false
|
908ff1d7ed7b294b3bef209c6ca6ffbf43851ba8
|
loc-dev/CursoEmVideo-Python-Exercicios
|
/Exercicio_008/desafio_008.py
| 598
| 4.15625
| 4
|
# Desafio 008 - Referente aula Fase07
# Escreva um programa que leia um valor em metros
# e o exiba em outras unidades de medidas de comprimento.
# Versão 01
valor_m = float(input('Digite um valor em metros: '))
print(' ')
print('A medida de {}m corresponde a: '.format(valor_m))
print('{}km (Quilômetro)'.format(valor_m / 1000))
print('{}hm (Hectômetro)'.format(valor_m / 100))
print('{:.2f}dam (Decâmetro)'.format(valor_m / 10))
print('{:.0f}dm (Decímetro)'.format(valor_m * 10))
print('{:.0f}cm (Centímetro)'.format(valor_m * 100))
print('{:.0f}mm (Milímetro)'.format(valor_m * 1000))
| false
|
37e9ec85ea551c5a0f77ba61a24f955da77d0426
|
loc-dev/CursoEmVideo-Python-Exercicios
|
/Exercicio_022/desafio_022.py
| 662
| 4.375
| 4
|
# Desafio 022 - Referente aula Fase09
# Crie um programa que leia o nome completo de uma pessoa
# e mostre:
# - O nome com todas as letras maiúsculas e minúsculas.
# - Quantas letras no total (sem considerar espaços).
# - Quantas letras tem o primeiro nome.
nome = input("Digite o seu nome completo: ")
print('')
print("Analisando o seu nome...")
print("Seu nome em letras maiúsculas é: {}".format(nome.upper()))
print("Seu nome em letras minúsculas é: {}".format(nome.lower()))
print("Seu nome tem ao todo {} letras".format(len(nome.replace(" ", ""))))
print("Seu primeiro nome é {} e ele tem {} letras".format(nome.split()[0], len(nome.split()[0])))
| false
|
c21762ec2545a3836c039837ec782c8828044fca
|
jkusita/Python3-Practice-Projects
|
/count_vowels.py
| 1,833
| 4.25
| 4
|
# Count Vowels – Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found.
vowel_list = ["a", "e", "i", "o", "u"]
vowel_count = 0 # Change this so it adds all the values of the keys in the new dictionary.
vowel_count_found = {"a": 0, "e": 0, "i": 0, "o": 0, "u": 0} # TODO: maybe you can change the keys from strings to variable (if possible)?
# vowel_count_a = 0
# vowel_count_e = 0
# vowel_count_i = 0
# vowel_count_o = 0
# vowel_count_u = 0
# Counts the number of vowels in the inputted string.
user_input = str.lower(input("Please enter a string: "))
for i in range(len(user_input)):
if user_input[i] in vowel_list:
# Counts the sum of each vowels found in the inputted string.
if user_input[i] == "a":
vowel_count_found[user_input[i]] += 1 # Is there a way to add to a non-string key value in dict?
vowel_count += 1
elif user_input[i] == "e":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
elif user_input[i] == "i":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
elif user_input[i] == "o":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
elif user_input[i] == "u":
vowel_count_found[user_input[i]] += 1
vowel_count += 1
# Prints out how much vowels are in the string based on certain conditions.
if vowel_count == 0:
print("There are no vowels.")
elif vowel_count == 1:
print("There is only one vowel.")
else:
print(f"There are {vowel_count} vowels.")
# Prints out the sum of each vowels found in the inputted string.
for i, j in vowel_count_found.items():
print(i + ":" + str(j))
# For design/spacing.
print("")
| true
|
2487fdd78e971f078f6844a2fa5bb0cd031b0d71
|
Dunkaburk/gruprog_1
|
/grundlaggande_programvareutveckling/week2/src/samples/MathMethods.py
| 751
| 4.25
| 4
|
# package samples
# math is the python API for numerical calculations
from math import *
def math_program():
f_val = 2.1
print(f"Square root {sqrt(f_val)}")
print(f"Square {pow(f_val, 2)}")
print(f"Floor {floor(f_val)}")
print(f"Ceil {ceil(f_val)}")
print(f"Round {round(f_val)}")
# etc. many more ... type math. (dot) and they will show up ...
print(pi) # Declared in Math library
# Comparing floats
f1 = 1.0 - 0.7 - 0.3 # ~= 0.0
f2 = 1.0 - 0.6 - 0.4 # ~= 0.0
print(f1 == f2) # False!! Rounding error!
print(abs(f1 - f2)) # How large is the rounding error?
# Pythagoras ... (nested calls)
print(sqrt(pow(3, 2) + pow(4, 2)) == 5)
if __name__ == "__main__":
math_program()
| true
|
1b54c0d17ea896a12aa2a20779416e0bac85d066
|
Dunkaburk/gruprog_1
|
/grundlaggande_programvareutveckling/week3_tantan/src/exercises/Ex4MedianKthSmallest.py
| 901
| 4.15625
| 4
|
# package exercises
#
# Even more list methods, possibly even trickier
#
def median_kth_smallest_program():
list1 = [9, 3, 0, 1, 3, -2]
# print(not is_sorted(list1)) # Is sorted in increasing order? No not yet!
# sort(list1) # Sort in increasing order, original order lost!
print(list1 == [-2, 0, 1, 3, 3, 9])
# print(is_sorted(list1)) # Is sorted in increasing order? Yes!
list2 = [5, 4, 2, 1, 7, 0, -1, -4, 12]
list3 = [2, 3, 0, 1]
# print(median(list2) == 2) # Calculate median of elements
# print(median(list3) == 1.5)
list4 = [2, 3, 0, 1, 5, 4]
list5 = [5, 4, 2, 2, 1, 7, 4, 0, -1, -4, 0, 0, 12]
# print(k_smallest(list4, 2) == 1) # Second smallest is 1
# print(k_smallest(list5, 5) == 2) # 5th smallest is 2
# ---------- Write methods here --------------
if __name__ == "__main__":
median_kth_smallest_program()
| true
|
16acd854ef3b668e05578fd5efff2b5c2a6f88f4
|
Dunkaburk/gruprog_1
|
/grundlaggande_programvareutveckling/Week1Exercises/Week1Exercises/week1/src/exercises/Ex2EasterSunday.py
| 1,705
| 4.3125
| 4
|
# package exercises
# Program to calculate easter Sunday for some year (1900-2099)
# https://en.wikipedia.org/wiki/Computus (we use a variation of
# Gauss algorithm, scroll down article, don't need to understand in detail)
#
# To check your result: http://www.wheniseastersunday.com/
#
# See:
# - LogicalAndRelationalOps
# - IfStatement
def when_is_easter_sunday_program():
# int a, b, c, d, e, s, t // Avoid variables on same line (but acceptable here)
# int date;
# int year;
# int month = 0;
# ---- Input --------------
year = int(input("Input a year (1900-2099) > "))
# ----- Process -----------
a = year % 19 # Don't need to understand, Gauss did understand
b = year % 4
c = year % 7
s = 19 * a + 24
d = s % 30
t = 2 * b + 4 * c + 6 * d + 5
e = t % 7
date = 22 + d + e
# TODO Now you continue ...
# If date is less than 32, then date is found and month is march.
# Else: Date is set to d + e - 9 and month is april ...
# ... but with two exceptions
# If date is 26 easter is on 19 of april.
# If date is 25 and a = 16 and d = 28 then date is 18 of april.
if date < 32 and date!=26 and date!=25:
month = "march"
elif date == 26:
month = "april"
date = 26
elif date == 25 and a == 16 and d == 28:
month = "april"
date = 18
else:
month = "april"
date = d + e - 9
# --------- Output -----------
print("Easter Sunday for " + str(year) + " is : " + str(date) + "/" + str(month))
# Recommended way to make module executable
if __name__ == "__main__":
when_is_easter_sunday_program()
| true
|
fd550e115ac526fe5ac6bc9543278a7d852325b6
|
anthonysim/Python
|
/Intro_to_Programming_Python/pres.py
| 444
| 4.5
| 4
|
"""
US Presidents
Takes the names, sorts the order by first name, then by last name.
From there, the last name is placed in front of the first name, then printed
"""
def main():
names = [("Lyndon, Johnson"), ("John, Kennedy"), ("Andrew, Johnson")]
names.sort(key=lambda name: name.split()[0])
names.sort(key=lambda name: name.split()[1])
for name in names:
space = name.find(" ")
print(name[space + 1:] + ", " + name[ : space-1])
main()
| true
|
c1dceb57ede0b3eb1f1fe5fe658fe283116d68f3
|
pythonic-shk/Euler-Problems
|
/euler1.py
| 229
| 4.34375
| 4
|
n = input("Enter n: ")
multiples = []
for i in range(int(n)):
if i%3 == 0 or i%5 == 0:
multiples.append(i)
print("Multiples of 3 or 5 or both are ",multiples)
print("Sum of Multiples of ",n," Numbers is ",sum(multiples))
| true
|
7468f255b87e3b4aa495e372b44aba87ff2928d1
|
tengrommel/go_live
|
/machine_learning_go/01_gathering_and_organizating_data/gopher_style/python_ex/myprogram.py
| 449
| 4.3125
| 4
|
import pandas as pd
'''
It is true that, very quickly, we can write some Python code to parse this CSV
and output the maximum value from the integer column without even
knowing what types are in the data:
'''
# Define column names
cols = [
'integercolumn',
'stringcolumn'
]
# Read in the CSV with pandas.
data = pd.read_csv('myfile.csv', names=cols)
# Print out the maximum value in the integer column.
print(data['integercolumn'].max())
| true
|
e863fd0cfe96478d6550b426d675de6cfc84c08a
|
kami71539/Python-programs-4
|
/Program 19 Printing even and odd number in the given range.py
| 515
| 4.28125
| 4
|
#To print even numbers from low to high number.
low=int(input("Enter the lower limit: "))
high=int(input("ENter the higher limit: "))
for i in range(low,high):
if(i%2==0):
print(i,end=" ")
print("")
for i in range(low,high):
if(i%2!=0):
print(i,end=" ")
#Printing odd numbers from higher number to lower number
low=int(input("Enter the lower limit: "))
high=int(input("ENter the higher limit: "))
for i in range(high,low,-1):
if(i%2!=0):
print(i,end=" ")
| true
|
61bef90211ffd18868427d3059e8ab8dee3fefde
|
kami71539/Python-programs-4
|
/Program 25 Printing text after specific lines.py
| 303
| 4.15625
| 4
|
#Printing text after specific lines.
text=str(input("Enter Text: "))
text_number=int(input("Enter number of text you'd like to print; "))
line_number=1
for i in range(0,text_number):
print(text)
for j in range(0,line_number):
print("1")
line_number=line_number+1
print(text)
| true
|
38658702ed937a7ba65fd1d478a371e4c6d5e789
|
kami71539/Python-programs-4
|
/Program 42 Finding LCM and HCF using recursion.py
| 259
| 4.25
| 4
|
#To find the HCF and LCM of a number using recursion.
def HCF(x,y):
if x%y==0:
return y
else:
return HCF(y,x%y)
x=int(input(""))
y=int(input(""))
hcf=HCF(x,y)
lcm=(x*y)/hcf
print("The HCF is",hcf,". The LCM is",lcm)
| true
|
6f2ac1ae18a208e032f7f1db77f64710f3b9bd00
|
kami71539/Python-programs-4
|
/Program 15 Exponents.py
| 221
| 4.375
| 4
|
print(2**3)
def exponents(base,power):
i=1
for index in range(power):
i=i*base
return i
a=int(input(""))
b=int(input(""))
print(a, "raised to the power of" ,b,"would give us", exponents(a,b))
| true
|
e80d7d475ddcf65eddd08d77aa4c2c03f965dfb9
|
kami71539/Python-programs-4
|
/Program 35 To count the uppercase and lowercase characters in the given string. unresolved.py
| 458
| 4.125
| 4
|
#To count the uppercase and lowercase characters in the given string.
string=input("")
j='a'
lower=0
upper=0
space=0
for i in string:
for j in range(65,92):
if chr(j) in i:
upper=upper+1
elif j==" ":
space=space+1
for j in range(97,123):
if chr(j) in i:
lower=lower+1
#print(chr(j))
print("There are",lower-space,"lower characters and",upper,"upper characters.")
| true
|
870b35565e3ae8e46a0e2a12179675a20825f5c4
|
targupt/projects
|
/project -1 calculator.py
| 325
| 4.3125
| 4
|
num1 = int(input("1st number "))
num2 = int(input("2nd number "))
sign = input("which sign(+,-,/,x or *)")
if sign == "+":
print(num1+num2)
elif sign == "-":
print(num1-num2)
elif sign == "/":
print(num1/num2)
elif sign == "x" or sign == "X":
print(num1*num2)
else:
print("wrong input please try again")
| false
|
01c172d4c6c6b4d9714c2aca9b9d4b425a3933d3
|
lexjox777/Python-conditional
|
/main.py
| 838
| 4.21875
| 4
|
# x=5
# y=6
# if x<y:
# print('Yes')
#==========
# if 'Hello' in 'Hello World!':
# print('Yes')
#==================
# x=7
# y=6
# if x > y:
# print('yes it is greater')
# elif x < y:
# print('no it is less')
# else:
# print('Neither')
#==================
# '''
# Nested if statement
# '''
# num = -3
# if num >= 0:
# if num==0:
# print('Zero')
# else:
# print('Positive number')
# else:
# print('Negative number')
# ===================
# '''
# one-Line 'if' statements
# '''
# if 7>5: print('yes it is')
#==========================
'''
Ternary operator
'''
# print('Yes') if 4>5 else print('No')
#or the above can be written in this form below too
if 4>5:
print('Yes')
else:
print('No')
# num=5
# if num >=0:
# print('Zero')
# else:
# print('Negative')
| false
|
84650242ab531d3a0755452b8c6eb4476e0a710c
|
dncnwtts/project-euler
|
/1.py
| 582
| 4.21875
| 4
|
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
# multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def multiples(n,k):
multiples = []
i = 1
while i < n:
if k*i < n:
multiples.append(k*i)
i += 1
else:
return multiples
m3 = multiples(10,3)
m5 = multiples(10,5)
mults = m3 + m5
answer = sum(set(mults))
assert answer == 23, "Test case failed, I got {0}".format(answer)
m3 = multiples(1000,3)
m5 = multiples(1000,5)
mults = m3 + m5
answer = sum(set(mults))
print(answer)
| true
|
e047b285aa5bf1b187187c52a22fae191836ed0f
|
chubaezeks/Learn-Python-the-Hard-Way
|
/ex19.py
| 1,804
| 4.3125
| 4
|
#Here we defined the function by two (not sure what to call them)
def cheese_and_crackers (cheese_count, boxes_of_crackers):
print "You have %d cheese!" % cheese_count
print "You have %d boxes of crackers!" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
#We take that function and give it a number directly, so no need to define what's in the function
#Just give the function numbers
print "We can just give the funtion numbers directly:"
cheese_and_crackers (20,30)
#We can also create variables that contain numbers
print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
#Then run the function by those variables
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
#Or we can run calculations within the function too
print "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 +6)
#Remember those variables we created earlier? We can also include them in the function
#as well as numbers to run calculations
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
def me_and_you (chuba,mo):
print "You love %d" % chuba
print "I love %d" % mo
print "We both love each other.\n"
print "We can represent ourselves as numbers!:"
me_and_you (100,100)
print "We can add variables and use it within the function:"
half_of_me = 0.5
half_of_you = 0.5
print " Let's work the math of both of us:"
me_and_you (25+25, 25+25)
print " We combine numbers and variables to get more of us:"
me_and_you (half_of_me + 0.5, half_of_you + 0.5)
me= 10 +10
you=10+10
print "What other combination can we run?:"
me_and_you(half_of_me,half_of_you)
print "What happens when we make a family?:"
me_and_you(me + 1, you + 1)
| true
|
965cd05ce217b1b5d27cefb89b62935dc250a692
|
hmkthor/play
|
/play_006.py
| 590
| 4.40625
| 4
|
"""
Change a Range of Item Values
To change the value of items within a specific range, define a list with the new values,
and refer to the range of index numbers where you want to insert the new values:
"""
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist[1] = ["blackcurrant", "watermelon"]
print(len(thislist))
print(thislist)
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(len(thislist))
print(thislist)
| true
|
359ce1c69a952d51fd9024adade90be51e6ebb00
|
LiuPengPython/algorithms
|
/algorithms/strings/is_rotated.py
| 324
| 4.3125
| 4
|
"""
Given two strings s1 and s2, determine if s2 is a rotated version of s1.
For example,
is_rotated("hello", "llohe") returns True
is_rotated("hello", "helol") returns False
accepts two strings
returns bool
"""
def is_rotated(s1, s2):
if len(s1) == len(s2):
return s2 in s1 + s1
else:
return False
| true
|
b1a9fee52ca6eae1ee380a0d95491d735c7360bd
|
jeantardelli/wargameRepo
|
/wargame/designpatterns/strategies_traditional.py
| 1,633
| 4.15625
| 4
|
"""strategies_traditional
Example to show one way of implementing different design pattern strategies
in Python.
The example shown here resembles a 'traditional' implementation in Python
(traditional = the one you may implement in languages like
C++). For a more Pythonic approach, see the file strategies_pythonic.py.
This module is compatible with Python 3.6.x.
RUNNING THE PROGRAM:
Assuming you have python in your environment variable PATH, type the following
in the command prompt to run the program:
$ python name_of_the_file.py
(Replace name_of_the_file.py with the name of this file)
:copyright: 2020, Jean Tardelli
:license: The MIT license (MIT). See LICENSE file for further details.
"""
from strategypattern_traditional_jumpstrategies import CanNotJump, PowerJump
from traditional_dwarffighter import DwarfFighter
from traditional_unitfactory import UnitFactory
from traditional_unitfactory_kingdom import Kingdom
if __name__ == '__main__':
# Strategy Example
print("Strategy Pattern")
print("="*17)
jump_strategy = CanNotJump()
dwarf = DwarfFighter("Dwarf", jump_strategy)
print("\n{STRATEGY-I} Dwarf trying to jump:")
dwarf.jump()
print("-"*56)
# Optionally change the jump strategy later
print("\n{STRATEGY-II} Dwarf given a 'magic potion' to jump:")
dwarf.set_jump_strategy(PowerJump())
dwarf.jump()
print("-"*56)
# Factory example
print("\nFactory Example")
print("="*17)
factory = UnitFactory()
k = Kingdom(factory)
elf_unit = k.recruit("ElfRider")
print("Created an instance of: {0}".format(elf_unit.__class__.__name__))
| true
|
93b2af4c8f1a23483747d04ea3902c644b581543
|
jeantardelli/wargameRepo
|
/wargame/performance-study/pool_example.py
| 1,201
| 4.375
| 4
|
"""pool_example
Shows a trivial example on how to use various methods of the class Pool.
"""
import multiprocessing
def get_result(num):
"""Trivial function used in multiprocessing example"""
process_name = multiprocessing.current_process().name
print("Current process: {0} - Input number: {1}".format(process_name, num))
return 10 * num
if __name__ == '__main__':
numbers = [2, 4, 6, 8, 10]
# Create two worker processes.
pool = multiprocessing.Pool(3)
# Use Pool.apply method to run the task using pools of processes
#mylsit = [pool.apply(get_result, args=(num,) for num in numbers]
# Use Pool.map method to run the task using the pool of processes
#mylist = pool.map(func=get_result, iterable=numbers)
# Use Pool.apply_async method to run the task
results = [pool.apply_async(get_result, args=(num,))
for num in numbers]
# The elements of results list are instances of Pool.ApplyResult
# Use the object's get() method to get the final values.
mylist = [p.get() for p in results]
# Stop the worker processes
pool.close()
# Join the processes
pool.join()
print("Output: {0}".format(mylist))
| true
|
d37a677d52bcb30328947235f0198a9447ddeb34
|
jeantardelli/wargameRepo
|
/wargame/GUI/simple_application_2.py
| 1,025
| 4.125
| 4
|
"""simple_application_2
A 'Hello World' GUI application OOP using Tkinter module.
"""
import sys
if sys.version_info < (3, 0):
from Tkinter import Tk, Label, Button, LEFT, RIGHT
else:
from tkinter import Tk, Label, Button, LEFT, RIGHT
class MyGame:
def __init__(self, mainwin):
"""Simple Tkinter GUI example that shows a label and an exit button.
:param mainwin: The Tk instance (also called 'root' sometimes)
"""
lbl = Label(mainwin, text="Hello World!", bg='yellow')
exit_button = Button(mainwin, text='Exit',
command=self.exit_btn_callback)
# pack the widgets
lbl.pack(side=LEFT)
exit_button.pack(side=RIGHT)
def exit_btn_callback(self):
"""Callback function to handle the button click event."""
mainwin.destroy()
if __name__ == '__main__':
# Create the main window or Tk instance
mainwin = Tk()
mainwin.geometry("140x40")
game_app = MyGame(mainwin)
mainwin.mainloop()
| true
|
c72fb1953ee65169041fa399508fbd5204986270
|
yeti98/LearnPy
|
/src/basic/TypeOfVar.py
| 978
| 4.125
| 4
|
#IMMUTABLE: int,
## Immutable vs immutable var
#Case3:
# default parameter for append_list() is empty list lst []. but it is a mutable variable. Let's see what happen with the following codes:
def append_list(item, lst=[]):
lst.append(item)
return lst
print(append_list("item 1")) # ['item 1']
print(append_list("item 2")) # ['item 1', 'item 2']
# Shouldn't use mutable var as a parameter
def append_list(item, lst= None):
if lst is None:
lst = []
lst.append(item)
return lst
#Case2: don't use += for string, because string is immutable. Instead, use join() method
msg= ""
for i in range(1000):
msg+= "hello"
# each for loop, new msg varible created and that make RAM quickly full
#Case1: //list is mutable
def double_list(lists):
for i in range(len(lists)):
lists[i] = lists[i]*2
return lists
lists = [x for x in range(1, 12)]
doubled = double_list(lists)
for i in range(len(lists)):
print(doubled[i] / lists[i])
| true
|
0243e8d54259a3cecd9e84443bae674a66f090f7
|
amandamurray2021/Programming-Semester-One
|
/labs/week06-functions/menu2.py
| 801
| 4.34375
| 4
|
# Q3
# This program uses the function from student.py.
# It keeps displaying the menu until the user picks Q.
# If the user chooses a, then call a function called doAdd ().
# If the user chooses v, then call a function called doView ().
def displayMenu ():
print ("What would you like to do?")
print ("\t (a) Add new student")
print ("\t (v) View students")
print ("\t (q) Quit")
choice = input ("Type one letter (a/v/q):").strip ()
return choice
def doAdd ():
print ("in adding")
def doView ():
print ("in viewing")
# main program
choice = displayMenu ()
while (choice != 'q'):
if choice == 'a':
doAdd ()
elif choice == 'v':
doView ()
elif choice != 'q':
print ("\n\n please select either a, v or q")
choice = displayMenu ()
| true
|
581152e31c7db41497c55661eee0ad92026487cf
|
berkcangumusisik/CourseBuddiesPython101
|
/Pratik Problemler/09 - Math Seviye 2/02 - basicCalculator.py
| 477
| 4.3125
| 4
|
"""İki sayı ve bir operatör (+, -, *, /) alan ve hesaplamanın sonucunu döndüren bir fonksiyon yazın."""
def calculate(num1, operator, num2):
if operator == "+":
return num1 + num2
elif operator == "-":
return num1 - num2
elif operator == "*":
return num1 * num2
elif operator == "/":
return num1 / num2
print(calculate(5,"+",7))
print(calculate(5,"-",7))
print(calculate(5,"*",7))
print(calculate(5,"/",7))
| false
|
1f4677231483102e14e550023ca914280acf3a5c
|
berkcangumusisik/CourseBuddiesPython101
|
/Pratik Problemler/06 - Lists Seviye 1/05 - insertLast.py
| 387
| 4.125
| 4
|
""" Alıştırma 4.1.5: Son Ekle
Listenin son elemanı olarak insert_last eklenen adında bir fonksiyon yazın x.
Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir
değil bu liste boş olmadığını varsayalım."""
def insert_last(my_list, x):
if len(my_list) >= 0:
my_list.append(x)
return my_list
print(insert_last([3,4,6], 5))
| false
|
d39156f96eeac77c4a9e1606b3566ae0afbb4f84
|
berkcangumusisik/CourseBuddiesPython101
|
/1. Hafta/05 - Lab Saati Uygulamaları/ornek1.py
| 1,012
| 4.40625
| 4
|
"""Python Hafta 1 - 1:
CourseBuddies üniversitesi öğrencilerinin mezun olup olamayacağını göstermek için
bir sistem oluşturmaya çalışıyor.
Öncelikle durumunu öğrenmek isteyen öğrencinin, ismini yaşını ve not ortalamasını
(0 - 100 arası) girmesi gerekiyor (input() fonksiyonu ile kullanıcıdan alıcak).
eğer kullanıcının yaşı 17 ve 21 arasındaysa ve not ortalaması 80 ve üzeri
ise okulunu tamamlayabilecek.
eğer bu koşulları sağlamıyor ise okulunu tamamlayamayacaktır ve
duruma göre ekrana bir çıktı gösterecektir (print() fonksiyonu ile)
CourseBuddies Üniversitesinin böyle bir sisteme ihtiyacı var,
Hadi sen de yardım et"""
try:
isim = input("İsminizi giriniz:")
yas = int(input("Yaşınızı giriniz:"))
ortalama = int(input("Not Ortalaması giriniz:"))
if(yas>16 and yas <22 and ortalama>79 and ortalama<101):
print("Sınıfı Geçti")
else:
print("Sınıfı Geçemedi")
except:
print("Lütfen bir sayı giriniz.")
| false
|
0c8874c6ed0902384e7ba0790e5e1b28741868ba
|
berkcangumusisik/CourseBuddiesPython101
|
/Pratik Problemler/13 - Lists Seviye 3/07 - sumTheLenghts.py
| 413
| 4.21875
| 4
|
"""
Uzunlukları Topla
Bir sum_the_lengths listedeki tüm dizelerin uzunluğunu toplayan adlı bir işlev yazın .
Not: Sen, işlev her zaman bir liste adı verilecek varsayabiliriz ancak, olabilir
değil bu liste boş olmadığını varsayalım.
"""
def sum_length(my_list):
length = 0
for string in my_list:
length += len(string)
return length
print(sum_length(["python", "is", "fun"]))
| false
|
dd32bd386f65c98a15f23d9a62b563eb8e48b96e
|
joscelino/Calculadora_estequiometrica
|
/Formula_Clapeyron/clapeyron_dinamica.py
| 1,121
| 4.125
| 4
|
variable = int(input("""Choose a variable:
[1] Pressure
[2] Volume
[3] Number of moles
[4] Temperature
"""))
R = 0.082
if variable == 1:
# Inputs
V = float(input('Volume (L): '))
T = float(input('Temperature (K): '))
n = float(input('Number of moles: '))
# Formula
P = (n * R * T) / V
# Printing
print(f'The pressure is: {P} atm')
elif variable == 2:
# Inputs
P = float(input('Pressure (atm): '))
T = float(input('Temperature (K): '))
n = float(input('Number of moles: '))
# Formula
V = (n * R * T) / P
# Printing
print(f'The volume is: {V} L')
elif variable == 3:
# Inputs
P = float(input('Pressure (atm): '))
T = float(input('Temperature (K): '))
V = float(input('Volume (L): '))
# Formula
n = (P * V) / (R * T)
# Printing
print(f'The number of moles are: {n} .')
elif variable == 4:
# Inputs
P = float(input('Pressure (atm): '))
V = float(input('Volume (L): '))
n = float(input('Number of moles: '))
# Formula
T = (P * V) / (n * R)
# Printing
print(f'Temperature is: {T} K.')
| false
|
2df05235e11b4f969f147ffa6dcde19ceb0c0dec
|
VB-Cloudboy/PythonCodes
|
/10-Tuples/02_Access-Tuple.py
| 403
| 4.125
| 4
|
mytuple = (100,200,300,400,500,600,700,800,900)
#1. Print specific postion of the tuples starting from Right
print(mytuple[2])
print(mytuple[4])
print(mytuple[5])
#2. Print specific postion of the tuples starting from Left
print(mytuple[-3])
print(mytuple[-5])
print(mytuple[-4])
#3. Slicing (Start: Stop: Stepsize)
print(mytuple[:])
print(mytuple[1:3])
print(mytuple[::-3])
print(mytuple[-1::-5])
| true
|
b286bc4bd3179f174b808381c6f408bd80e2bcfe
|
ml758392/python_tedu
|
/python2/Day3_modlue_oop/pycharm/9.重写__repr__与__str__.py
| 807
| 4.15625
| 4
|
# -*-coding:utf-8-*-
"""
重写:可将函数重写定义一遍
__str__()
__repr__()
"""
class Person(object):
"""
:param
:parameter
"""
def __init__(self, name, age):
self.name = name
self.age = age
def myself(self):
print("I'm %s , %s years old " % (self.name, self.age))
# __str__()在调用print打印对象时自动调用,是给用户用的,是一个描述对象的方法
def __str__(self):
return 'person'
# __repr__():给机器用的,再python解释起里面直接敲对象名在回车后调用的方法
def __repr__(self):
return 'ppp'
person1 = Person('yy', 18)
print(person1.__dict__)
print(person1.__class__)
print(person1.__doc__)
print(person1.__dir__())
print(person1.__repr__())
print(person1)
| false
|
7e40c4b9259486ee55d80691c66f8a8cc0efb36c
|
ml758392/python_tedu
|
/nsd2018-master/nsd1804/python/day01/hello.py
| 706
| 4.1875
| 4
|
# 如果希望将数据输出在屏幕上,常用的方法是print
print('Hello World!')
print('Hello' + 'World!')
print('Hello', 'World!') # 默认各项之间用空格分隔
print('Hello', 'World!', 'abc', sep='***') # 指定分隔符是***
print('Hello World!', end='####')
# print默认在打印结束后加上一个回车,可以使用end=重置结束符
n = input('number: ') # 屏幕提示number: 用户输入的内容赋值给n
print(n) # input得到的数据全都是字符类型
# a = n + 10 # 错误,不能把字符和数字进行运算
a = int(n) + 10 # int可以将字符串数值转成相应的整数
print(a)
b = n + str(10) # str可以将其他数据转换成字符
print(b)
| false
|
8c326cefac9c979874f8a03334934c685a88c953
|
forthing/leetcode-share
|
/python/152 Maximum Product Subarray.py
| 813
| 4.21875
| 4
|
'''
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
'''
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
positive, negative = nums[0], nums[0]
result = nums[0]
for num in nums[1:]:
positive, negative = max(num, positive * num, negative * num), min(num,
positive * num, negative * num)
result = max(result, positive)
return result
if __name__ == "__main__":
assert Solution().maxProduct([2, 3, -2, 4]) == 6
| true
|
88ddaec1c09a46fac173c4b520c6253b59aad09b
|
kmair/Graduate-Research
|
/PYOMO_exercises_w_soln/exercises/Python/fcn_soln.py
| 1,248
| 4.40625
| 4
|
## Write a function that takes in a list of numbers and *prints* the value of the largest number. Be sure to test your function.
def print_max_value(nums):
print("The max value is: ")
print(max(nums))
## Write a function that takes a list of numbers and *returns* the largest number
def max_value(nums):
return max(nums)
## Do so without using any built-in functions
def my_max_value(nums):
tmp = nums[0]
for i in range(1, len(nums)):
if nums[i] > tmp:
tmp = nums[i]
return tmp
## Call both functions on a couple different lists of numbers to verify they return the same value
l1 = [1, 3, 0, 5, -2]
ans1 = max_value(l1)
print(ans1)
ans2 = my_max_value(l1)
print(ans2)
l2 = [12, 0, 11.9]
print(max_value(l2))
print(my_max_value(l2))
## Write a function that takes a list of numbers and returns a dict consisting of the smallest and largest number
## (use keys 'smallest' and 'largest'). Be sure to test your function.
def max_and_min(nums):
return {'smallest': min(nums), 'largest': max(nums)}
## Write a function that takes in two lists and prints any common elements between them
## hint: check if an item is in a list using:
## if item in list
def get_common(l1, l2):
for i in l1:
if i in l2:
print(i)
| true
|
82d3e7c695fbab62b222781240a1865cfe877151
|
Kaushalendra-the-real-1/Python-assignment
|
/Q2.py
| 779
| 4.125
| 4
|
# class Person:
# def __init__(self):
# print("Hello Reader ... ")
# class Male(Person):
# def get_gender(self):
# print("I am from Male Class")
# class Female(Person):
# def get_gender(self):
# print("I am from Female Class")
# Obj = Female()
# Obj.get_gender()
# ----------------------------------------------------------------------------------------------------------------------
# Bonus Section
from abc import ABC, abstractmethod
class Person(ABC):
@abstractmethod
def get_gender(self):
return 0
class Male(Person):
def get_gender(self):
print("I am from Male Class")
class Female(Person):
def get_gender(self):
print("I am from Female Class")
unknown = Person() #expecteed to throw an error.
| true
|
e33a070506458cacbf4d52304982c491f2c9980d
|
xynicole/Python-Course-Work
|
/lab/435/ZeroDivideValue.py
| 595
| 4.25
| 4
|
def main():
print("This program will divide two numbers of your choosing for as long as you like\n")
divisorStr = input("Input a divisor: ")
while divisorStr:
dividendStr = input("Input a dividend: ")
try:
divisor = int(divisorStr)
dividend = int(dividendStr)
print (dividend / divisor)
except ZeroDivisionError:
print("You cannot divide by zero\n")
except ValueError:
print("You must input a number\n")
except Exception:
print("Something happened\n")
divisorStr = input("Input a divisor: ")
main()
| true
|
881fc46faa626aaac3317dd9f65d3e8975b3f32e
|
xynicole/Python-Course-Work
|
/W12/kiloToMiles.py
| 1,148
| 4.25
| 4
|
'''
Stores value in kilometers
Retrieves value in kilometers or miles
Displays value in kilometers and miles
'''
class KiloToMiles:
# Constructor
def __init__(self, kilo = 0.0):
self.__kilo = float(kilo)
self.__KILO_TO_MILES = 0.6214 # Conversion constant
# ---------------------------------------------------------------------------
# Accessors
# return kilometers (float)
def get_kilo(self):
return self.__kilo
# return kilo converted to miles (float)
def to_miles(self):
return self.__kilo * self.__KILO_TO_MILES
# ---------------------------------------------------------------------------
# Mutators
# param kilo (float)
def set_kilo(self, kilo):
self.__kilo = kilo
# param kilo (float)
def reset_kilo(self):
self.__kilo = 0.0
# ---------------------------------------------------------------------------
# 'toString'
def __str__(self):
return "\n%.2f kilometers = %.2f miles" % (self.get_kilo(), self.to_miles())
'''
def main():
k = KiloToMiles(10)
k2 = KiloToMiles()
k2.set_Kilo(20)
print(k, k2)
main()
'''
| false
|
240868c7fb1cf39a3db78c9c5912d7dc93c79e45
|
SamuelMontanez/Shopping_List
|
/shopping_list.py
| 2,127
| 4.1875
| 4
|
import os
shopping_list = []
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def show_help():
clear_screen()
print("What should we pick up at the store?")
print("""
Enter 'DONE' to stop adding items.
Enter 'HELP' for this help.
Enter 'SHOW' to see your current list.
Enter 'REMOVE' to delete an item from your list.
""")
def add_to_list(item):
show_list()
if len(shopping_list): #If there are items in the shopping list
position = input("Where should I add {}?\n"
"Press ENTER to add to the end of the list\n"
"> ".format(item))
else:
position = 0 #This means if this is the first item in the list then the position is 0.
try:
position = abs(int(position)) #abs stands for absolute, so if a user gives us -5 the abs of that is 5.
except ValueError:
position = None #If value error occurs, then 'none' means dont put the item in the list.
if position is not None:
shopping_list.insert(position-1, item) #The reason for the -1 is beacuse the user should input 1 for the first spot or 2 for the second spot so the -1 will put it in the correct spot.
else:
shopping_list.append(new_item)
show_list()
def show_list():
clear_screen()
print("Here's your list:")
index = 1
for item in shopping_list:
print("{}. {}".format(index, item))
index += 1
print("-"*10)
def remove_from_list():
show_list()
what_to_remove = input("What would you like to remove?\n> ")
try:
shopping_list.remove(what_to_remove)
except ValueError:
pass
show_list()
show_help()
while True:
new_item = input("> ")
if new_item.upper() == 'DONE' or new_item.upper() == 'QUIT':
break
elif new_item.upper() == 'HELP':
show_help()
continue
elif new_item.upper() == 'SHOW':
show_list()
continue
elif new_item.upper() == 'REMOVE':
remove_from_list()
else:
add_to_list(new_item)
show_list()
| true
|
ec8887453eaa5f263665f651338a470b4b8c5f7c
|
lura00/guess_the_number
|
/main.py
| 915
| 4.15625
| 4
|
from random import randint
from game1 import number_game
def show_menu():
print("\n===========================================")
print("| Welcome |")
print("| Do you want to play a game? |")
print("| 1. Enter the number game |")
print("| 2. Exit |")
print("===========================================")
while True:
random_value = randint(0,10)
show_menu()
try:
menu_choice = int(input("Make your choice, guess or exit: "))
if menu_choice == 1:
number_game(random_value)
elif menu_choice == 2:
print("Thanks for playing, welcome back! ")
break
else:
print("Thats a strange symbol, I can't seem to understand your input?")
except ValueError:
print("An error occurred, please try another input!")
| true
|
13006b2b8a77c97f0f190a3228aa53452bbefc6d
|
scardona7/nuevasTecnologias
|
/taller1/ejercicio11.py
| 665
| 4.1875
| 4
|
""" 11) Algoritmo que nos diga si una persona puede acceder a cursar un ciclo formativo de grado superior o no. Para acceder a un grado superior, si se tiene un titulo de bachiller, en caso de no tenerlo, se puede acceder si hemos superado una prueba de acceso. """
titulo_bach = input("¿Tiene un titulo Bachiller?: (si o no): ")
if titulo_bach == "si" or titulo_bach == "Si":
print("Puede acceder a un Grado Superior. Bienvenido!")
else:
prueba_acce=(input("¿Tiene la Prueba de Acceso?"))
if prueba_acce == "si" or titulo_bach == "Si":
print("Puede cursar el Grado Superior")
else:
print("No puede ingrsar al Grado Superior")
| false
|
18a73e6c8cd9289ce5ba0fd1006dc2ce400e375f
|
LehlohonoloMopeli/level_0_coding_challenge
|
/task_3.py
| 350
| 4.1875
| 4
|
def hello(name):
"""
Description: Accepts the name of an individual and prints "Hello ..." where
the ellipsis represents the name of the individual.
type(output) : str
"""
if type(name) == str:
result = print("Hello " + name + "!")
return result
else:
return "Invalid input!"
| true
|
9d07cb1bbb8e780c193dbb19c6c0ef4b83cb7914
|
unfo/exercism-python
|
/bob/bob.py
| 723
| 4.25
| 4
|
def hey(sentence):
"""
Bob is a lackadaisical teenager. In conversation, his responses are very limited.
Bob answers 'Sure.' if you ask him a question.
He answers 'Whoa, chill out!' if you yell at him.
He says 'Fine. Be that way!' if you address him without actually saying
anything.
He answers 'Whatever.' to anything else.
"""
sentence = sentence.strip()
response = "Whatever."
if len(sentence) == 0:
response = "Fine. Be that way!"
elif sentence.startswith("Let's"):
# This is just silly. If it ends with an ! then it is shouting...
response = "Whatever."
elif sentence[-1] == "!" or sentence.isupper():
response = "Whoa, chill out!"
elif sentence[-1] == "?":
response = "Sure."
return response
| true
|
be97e8da8f3733fbb6c0a2e8abb0b950a11181c4
|
fitzcn/oojhs-code
|
/loops/printingThroughLoops.py
| 313
| 4.125
| 4
|
"""
Below the first 12 numbers in the Fibonacci Sequence are declared in an array list (fibSeq).
Part 1, Use a loop to print each of the 12 numbers.
Part 2, use a loop to print each of the 12 numbers on the same line.
"""
fibSeq = ["1","1","2","3","5","8","13","21","34","55","89","144"]
#part 1
#part 2
| true
|
d190cf17e29502fd451ff812f68414fef94eeec9
|
aysin/Python-Projects
|
/ex32.py
| 538
| 4.65625
| 5
|
#creating list while doing loops
the_count = [1, 2, 3, 4, 5]
fruits = ['apple', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#this first kind of for loop goes through a list
for n in the_count:
print "This is count %d." % n
#same as above
for n in fruits:
print "A fruit type is: %s." % n
for n in change:
print "I got: %r." % n
#build an empty list
element = []
for n in range(0,6):
print "Adding %d to the list." % n
element.append(n)
for i in element:
print "elements was: %d" % i
| true
|
cde03d01900ffa7f01f5f80e4bfc869454ac8116
|
AshTiwari/Python-Guide
|
/OOPS/OOPS_Abstract_Class_and_Method.py
| 720
| 4.5625
| 5
|
#abstract classes
# ABC- Abstract Base Class and abstractmethod
from abc import ABC, abstractmethod
print('abstract method is the method user must implement in the child class.')
print('abstract method cannot be instantiated outside child class.')
print('\n\n')
class parent(ABC):
def __init__(self):
pass
@abstractmethod #it is a decorator.
def square():
pass
class child(parent):
def __init__(self,num):
self.num = num
def square(self): # if not implemented here, it will give TypeError:
return self.num**2
Child =child(5)
print(Child.square())
try:
Parent =parent()
except TypeError:
print('Cant instantiate abstract class.')
| true
|
94555b4909e244e1e8e9e23bb97ad48b81308118
|
jinliangXX/LeetCode
|
/380. Insert Delete GetRandom O(1)/solution.py
| 1,462
| 4.1875
| 4
|
import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.result = list()
self.index = dict()
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.index:
return False
else:
self.result.append(val)
self.index[val] = len(self.result) - 1
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val in self.index:
index = self.index[val]
last_val = self.result[len(self.result) - 1]
self.result[index] = last_val
self.index[last_val] = index
self.result.pop()
self.index.pop(val,0)
return True
else:
return False
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return self.result[random.randint(0, len(self.result) - 1)]
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
| true
|
076a40fc02b0791eedaae92747394f46170a9678
|
prathyusak/pythonBasics
|
/errors.py
| 2,720
| 4.21875
| 4
|
#Syntax Errors and Exceptions
#while True print('Hello world') => syntax error
#ZeroDivisionError =>10 * (1/0)
#NameError => 4 + spam*3
#TypeError => '2' + 2
#################
# Handling Exceptions
import sys
def this_fails():
x = 1/0
while True:
try:
x = int(input("Please enter a number: "))
this_fails()
break
except ValueError:
print("Oops! That was no valid number. Try again...")
except (RuntimeError, TypeError, NameError): #except clause can have multiple exceptions
pass
except ZeroDivisionError as err:
print('Handling run-time error:', err)
break
except: #empty exception name serves as wildcard
print("Unexpected error:", sys.exc_info()[0])
raise #raising exceptions
################
#Exception chaining : when exception raised from except or finally block
# try:
# open('database.sqlite')
# except IOError as ioerr :
# raise RuntimeError from ioerr
# #To disable exception chaining
# try:
# open('database.sqlite')
# except IOError as ioerr :
# raise RuntimeError from None
################
#try except else finally
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else: #additional code in try block
print("result is", result)
finally: # executes at all times , cleanup acions
print("executing finally clause")
################
#User defined exceptions
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
#####################
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except B:
print("B")
# raise InputError('erro','mess')
except D: #an except clause listing a derived class is not compatible with a base class
print("D")
except C:
print("C")
| true
|
57e443004e07c95bc99217d700e6b4f40f5c8a5f
|
yamaz420/PythonIntro-LOLcodeAndShit
|
/pythonLOL/vtp.py
| 2,378
| 4.125
| 4
|
from utils import Utils
class VocabularyTrainingProgram:
words = [
Word("hus", "house")
Word("bil", "car")
]
def show_menu(self):
choice = None
while choice !=5:
print(
'''
1. Add a new word
2. Shuffle the words in the list
3. Take the test
4. show all the words
5. Exit
'''
)
choice = Utils.get_int_input("Enter your menu choice: ")
if choice < 1 or choice > 5:
print("Error: not a valid menu choice")
elif choice != 5:
# print(self.menu_switcher(str(choice)))
# pass # invoke the corresponding method
self.menu_switcher(str(choice))()
else:
print("Closing the game...")
def menu_switcher(self, choice):
switch = {
"1": self.add_new_word,
"2": self.shuffle_words,
"3": self.take_the_test,
"4": self.show_all_words
}
return switch[choice]
def add_new_word(self):
swedish_word = Utils.get_string_input("Enter the swedish word: ")
english_word = Utils.get_string_input("Enter english word: ")
self.words.append(word(swedish_word, english_word))
print()
print("The new word has been added")
def show_all_words(self):
for word in self.words:
print(word.to_string())
def shuffle_words(self):
shuffle(self.words)
print("the words have been shuffeled")
def take_the_test(self):
points = 0
max_failures = 3
misses = 0
for word in self.words:
print()
answer = Utils.get_string_input(f"What is the translation for {word.get_english_word()}?")
if word.verify_answer(answer):
points += len(word.get_english_word())
print("CORRECT!")
else:
misses += 1
print(f"WronG! The Correct answer is {word.get_english_word()}.")
if misses = max_failures:
print()
print("GAME OVAH BIATCH, go practice nooooob")
print()
print(f"the test is ovah matey u focken focker fuuuuuuuuuuuuuuuuuuuck you got {points}")
| true
|
4f55c17a043ee6a78b76220c8c25240a21b8195c
|
yamaz420/PythonIntro-LOLcodeAndShit
|
/pythonLOL/IfAndLoops.py
| 1,881
| 4.15625
| 4
|
#-----------!!!INDENTATION!!!-----------
# age = int(input("What is your age?"))
# if age >= 20:
# print("You are grown up, you can go to Systemet!")
# else:
# print("you are to young for systemet...")
# if age >= 20:
# if age >= 30:
# print("Allright, you can go to systemet for me, i hate showing ID")
# else:
# print("you can fo to systemet, just don't forget your ID...")
# else:
# print("you are too young for systemet")
### "or" = "||" "and" = "&&"
# if (day == "friday" or day == "Saturday") and age >= 18:
# print("is is a foot day to hit the club")
# elif day == "monday" or day == "tuseday":
# print("noooo, i hate these days")
# numbers = [1,2,3,45]
# if 45 in numbers:
# print("exists")
# else:
# print("no existo")
# truthy and falsy values also exist in python.
my_list = []
if my_list: # my_list.size() > 0 - in Java"
print(my_list)
else:
print("the list is empty")
i = 0 ## while-LOOP
while i < 10:
print (i, end = " ")
i += 1
# for-each-LOOP
names = ["hej", "niklas", "Erik"]
for name in names:
print(name, end = " ")
print(i, end = "\U0001F606") #Smiley ahahah #tackPelle
for i in range(10):
print(i, end = " ")
for i in range (1,20,2):
print (i, end= " ")
numbers = [1,24,12,52,26]
for i in range(len(numbers)):
print(numbers[i], end = " ")
persons = [ #list=arraylist of persons
{
"name": "Erik",
"age": 28
},
{
"name": "Martin",
"age": 34
},
{
"name": "Louise",
"age": 30
}
]
for person in persons:
print(person)
'''
multi-line-Commment
lalala
hahahahhahahahahahaHAH.
'''
just_names = [person["name"] for person in persons]
print(just_names)
over_30 = [person for person in persons if person["age"] >= 30] ##sortera persons-lista över 30
print(over_30)
| true
|
a891ee5380c54a475737976341d776b9ef44e15c
|
ShubhamGarg01/Faulty-Calculator
|
/faultycalci.py
| 619
| 4.1875
| 4
|
print("enter 1st number")
num1= int(input())
print("enter 2nd number")
num2= int(input())
print("so what u weant" ,"+,*,/,-,%")
num3= input()
if num1 == 45 and num2==3 and num3== "*":
print("555")
elif num1 ==56 and num2==9 and num3=="+":
print("77")
elif num1== 56 and num2==6 and num3=="/":
print("4")
elif num3 == "*":
multiply =num1*num2
print(multiply)
elif num3=="+":
plus= num1+num2
print(plus)
elif num3 == "-":
subtrt = num2 - num1
print(subtrt)
elif num3== "/":
percent=num2%num1
print(percent)
else:
print("out of range")
| false
|
421a3a05798ec7bfdfd104994e220ffb9f2613f7
|
Tornike-Skhulukhia/IBSU_Masters_Files
|
/code_files/__PYTHON__/lecture_2/two.py
| 1,401
| 4.1875
| 4
|
def are_on_same_side(check_p_1, check_p_2, point_1, point_2):
'''
returns True, if check points are on the same side of a line
formed by connecting point_1 and point_2
arguments:
1. check_p_1 - tuple with x and y coordinates of check point 1
2. check_p_2 - tuple with x and y coordinates of check point 2
2. point_1 - tuple with x and y coordinates of point 1
3. point_2 - tuple with x and y coordinates of point 2
'''
(x_3, y_3), (x_4, y_4), (x_1, y_1), (x_2, y_2) = check_p_1, check_p_2, point_1, point_2
value_1 = (x_3 - x_1) * (y_2 - y_1) - (y_3 - y_1) * (x_2 - x_1)
value_2 = (x_4 - x_1) * (y_2 - y_1) - (y_4 - y_1) * (x_2 - x_1)
# will be True only when value_1 * value_2 > 0, False otherwise
result = (value_1 * value_2 > 0)
return result
# test | run only if file is executed directly
if __name__ == "__main__":
point_1 = (1, 2)
point_2 = (5, 6)
check_points = [
(3, 4),
(1, 1),
(2, 0),
(0, 2),
]
# check point to every other point
for index_1, check_p_1 in enumerate(check_points):
for check_p_2 in check_points[index_1 + 1:]:
check_result = are_on_same_side(check_p_1, check_p_2, point_1, point_2)
print(f'Points {check_p_1} and {check_p_2} are {"not " if not check_result else ""}on the same side of a line')
| true
|
4cd244592bd39514d627fd2eea224af3edd60a48
|
matheuszei/Python_DesafiosCursoemvideo
|
/0014_desafio.py
| 231
| 4.34375
| 4
|
#Escreva um programa que converta uma temperatura digitada em °C e converta para °F.
c = float(input('Informe a temperatura em C: '))
f = (c * 1.80) + 32
print('A temperatura de {}°C corresponde a {:.1}°F!'.format(c, f))
| false
|
0fdc190bda0f1af4caf7354f380ce94134c70c78
|
cizamihigo/guess_game_Python
|
/GuessTheGame.py
| 2,703
| 4.21875
| 4
|
print("Welcome To Guess: The Game")
print("You can guess which word is that one: ")
def check_guess(guess, answer):
global score
Still = True
attempt = 0
var = 2
global NuQuest
while Still and attempt < 3 :
if guess.lower() == answer.lower() :
print("\nCorrect Answer " + answer)
Still = False
score += 1
NuQuest += 1
else :
if attempt < 2 :
guess = input("Wrong answer. Try again. {0} chance(s) reamining . . .".format(var))
var = 2 - 1
attempt += 1
pass
if attempt == 3 :
print("The correct answer is " + answer)
NuQuest += 1
score = 0
NuQuest = 0
guess1 = input("Designe une oeuvre littéraire en vers: ")
check_guess(guess1,'Poème')
guess1 = ""
guess1 = input("Designe ce qui est produit par un ouvrier un artisan un travail quelconque: ")
check_guess(guess1,'Ouvrage')
guess1 = ""
guess1 = input("En anglais DOOM quelle est sa variance en français???: ")
check_guess(guess1,'destin')
guess1 = ""
guess1 = input("Désigne Un Habittant de Rome: ")
check_guess(guess1,'Romain')
guess1 = ""
guess1 = input("Ce qui forme Un angle droit est dit: ")
check_guess(guess1,'Perpendiculaire')
guess1 = ""
guess1 = input("Adjectif, désignant ce qui est rélatif aux femmes: ")
check_guess(guess1,'Féminin')
guess1 = ""
guess1 = input("Nom masculin désignant le corps céleste: ")
check_guess(guess1,'astre')
guess1 = ""
guess1 = input("Ma messe, la voici ! c'est la Bible, et je n'en veux pas d'autre ! de qui on tient cette citation ")
check_guess(guess1,"Jean Calvin")
guess1 = ""
guess1 = input("Le vin est fort, le roi est plus fort, les femmes le sont plus encore, mais la vérité est plus forte que tout. ! de qui tenons-nous cette citation ")
check_guess(guess1,"Martin Luther")
guess1 = ""
mpt = "plrboèem"
guess1 = input("Voici Un anagramme: " + str(mpt.upper()) +" Trouvez en un mot complet : ")
check_guess(guess1,"Problème")
guess1 = ""
mpt = "uonjcgnaiso"
guess1 = input("Voici Un anagramme: " + str(mpt.upper()) +" Trouvez en un mot complet : ")
check_guess(guess1,"conjugaison")
guess1 = ""
guess1 = input("Which is the fastest land animal?")
check_guess(guess1,"Cheetah")
##################################################
# OTHER QUESTIONS CAN BE ADDED LATERLY. #
##################################################
Prcentage = (score * 100 ) / NuQuest
print("Votre Pourcentage a ce test a ete de : {0}".format(Prcentage))
print("Your score is : " +str(score) + " Sur " + str(NuQuest))
######################################## THE END ######################################
| true
|
0ebfa784abeddd768186f99209602dd7ef870e56
|
feleHaile/my-isc-work
|
/python_work_RW/6-input-output.py
| 1,745
| 4.3125
| 4
|
print
print "Input/Output Exercise"
print
# part 1 - opening weather.csv file
with open ('weather.csv', 'r') as rain: # opens the file as 'read-only'
data = rain.read() # calls out the file under variable rain and reads it
print data # prints the data
# part 2 - reading the file line by line
with open ('weather.csv', 'r') as rainy:
line = rainy.readline() # uses .readline()
while line: # while there is still data to read
print line # print the line
line = rainy.readline() # need to re-iterate here so it goes beyond just line 1.
print "That's the end of the data"
# part 3 - using a loop and collecting just rainfall values
with open ('weather.csv', 'r') as rainfall:
header = rainfall.readline() # this reads and discards the first line of the data (we dont want to use the header line with the text in it
droplet = [] # creating an empty list to store rainfall data
for line in rainfall.readlines():
# readlines reads the whole file, readline just takes the first line
r = line.strip() .split(',')[-1] # takes last variable, see below
r = float(r) # make it a float (with decimals)
droplet.append(r) # append r to droplet list (store the data)
print droplet # prints the data for rainfall
with open ('myrain.txt', 'w') as writing: # creates a text file with the result
for r in droplet: # prints the rainfall results in the text file
writing.write(str(r) + '\n')
"""
Explantation for r = line.strip() .split(',')[-1]
one line as example: 2014-01-01,00:00,2.34,4.45\n
line.strip() removes the \n, so takes just one line without the paragraphing
.split(',') splits the list by the comma, and takes each as a seperate item
.split(',')[-1] means, seperate out and then take the last item
"""
print
| true
|
a40fd3e7668b013a356cfa8559e993e770cc7231
|
feleHaile/my-isc-work
|
/python_work_RW/13-numpy-calculations.py
| 2,314
| 4.3125
| 4
|
print
print "Calculations and Operations on Numpy Arrays Exercise"
print
import numpy as np # importing the numpy library, with shortcut of np
# part 1 - array calculations
a = np.array([range(4), range(10,14)]) # creating an array 2x4 with ranges
b = np.array([2, -1, 1, 0]) # creating an array from a list
# multiples the array by each other, 1st line of a * b, then the 2nd line of a * b
multiply = a * b
b1 = b * 1000 # creates a new array with every item in b * 1000
b2 = b * 1000.0 # creates new array similar to b1 but with floats rather than int
b2 == b1 # yes, this is True. b2 is a float but they are the same
print b1.dtype, b2.dtype # how to print the type of each
# part 2 - array comparisons
arr = np.array([range(10)]) # creates an array with items 0 to 9
print arr < 3 # prints true and false values in the array where item is <3
print np.less(arr, 3) # exactly the same as above, just different format of asking
# sets a condition to call true or false based on two parameters, <3 OR > 8
condition = np.logical_or(arr < 3, arr > 8)
print "condition: ", condition
# uses "where" function to create new array where value is arr*5 if "condition" is true, and arr*-5 where "condition" is false
new_arr = np.where(condition, arr * 5, arr * -5)
# part 3 - mathematical functions working on arrays
"""
Calculating magnitudes of wind, where a minimum acceptable value is 0.1, and all values below this are set to 0.1. Magnitude of wind is calculated by the square-root of the sum of the squares of u and v (which are east-west and north-south wind magnitudes)
"""
def calcMagnitude(u, v, minmag = 0.1): # these are the argument criteria
mag = ((u**2) + (v**2))**0.5 # the calculation
# sets a where function so that minmag is adopted where values are less than 0.1:
output = np.where(mag > minmag, mag, minmag)
return output
u = np.array([[4, 5, 6],[2, 3, 4]]) # the east-west winds
v = np.array([[2, 2, 2],[1, 1, 1]]) # the north-south winds
print calcMagnitude(u,v) # calls the argument with the u and v arrays
# testing on different wind values, these values use the minmag clause
u = np.array([[4, 5, 0.01],[2, 3, 4]]) # the east-west winds
v = np.array([[2, 2, 0.03],[1, 1, 1]]) # the north-south winds
print calcMagnitude(u,v) # calls the argument with the u and v arrays
print
| true
|
12f3789e81a69e4daa75f9497dd94f382f5f0153
|
zamunda68/python
|
/main.py
| 507
| 4.21875
| 4
|
# Python variable function example
# Basic example of the print() function with new line between the words
print("Hello \n Marin")
print("Bye!")
# Example of .islower method which returns true if letters in the variable value are lower
txt = "hello world" # the variable and its value
txt.islower() # using the .islower() boolean method to print true or false
print("\n") # print a new line
print(txt) # print the variable
# Example of .isupper method
txt2 = "UPPER"
y = txt2.isupper()
print("\n", y)
| true
|
1ef4a7869a5048f6d66fbdb56203fa2f0198fb22
|
zamunda68/python
|
/dictionaries.py
| 1,116
| 4.75
| 5
|
""" Dictionary is a special structure, which allows us to store information in what is called
key value pairs (KVP). You can create one KVP and when you want to access specific information
inside of the dictionary, you can just refer to it by its key """
# Similar to actual dictionary, the word is the key and the meaning is the value
# Word - meaning == Key - value
# Every dictionary has a name:
# directory_name = {key_value_pair1, key_value_part2,}
monthConversions = {
"Jan": "January", # "Jan" is the key, "January" is the value
"Feb": "February",
"Mar": "March",
"Apr": "April",
"May": "May",
"Jun": "June",
"Jul": "July",
"Aug": "August",
"Sep": "September",
"Oct": "October",
"Nov": "November",
"Dec": "December",
}
# Printing out the value of the key, by referring to the key itself:
print(monthConversions["Nov"])
# Another way to retrieve the value is using the "get()" function:
print(monthConversions.get("Dec"))
# If we want to pass a default value, which is not listed in the list above:
print(monthConversions.get("Dec", "Not a valid key"))
| true
|
a95b3e4a2102e76c1a6b4932d6053a66b9593d5d
|
b-zhang93/CS50-Intro-to-Computer-Science-Harvard-Problem-Sets
|
/pset6 - Intro to Python/caesar/caesar.py
| 1,022
| 4.21875
| 4
|
from cs50 import get_string
from cs50 import get_int
from sys import argv
# check for CLA to be in order and return error message if so
if len(argv) != 2:
print("Usage: ./caesar key k")
exit(1)
# checks for integer and positive
elif not argv[1].isdigit():
print("Usage: ./caesar key k")
exit(1)
# defining the key and converting it to an integer
key = argv[1]
k = int(key)
# prompt for user and return cipher
word = get_string("plaintext: ")
print("ciphertext: ", end="")
# c is the iterator for each letter in input
for c in word:
# for lowercase letters to convert and mod to wrap around then convert back to letter
if c.islower():
x = (ord(c) - 97 + k) % 26
y = 97 + x
z = chr(y)
print(z, end="")
# do the same for upper case
elif c.isupper():
x = (ord(c) - 65 + k) % 26
y = 65 + x
z = chr(y)
print(z, end="")
# every other non-alpha char just print it out no conversion
else:
print(c, end="")
print()
| true
|
c891f23d90e49fa066d06e90fd5ad2d45c9afd7d
|
gmarler/courseware-tnl
|
/labs/py3/decorators/memoize.py
| 1,122
| 4.1875
| 4
|
'''
Your job in this lab is to implement a decorator called "memoize".
This decorator is already applied to the functions f, g, and h below.
You just need to write it.
HINT: The wrapper function only needs to accept non-keyword arguments
(i.e., *args). You don't need to accept keyword arguments in this lab.
(That is more complex to do, which is why it's saved for a later
next lab.)
>>> f(2)
CALLING: f 2
4
>>> f(2)
4
>>> f(7)
CALLING: f 7
49
>>> f(7)
49
>>> g(-6, 2)
CALLING: g -6 2
4.0
>>> g(-6, 2)
4.0
>>> g(6, 2)
CALLING: g 6 2
-2.0
>>> g(6, 2)
-2.0
>>> h(2, 4)
CALLING: h 2 4 42
7
>>> h(2, 4)
7
>>> h(3, 2, 31)
CALLING: h 3 2 31
6
>>> h(3, 2, 31)
6
'''
# Write your code here:
# Do not edit any code below this line!
@memoize
def f(x):
print("CALLING: f {}".format(x))
return x ** 2
@memoize
def g(x, y):
print("CALLING: g {} {}".format(x, y))
return (2 - x) / y
@memoize
def h(x, y, z=42):
print("CALLING: h {} {} {}".format(x, y, z))
return z // (x + y)
if __name__ == '__main__':
import doctest
doctest.testmod()
# Copyright 2015-2017 Aaron Maxwell. All rights reserved.
| true
|
3f7a247198d94307902d20edec5016511a4343e6
|
kpetrone1/kpetrone1
|
/s7hw_mysqrt_final.py
| 1,348
| 4.4375
| 4
|
#23 Sept 2016 (Homework following Session 7)
#While a few adjustments have been made, the majority of the following code has been sourced from a blog titled "Random Thoughts" by Estevan Pequeno at https://epequeno.wordpress.com/2011/01/04/solutions-7-3/.
#function to test Newton's method vs. math.sqrt() to find square root
#Note: Newton's method is represented below as "mysqrt," and math.sqrt, I believe, is represented as "libmath_method."
import math
def mysqrt(n):
a = float(n)
x = n / 2 #rough estimate
i = 0
while i < 10:
y = (x + n/x) / 2 #Newton's method
x = y
i += 1
return y
def libmath_method(n):
a = float(n)
return math.sqrt(n)
#This function has a mix of int, str and float, so there is a bit of conversion going on.
def test_square_root():
for i in range(1,10):
n = str(mysqrt(i)) #mysqrt() gets int and returns float. Change to str.
l = str(libmath_method(i)) #libmath_method() gets int and returns float. Change to str.
ab = abs(mysqrt(i)-libmath_method(i)) #out as int in as float, no str
if (len(n) or len (l)) == 3:
print(i, n, ' ', 1, ' ', ab)
elif len(n) == 12:
print(i, n, ' ', ab)
else:
print(i, n, l, ' ', ab)
test_square_root()
| true
|
92297bb3778093c35679b32b2a1ffd22a3339403
|
harsh52/Assignments-competitive_coding
|
/Algo_practice/LeetCode/Decode_Ways.py
| 1,874
| 4.1875
| 4
|
'''
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
Given a string s containing only digits, return the number of ways to decode it.
Input: s = "12"
Output: 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
'''
class Solution:
def numDecodings(self, s: str) -> int:
s = list(s)
#print(s)
dp = [0 for _ in range(len(s))]
dp[0] = 1
if(len(s) == 1 and s[0] == '0'):
return 0
if(s[0] == '0'):
dp[0]=0
for i in range(1,len(s)):
print(s)
#print("in loop")
if(s[i-1] == '0' and s[i] == '0'):
dp[i] = 0
elif(s[i-1] == '0' and s[i] != '0'):
#print("in second")
dp[i] = dp[i-1]
elif(s[i-1] != '0' and s[i] == '0'):
#print("here")
if(s[i-1] == '1' or s[i-1] == '2'):
dp[i] = (dp[i-2] if i>=2 else 1)
print(dp)
else:
dp[i]=0
else:
#print("in last")
temp = ''.join(map(str,s[i-1:i+1]))
if(int(temp) <= 26):
dp[i] = dp[i-1] + (dp[i-2] if i>=2 else 1)
else:
dp[i] = dp[i-1]
#print("test")
return(dp[-1])
| true
|
28f0e5637cd7ca7d5b47451e27e6e1d0ac7db093
|
zlatnizmaj/GUI-app
|
/OOP/OOP-03-Variables.py
| 642
| 4.40625
| 4
|
# In python programming, we have three types of variables,
# They are: 1. Class variable 2. Instance variable 3. Global variable
# Class variable
class Test():
class_var = "Class Variable"
class_var2 = "Class Variable2"
# print(class_var) --> error, not defined
x = Test()
print(x.class_var)
print(x.class_var2)
# Instance Variables
# This variable is created within class in instance method
class TestIns():
def __init__(self, name, age):
self.name = name
self.age = age
y = TestIns('Y', 9)
print(y.name)
print(y.age)
# Global variable:
# It can be accessed anywhere in the project as it is assigned globally
| true
|
1e45cfd30735bc93f3341bb6bfdec05603fa77fc
|
pravsp/problem_solving
|
/Python/BinaryTree/solution/invert.py
| 1,025
| 4.125
| 4
|
'''Invert a binary tree.'''
import __init__
from binarytree import BinaryTree
from treenode import TreeNode
from util.btutil import BinaryTreeUtil
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Invert:
def invertTree(self, root: TreeNode) -> TreeNode:
if root:
right = root.right
left = root.left
root.right = self.invertTree(left)
root.left = self.invertTree(right)
return root
if __name__ == '__main__':
print("Create a binary tree")
bt = BinaryTree()
btutil = BinaryTreeUtil()
btutil.constructBinaryTree(bt)
bt.printTree(traversal=BinaryTree.LevelOrder, verbose=True)
bt.printTree(traversal=BinaryTree.InOrder)
print("Height of the tree: ", bt.getHeight())
bt.printTree(traversal=BinaryTree.LevelOrder, verbose=True)
bt.root = Invert().invertTree(bt.root)
bt.printTree(traversal=BinaryTree.InOrder)
| true
|
b6ff3bb38beaea248d13389d5246d449e8e8bf8a
|
Arushi96/Python
|
/Radical- Python Assignment Solutions/Loops and Conditions/Question 3.py
| 367
| 4.15625
| 4
|
#Assignment Questions
#Q: Write a program which calculates the summation of first N numbers except those which are divisible by 3 or 7.
n = int(input ("Enter the number till which you want to find summation: "))
s=0
i=0
while i<=n:
if (i%3==0)or(i%7==0):
#print(i)
i+=1
continue
else:
s=s+i
i=i+1
print("sum is: ", s)
| true
|
35025370621c265eff6d02c68d4284525634f5e1
|
mtjhartley/codingdojo
|
/dojoassignments/python/fundamentals/find_characters.py
| 568
| 4.21875
| 4
|
"""
Write a program that takes a list of strings and a string containing a single character, and prints a new list of all the strings containing that character.
Here's an example:
# input
word_list = ['hello','world','my','name','is','Anna']
char = 'o'
# output
new_list = ['hello','world']
"""
def find_characters(lst, char):
new_list = []
for word in lst:
if char in word:
new_list.append(word)
return new_list
word_list = ['hello','world','my','name','is','Anna']
char = 'o'
print find_characters(word_list, char)
| true
|
ac0c500a62196c5bf29fe013f86a82946fdb65b2
|
mtjhartley/codingdojo
|
/dojoassignments/python/fundamentals/list_example.py
| 854
| 4.28125
| 4
|
fruits = ['apple', 'banana', 'orange']
vegetables = ['corn', 'bok choy', 'lettuce']
fruits_and_vegetables = fruits + vegetables
print fruits_and_vegetables
salad = 3 * vegetables
print salad
print vegetables[0] #corn
print vegetables[1] #bok choy
print vegetables[2] #lettuce
vegetables.append('spinach')
print vegetables[3]
print vegetables[2:] #[lettuce, spinach]
print vegetables[1:3] #[bok choy, lettuce]
for index, item in enumerate(vegetables):
item = item.upper()
vegetables[index] = item
print vegetables
index = 0
for food in vegetables:
vegetables[index] = food.lower()
index += 1
print vegetables
#another enumerate example
my_list = ['apple', 'banana', 'grapes', 'pear']
counter_list = list(enumerate(my_list, 1))
print counter_list
numbers = [1,2,3,4]
new_numbers = map(lambda x: x*3, numbers)
print new_numbers
| true
|
3389a2cb84c667ada3e41ec096592cfdbf6c2e07
|
mtjhartley/codingdojo
|
/dojoassignments/python/fundamentals/compare_array.py
| 2,432
| 4.3125
| 4
|
"""
Write a program that compares two lists and prints a message depending on if the inputs are identical or not.
Your program should be able to accept and compare two lists: list_one and list_two.
If both lists are identical print "The lists are the same".
If they are not identical print "The lists are not the same."
Try the following test cases for lists one and two:
"""
list_one = [1,2,5,6,2]
list_two = [1,2,5,6,2]
list_three = [1,2,5,6,5]
list_four = [1,2,5,6,5,3]
list_five = [1,2,5,6,5,16]
list_six = [1,2,5,6,5]
list_seven = ['celery','carrots','bread','milk']
list_eight = ['celery','carrots','bread','cream']
list_nine = ['a', 'b', 'c']
list_ten = ['a','b','z']
#assumes order matters. if order doesn't matter, would call sorted() or .sort on both lists before checking.
def compare_array_order_matters(lst1, lst2):
if len(lst1) != len(lst2):
print "The lists are not the same"
print "This is because the list lengths are not the same."
else:
for index in range(len(lst1)):
if lst1[index] == lst2[index] and (index == len(lst1)-1):
print lst1[index], lst2[index]
print "The lists are identical"
elif lst1[index] == lst2[index]:
print lst1[index], lst2[index]
continue
else:
print lst1[index], lst2[index]
print "These items are not the same, thus: "
print "The lists are not the same."
break
compare_array_order_matters(list_one, list_two)
print
compare_array_order_matters(list_three, list_four)
print
compare_array_order_matters(list_five, list_six)
print
compare_array_order_matters(list_seven, list_eight)
print
compare_array_order_matters(list_nine, list_ten)
print
def compare_array_order_doesnt_matter(lst1, lst2):
sorted_lst1 = sorted(lst1)
sorted_lst2 = sorted(lst2)
if sorted_lst1 == sorted_lst2:
print "The lists are equal"
else:
print "The lists are not equal"
print "--------------------------------------------------"
print "Now testing the lists when order doesn't matter"
print
compare_array_order_doesnt_matter(list_one, list_two)
compare_array_order_doesnt_matter(list_three, list_four)
compare_array_order_doesnt_matter(list_five, list_six)
compare_array_order_doesnt_matter(list_seven, list_eight)
compare_array_order_doesnt_matter(list_nine, list_ten)
| true
|
19aa6ef97da6fdbb4a2a11fd2e66060d8a04f72e
|
nmarriotti/PythonTutorials
|
/readfile.py
| 659
| 4.125
| 4
|
################################################################################
# TITLE: Reading files in Python
# DESCRIPTION: Open a text file and read the contents of it.
################################################################################
def main():
# Call the openFile method and pass it Files/file1.txt
openFile('Files/file1.txt')
def openFile(filename):
# Create variable and set it to the contents of the file
fh = open(filename)
# Output each line in the file
for line in fh:
print(line.strip())
if __name__ == "__main__":
# Here we start the program by calling the main method
main()
| true
|
6a6034e699003b4a4ab0f11f7b2a9e89f235dc92
|
Eugene-Korneev/GB_01_Python_Basics
|
/lesson_03/task_01.py
| 822
| 4.25
| 4
|
# Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def divide(number_1, number_2):
if number_2 == 0:
return None
return number_1 / number_2
# num_1 = input("Введите первое число: ")
num_1 = '5'
# num_2 = input("Введите второе число: ")
num_2 = '2'
num_1, num_2 = float(num_1), float(num_2)
result = divide(num_1, num_2)
if result is None:
print("Ошибка! Деление на 0")
else:
print(f"Результат деления: {f'{result:.2f}'.rstrip('0').rstrip('.')}")
| false
|
7b72749a9f1bbf33723e47ddd491529226a414d5
|
Eugene-Korneev/GB_01_Python_Basics
|
/lesson_03/task_06.py
| 1,205
| 4.4375
| 4
|
# Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
# Каждое слово состоит из латинских букв в нижнем регистре.
# Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы.
# Необходимо использовать написанную ранее функцию int_func().
def int_func(word):
chars = list(word)
chars[0] = chr(ord(chars[0]) - 32)
return ''.join(chars)
print(int_func('text'))
string = 'hello world. python is the best!'
words = string.split()
capitalized_words = []
for w in words:
capitalized_words.append(int_func(w))
capitalized_string = ' '.join(capitalized_words)
print(capitalized_string)
| false
|
22d1c4d381fbbf7cbf52568137b1b079f41e1e3c
|
RicardoBaniski/Python
|
/Opet/4_Periodo/Scripts_CEV/Mundo_01/Aula009.py
| 1,449
| 4.78125
| 5
|
print('''Nessa aula, vamos aprender operações com String no Python. As principais operações que vamos aprender são o Fatiamento de String, Análise com len(), count(), find(), transformações com replace(), upper(), lower(), capitalize(), title(), strip(), junção com join().
''')
frase = 'Curso em Video Python'
print(frase[3]) # indice 3
print(frase[3:13]) # indice 3 ao 13
print(frase[:13]) # até o indice 13
print(frase[1:15]) # indice 1 ao 15
print(frase[1:15:2]) # indice 1 ao 15, com intervalo de 2
print(frase[1::2]) # indice 1 até o fim com intervalo de 2
print(frase[::2]) # do inicio ao fim com intervalo
print(frase.count('o')) # conta "o" minusculo
print(frase.count('O')) # conta "O" maiusculo
print(frase.upper().count('O')) # transforma em maiusculo e depois conta "O"
print(len(frase)) # tamanho do vetor
print(len(frase.strip())) # tamanho sem espaços no inicio e fim
print(frase.replace('Python', 'Android')) # substitui palavras para impressão
# frase = frase.replace('Python', 'Android') // substitui palavra na variável
print('Curso' in frase) # Se palavra está contida
print(frase.find('Video')) # encontre a posição da palavra exata
print(frase.lower().find('video')) # transforma o conteudo do vetor em minusculo para depois encontrar a palavra
print(frase.split()) # divide por espaçamento
dividido = frase.split() # armazena em lista
print(dividido[0]) #imprime um indice da lista
| false
|
85d84d9c937233fb243c2a67a482c84d778bb60b
|
nicolas-huber/reddit-dailyprogrammer
|
/unusualBases.py
| 1,734
| 4.3125
| 4
|
# Decimal to "Base Fib" - "Base Fib" to Decimal Converter
# challenge url: "https://www.reddit.com/r/dailyprogrammer/comments/5196fi/20160905_challenge_282_easy_unusual_bases/"
# Base Fib: use (1) or don't use (0) a Fibonacci Number to create any positive integer
# example:
# 13 8 5 3 2 1 1
# 1 0 0 0 1 1 0 = 16 in "Base Fib"
# collect and save user input
input_line = raw_input("Enter base (F or 10) and number to be converted: ")
input_list = input_line.split(" ")
base = input_list[0]
number = input_list[1]
# translate from base fib to decimal
if base == "F":
# Create sufficient amount of Fibonacci Numbers
a, b = 0, 1
fib_numbers = []
for i in range(len(number)):
a, b = b, a+b
fib_numbers.append(a)
fib_numbers.sort(reverse=True)
result = []
number_digit_list = [int(i )for i in str(number)]
for item1, item2 in zip(number_digit_list, fib_numbers):
if item1 == 1:
result.append(item2)
else:
pass
print(sum(result))
# translate from decimal to base fib
elif base == "10":
# Create sufficient amount of Fibonacci Numbers
a, b = 0, 1
fib_num_list = []
while True:
a, b = b, a+b
fib_num_list.append(a)
if fib_num_list[-1] >= int(number):
fib_num_list.sort(reverse=True)
break
fib_result = []
for entry in fib_num_list:
if int(number)/entry == 1:
fib_result.append(int(number)/entry)
number = int(number)%entry
else:
fib_result.append(0)
# remove first item of fib_results since excess 0 is added (?)
print(" ".join(str(x) for x in fib_result[1:]))
| true
|
b0b353eb1b6e426d235a046850ba74aea627d7a2
|
LJ-Godfrey/Learn-to-code
|
/Encryption-101/encryption_project/encrypt.py
| 1,178
| 4.25
| 4
|
# This file contains various encryption methods, for use in an encryption / decryption program
def caesar(string):
res = str()
for letter in string:
if letter.lower() >= 'a' and letter.lower() <= 'm':
res += chr(ord(letter) + 13)
elif letter.lower() >= 'n' and letter.lower() <= 'z':
res += chr(ord(letter) - 13)
else:
res += letter
return res
def reverse(string):
res = str()
for letter in string:
res = letter + res
return res
def xor(string, key):
res = str()
for letter in string:
res += chr(ord(letter) ^ key)
return res
def rotate(string):
res = str()
if len(string) % 2 > 0:
mid = string[len(string)/2 + 1]
res = string[:mid] + string[mid+1:]
res = rot_sub(res)
res = res[:len(res)/2] + mid + res[len(res)/2:]
else:
res = rot_sub(string)
return res
# This function is used in the 'rotate' function
def rot_sub(string):
res = string
# pylint: disable=unused-variable
for letter in range(int(len(string)/2)):
last = len(res) - 1
res = res[last] + res[:last]
return res
| true
|
fd1f0836c9c89a66ff6a555f48577538e398f026
|
Moby5/myleetcode
|
/python/671_Second_Minimum_Node_In_a_Binary_Tree.py
| 2,525
| 4.125
| 4
|
#!/usr/bin/env python
# coding=utf-8
"""
@File: 671_Second_Minimum_Node_In_a_Binary_Tree.py
@Desc:
@Author: Abby Mo
@Date Created: 2018-3-10
"""
"""
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node.
If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
If no such second minimum value exists, output -1 instead.
Example 1:
Input:
2
/ \
2 5
/ \
5 7
Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input:
2
/ \
2 2
Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.
题目大意:
给定一棵二叉树,树中的节点孩子个数为偶数(0个或者2个),若包含2个孩子节点,则值等于较小孩子的值。求树中第二小的节点。
解题思路:
遍历二叉树,记录比根节点大的所有节点中值最小的元素
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root or not root.left:
return -1
res = self.traverse(root)
res = sorted(res)
return res[1] if len(res) >= 2 else -1
def traverse(self, node):
if not node:
return {}
res = {node.val}
res.update(self.traverse(node.left))
res.update(self.traverse(node.right))
return res
def findSecondMinimumValue_ref(self, root): # http://bookshadow.com/weblog/2017/09/03/leetcode-second-minimum-node-in-a-binary-tree/
self.ans = 0x80000000
minVal = root.val
def traverse(root):
if not root: return
if self.ans > root.val > minVal:
self.ans = root.val
traverse(root.left)
traverse(root.right)
traverse(root)
return self.ans if self.ans != 0x80000000 else -1
if __name__ == '__main__':
solution = Solution()
n1, n2, n3 = TreeNode(5), TreeNode(8), TreeNode(5)
n1.left, n1.right = n2, n3
print solution.findSecondMinimumValue(n1)
| true
|
b76d2e373ea53f6ef7498888b0a80365bc48ec38
|
Moby5/myleetcode
|
/python/532_K-diff_Pairs_in_an_Array.py
| 2,592
| 4.125
| 4
|
#!/usr/bin/env python
# coding=utf-8
"""
LeetCode 532. K-diff Pairs in an Array
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].
题目大意:
给定一个整数数组nums,以及一个整数k,找出其中所有差恰好为k的不重复数对。
注意:
数对(i, j) 和 (j, i)算作同一个数对
数组长度不超过10,000
所有整数在范围[-1e7, 1e7]之间
解题思路:
字典(Map)
首先将nums中的数字放入字典c
遍历set(nums),记当前数字为n
若n + k在c中,则将结果+1
"""
import argparse
import collections
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0:
return 0
c = collections.Counter(nums)
thres = 0 if k else 1
return sum(c[n+k] > thres for n in c.keys())
# return sum(c[n+k] > 1 - bool(k) for n in c.keys())
def findPairs_2(self, nums, k): # Time Limit Exceeded
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k < 0:
return 0
ans = set()
arr = sorted(nums)
# print 'arr:', arr
for i in range(len(arr) - 1):
if arr[i] not in ans and (arr[i] + k) in arr[i+1:]:
# print arr[i], arr[i+1:]
ans.add(arr[i])
return len(ans)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='find k-diff pairs in an array')
parser.add_argument('-nums', type=int, nargs='+')
parser.add_argument('-k', type=int)
args = parser.parse_args()
test = Solution()
print test.findPairs(args.nums, args.k)
| true
|
1956ea7ce6d5955b343157031ad1089928bf0dfa
|
Moby5/myleetcode
|
/python/202_Happy_Number.py
| 2,098
| 4.125
| 4
|
#!/usr/bin/env python
# coding=utf-8
"""
202. Happy Number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits,
and repeat the process until the number equals 1 (where it will stay),
or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
题目大意:
编写一个算法判断某个数字是否是“快乐数”。
快乐数的定义过程如下:从任意一个正整数开始,将原数替换为其每一位的平方和,
重复此过程直到数字=1(此时其值将不再变化),
或者进入一个不包含1的无限循环。那些以1为过程终止的数字即为“快乐数”。
例如:19是一个快乐数,演算过程见题目描述。
解题思路:
模拟题,循环过程中用set记录每次得到的平方和
当出现非1的重复平方和时,返回False
否则,返回True
"""
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
def sum_of_squares_of_digits(num):
ans = 0
a = num
while a > 0:
ans += (a % 10) ** 2
a = a / 10
return ans
num = n
num_set = set()
while num != 1 and num not in num_set:
num_set.add(num)
num = sum_of_squares_of_digits(num)
# print num
return num == 1
def isHappy_v1(self, n):
numSet = set()
while n != 1 and n not in numSet:
numSet.add(n)
sum = 0
while n:
digit = n % 10
sum += digit * digit
n /= 10
n = sum
return n == 1
test = Solution()
print test.isHappy(19)
print test.isHappy(2)
| false
|
bd4619b0c4c69fddaa93c8e896a89873c74e245a
|
Moby5/myleetcode
|
/python/414_Third_Maximum_Number.py
| 2,199
| 4.15625
| 4
|
#!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2016/10/09/leetcode-third-maximum-number/
414. Third Maximum Number
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
题目大意:
给定一个整数数组,返回数组中第3大的数,如果不存在,则返回最大的数字。时间复杂度应该是O(n)或者更少。
解题思路:
利用变量a, b, c分别记录数组第1,2,3大的数字
遍历一次数组即可,时间复杂度O(n)
"""
import numpy as np
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a, b, c = None, None, None
for n in nums:
if n > a:
a, b, c = n, a, b
elif a > n > b:
b, c = n, b
elif b > n > c:
c = n
return c if c is not None else a # 不能直接 return c if c else a 因为c可能为0
def thirdMax_runtime_error(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ns = np.unique(nums)
return np.max(ns) if len(ns) < 3 else ns[-3]
def thirdMax_ref(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = b = c = None
for n in nums:
if n > a:
a, b, c = n, a, b
elif a > n > b:
b, c = n, b
elif b > n > c:
c = n
return c if c is not None else a
test = Solution()
print test.thirdMax([3,2,1])
print test.thirdMax([1,2])
print test.thirdMax([2,2,3,1])
print test.thirdMax([3,3,4,3,4,3,0,3,3])
| true
|
435ea91454abcafece1d68c23106f565bc004030
|
Moby5/myleetcode
|
/python/263_Ugly_Number.py
| 1,258
| 4.1875
| 4
|
#!/usr/bin/env python
# coding=utf-8
"""
http://bookshadow.com/weblog/2015/08/19/leetcode-ugly-number/
263. Ugly Number
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
题目大意:
编写程序判断一个给定的数字是否为“丑陋数” ugly number
丑陋数是指只包含质因子2, 3, 5的正整数。例如,6, 8是丑陋数而14不是,因为它包含额外的质因子7
注意,数字1也被视为丑陋数
解题思路:
将输入数重复除2, 3, 5,判断得数是否为1即可
时间复杂度:
记num = 2^a * 3^b * 5^c * t,程序执行次数为 a + b + c,换言之,最坏情况为O(log num)
"""
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
for x in [2, 3, 5]:
while num % x == 0:
num = num / x
return num == 1
test = Solution()
nums = [1, 6, 8, 14]
for num in nums:
print num, test.isUgly(num)
| false
|
a3f0ed60542ab8174c23174d1a48c8e2273b9e50
|
Moby5/myleetcode
|
/python/640_Solve_the_Equation.py
| 2,492
| 4.3125
| 4
|
#!/usr/bin/env python
# coding=utf-8
# 566_reshape_the_matrix.py
"""
http://bookshadow.com/weblog/2017/07/09/leetcode-solve-the-equation/
LeetCode 640. Solve the Equation
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: "x=x"
Output: "Infinite solutions"
Example 3:
Input: "2x=x"
Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2"
Output: "x=-1"
Example 5:
Input: "x=x+2"
Output: "No solution"
题目大意:
给定一元一次方程,求x的值
解题思路:
字符串处理
用'='将等式分为左右两半
分别求左右两侧x的系数和常数值,记为lx, lc, rx, rc
令x, c = lx - rx, rc - lc
若x != 0,则x = c / x
否则,若c != 0,说明方程无解
否则,说明有无数组解
"""
class Solution(object):
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
left, right = equation.split('=')
lcoef, lconst = self.solve(left)
rcoef, rconst = self.solve(right)
coef, const = lcoef - rcoef, rconst - lconst
if coef: return 'x=%d' % (const / coef)
elif const: return 'No solution'
return 'Infinite solutions'
def solve(self, expr):
coef = const = 0
num, sig = '', 1
for ch in expr + '#':
if '0' <= ch <= '9':
num += ch
elif ch == 'x':
coef += int(num or '1') * sig
num, sig = '', 1
else:
const += int(num or '0') * sig
num, sig = '', 1
if ch == '-': sig = -1
return coef, const
if __name__ == '__main__':
solution = Solution()
equations = ["x+5-3+x=6+x-2", "x=x" ,"2x=x", "2x+3x-6x=x+2", "x=x+2"]
for e in equations:
print e, solution.solveEquation(e)
pass
| true
|
549ae44ba1517ca134e2677a63cc3fe5cfb5f205
|
joaoribas35/distance_calculator
|
/app/services/calculate_distance.py
| 943
| 4.34375
| 4
|
import haversine as hs
def calculate_distance(coordinates):
""" Will calculate the distance from Saint Basil's Cathedral and the address provided by client usind Haversine python lib. Saint Basil's Cathedral is used as an approximation to define whether the provided address is located inside the MKAD Moscow Ring Road (MKAD) or not. It's location is the center point to a 18 km radius circle. Will return a null string indicating the address is inside MKAD or a string with the distance from MKAD border, expressed in kilometers, if the address falls outside the MKAD. """
CENTER_POINT = (55.75859164153293, 37.623173678442136)
CIRCLE_RADIUS = 18
input_address = (coordinates['lat'], coordinates['lon'])
distance = hs.haversine(CENTER_POINT, input_address)
if distance <= CIRCLE_RADIUS:
return 'null'
distance_from_border = round(distance - CIRCLE_RADIUS, 2)
return f'{distance_from_border} km'
| true
|
536bf2470f47c6353bc674b6c1efd668f8c03473
|
nonbinaryprogrammer/python-poet
|
/sentence_generator.py
| 787
| 4.15625
| 4
|
import random
from datetime import datetime
from dictionary import Words
#initializes the dictionary so that we can use the words
words = Words();
#makes the random number generator more random
random.seed(datetime.now)
#gets 3 random numbers between 0 and the length of each list of words
random1 = random.randint(0, 3000) % (len(words.plural_nouns))
random2 = random.randint(0, 3000) % (len(words.plural_verbs))
random3 = random.randint(0, 3000) % (len(words.plural_nouns))
#gets the n-th word from the list of words
#where n is the randomly chosen number above
noun1 = words.plural_nouns[random1]
verb1 = words.plural_verbs[random2]
noun2 = words.plural_nouns[random3]
#prints out each of the randomly chosen words with spaces between them
print noun1 + " " + verb1 + " " + noun2
| true
|
5ac31df1a7457d4431e7c8fbdc1892bf02d393d0
|
qtdwzAdam/leet_code
|
/py/back/work_405.py
| 1,282
| 4.53125
| 5
|
# -*- coding: utf-8 -*-
#########################################################################
# Author : Adam
# Email : zju_duwangze@163.com
# File Name : work_405.py
# Created on : 2019-08-30 15:26:20
# Last Modified : 2019-08-30 15:29:47
# Description :
# Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
#
# Note:
#
# All letters in hexadecimal (a-f) must be in lowercase.
# The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
# The given number is guaranteed to fit within the range of a 32-bit signed integer.
# You must not use any method provided by the library which converts/formats the number to hex directly.
# Example 1:
#
# Input:
# 26
#
# Output:
# "1a"
# Example 2:
#
# Input:
# -1
#
# Output:
# "ffffffff"
#########################################################################
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
def main():
return 0
if __name__ == '__main__':
main()
| true
|
4b3ce42dde5e951efe9620bfce24c01f380715e7
|
gauravtatke/codetinkering
|
/leetcode/LC110_balanced_bintree.py
| 2,087
| 4.3125
| 4
|
# Given a binary tree, determine if it is height-balanced.
# For this problem, a height-balanced binary tree is defined as:
# a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
# Example 1:
# Given the following tree [3,9,20,null,null,15,7]:
# 3
# / \
# 9 20
# / \
# 15 7
# Return true.
# Example 2:
# Given the following tree [1,2,2,3,3,null,null,4,4]:
# 1
# / \
# 2 2
# / \
# 3 3
# / \
# 4 4
# Return false
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution1:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
hleft = self.height(root.left)
hright = self.height(root.right)
if abs(hleft - hright) > 1 and self.isBalanced(
root.left) and self.isBalanced(root.right):
return True
return False
def height(self, root):
if root is None:
return 0
return max(self.height(root.left), self.height(root.right)) + 1
class Solution2:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
# another way is to return height at each recursion and -1 if it is un-balanced.
# no need to traverse tree twice, once for height and once for isBalance as in above solution
height = self.heightBalance(root)
if height == -1:
return False
return True
def heightBalance(self, root):
if root is None:
return 0
left_height = self.heightBalance(root.left)
if left_height == -1:
return -1
right_height = self.heightBalance(root.right)
if right_height == -1:
return -1
if abs(left_height - right_height) > 1:
return -1
return max(left_height, right_height) + 1
| true
|
32a89094e2c55e2a5b13cf4a52a1cf6ef7206894
|
gauravtatke/codetinkering
|
/leetcode/LC98_validate_BST.py
| 798
| 4.21875
| 4
|
# Given a binary tree, determine if it is a valid binary search tree (BST).
#
# Assume a BST is defined as follows:
#
# The left subtree of a node contains only nodes with keys less than the node's key.
# The right subtree of a node contains only nodes with keys greater than the node's key.
# Both the left and right subtrees must also be binary search trees.
def isValidBST(root):
def isValid(root, minNode, maxNode):
# define the min and max between which the node val should be
if root is None:
return True
if (minNode and minNode.val >= root.val) or (maxNode and maxNode.val <= root.val):
return False
return isValid(root.left, minNode, root) and isValid(root.right, root, maxNode)
return isValid(root, None, None)
| true
|
996e3858f7eb3c4a8de569db426c2f9cdd5fd71a
|
gauravtatke/codetinkering
|
/dsnalgo/firstnonrepeatcharinstring.py
| 1,292
| 4.15625
| 4
|
#!/usr/bin/env python3
# Given a string, find the first non-repeating character in it. For
# example, if the input string is “GeeksforGeeks”, then output should be
# ‘f’ and if input string is “GeeksQuiz”, then output should be ‘G’.
def findNonRepeatChar(stri):
chlist = [0 for ch in range(256)]
for ch in stri:
chlist[ord(ch)] += 1
for ch in stri:
if chlist[ord(ch)] == 1:
return ch
return None
def findNonRepeatCharFromCount(str1):
# store count of char and index at which it first occured in count list
count = [[0, None] for i in range(256)]
for i, ch in enumerate(str1):
count[ord(ch)][0] += 1
if not count[ord(ch)][1]:
# if index is None, set it else leave as it is
count[ord(ch)][1] = i
# now only traverse count list i.e. 256 elements instead of whole string
# again which could be very long
maxi = 257
result = None
for cnt, indx in count:
if cnt == 1 and indx < maxi:
result = str1[indx]
maxi = indx
return result
def main(argv):
print(findNonRepeatChar(argv[0]))
print(findNonRepeatCharFromCount(argv[0]))
return 0
if __name__ == '__main__':
import sys
sys.exit(main(sys.argv[1:]))
| true
|
c106671082f8f393f73ebad1a355929e142cfdc6
|
gauravtatke/codetinkering
|
/leetcode/LC345_reverse_vowelsof_string.py
| 739
| 4.28125
| 4
|
# Write a function that takes a string as input and reverse only the vowels of a string.
#
# Example 1:
# Given s = "hello", return "holle".
#
# Example 2:
# Given s = "leetcode", return "leotcede".
#
# Note:
# The vowels does not include the letter "y".
def reverseVowels(s):
lstr = list(s)
i = 0
j = len(lstr) - 1
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
while i < j:
while i < j and lstr[i] not in vowels:
i = i + 1
while i < j and lstr[j] not in vowels:
j = j - 1
lstr[i], lstr[j] = lstr[j], lstr[i]
# print(i, j)
i = i + 1
j = j - 1
return ''.join(lstr)
if __name__ == '__main__':
print(reverseVowels('hello'))
| true
|
0d37f87ebde2412443f7fefbf53705ac0f03b019
|
gauravtatke/codetinkering
|
/dsnalgo/lengthoflongestpalindrome.py
| 2,308
| 4.1875
| 4
|
#!/usr/bin/env python3
# Given a linked list, the task is to complete the function maxPalindrome which
# returns an integer denoting the length of the longest palindrome list that
# exist in the given linked list.
#
# Examples:
#
# Input : List = 2->3->7->3->2->12->24
# Output : 5
# The longest palindrome list is 2->3->7->3->2
#
# Input : List = 12->4->4->3->14
# Output : 2
# The longest palindrome list is 4->4
class SllNode:
def __init__(self, val=None):
self.key = val
self.nextp = None
def __str__(self):
return str(self.key)
def createlist(alist):
head = tail = None
for val in alist:
if tail:
tail.nextp = SllNode(val)
tail = tail.nextp
else:
head = tail = SllNode(val)
tail.nextp = SllNode() # just put dummy node at end so that comparisons are easy.
return head
def printlist(head):
curr = head
while curr.key:
print(curr, end='->')
curr = curr.nextp
print(None)
def findMaxPalindromeLen(head):
# reverse the linked list at each node and traverse from that node in opp
# directions.
curr = head
prev = SllNode()
maxlen = 0
while curr.key:
nxt = curr.nextp
curr.nextp = prev
# now from curr traverse back and forward and check if palindrome exists. if exists then get the length.
# first check for odd length palindrome from curr
i = prev
j = nxt
currmax = 1
while i.key == j.key:
# print('i == j for odd')
currmax += 2
i = i.nextp if i else None
j = j.nextp if j else None
maxlen = max(maxlen, currmax)
# now check for even length palindrome starting at curr and nxt
i = curr
j = nxt
currmax = 0
while i.key == j.key:
currmax += 2
i = i.nextp if i else None
j = j.nextp if j else None
maxlen = max(maxlen, currmax)
prev = curr
curr = nxt
return maxlen
def main():
alist1 = [2, 3, 7, 3, 2, 12, 24]
alist2 = [12, 4, 4, 3, 14]
alist3 = [1,2,3,6,3,9,6,6,9,3]
head = createlist(alist3)
printlist(head)
print(findMaxPalindromeLen(head))
if __name__ == '__main__':
main()
| true
|
8d9bb6926f1bd85ef8da53778229913d6ac4bc86
|
gauravtatke/codetinkering
|
/dsnalgo/sort_pile_of_cards.py
| 1,047
| 4.125
| 4
|
#!/usr/bin/env python3
# We have N cards with each card numbered from 1 to N. All cards are randomly shuffled. We are allowed only operation moveCard(n) which moves the card with value n to the top of the pile. You are required to find out the minimum number of moveCard() operations required to sort the cards in increasing order.
def minMove(arr):
# start iterating from back and count number of elements already in descending order.
# minimum movement to sort will be n-(num of elem in desc ord) because only those elem need to move
# for e.g. 4, 2, 5, 1, 6, 3 item in desc ord are 3 i.e.{6, 5, 4} so 6 - 3 = 3 movement to sort.
# moveCard(3) -> moveCard(2) -> moveCard(1)
n = len(arr)
count = 0
for i in arr[-1::-1]:
if i == n:
count += 1
n -= 1
return len(arr)-count
def main():
arr1 = [4, 2, 5, 1, 6, 3]
arr2 = [5, 1, 2, 3, 4]
arr3 = [3, 4, 2, 1]
print(minMove(arr1))
print(minMove(arr2))
print(minMove(arr3))
if __name__ == '__main__':
main()
| true
|
a783b4053b012143e18b6a8bd4335a8b84b5d031
|
gauravtatke/codetinkering
|
/leetcode/LC433_min_gene_mut.py
| 2,495
| 4.15625
| 4
|
# A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T".
# Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.
# For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
# Also, there is a given gene "bank", which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string.
# Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from "start" to "end". If there is no such a mutation, return -1.
# Note:
# Starting point is assumed to be valid, so it might not be included in the bank.
# If multiple mutations are needed, all mutations during in the sequence must be valid.
# You may assume start and end string is not the same.
# Example 1:
# start: "AACCGGTT"
# end: "AACCGGTA"
# bank: ["AACCGGTA"]
# return: 1
# Example 2:
# start: "AACCGGTT"
# end: "AAACGGTA"
# bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]
# return: 2
# Example 3:
# start: "AAAAACCC"
# end: "AACCCCCC"
# bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]
# return: 3
from collections import deque
class Solution(object):
def minMutation(self, start, end, bank):
"""
:type start: str
:type end: str
:type bank: List[str]
:rtype: int
"""
bankset = set(bank)
visited = set()
dq = deque()
dq.append(start)
level = 0
while dq:
size = len(dq)
while size:
gene = dq.popleft()
if gene == end:
return level
gene_list = list(gene)
for i, ch in enumerate(gene_list):
# oldchar = ch
for repch in ('A', 'C', 'G', 'T'):
gene_list[i] = repch
# print(gene_list)
mut_gene_str = ''.join(gene_list)
if mut_gene_str in bankset and mut_gene_str not in visited:
visited.add(mut_gene_str)
dq.append(mut_gene_str)
gene_list[i] = ch
size -= 1
level += 1
return -1
def main():
retval = Solution().minMutation("AACCGGTT", "AACCGGTA", ["AACCGGTA"])
print(retval)
if __name__ == '__main__':
main()
| true
|
ffe24156489d5063ee564b1b5c558585363a7944
|
directornicm/python
|
/Project_4.py
| 572
| 4.28125
| 4
|
# To calculate leap year:
# A leap year is a year which is divisible by 4 but ...
# if it is divisible by 100, it must be divisible by 400.
# indentation matters - take care of it
year = int(input("Give the year to be checked for leap year"))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"The year {year} is a leap year")
else:
print(f"The year {year} is not a leap year")
else:
print(f"The year {year} is a leap year")
else:
print(f"The year {year} is not a leap year")
| true
|
b0beed001a2b92c2770e863690799397ce682581
|
kkowalsks/CS362-Homework-7
|
/leapyear.py
| 603
| 4.1875
| 4
|
def leapCheck(int):
if int % 4 != 0:
int = str(int)
print(int + " is not a leap year")
return False
else:
if int % 100 != 0:
int = str(int)
print(int + " is a leap year")
return True
else:
if int % 400 != 0:
int = str(int)
print(int + " is not a leap year")
return False
else:
int = str(int)
print(int + " is a leap year")
return True
leapCheck(2020)
leapCheck(2021)
leapCheck(1900)
leapCheck(2000)
| false
|
67eb2e0043b1c1d63395df0de8f4e39a98930a7e
|
luthraG/ds-algo-war
|
/general-practice/17_09_2019/p16.py
| 996
| 4.1875
| 4
|
'''
Given a non-empty string check if it can be constructed by taking a substring of it and
appending multiple copies of the substring together.
You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
Example 1:
Input: "abab"
Output: True
Explanation: It's the substring "ab" twice.
Example 2:
Input: "aba"
Output: False
Example 3:
Input: "abcabcabcabc"
Output: True
Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
'''
def can_construct_string(str1):
length = len(str1)
i = 1
limit = length // 2
while i <= limit:
if length % i == 0:
times = length // i
if str1[:i] * times == str1:
return True
i += 1
return False
str1 = str(input('Enter input string :: '))
print('can this string be constructed by sub strings :: {}'.format(can_construct_string(str1)))
| true
|
bd48564a03e15ec4c6f2d287ec3b651947418118
|
luthraG/ds-algo-war
|
/general-practice/20_08_2019/p1.py
| 861
| 4.125
| 4
|
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 10 Million.
from timeit import default_timer as timer
if __name__ == '__main__':
start = timer()
number = 1000
# Since we want below hence
number -= 1
# Sum of multiple of 3s
upper3 = number // 3
sum3 = 3 * upper3 * (upper3 + 1) // 2
# Sum of multiple of 5s
upper5 = number // 5
sum5 = 5* upper5 * (upper5 + 1) // 2
# Sum of multiple of 15s
upper15 = number // 15
sum15 = 15 * upper15 * (upper15 + 1) // 2
sum = sum3 + sum5 - sum15
print("sum3 {}, sum5 {} and sum15 {}".format(sum3, sum5, sum15))
print("Overall sum = {}".format(sum))
end = timer()
print("Time taken is {}".format(end - start))
| true
|
3ec6fd0dcd97904b08c95fe17cac67b03a75a61f
|
luthraG/ds-algo-war
|
/general-practice/11_09_2019/p11.py
| 648
| 4.15625
| 4
|
'''
2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
'''
from timeit import default_timer as timer
power = int(input('Enter the power that needs to be raised to base 2 :: '))
start = timer()
sum_of_digits = 0
number = 2 << (power - 1)
number = str(number)
length = len(number)
i = 0
while i < length:
sum_of_digits += int(number[i])
i += 1
# while number != 0:
# sum_of_digits += (number % 10)
# number //= 10
end = timer()
print('Sum of digits of 2 raised to power {} is {}'.format(power, sum_of_digits))
print('Time taken is {}'.format(end - start))
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.