blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
637e5bfa60d76ddd8f2fb810dc050dde24c9be4b | Ady-6720/python | /Guess the Color Game .py | 806 | 4.1875 | 4 | #Guess the colour game
import random
colour=["red","green","blue","yellow","black","white","orange","pink","brown","purple","voilet"]
while True:
c=colour[random.randint(0,len(colour)-1)] #we put this here because we want to repeat this code to get random colour each time
p=input("Guess the colour: ")
while True:
if(c==p.lower()): #if condition is true then it will jump to line 14.
break
else: #if condition becomes false the code will run below code block.
p=input("Nope ! Try again: ")
print("Yeahh! You guessed it, it was",c)
#here below code will ask user to play it again or not if no then code will break
plag=input("Do you want to play again yes/no?")
if(plag.lower()=='no'):
break
| true |
824af8902886f3d3b343f88fbf2fd0258baa380f | Ady-6720/python | /MATPLOTLIB.py | 788 | 4.46875 | 4 | #matplotlib is used to visualize data in forms of bar, histograph etc
import matplotlib.pyplot as plt #importing matplotlib
x=[1,2,3,4,5,6,7,8,9,10,11,12] #this list will be used as data on x axis
y=[10,11,44,9,12,33,48,100,4,27,104,55] #this willbe data on y axis
plt.plot(x, y) #this will plot in form of point which are joined with lines
plt.show()
legend=["Jan","Feb","March","April","May","June","July","Aug","Sept","Oct","Nov","Dec"]
plt.bar(legend, y) #this will be a barchart
plt.show()
plt.hist(x) # Function to plot histogram
plt.show() # Function to show the plot
plt.scatter(x, y) # Function to plot scatter
plt.show() # function to show the plot | true |
51bf02dfac182424fe5e00a60b1bab2f75cd6b75 | Ady-6720/python | /Name Printing String Conc.py | 243 | 4.25 | 4 | #program to ask First name middle name and surname and then print full name.
F = input("Enter your First name = ")
M = input("Enter your Middle name = ")
S = input("Enter your Surname = ")
print("your initials are = ",F[0],M[0],S[0])
| true |
8dd59b653da868137a0ba87c0999bbbad8ccc19d | AndreMicheletti/zenvia-dojo | /romanos/convert.py | 2,455 | 4.125 | 4 |
romans_symbols_by_unit = {
"unidade": ("I", "V", "X"),
"dezena": ("X", "L", "C"),
"centena": ("C", "D", "M")
}
def convert_arabic_to_roman(
arabic_number: int
) -> str:
"""
Function to convert arabic numeral to roman numeral
:param arabic_number: (int) value to be converted
:return: (str) converted value to roman numeral
"""
if not isinstance(arabic_number, int) or isinstance(arabic_number, bool):
raise TypeError("Can't convert values other than integers")
if arabic_number > 9999 or arabic_number < 1:
raise ValueError("Can't convert numbers less than 1 or greater than 9999")
# extract each digit from the number
milhares_digit = int(arabic_number / 1000) % 10
centenas_digit = int(arabic_number / 100) % 10
dezenas_digit = int(arabic_number / 10) % 10
unidade_digit = int(arabic_number / 1) % 10
milhares_romano = (milhares_digit * "M")
centenas_romano = apply_roman_digit_logic(centenas_digit, *romans_symbols_by_unit["centena"])
dezenas_romano = apply_roman_digit_logic(dezenas_digit, *romans_symbols_by_unit["dezena"])
unidades_romano = apply_roman_digit_logic(unidade_digit, *romans_symbols_by_unit["unidade"])
romano = milhares_romano + centenas_romano + dezenas_romano + unidades_romano
return romano
def apply_roman_digit_logic(
digit: int,
symbol: str,
middle_symbol: str,
next_digit_symbol: str
) -> str:
"""
Apply the Roman addition and subtration logic using the given
symbols, depending on the unit needed
:param digit: the digit value for this unit
:param symbol: the symbol for this unit that represents '1'
:param middle_symbol: the symbol for this that represents '5'
:param next_digit_symbol: the symbol for the next unit (represents '10')
:return: the roman numeral to represent the digit on the given unit
"""
if digit == 0:
return ""
if digit == 5:
# for example: V
return middle_symbol
if digit > 5:
if digit == 9:
# for example, IX
return symbol + next_digit_symbol
else:
to_next = digit % 5
# for example, VII
return middle_symbol + (symbol * to_next)
elif digit < 5:
if digit == 4:
# for example, IV
return symbol + middle_symbol
else:
# for example, III
return digit * symbol
| false |
26e786b8abb5fbd1275a4dea5a6dd36979be32f4 | etikrusteva/python_scripts | /day.py | 1,187 | 4.3125 | 4 | #!/usr/bin/env python3
def weekdays():
print("Please type Number from 1 to 7 - which day of the week is today:")
today = input("Number:")
today = int(today)
def Monday(today):
return "Monday"
def Thuesday(today):
return "Thuesday"
def Wednesday(today):
return "Wednesday"
def Thursday(today):
return "Thursday"
def Friday(today):
return "Friday"
def Sunday(today):
return "Sunday"
def Saturday(today):
return "Saturday"
if today > 7 or today <1:
print("Sorry, the days of the week are only 7!")
elif today <7 and today >1:
if today == 1:
result = Monday(today)
elif today == 2:
result = Thuesday(today)
elif today == 3:
result = Wednesday(today)
elif today == 4:
result = Thursday(today)
elif today == 5:
result = Friday(today)
elif today == 6:
result = Sunday(today)
elif today == 7:
result = Saturday(today)
print("Today is", result, "and it's a beautiful day!")
if __name__ == "__main__":
weekdays()
| true |
e9928be9b973b122c8884950d0e60eb8cacc0915 | MrDrDAVID/leetcode-answers | /leetcode-stuff/reverse_integer.py | 489 | 4.125 | 4 | def reverse(x: int) -> int:
int_string = str(x)
result = 0
reversed_int = ''
if '-' in int_string :
for char in int_string[1:] :
reversed_int = char + reversed_int
result = int('-' + reversed_int)
else :
for char in int_string :
reversed_int = char + reversed_int
result = int(reversed_int)
if result > 2**31 - 1 or result < -2**31 :
return 0
else :
return result | true |
b490cd0feecca9333821394350e1a52622e46f76 | AaronWendell/MIS3640 | /Session 08/quiz1.py | 2,119 | 4.21875 | 4 | """
Question 1:
If the number, n, is divisible by 4, return True; return False otherwise. Return False if n is divisible by 100 (for example, 1900); the only exception is when n is divisible by 400(for example, 2000), return True.
"""
def is_special(n):
"""
If the number, n, is divisible by 4 (for example, 2020), return True. Return False if n is divisible by 100 (for example, 300); the only exception is when n is divisible by 400(for example, 2400), return True.
"""
if n % 100 == 0:
if n == 400:
return True
else:
return False
elif n % 4 == 0:
return True
else:
return False
# When you've completed your function, uncomment the
# following lines and run this file to test!
# print(is_special(2020))
# print(is_special(300))
# print(is_special(2018))
# print(is_special(2000))
"""
-----------------------------------------------------------------------
Question 2:
"""
def detect(a, b, n):
"""
Returns True if either a or b is n, or if the sum or difference or product of a and b is n.
"""
if (a <= n) or (b <= n):
return True
elif ((a+b) <= n) or (abs(a-b) <= n):
return True
elif (a * b <= n):
return True
else:
return False
# When you've completed your function, uncomment the
# following lines and run this file to test!
# print(detect(2018, 9, 2018))
# print(detect(2017, 1, 2018))
# print(detect(1009, 2, 2018))
# print(detect(2020, 2, 2018))
# print(detect(2017, 3, 2018))
"""
-----------------------------------------------------------------------
Question 3:
Write a function with loops that computes the sum of all cubes of all the odd numbers between 1(inclusive) and n (inclusive if n is not even).
"""
def sum_cubes_of_odd_numbers(n):
running_sum = 0
for i in range(n + 1):
if i % 2 != 0:
running_sum += (i ** 3)
return running_sum
# When you've completed your function, uncomment the
# following lines and run this file to test!
# print(sum_cubes_of_odd_numbers(1))
# print(sum_cubes_of_odd_numbers(10))
| true |
fb1d2df13a87da9eda1e92f733541ada060691aa | sagorbd91/hello-world | /Map_filter.py | 1,064 | 4.21875 | 4 | #MAP Function
# here you will need to pass a list and a function to map the data
import math
radii = [2,5,6,7]
def area(r):
return math.pi * (r**2)
x = list(map(area,radii))
print(x)
# Another Example
temps = [("berlin", 29), ("cairo", 45), ("dhaka", 30)]
c_to_f = lambda data:(data[0],9/5*data[1] +32)
#def celsious(x):
# for i in x:
# return i[0]*9/5 + 32
z = list(map(c_to_f,temps))
print(z)
# so in map function we will apply the function by iterating the data of list
##############################################################3
# ZIP function
# list of dictionaries using zip function using 2 lists
# 2 list converted into list of dictionaries
color_name = ['red', 'maroon', 'yellow']
color_code = ['#0090', '#6887', '#6789']
name_with_code = [{'color_name': f, 'color_code': c} for f, c in zip(color_name, color_code)]
print(name_with_code)
# Filter Function
#import statistics
data = [6.6,7.5,8.5]
def avg(data):
return sum(data)/len(data)
# print(y)
#avg(data)
value =list(filter(avg,data))
print(value)
| true |
b6129e8e6a49dd7e31d00d5941c8b87835d00d25 | SACHSTech/livehack-3-keira-h | /problem1.py | 793 | 4.34375 | 4 | """
----------------------------------------------------------
Name: problem1.py
Purpose: Write a program to determine which group a player is placed in
Author: Hosey.K
Created: date in 03/03/2021
----------------------------------------------------------
"""
# Header of tracker
print("~~~~~~~~~~~~ Tournament Tracker ~~~~~~~~~~~~")
# Input wins and losses
win_count = 0
for i in range(6):
game = input("Enter the wins and losses for your team: ")
if game == "W":
win_count += 1
# Determining Group
if win_count >= 5:
print("Your team is in Group 1.")
elif (win_count == 3) or (win_count == 4):
print("Your team is in Group 2.")
elif (win_count == 1) or (win_count == 2):
print("Your team is in Group 3.")
else:
print("Your team is eliminated from the tournament.")
| true |
0f390f148465cca0f0c737c6d431bc65989555df | rajeshchangdar/Python-Introduction | /VariableNdOperators/OperatorDemo.py | 905 | 4.4375 | 4 | # Introduction to Python Operators
# Arithmatic Operators
"""
print(2+3)
print(3/2)
print("This is Floor Division: ",3//2)
print("This is Modulo Operation: ",3%2)
"""
"""
#Sample code
days=int(input("Enter the no of Days:"))
months=(days/30)
days=(days%30)
print(" %d Months and %d Days"%(months,days))
#Sample code using divmod function
days1=int(input("Enter Days: "))
print("%d Months and %d Days"%divmod(days1, 30))
"""
"""
#Relational Operators
print(3>10)
print(2<4)
print(23==56)
print(11!=11)
"""
"""
#Logical Operators
print(1 and 4)
print(-1 and 4)
print(4 and 1)
print(4 and -1)
print(0 and 4)
print(4 and 0)
print(1 or 4)
print(0 or 4)
print(-1 or 7)
"""
#Type Conversions
inp=int(input("Enter String: "))
print(inp+1)
st=str(input("Enter Integer: "))
print(st+" "+"hello")
'''
Created on 09-May-2018
@author: RAJESH
'''
| true |
fdde745104d868f5d2cb7213862c4c1866621722 | rajeshchangdar/Python-Introduction | /PyClass/PropertyDemo.py | 741 | 4.125 | 4 | #Here is the application of Property method of Python
class Account(object):
def __init__(self,rate):
self.amt=0
self.rate=rate
@property
def amount(self):
return(self.amt)
@property
def inr(self):
return(self.amt*self.rate)
@amount.setter
def amount(self,value):
if(value<0):
print("Enter Positive Number")
return
self.amt=value
if(__name__=='__main__'):
acc1=Account(rate=61)
acc1.amount=20
print("Dollar Amount: ",acc1.amount)
print("INR Value: ",acc1.inr)
acc1.amount=-100
print("Daller Amount: ",acc1.amount)
'''
Created on 23-May-2018
@author: RAJESH
'''
| true |
1166e0af03710f7098d77fdded7817afee32304e | ehab1980/Supplemental-Lab-Tutorial-Solution-Set-Lab-3.1.2.3 | /Lab 3.1.2.3.py | 590 | 4.25 | 4 | secret_number = 777
print(
"""
+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+
""")
answer = 0
while answer !=777:
answer =int(input('Please Enter the Guess Number : '))
if answer == secret_number:
print('You guessed :' , answer, 'Correct! :)')
print("Well done, muggle! You are free now.")
else:
print("Ha ha! You're stuck in my loop!") | true |
6232faf4d2f17502e4b62e652aa8bc888726ae05 | vmred/codewars | /katas/6kyu/Remove the parentheses/solution.py | 731 | 4.53125 | 5 | # Remove the parentheses
# In this kata you are given a string for example:
# "example(unwanted thing)example"
# Your task is to remove everything inside the parentheses as well as the parentheses themselves.
# The example above would return:
# "exampleexample"
# Notes
# Other than parentheses only letters and spaces can occur in the string.
# Don't worry about other brackets like "[]" and "{}" as these will never appear.
# There can be multiple parentheses.
# The parentheses can be nested.
def remove_parentheses(s):
ret = ''
skip = 0
for i in s:
if i == '(':
skip += 1
elif i == ')' and skip > 0:
skip -= 1
elif skip == 0:
ret += i
return ret
| true |
37b9fb311fc3b9302b1228dfba1b6373a556529b | vmred/codewars | /katas/6kyu/Convert string to camel case/solution.py | 690 | 4.40625 | 4 | # Complete the method/function so that it converts dash/underscore delimited words into camel casing.
# The first word within the output should be capitalized only if the original word was capitalized
# (known as Upper Camel Case, also often referred to as Pascal case).
# Examples
# to_camel_case("the-stealth-warrior") # returns "theStealthWarrior"
# to_camel_case("The_Stealth_Warrior") # returns "TheStealthWarrior"
def to_camel_case(text):
if not text:
return ''
text = text.replace('-', ' ').replace('_', ' ').split(' ')
result = [text[0]]
for i in range(1, len(text)):
result.append(text[i][0].upper() + text[i][1:])
return ''.join(result)
| true |
5d417b80048cba9333af7d6d046439f1d91277b4 | vmred/codewars | /katas/beta/Generating permutations/test_generating_permutations.py | 921 | 4.3125 | 4 | # Write a generator function named permutations that returns all permutations of the supplied list.
# This function cannot modify the list that is passed in, or modify the lists that it returns inbetween iterations.
# In Python a generator function is a function that uses the yield keyword
# instead of return to return an iterable set of results.
# example output:
# for p in permutations([1, 2, 3]):
# print p
# [1, 2, 3]
# [1, 3, 2]
# [2, 1, 3]
# [2, 3, 1]
# [3, 2, 1]
# [3, 1, 2]
import importlib
from asserts.asserts import assert_true
permutations = importlib.import_module('katas.beta.Generating permutations.solution').permutations
class TestSolution:
def test_generating_permutations(self):
results = set(tuple(p) for p in permutations([1, 2, 3]))
expected_results = {(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 2, 1), (3, 1, 2)}
assert_true(expected_results, results)
| true |
c43aeee1329185e85224a9cd931c68ffd4401080 | vmred/codewars | /katas/6kyu/Write Number in Expanded Form/solution.py | 730 | 4.4375 | 4 | # Write Number in Expanded Form
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
# NOTE: All numbers will be whole numbers greater than 0.
# If you liked this kata, check out part 2!!
def expanded_form(num):
extensions = []
while num != 0:
l = len(str(num))
if l > 1:
v = int(str(num)[0]) * int('1' + '0' * (l - 1))
extensions.append(v)
num -= v
else:
extensions.append(num)
break
return ' + '.join(str(x) for x in extensions)
| true |
53b15ac865413799eaf997f9588794ed3e9ad176 | vmred/codewars | /katas/4kyu/Counting Change Combinations/solution.py | 777 | 4.28125 | 4 | # Write a function that counts how many different ways you can make change for an amount of money,
# given an array of coin denominations. For example, there are 3 ways to give change for 4 if you have coins
# with denomination 1 and 2:
# 1+1+1+1, 1+1+2, 2+2.
# The order of coins does not matter:
# 1+1+2 == 2+1+1
# Also, assume that you have an infinite amount of coins.
# Your function should take an amount to change and an array of unique denominations for the coins:
# count_change(4, [1,2]) # => 3
# count_change(10, [5,2,3]) # => 4
# count_change(11, [5,7]) # => 0
def count_change(money, coins):
if money == 0:
return 1
if money < 0 or not coins:
return 0
return count_change(money - coins[0], coins) + count_change(money, coins[1:])
| true |
29206bfb825becfd7582546f7693308d41859d19 | vmred/codewars | /katas/8kyu/Return negative/solution.py | 309 | 4.375 | 4 | # In this simple assignment you are given a number and have to make it negative.
# But maybe the number is already negative?
# Example:
# make_negative(1); # return -1
# make_negative(-5); # return -5
# make_negative(0); # return 0
def make_negative(number):
return -number if number > 0 else number
| true |
68f19eb8d0531ac2cfae9e381efabf75f5ddabd7 | anbreaker/py.checkio | /elementary/absolute-sorting.py | 1,664 | 4.375 | 4 | import unittest
# Let's try some sorting. Here is an array with the specific rules.
# The array (a tuple) has various numbers. You should sort it,
# but sort it by absolute value in ascending order. For example,
# the sequence (-20, -5, 10, 15) will be sorted like so: (-5, 10, 15, -20).
# Your function should return the sorted list or tuple.
# Precondition: The numbers in the array are unique by their absolute values.
# Input: An array of numbers , a tuple..
# Output: The list or tuple (but not a generator) sorted by absolute
# values in ascending order.
# Addition: The results of your function will be shown as a list in
# the tests explanation panel.
# Example:
# checkio((-20, -5, 10, 15)) == [-5, 10, 15, -20] # or (-5, 10, 15, -20)
# checkio((1, 2, 3, 0)) == [0, 1, 2, 3]
# checkio((-1, -2, -3, 0)) == [0, -1, -2, -3]
import unittest
def checkio(numbers_array: tuple) -> list:
return sorted(numbers_array, key=lambda valor: abs(valor))
# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print('Example:')
print(list(checkio((-20, -5, 10, 15))))
def check_it(array):
if not isinstance(array, (list, tuple)):
raise TypeError("The result should be a list or tuple.")
return list(array)
assert check_it(checkio((-20, -5, 10, 15))
) == [-5, 10, 15, -20], "Example" # or (-5, 10, 15, -20)
assert check_it(checkio((1, 2, 3, 0))) == [0, 1, 2, 3], "Positive numbers"
assert check_it(checkio((-1, -2, -3, 0))
) == [0, -1, -2, -3], "Negative numbers"
print("Coding complete, cool rewards!")
| true |
0cbc44f3411a612afdcbd893ff67bd925cf563af | propuk/pythontestcode | /6.py | 253 | 4.375 | 4 | def factorial(num):
if num == 1:
return num
else:
return num * factorial(num - 1)
num = int(input("Enter Number : "))
if num < 0:
print("factorial cannot be found.")
else:
print("Factorial of ",num," is ",factorial(num))
| true |
c30aa378cbdba6fb022609090d3518f21535f5d2 | thepedroferrari/DataStructuresAndAlgorithms | /1. Introduction/Unscramble Computer Science Problems/Task0.py | 1,997 | 4.21875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 0:
What is the first record of texts and what is the last record of calls?
Print messages:
"First record of texts, <incoming number> texts <answering number> at time <time>"
"Last record of calls, <incoming number> calls <answering number> at time <time>, lasting <during> seconds"
"""
# the first record on a list is the list[0] entry
# the last record on a list is the list[length-of-list - 1] entry
# I assume every time you reach into the array it is going to count as one operation,
# eg: texts[0] and text[2] would be two different operations.
# There are two variable declarations, one of which takes the len method and a math operation and two array access
# There is then three array access for the text print, plus five concatenations.
# There are four array access for the calls print, plus eight concatenations.
# also, account for two print operations and the function call itself.
# Totalling in O(27)
def getFirstTextAndLastCall():
# first_text = texts[0]
# last_call = calls[len(calls) - 1]
# print("First record of texts, " + first_text[0] + " texts " + first_text[1] + " at time " + first_text[2])
# print(
# "Last record of calls, " +
# last_call[0] +
# " calls " +
# last_call[1] +
# " at time " +
# last_call[2] +
# " lasting " +
# last_call[3] +
# " seconds"
# )
# Udacity Feedback:
# Suggestion / Learning: inline print. Interesting!
print(f"First record of texts, {texts[0][0]} texts {texts[0][1]} at time {texts[0][2]}.")
print(f"Last record of calls, {calls[-1][0]} calls {calls[-1][1]} at time {calls[-1][2]}, lasting {calls[-1][3]} seconds.")
getFirstTextAndLastCall()
| true |
663be3a0fa61c2daf6dbbd148f0ac27cc33df6a7 | olaramoni/Zeller-s-Congruence | /Zeller.py | 1,624 | 4.34375 | 4 |
dayValid=False #Boolean to create loop
while dayValid==False: #Creating loop
try:
day = input("Please enter the day of the month as a number: ")
day=int(day)
if 0<day<32:
dayValid=True
else:
print("Please enter a number between 1 and 31")
except ValueError:
print("That wasn't a number")
monthValid = False
print(
"March=3, April=4, May=5, June=6, July=7, August=8, September=9, October=10, November=11, December=12, January=13, February=14")
while monthValid == False:
try:
month = input("Please enter the number corresponding to the month you want: ")
month = int(month)
if 2 < month < 15:
monthValid = True
else:
print("Please enter a number between 3 and 14")
except ValueError:
print("That was not a number")
yearValid = False
while yearValid == False:
try:
year = input("Please enter the year: ")
year = int(year)
if year > 0:
yearValid = True
else:
print("Please enter a positive number: ")
except ValueError:
print("That was not a number")
a = (13 * (month + 1)) / 5 # first part of equation
centuryYear = (year % 100) / 4 # Calculating year of century
century = (year // 100) / 4 # Calculating the century
d = 2 * (year // 100) - 1 # Value that is double the century
total = day + a + century + centuryYear - d
total = total % 7
total = str(total)
daysOfWeek = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
print(total)
print(daysOfWeek[int(total[0])])
| true |
0a8a5e93bf53ed868c39f6af8828144295c92e97 | alexshchegretsov/algorithms | /data_structures/binary_tree/bfs.py | 1,280 | 4.1875 | 4 | class Node:
def __init__(self, v=None):
self.v = v
self.left = None
self.right = None
def search(node: Node, target: int):
if not node:
return
if node.v == target:
return node
if node.v < target:
return search(node.right, target)
else:
return search(node.left, target)
def insert(root: Node, node: Node):
if root.v < node.v:
if not root.right:
root.right = node
else:
insert(root.right, node)
elif root.v > node.v:
if not root.left:
root.left = node
else:
insert(root.left, node)
def breadth_first_search(node: Node):
nodes = []
queue = [node]
while queue:
curr = queue.pop(0)
if curr.left:
queue.append(curr.left)
if curr.right:
queue.append(curr.right)
nodes.append(curr.v)
return nodes
if __name__ == '__main__':
root = Node(10)
root.left = Node(8)
root.left.right = Node(9)
root.right = Node(14)
root.left.left = Node(5)
root.right.right = Node(20)
print(breadth_first_search(root))
insert(root, Node(12))
insert(root, Node(-3))
insert(root, Node(34))
print(breadth_first_search(root))
| true |
542b448e6f2241081130a9505e8cc4ddaae7d675 | tzieba1/IntroPythonFiles | /PythonCodeSnippets/passwordValidation.py | 823 | 4.3125 | 4 | myPassword = input( "Please enter a password: " )
validLength = False
validUpper = False
validLower = False
validNumber = False
while not (validLength and validUpper and validLower and validNumber):
length = len( myPassword )
if length >= 8:
validLength = True
loop = 0
while loop < length:
if myPassword[loop].isupper():
validUpper = True
if myPassword[loop].islower():
validLower = True
if myPassword[loop].isdecimal():
validNumber = True
loop += 1
if not (validLength and validUpper and validLower and validNumber):
print( "Your password is invalid, try again" )
myPassword = input( "Please enter a password: " )
print( "Your password is:", myPassword )
| true |
e183d51e8426842024bb51b923b59c81f510f6c7 | debby975241/stancodeproject | /stanCode Project/SC101_Assignment5/largest_digit.py | 1,382 | 4.5625 | 5 | """
File: largest_digit.py
Name:
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(find_largest_digit(281)) # 8
print(find_largest_digit(6)) # 6
print(find_largest_digit(-111)) # 1
print(find_largest_digit(-9453)) # 9
def find_largest_digit(n):
"""
:param n: (int) to find the largest digit in it
:return: the largest digit of n
"""
if n < 0:
n = n - (2*n)
return helper(n, 0)
def helper(n, largest):
last_digit = n % 10
if n == 0:
return largest
else:
if last_digit > largest:
largest = last_digit
n //= 10
return helper(n, largest)
# if n < 0: # if n is a negative int
# n = n - (2*n) # make n a positive int
#
# if n < 10: # base case
# return n
#
# else:
# last_digit = n % 10
# last_second = (n - n % 10) // 10 % 10
# if last_second > last_digit:
# n = (n - last_digit) // 10 # ex: 8 > 1, make 281 to 28
# else:
# n = (n - last_digit) // 10 - last_second + last_digit # ex: 4 < 5, make 12345 to 1235
# return find_largest_digit(n)
if __name__ == '__main__':
main()
| true |
decf5e4ccd4da4166aae4a995e6d027d03bb3a86 | ExcelsiorCJH/algorithm_solving | /00-code_snippets/trie_v2.py | 2,808 | 4.15625 | 4 | from collections import deque
class Node(object):
"""
A single node of a trie.
Children of nodes are defined in a dictionary
where each (key, value) pair is in the form of
(Node.key, Node() object).
"""
def __init__(self, key, data=None):
self.key = key
self.data = data # data is set to None if node is not the final char of string
self.children = {}
class Trie(object):
"""
A simple Trie with insert, search, and starts_with methods.
"""
def __init__(self):
self.head = Node(None)
"""
Inserts string in the trie.
"""
def insert(self, string):
curr_node = self.head
for char in string:
if char not in curr_node.children:
curr_node.children[char] = Node(char)
curr_node = curr_node.children[char]
# When we have reached the end of the string, set the curr_node's data to string.
# This also denotes that curr_node represents the final character of string.
curr_node.data = string
"""
Returns if string exists in the trie
"""
def search(self, string):
curr_node = self.head
for char in string:
if char in curr_node.children:
curr_node = curr_node.children[char]
else:
return False
# Reached the end of string,
# If curr_node has data (i.e. curr_node is not None), string exists in the trie
if curr_node.data != None:
return True
"""
Returns a list of words in the trie
that starts with the given prefix.
"""
def starts_with(self, prefix):
curr_node = self.head
result = []
subtrie = None
# Locate the prefix in the trie,
# and make subtrie point to prefix's last character Node
for char in prefix:
if char in curr_node.children:
curr_node = curr_node.children[char]
subtrie = curr_node
else:
return None
# Using BFS, traverse through the prefix subtrie,
# and look for nodes with non-null data fields.
queue = deque(subtrie.children.values())
while queue:
curr = queue.popleft()
if curr.data != None:
result.append(curr.data)
queue += list(curr.children.values())
return result
if __name__ == "__main__":
# Test
t = Trie()
words = ["romane", "romanus", "romulus", "ruben", "rubens", "ruber", "rubicon", "ruler"]
for word in words:
t.insert(word)
print(t.search("romulus"))
print(t.search("ruler"))
print(t.search("rulere"))
print(t.search("romunus"))
print(t.starts_with("ro"))
print(t.starts_with("rube")) | true |
bb0f27c0076611eabc0c70ad7597beea362a3d24 | deesaw/PythonD-04 | /RegEx/re1.py | 503 | 4.3125 | 4 | #regex examples
import re
#finding
#find any number anywhere in the string
print(re.findall("\d","3 pens cost 20 rupees and 50 paise"))
print(re.findall("\d+","3 pens cost 20 rupees and 50 paise"))
#find any number at the begining of the string
print(re.findall("^\d+","3 pens cost 20 rupees and 50 paise"))
#find any number at the end of the string
print(re.findall("\d+$","3 pens cost 20 rupees and 50 paise "))
#Split with multiple separaters
print(re.split("[,:-]","Lakshmi,276-plakshmipriya@gmail.com:female"))
| true |
fcbb73955cd92c785039af6d15dbe9ac9e5b3689 | deesaw/PythonD-04 | /RegEx/re7.py | 300 | 4.1875 | 4 | import re
ss='test hello TEST'
print(re.findall('TeSt',ss,re.IGNORECASE))
name_check = re.compile(r"[^A-Z]",re.IGNORECASE)
name = input ("Please, enter your name: ")
while name_check.search(name):
print ("Please enter your name correctly!")
name = input ("Please, enter your name: ")
| true |
c24c15c884155a1aa04198f24836998f1ac1d202 | jdamato41/python4e | /chap3-ex2.py | 761 | 4.40625 | 4 | #this program will calculate by given the rate and hours, it also does overtime
hours=input("Enter the hours worked \n")
try:
hours=float(hours)
print("You entered:", hours)
ot=hours-40
print(ot)
except:
print("you need to enter a number")
rate=input("Enter your hourly rate of pay\n")
try:
rate=float(rate)
print ("You entered an hourly rate of", rate)
""" except:
print("You must enter a number")
if hours>40:
print("over40")
#pay=(hours*rate)+(ot)*(rate*1.5))
else:
pay=(hours*rate) """
print("you have", hours,"and",hours-40,"overtime")
print(pay, "is the amount of pay you will receive")
| true |
fc17f448d95d5026f03824bc84cf702770816c1e | jdamato41/python4e | /chap2_ex5.py | 393 | 4.125 | 4 | # this program converts temperatures from far-cel
answer= input("hello, are you ready to convert some tempertures? y or n \n")
if answer == "y":
print ("ok, great!\n")
print("let's get to it")
temp=input("enter a temperature in farenheit \n")
temp=int(temp)
print(temp)
newtemp=(temp-32)/2
print ("that will be ", newtemp, "degrees celcius")
print("ok goodbye")
| true |
1f73cee78a10556b9d924101ddc2948961c25264 | Sdubazan/wtc-projects | /submission_001-problem/course.py | 1,936 | 4.125 | 4 |
def create_outline():
"""
TODO: implement your code here
"""
Course_Topics = set(
[
'Introduction to Python',
'Tools of the Trade',
'How to make decisions',
'How to repeat code',
'How to structure data',
'Functions',
'Modules'
]
)
Topics = []
Problems = {}
problems_list = ['Problem 1','Problem 2','Problem 3']
student_records = [
('Nyari','Introduction to Python','Problem 2','[STARTED]'),
('Adan','How to make decisions','Problem 1','[GRADED]'),
('Tom','Modules','Problem 2','[COMPLETED]'),
('Sihle','Tools of the Trade','Problem 3','[STARTED]',),
('David','functions','Problam 1','[GRADED]'),
('Joy','How to pepeat code','Problem 2','[GRADED]'),
('Timmy','How to structure data','Problem 1','[GRADED]')
]
print('Course Topics:')
for items in Course_Topics:
Topics.append(items)
Topics.sort()
for topics in Topics:
print('*', topics)
print('Problems:')
for topic in Course_Topics:
Problems[topic] = problems_list
for key,value in Problems.items():
print('* '+str(key)+' :', str(value[0])+', '+str(value[1])+', '+str(value[2]))
print('Student Progress:')
i = 1
student_records = [(index[3],index[1],index[2],index[0]) for index in student_records]
student_records.sort(reverse = True)
student_records = [(index[3],index[2],index[1],index[0]) for index in student_records]
for indexer in range(len(student_records)):
k = 0
print(str(indexer + 1) + '.',end='')
while(k < len(student_records[i])):
if k < 3:
print(student_records[indexer][k], end = '-')
else:
print(student_records[indexer][k])
k += 1
pass
if __name__ == "__main__":
create_outline()
| true |
5631c5d0c765664c15e993aae5c4ee108d7b28c6 | rafidakhter/DataStrctures | /queued_list.py | 2,149 | 4.15625 | 4 | class node:
def __init__(self,data=None):
self.data=data
self.next=None
class queuelist:
#first in first out
#doubly link based que structure
def __init__(self):
self.head=node()
#adds an element to the linked list:
def enqueue(self,data):
newnode=node(data)
current_node=self.head
while current_node.next != None:
current_node=current_node.next
current_node.next=newnode
#take first the last element in the queueedlist:
def dequeue(self):
if self.length()<=0:
print ("ERROR: 'empty list' Index out of range!")
return None
head_node=self.head
first_node=head_node.next
data=first_node.data
sec_node=first_node.next
head_node.next=sec_node
return data
def length(self):
current_node=self.head
counter=0
while current_node.next !=None:
counter +=1
current_node=current_node.next
return counter
#get all element of the queue
def getallelements(self):
current_node=self.head
elements=[]
while current_node.next != None:
current_node=current_node.next
elements.append(current_node.data)
return elements
#displays all the elements in the queueedlist
def display(self):
print(self.getallelements())
#delete an element at a given index:
def erase(self,index):
if index>=self.length() or index<0:
print ("ERROR: 'erase' Index out of range!")
return
current_node=self.head
counter=0
while True:
last_node=current_node
current_node=current_node.next
if counter==index:
#we will be deleting current node:
last_node.next=current_node.next
next_node=current_node.next
return
counter+=1
mylist=queuelist()
for x in range (0,5):
mylist.enqueue(x)
mylist.display()
for x in range (0,5):
mylist.dequeue()
mylist.display()
| true |
31be40ac533cacf8bfc5d23ef5411c3f400a397b | George-Eremin/Geekbrains_Python_Basics | /Lesson_6/L6_02.py | 1,305 | 4.34375 | 4 | """
2. Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина).
Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными.
Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна.
Использовать формулу: длина*ширина*масса асфальта для покрытия одного кв метра дороги асфальтом,
толщиной в 1 см*число см толщины полотна.
Проверить работу метода.
Например: 20м*5000м*25кг*5см = 12500 т
"""
class Road:
_length: float
_width: float
def __init__(self, length: float, width: float):
self._length = length
self._width = width
def mass_calculate(self, weight=25, thickness=5):
return self._length * self._width * weight * thickness / 1000
my_road = Road(5000, 20)
print(f'Масса асфальта = {my_road.mass_calculate(weight=25, thickness=5)} тонн')
| false |
ff629b7f3633597eb5cda3a1fbbeea3c8609bc71 | kstaver/Numerical-Properties-Project | /base.py | 692 | 4.25 | 4 |
#print ('This application is meant to provide.')
print('Please input a number.')
num = input()
num = int(num)
def main(num):
if num % 4 == 0:
print (num, 'is a multiple of 4. Therefore it is even by definition.')
elif num % 2 == 0:
myList = []
for i in range(1, num + 1):
if num % i == 0:
myList.append(i)
print (num, 'is an even number. Its factors are', myList,'.')
else:
myList = []
for i in range(1, num + 1):
if num % i == 0:
myList.append(i)
print(num, 'is not an even number. Its factors are',myList,'.')
main(num)
#function for menu
#function for exit?? | true |
abd755f62e41eeb90960727c33998e7b0177041b | ShresthaSrijana13/Homework3 | /Zylab_10.17_OnlineShopping_1.py | 1,737 | 4.25 | 4 | # Srijana Shrestha
# 1918305
class ItemToPurchase: # creating a class itemToPurchase
def __init__(self): # constructor
self.item_name = 'none'
self.item_price = 0
self.item_quantity = 0
def print_item_cost(self): # defining function to print item cost
print(self.item_name, self.item_quantity, '@', '$' + str(int(self.item_price)), '=',
'$' + str(int(self.item_quantity) * int(self.item_price))) # printing and calculation of cost
if __name__ == "__main__":
item = ItemToPurchase() # calling itemToPurchase function
print('Item 1') # printing block
print('Enter the item name:') # printing block
item.item_name = input() # user input
print('Enter the item price:') # printing block
item.item_price = float(input()) # user input
print('Enter the item quantity:') # printing block
item.item_quantity = int(input()) # user input
print() # printing empty line
item2 = ItemToPurchase() # itemToPurchase function call
print('Item 2') # printing block
print('Enter the item name:') # printing block
item2.item_name = input() # user input
print('Enter the item price:') # printing block
item2.item_price = float(input()) # user input
print('Enter the item quantity:') # printing block
item2.item_quantity = int(input()) # user input
print() # printing empty line
print('TOTAL COST') # printing block
item.print_item_cost() # print_item_cost function call for item
item2.print_item_cost() # print_item_cost function call for item2
print() # printing empty line
print('Total:', '$' + str(int(item.item_price * item.item_quantity) + int(item2.item_price * item2.item_quantity)))
| true |
6f65d246cadf8c764f65ed2b39a85531eb37d908 | mucheniski/curso-em-video-python | /Mundo1/003TratandoDadosEFazendoContas/003FuncoesComVariaveis.py | 588 | 4.15625 | 4 | algoDigitado = input('Digite algo : ')
print('É numerico? ', algoDigitado.isnumeric()) # Se é possível converter o valor digitado em númerico, retorna True ou False
print('É alfabético? ', algoDigitado.isalpha()) # Se é alfabético ou seja, somente letras
print('É alfanumérico? ', algoDigitado.isalnum()) # Se é alfanumérico, letras ou números
print('Está em maiúscula? ', algoDigitado.isupper()) # Se tem somente letras maiúsculas
print('É espaço? ', algoDigitado.isspace())
print('Está capitalizado? ', algoDigitado.istitle)
| false |
5f84f9e25b3bbb67d3d0b11553870b5ea8e7f3d4 | mucheniski/curso-em-video-python | /Mundo3/funcoes/102Fatorial.py | 791 | 4.25 | 4 | # Exercício Python 102: Crie um programa que tenha uma função fatorial() que receba dois parâmetros:
# o primeiro que indique o número a calcular e outro chamado show, que será um valor lógico (opcional)
# indicando se será mostrado ou não na tela o processo de cálculo do fatorial.
def fatorial(numero, show=False):
"""
:param numero:
:param show: Opcional para mostrar a conta
:return: Fotorial do número passado
"""
fat = 1
for i in range(numero, 0, -1):
if show:
print(i, end='')
if i > 1:
print(' x ', end='')
else:
print(' = ', end='')
fat *= i
return fat
numero = int(input('Informe o número: '))
print(fatorial(numero, True))
| false |
0f0c63586daaaef8af876f42969fbe64b26f3638 | mucheniski/curso-em-video-python | /Mundo1/005CondicoesPython/035VerificarSePodeFormarTriangulo.py | 613 | 4.15625 | 4 | # Exercício Python 35: Desenvolva um programa que leia o comprimento de três retas
# e diga ao usuário se elas podem ou não formar um triângulo.
# pode formar um triangulo quando a soma de dois lados é menor que o terceiro lado
reta1 = int(input('Informe o tamanho da primeira reta: '))
reta2 = int(input('Informe o tamanho da segunda reta: '))
reta3 = int(input('Informe o tamanho da terceira reta: '))
if reta1 < reta2 + reta3 and reta2 < reta1 + reta3 and reta3 < reta1 + reta2:
print('Os valores podem formar um triângulo!')
else:
print('Os valores não podem formar um triângulo!') | false |
fa79e4e7348cf77d0f25e2fd9727f734ef99631b | mucheniski/curso-em-video-python | /Mundo2/003EstruturasDeRepeticao/068ParOuImpar.py | 1,056 | 4.1875 | 4 | # Exercício Python 68: Faça um programa que jogue par ou ímpar com o computador.
# O jogo só será interrompido quando o jogador perder, mostrando o total de vitórias consecutivas
# que ele conquistou no final do jogo.
import random
qtdeVitorias = 0
while True:
numeroComputador = random.randint(0,10)
print(f'Valor do computador {numeroComputador}')
opcao = str(input('Voce escolhe Par(P) ou Impar(I)?: ')).strip().upper()[0]
numeroJogador = int(input('Digite um número: '))
resultado = numeroJogador + numeroComputador
if resultado % 2 == 0:
print('Deu par!')
if opcao == 'P':
print('Você ganhou!')
qtdeVitorias += 1
else:
print('Você perdeu!')
break
else:
print('Deu impar!')
if opcao == 'I':
print('Você ganhou!')
qtdeVitorias += 1
else:
print('Você perdeu!')
break
print(f'Quantidade de vitórias consecutivas {qtdeVitorias}')
| false |
8d078d575b184ae313ac27d0689a382f95a4c8b4 | mucheniski/curso-em-video-python | /Mundo2/001CondicoesAninhadas/041ClassificacaoAtletaNatacao.py | 671 | 4.15625 | 4 | # Exercício Python 041: A Confederação Nacional de Natação precisa de um
# programa que leia o ano de nascimento de um atleta e mostre sua categoria,
# de acordo com a idade:
# – Até 9 anos: MIRIM
# – Até 14 anos: INFANTIL
# – Até 19 anos: JÚNIOR
# – Até 25 anos: SÊNIOR
# – Acima de 25 anos: MASTER
import datetime
anoAtual = datetime.date.today().year
anoNascimento = int(input('Informe o ano de nascimento: '))
idade = anoAtual - anoNascimento
if idade <= 9:
print('MIRIN')
elif idade <= 14:
print('INFANTIL')
elif idade <= 19:
print('JUNIOR')
elif idade <= 25:
print('SÊNIOR')
else:
print('MASTER') | false |
3124bec3a521b00bad8c119c0442223cb9713007 | mucheniski/curso-em-video-python | /Mundo3/listas/Aula17Listas.py | 2,455 | 4.1875 | 4 | listaNumeros = [4,6,8,3,4,6,5,1,4]
print(listaNumeros)
print('-'*100)
print('substituir um valor listaNumeros[2] = 0')
listaNumeros[2] = 0
print(listaNumeros)
print('-'*100)
print('Adicionar um valor listaNumeros.append(10)')
listaNumeros.append(10)
print(listaNumeros)
print('-'*100)
print('Ordenar os numeros em ordem crescente listaNumeros.sort()')
listaNumeros.sort()
print(listaNumeros)
print('-'*100)
print('Ordenar os numeros em ordem decrescente listaNumeros.sort(reverse=True)')
listaNumeros.sort(reverse=True)
print(listaNumeros)
print('-'*100)
print('Ver a quantidade de elementos len(listaNumeros)')
print(len(listaNumeros))
print('-'*100)
print('Pegar o último elemento da lista')
print(listaNumeros[-1])
print('-'*100)
print('Inserir em um local específico listaNumeros.insert(posicao, valor) listaNumeros.insert(2,0)')
print(listaNumeros)
listaNumeros.insert(2,0)
print(listaNumeros)
print('-'*100)
print('Remover com pop listaNumeros.pop(2), sem parametros elimina o último valor')
listaNumeros.pop(2)
print(listaNumeros)
listaNumeros.pop()
print(listaNumeros)
print('-'*100)
print('Remover o um elemento com remove voce passa o valor, não a posição')
print(listaNumeros)
listaNumeros.remove(6)
print(listaNumeros)
print('-'*100)
if 7 in listaNumeros:
listaNumeros.remove(7)
else:
print('Não achei o número')
print('-'*100)
print('Nova lista')
valores = list()
valores.append(4)
valores.append(5)
valores.append(7)
for valor in valores:
print(f'{valor}...', end='')
print('-'*100)
for chave, valor in enumerate(valores):
print(f'na chave {chave} tem o valor {valor}')
print('-'*100)
novosValores = list()
# for i in range(0, 3):
# novosValores.append(int(input('Informe um valor: ')))
# print(novosValores)
print('-'*100)
lista1 = [2, 4, 6, 8]
print('sempre que iguala uma lista na outra o python cria uma ligação, quando for alterada uma lista a outra também é')
lista2 = lista1
print(f'lista1 {lista1}')
print(f'lista2 {lista2}')
lista2[2] = 3
print('foi alterado')
print(f'lista1 {lista1}')
print(f'lista2 {lista2}')
print('-'*100)
lista1 = [2, 4, 6, 8]
print('Se quiser que receba uma cópia dos valores, é feito assim')
lista2 = lista1[:]
print(f'lista1 {lista1}')
print(f'lista2 {lista2}')
lista2[2] = 3
print('não foi alterado')
print(f'lista1 {lista1}')
print(f'lista2 {lista2}')
| false |
b2da6351ec32b637c4ae4513e7a5027847bee1c8 | Musawir-Ahmed/OOP | /WEEK-1/PDF 3/RAISE_TO_THE_POWER.py | 384 | 4.5 | 4 | # PROGRAM TO RAISE A NUMBER TO A SPECIFIC POWER
# TAKING A NUMBER AS A INPUT
number = int(input("ENTER A NUMBER ="))
# TAKING ITS POWER AS THE INPUT
power = int(input("ENTER POWER OF THE NUMBER ="))
# INITIALIZING IT BY 1 SO TO ELIMINATE GARBAGE VALUE
multiple = 1
for i in range(0, power):
multiple = multiple * number
print(" POWER OF THE THE NUMBER IS =", multiple)
| true |
e95a646ccc591855a98e71d8bf9340bc3a476469 | Musawir-Ahmed/OOP | /WEEK-1/PDF 1/SUM_OF_FIRST_FIVE_MULTIPLE_OF THE_GIVEN_NUMBER.py | 1,292 | 4.34375 | 4 | # to find the first 5 multiple of the number we will multiply them by 1 2 3 4 5
# taking first number from the user
number1 = input("ENTER FIRST NUMBER TO FIND ITS FIVE MULTIPLE =")
number1 = int(number1)
# taking second number from the user
number2 = input("ENTER SECOND NUMBER TO FIND ITS FIVE MULTIPLE =")
number2 = int(number2)
# to find the ultiple of the fiest number
print("MULTIPLES OF THE NUMBER ", number1, " ARE ")
multiple = number1 * 1
sum1 = multiple
print(multiple)
multiple = number1 * 2
sum1 = sum1+multiple
print(multiple)
multiple = number1 * 3
sum1 = sum1+multiple
print(multiple)
multiple = number1 * 4
sum1 = sum1+multiple
print(multiple)
multiple = number1 * 5
sum1 = sum1+multiple
print(multiple)
# to find the ultiple of the second number
print("MULTIPLES OF THE NUMBER ", number2, " ARE ")
multiple = number2 * 1
sum1 = sum1+multiple
print(multiple)
multiple = number2 * 2
sum1 = sum1+multiple
print(multiple)
multiple = number2 * 3
sum1 = sum1+multiple
print(multiple)
multiple = number2 * 4
sum1 = sum1+multiple
print(multiple)
multiple = number2 * 5
sum1 = sum1+multiple
print(multiple)
# to print the sum1 of the multiples of the two numbers
print("SUM OF FIRST FIVE MULTIPLE OF THE GIVEN NUMBER IS =", sum1)
| true |
19a3e7630e86920fc100ce5b0908ab790870e799 | ariyaths/toronto | /is_palindrome.py | 1,367 | 4.15625 | 4 | def reverse(word):
""" (srt) -> bool
Return True if and only if 'word' is a palindrome
>>> is_palindrome.reverse('kayak')
True
"""
word = word.strip()
s = word
# return word == word[::-1]
# Option 1
# for i in range(len(s) // 2 + 1):
# if s[i] != s[len(s) - i - 1]:
# return False
#
# return True
# Option 2
# for i in range(len(s) // 2):
# if s[i] != s[len(s) - i - 1]:
# return False
#
# return True
# Option 3
j = len(s) - 1
for i in range(len(s) // 2):
if s[i] != s[j - i]:
return False
return True
# Option 4 - This does not work
# for i in range(len(s) // 2):
# if s[i] != s[len(s) - i]:
# return False
#
# return True
def front_back(word):
""" (srt) -> bool
Return True if and only if 'word' is a palindrome
>>> is_palindrome.front_back('kayak')
True
"""
word = word.strip()
l = len(word)
return word[:l // 2:1] == word[:l // 2 - (l % 2 == 0):-1]
def compare_loop(word):
""" (srt) -> bool
Return True if and only if 'word' is a palindrome
>>> is_palindrome.compare_loop('kayak')
True
"""
word = word.strip()
l = len(word)
for i in range(len(word)):
l -= 1 if word[i] == word[len(word)-i-1] else 0
return l == 0
| false |
f1af7effca081ef8f9f98adf09a3fb4199df92b6 | sabrih146/python-java | /Drawings/stop sighn.py | 1,893 | 4.15625 | 4 |
import turtle # Allows us to use turtles
x = turtle.Turtle()
turtle.setup(400, 600) # Determine the window size
wn = turtle.Screen() # Creates a playground for turtles
wn.title('traffic light using different turtles') # Set the window title
wn.bgcolor('black') # Set the window background color
tess = turtle.Turtle() # Create a turtle, assign to tess
alex = turtle.Turtle() # Create alex
henry = turtle.Turtle() # Create henry
def draw_housing():
""" Draw a nice housing to hold the traffic lights"""
tess.pensize(3) # Change tess' pen width
tess.color('black', 'white') # Set tess' color
tess.begin_fill() # Tell tess to start filling the color
tess.forward(80) # Tell tess to move forward by 80 units
tess.left(90) # Tell tess to turn left by 90 degrees
tess.forward(200)
tess.circle(40, 180) # Tell tess to draw a semi-circle
tess.forward(200)
tess.left(90)
tess.end_fill() # Tell tess to stop filling the color
draw_housing()
def circle(t, ht, colr):
"""Position turtle onto the place where the lights should be, and
turn turtle into a big circle"""
t.penup() # This allows us to move a turtle without drawing a line
t.forward(40)
t.left(90)
t.forward(ht)
t.shape('circle') # Set tutle's shape to circle
t.shapesize(3) # Set size of circle
t.fillcolor(colr) # Fill color in circle
circle(tess, 50, 'green')
circle(alex, 120, 'orange')
circle(henry, 190, 'red')
x.goto(20,0)
def drawRectangle(t, width, height, color):
x.fillcolor(color)
x.begin_fill()
x.forward(width)
x.left(90)
x.forward(height)
x.left(90)
x.forward(width)
x.left(90)
x.forward(height)
x.left(90)
x.end_fill()
drawRectangle(x, 20, -100, 'blue')
x.right(90)
x.forward(100)
x.goto(-600,-100)
drawRectangle(x, 100, 1200, 'brown')
| true |
b49f1bfd656c1f8e8ca69842bc62ab3fe6cf5b3a | HGC-teacher/5023-OOP-scenarios | /turtle_drawing/main.py | 1,709 | 4.4375 | 4 | import turtle
# from turtle_drawing.drawing import Point, Shape
import drawing
'''
The mainline of the drawing program starts here
'''
# A list of shapes, which we'll loop through later in the program to draw our shapes
shapes = []
# Creates an instance of a turtle which will be used for drawing the shapes
my_turtle = turtle.Turtle()
# Creates a dictionary for a blue triangle shape
# create a list of Point objects and a Shape object, rather than a dictionary
bt_points = [drawing.Point(-120, 200), drawing.Point(-20, 200), drawing.Point(-70, 100)]
blue_triangle = drawing.Shape('blue', bt_points, my_turtle)
# Adds the blue triangle to the list of shapes
shapes.append(blue_triangle)
# Creates a dictionary for an orange square shape
# create a list of Point objects and a Shape object, rather than a dictionary
os_points = [drawing.Point(-200, -100), drawing.Point(-200, -150), drawing.Point(-150, -150), drawing.Point(-150, -100)]
orange_square = drawing.Shape('orange', os_points, my_turtle)
# Adds the orange square to the list of shapes
shapes.append(orange_square)
# Creates a dictionary for a red triangle shape
# TODO: Change this code to create a list of Point objects and a Shape object, rather than a dictionary
rt_points = [drawing.Point(100, 200), drawing.Point(250, 200), drawing.Point(175, 50)]
red_triangle = drawing.Shape('red', rt_points, my_turtle)
# Adds the blue triangle to the list of shapes
shapes.append(red_triangle)
# Draws all of the shapes that are in the list in the window
for obj in shapes:
# calls the draw method on the Shape object
obj.draw()
# This line will mean that the Turtle window won't close until we click
turtle.Screen().exitonclick() | true |
722917fa440a0b36cf34a2cfdc9b2adaecfa5429 | govindpandey96/govindpandey96 | /8.python exercise answer.py | 1,358 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Advanced Python Objects and Data Structures
# ## Advanced Numbers
# #### Convert 1024 to binary and hexadecimal representation
# In[3]:
print (bin(1024))
# In[4]:
print (hex(1024))
# #### Round 5.23222 to two decimal places
# In[5]:
print (round(5.2322, 2))
# ## Advanced Strings
# #### Check if every letter in the string s is lower case
# In[9]:
s = 'hello how are you Mary, are you feeling okay?'
print ('Yup' if s.islower() else 'Nope')
# #### How many times does the letter 'w' show up in the string below?
# In[10]:
s = 'twywywtwywbwhsjhwuwshshwuwwwjdjdid'
print (s.count('w'))
# ## Advanced Sets
# #### Find the elements in set1 that are not in set2
# In[13]:
set1 = {2,3,1,5,6,8}
set2 = {3,1,7,5,6,8}
print (set1.difference(set2))
print (set2.difference(set1))
# #### Find all elements that are in either set
# In[14]:
print (set1.union(set2))
print (set1.intersection(set2))
# ## Advanced Dictionaries
# #### Create this dictionary: {0: 0, 1: 1, 2: 8, 3: 27, 4: 64} using a dictionary comprehension.
# In[15]:
{x:x**3 for x in range(5)}
# ## Advanced Lists
# #### Reverse the list below
# In[20]:
list1 = [1,2,3,4]
list1.reverse()
list1
# #### Sort the list below in reverse order
# In[21]:
list2 = [3,4,2,5,1]
list2.sort()
list2
# ## Great Job!
| true |
272379e1aa3da855b5430a700c1addfd18f48c8f | achaudhri/PythonClass-2015 | /rename.py | 825 | 4.1875 | 4 | # Function that takes integers as inputs and returns 1st, 2nd, 3rd
def Rename(entry):
try:
if entry%1==0:
entry = str(entry)
if entry[-2:] == '11':
return "%sth" %(entry)
elif entry[-2:]== '12':
return "%sth" %(entry)
elif entry[-2:]== '13':
return "%sth" %(entry)
elif entry[-1] == '1':
return "%sst" %(entry)
elif entry[-1] == '2':
return "%snd" %(entry)
elif entry[-1] == '3':
return "%srd" %(entry)
else:
return "%sth" %(entry)
else:
return "Please do not enter decimal places."
except:
return "Please enter an integer."
finally:
print "This is a function."
print Rename(12)
print Rename(3)
print Rename('r')
print Rename(3.2)
print Rename(111)
print Rename(114)
| true |
a8a2c2e09f342fbc0bd98f80514475251e6a95f8 | Shawnmhy/BEProject | /venv1/lib/python3.6/site-packages/searching/graph/graph.py | 2,742 | 4.15625 | 4 | """Simple components for building graphs."""
from .base import Number
class Node(object):
"""A node / vertex in a graph."""
def __init__(self, data: any, key: any=None) -> None:
"""
Initialize a new node with given data and key.
Args:
data: the data the node houses
key: sort key for subscripting elements from data (default None)
Returns: None
Note: data[key] must be defined if key is not None
"""
self.data = data
self.key = key
@property
def comparable_data(self) -> Number:
"""Return the comparable data from the internal data store."""
# if there is no sort key, return the raw data as is
if self.key is None:
return self.data
# use the sort key to subscript comparable data from the object
return self.data[self.key]
def __repr__(self):
"""Return a Python string to create this object."""
return f'{self.__class__.__name__}(data={self.data}, key={self.key})'
def __str__(self):
"""Return a human friendly string of this object."""
return f'{self.__class__.__name__}: {self.data}'
def __eq__(self, other: 'Node'):
"""
Return a boolean determining if self is equal to other.
Args:
other: the other Node to compare to
Returns: self == other
"""
return self.comparable_data == other.comparable_data
def __ne__(self, other: 'Node'):
"""
Return a boolean determining if self is not equal to other.
Args:
other: the other Node to compare to
Returns: self != other
"""
return self.comparable_data != other.comparable_data
def __lt__(self, other: 'Node'):
"""
Return a boolean determining if self is less than other.
Args:
other: the other Node to compare to
Returns: self < other
"""
return self.comparable_data < other.comparable_data
def __le__(self, other: 'Node'):
"""
Return a boolean determining if self is less than or equal to other.
Args:
other: the other Node to compare to
Returns: self <= other
"""
return self.comparable_data <= other.comparable_data
def __gt__(self, other: 'Node'):
"""
Return a boolean determining if self is greater than other.
Args:
other: the other Node to compare to
Returns: self > other
"""
return self.comparable_data > other.comparable_data
def __ge__(self, other: 'Node'):
"""
Return a boolean determining if self is greater than or equal to other.
Args:
other: the other Node to compare to
Returns: self >= other
"""
return self.comparable_data >= other.comparable_data
class Edge(object):
"""An edge connecting two nodes in a graph."""
class Graph(object):
"""A graph of (nodes/vertices) (V) and edges (E)."""
| true |
c2d68bb2d6c3eae21d922ca788b4602dddfb790c | Fabricio-Lopees/computer-science-learning | /exercises/01.python-for-everybody/chapter03/ex03.py | 730 | 4.125 | 4 | # Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message. If the score is between 0.0 and 1.0, print a grade using the following table:
# Score Grade
# >= 0.9 A
# >= 0.8 B
# >= 0.7 C
# >= 0.6 D
# < 0.6 F
# Enter score: 0.95
# A
# Enter score: perfect
# Bad score
# Enter score: 10.0
# Bad score
# Enter score: 0.75
# C
# Enter score: 0.5
# F
try:
score = float(input('Enter a score between 0.0 and 1.0: '));
if score < 0 or score > 1:
print('Bad score.');
elif score >= 0.9:
print('A');
elif score >= 0.8:
print('B');
elif score >= 0.7:
print('C');
elif score >= 0.6:
print('D');
else:
print('F');
except:
print('Bad score.');
exit(); | true |
4a2cf60fe60e01122630dae92d462ce4f746d24c | Fabricio-Lopees/computer-science-learning | /exercises/01.python-for-everybody/chapter08/ex06.py | 605 | 4.21875 | 4 | # Exercise 6: Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after the loop completes.
numbers = [];
while True:
entry = input('Enter a number: ');
if entry.lower() == 'done':
print('Min:',min(numbers),'\nMax:', max(numbers));
break;
else:
try:
entry = float(entry);
numbers.append(entry);
except:
print('Invalid input!');
| true |
de527ed9c511bc40f65a35fc8f1999ca5f72ddad | Fabricio-Lopees/computer-science-learning | /exercises/01.python-for-everybody/chapter07/ex01.py | 260 | 4.375 | 4 | # Exercise 1: Write a program to read through a file and print the contents of the file (line by line) all in upper case. Executing the program will look as follows:
file = open('mbox-short.txt');
for line in file:
line = line.rstrip().upper()
print(line); | true |
4f6ab5925b1006be396f7e3a1af71535962e7d3d | Fabricio-Lopees/computer-science-learning | /exercises/01.python-for-everybody/chapter06/ex01.py | 304 | 4.40625 | 4 | # Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.
string = 'Fabricio';
pos = len(string) - 1;
while pos >= 0:
print(string[pos]);
pos = pos - 1; | true |
0815a783db6c1d47d094d1e69930976b31584fd7 | Nnamdi07/Functions-loops | /Zuri_3.py | 2,593 | 4.25 | 4 | # register
# - first name, last name, password, email
# - generaten user account
# login
# - account number & password
# bank operations
# Initializing the system
import random
database = {
4547365532: ["Nnamdi", "Ijeomah", "nnamdiijeomah90@gmail.com", "passwordA", 200]
} # dictionary
def init():
print("Good Day")
print("******** WELCOME TO BANK ZURI ********")
haveAccount = int(input("Do you have account with us: 1 (yes) 2 (no) \n"))
if haveAccount == 1:
login()
elif haveAccount == 2:
register()
else:
print("You have selected invalid option")
init()
def login():
print("********* Login ***********")
accountNumberFromUser = int(input("What is your account number? \n"))
password = input("What is your password \n")
for accountNumber, userDetails in database.items():
if (accountNumber == accountNumberFromUser):
if (userDetails[3] == password):
bankOperation(userDetails)
print('Invalid account or password')
login()
def register():
print("****** Register *******")
email = input("What is your email address? \n")
first_name = input("What is your first name? \n")
last_name = input("What is your last name? \n")
password = input("create a password for yourself \n")
accountNumber = generationAccountNumber()
database[accountNumber] = [first_name, last_name, email, password]
print("Your Account Has been created")
print(" == ==== ====== ===== ===")
print(f"Your account number is {accountNumber}")
# print("Your account number is: %d" % accountNumber)
print("Make sure you keep it safe")
print(" == ==== ====== ===== ===")
login()
def bankOperation(user):
print("Welcome %s %s " % (user[0], user[1]))
selectedOption = int(input("What would you like to do? (1) deposit (2) withdrawal (3) Logout (4) Exit \n"))
if (selectedOption == 1):
depositOperation()
elif (selectedOption == 2):
withdrawalOperation()
elif (selectedOption == 3):
logout()
elif (selectedOption == 4):
exit()
else:
print("Invalid option selected")
bankOperation(user)
def withdrawalOperation():
print("withdrawal function")
def depositOperation():
print("Deposit Operations")
def generationAccountNumber():
return random.randrange(1111111111, 9999999999)
def logout():
login()
#### ACTUAL BANKING SYSTEM #####
init()
| false |
f0690fbdbc3f65082dc3b57fab129817bfcbc727 | fanxiao168/pythonStudy | /AIDStudy/01-PythonBase/day07/exercise07.py | 318 | 4.34375 | 4 | # 定义一个将序列所有元素打印到终端的功能
# 如 list01 = [1,2,3,4]
# 1 2 3 4
# str = 'abcd'
# 'a' 'b' 'c' 'd'
def print_target(target):
for item in target:
print(item, end=' ')
list01 = [1, 2, 3, 4]
print_target(list01)
str01 = 'abcd'
print_target(str01)
# print(print_target(str01))
| false |
7fce9485e16543b8ec1092ffd2bf0ca9b6e02150 | fanxiao168/pythonStudy | /AIDStudy/01-PythonBase/day12/demo02.py | 1,005 | 4.21875 | 4 | # 老张开自己的车去东北
class Person:
def __init__(self, name):
self.name = name
self.car = Car()
def go_to(self, postion):
# 需要车
print(self.name + '去' + postion)
Car.run()
class Car:
def run():
print('走你~')
lz = Person('老张')
lz.go_to('东北')
ll = Person('老李')
ll.go_to('河南')
'''
class Person:
def __init__(self, name):
self.name = name
self.car = Car(self.name)
def go_to(self, postion, type):
# 需要车
# Car().run()
print(self.name + '去' + postion)
type.run()
# def go_to(self, postion):
# # 需要车
# # Car.run()
# print(self.name + '去' + postion)
class Car:
def __init__(self, owner):
self.owner = owner
def run(self):
print('这是%s的车' % self.owner)
print('走你~')
# c01 = Car('fan')
lz = Person('老张')
ll = Person('老李')
lz.go_to('东北', ll.car)
'''
| false |
e397ec2aecab0ec501f8aa21c1bc24eadfe94ef9 | fanxiao168/pythonStudy | /AIDStudy/01-PythonBase/day02/demo02.py | 463 | 4.21875 | 4 | """
变量:在内存中存储的数据
"""
#语法
#变量名 = 对象
name = '张无忌'
age = 20
#内存图
#变量名 对象内存地址的别名
#见名知意
#第一次使用变量 先创建对象然后用变量名绑定
#再次对同名的变量赋值时 不会创建新的变量
name = '周芷若'
name1 = name2 = '赵敏'
print(name)
print(name1)
print(name2)
teacher1, teacher2 = '老王','小郭'
#画内存图
print(teacher1)
print(teacher2)
| false |
c139402ebeee53ad4731e14f2332698e9cbc1f74 | fanxiao168/pythonStudy | /AIDStudy/01-PythonBase/day02/demo04.py | 660 | 4.15625 | 4 | """
数据类型转换
"""
# 接受用户的输入
str_dol = input('请输入美元:')
# 处理业务逻辑
# 将str_dol转换为整形
# int()只能转换数字类型的字符串
int_dol = int(str_dol)
# 整数和浮点数运算 结果会自动转为浮点数
result = int_dol * 6.9 # 10*6.9 = 69.0
# 显示结果
str_result = str(result)
print('转换人民币的结果是:' + str_result)
# 任意数据类型转换为布尔类型时
# 如果有值就为True 没有值就为False
# 字符串中包含空白字符 True
print(bool(' '))
print(bool('')) # 空字符串 False
print(bool(0)) # False
print(bool(0.0)) # False
print(bool(None)) # False
| false |
2145b5ef4e5aa52bba552447d28c39cea9eaf774 | fanxiao168/pythonStudy | /AIDStudy/01-PythonBase/day13/exercise02.py | 519 | 4.125 | 4 | # 定义车类 数据(品牌 速度) 行为 跑
# 定义电动车 电动车(品牌 速度 电池容量) 行为跑
# 画内存图
class Car:
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed
def run(self):
print('走你')
class Electrocar(Car):
def __init__(self, branch, speed, battery):
super().__init__(branch, speed)
self.battery = battery
c01 = Car('奔驰', 230)
c01.run()
e01 = Electrocar('BYD', 120, 15000)
e01.run()
| false |
488009397276beea5f96c60d00104302abf39e39 | fanxiao168/pythonStudy | /AIDStudy/01-PythonBase/day17/demo02.py | 2,154 | 4.21875 | 4 | '''
迭代器 ---> yield
练习:exercise04.py
目标:让自定义类所创建的对象,可以参与for.
iter价值:可以被for
next价值:返回数据/抛出异常
class 自定义类的迭代器:
def __next__(self):
pass
class 自定义类:
def __iter__(self):
pass
for item in 自定义类():
pass
'''
class SkillIterator:
def __init__(self, data):
self.__target = data
self.__index = -1
def __next__(self):
# 如果没有数据则抛出异常
if self.__index >= len(self.__target) - 1:
raise StopIteration
# 返回数据
self.__index += 1
return self.__target[self.__index]
class SkillManager:
'''
技能管理器 可迭代对象
'''
def __init__(self):
self.__skills = []
def add_skill(self, str_skill):
self.__skills.append(str_skill)
def __iter__(self):
# return SkillIterator(self.__skills)
# 执行过程:
# 1. 调用__iter__()不执行
# 2. 调用__next__()才执行当前代码
# 3. 执行到yield语句暂时离开
# 4. 再次调用__next__()继续执行
# ....
# yield作用: 标记着下列代码会自动转换为迭代器代码。
# 转换大致过程:
# 1. 将yield关键字以前的代码,放到next方法中
# 2. 将yield关键字后面的数据,作为next返回值
# print('准备数据:')
# yield '降龙十八掌'
#
# print('准备数据:')
# yield '黑虎掏心'
#
# print('准备数据:')
# yield '六脉神剑'
for item in self.__skills:
yield item
manager = SkillManager()
manager.add_skill('降龙十八掌')
manager.add_skill('黑虎掏心')
manager.add_skill('六脉神剑')
# 错误:manager必须是可迭代对象__iter__()
for item in manager:
print(item)
iterator = manager.__iter__()
while True:
try:
item = iterator.__next__()
print(item)
except StopIteration:
break
| false |
168ba19bcb9bb7e175f136f2f188f58172e98ce8 | fanxiao168/pythonStudy | /AIDStudy/01-PythonBase/day08/exercise02.py | 1,009 | 4.15625 | 4 | # 定义列表升序排列函数(从小到大)
# list01 = [1,5,13,2,4]
# 思路
# 用第一个与后面元素比较 只要发现比第一个小的就换位置
# 用第二个元素与后面的比较
# ...
# 用倒数第二个元素与后面比较
# r 0 1 2 3
# [5,6,13,2,4] 第一遍
# [2,6,12,5,4]
# [2,5,12,6,4]
# [2,4,12,6,5]
# [2,4,6,12,5]
# [2,4,5,12,6]
# [2,4,5,6,12]
# 循环的次数 取值 第一个值 第二个值
def mysort(list):
# len(list)-1 最后一个数据 后面没有值了 不需要再比较
for r in range(len(list) - 1):
# 从当前数据的位置+1(下一个数据)开始 一直逼到最后
for c in range(r + 1, len(list)):
# 如果当前数据比后面的数据大 交换位置
if list[r] > list[c]:
list[r], list[c] = list[c], list[r]
list01 = [6, 5, 13, 2, 4]
mysort(list01)
print(list01)
list02 = [1, 7, 2, 55, 40]
mysort(list02)
print(list02)
| false |
106ddd3f459bba4bfde25ee4a0411b3a35938c74 | DumbMachine/CS6-Py | /EXP4/exp4_8.py | 593 | 4.21875 | 4 | #Printing the loan
#Entry from user
amount=int(input("Enter the Loan Amount : "))
period=int(input("Enter the Loan Period (in years) : "))
interest=5.0 #interest
pay=0.0 #Total Amount Which is to be paid
monthly_pay=0.0 #Total monthly amount tobe paid
total_Pay=0.0 #Total Pay
print("Rate\tMonthly_Pay\tTotal_Pay") #Output
while(interest<=8):
pay=(amount*interest*period)/100
total_pay=pay+amount
monthly_pay=total_pay/12
print(interest,"\t",round(monthly_pay,3),"\t",round(total_pay,3))
interest=interest+(1/8)
| true |
0347acd81fb3fb2ab634a5b30581eaa5a2e48831 | DumbMachine/CS6-Py | /EXP4/exp4_9.py | 416 | 4.1875 | 4 | amount=int(input("Enter the Loan Amount : "))
years=int(input("Enter the Years : "))
rate=int(input("Enter the Interest Rate : "))
balance=amount
monthlyPayment=amount/12
print("Month\t\tInterest\t\tPrincipal\t\tBalance")
for i in range(1,years*12+1):
interest=rate*balance
principal=monthlyPayment-interest
balance=balance-principal
print(i,"\t\t",interest,"\t\t",principal,"\t\t",balance) | true |
59592d84b71952a30aec6742ad080dd8d153e029 | Abhinavnj/leetcode-solutions | /group-anagrams.py | 851 | 4.125 | 4 | def groupAnagrams(strs):
"""
strs: List[str]
rVal: List[List[str]]
T: O(n)
"""
# Values of 'groups' are the lists of words that are anagrams
# corresponding to the alphabetically sorted version of each word.
groups = {}
for w in strs:
# Set 'key' equal to the sorted version of the string
key = ''.join(sorted(w))
# **Could also use tuple as key since 'list' is not hashable
# key = tuple(sorted(w))
# Set the value at this key as the words that match it when
# they are sorted. The words are stored in a list, which is
# the value.
groups[key] = groups.get(key, []) + [w]
# The values of the dictionary are stored in a list, which is a
# list of lists containing the anagram groups in this case.
return groups.values() | true |
68dd81f3d1795f4025af04a8879a50baabf7ca32 | Javenkm/User-Bank-Account | /userBankAccount.py | 2,112 | 4.125 | 4 | class BankAccount:
def __init__(self, int_rate, balance): # don't forget to add some default values for these parameters!
# your code here! (remeber, this is where we specify the attributes for our class)
# don't worry about user info here; we'll involve the User class soon
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount): # increases the account balance by the given amount
self.balance += amount
return self
def withdraw(self, amount): # decreases the account balance by the givena amount if there are sufficient funds; if there is not
if self.balance >= amount:
self.balance -= amount
elif self.balance < amount:
print("Insuffucient funds: Charging a $2.50 fee")
self.balance -= 2.50
return self
def display_account_info(self):
print(f"Balance: ${self.balance}")
def yield_interest(self):
self.balance = self.balance * self.int_rate + self.balance
return self
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account = BankAccount (int_rate = 0.011, balance = 0)
# self.account2 = BankAccount ("savings", int_rate = 0.02, balance = 0) would use this to add separate account
def transfer_money(self, amount, other_user):
self.account.balance = self.account.balance - amount
other_user.account.balance = other_user.account.balance + amount
print(f"Name: {self.name} transferred {amount} dollars to {other_user.name}")
return self
def display_account_info(self):
print(f"Name: {self.name}, {self.account.display_account_info()}")
return self
Javen = User("Javen", "javenkm@gmail.com")
Israel = User("Israel", "Broheim@codingdojo.com")
Ella = User("Ella", "Ellaisawesome@codingdojo.com")
Javen.account.deposit(105000)
Javen.display_account_info()
Israel.account.deposit(5380)
Israel.display_account_info()
Ella.account.deposit(1300)
Ella.display_account_info()
Javen.transfer_money(1000, Israel)
Israel.display_account_info() | true |
926e494ec9458a86479099982268335650cf34fd | leehyowonzero/gawebawebo-sos | /gawebawebo.py | 1,808 | 4.40625 | 4 | """
This is a rock paper scissors game
==================================
chapter 1 ... RULE!!!
==================================
We play 10 games with Computer!!!
end of the game We print your score
and computer's score !!!
Have a nice game ~~~~
"""
import random
player_score = 0
computer_score = 0
play = True
n = 0
while play :
if n == 10:
break
#player_choice
player = input("Enter your choice (rock/paper/scissors): ")
player = player.lower()
while (player != "rock" and player != "paper" and player != "scissors"):
player = input("Enter your choice (rock/paper/scissors): ")
player = player.lower()
#computer_random
computer = random.randint(1,3)
if (computer == 1):
computer = "rock"
print("comper's choise : rock" )
elif (computer == 2):
computer = "paper"
print("comper's choise : paper" )
elif (computer == 3):
computer = "scissors"
print("comper's choise : scissors" )
else:
print ("Error. Enter your choice from rock, paper, scissors.")
#result
if (player == "rock"):
if (computer == "paper"):
computer_score += 1
if (computer == "scissors"):
player_score += 1
elif (player == "paper"):
if (computer == "rock"):
player_score += 1
if (computer == "scissors"):
computer_score += 1
elif (player == "scissors"):
if (computer == "rock"):
computer_score += 1
if (computer == "paper"):
player_score += 1
n += 1
print(player_score,":",computer_score)
if(player_score>computer_score):
print("player win!")
if(player_score==computer_score):
print("draw...")
if(player_score<computer_score):
print("coputer win!")
| true |
b1dfc72c7798004d83d453a11c5a55adf369cf7b | prashanth-ds/DevOps | /UnitTesting.py | 1,567 | 4.21875 | 4 | import unittest
from Calculator import Calculator
class UnitTesting(unittest.TestCase):
def setUp(self):
self.addition = Calculator("10+15")
self.subtraction = Calculator("10-5")
self.multiplication = Calculator("11*11")
self.multiple_operands = Calculator("1+2+3")
self.multiple_operators = Calculator("2+2*5")
self.invalid_operator = Calculator("2/2")
print("This is Evaluation on 30th august")
def test_add(self):
addition = self.addition.evaluate()
self.assertEqual(addition, 25, f"Addition is {addition}")
def test_sub(self):
subtraction = self.subtraction.evaluate()
self.assertEqual(subtraction, 5, f"Subtraction is {subtraction}")
def test_mul(self):
multiplication = self.multiplication.evaluate()
self.assertEqual(multiplication, 121, f"Multiplication is {multiplication}")
def test_operands(self):
multiple_operands = self.multiple_operands.evaluate()
self.assertEqual(multiple_operands, 'Same Operator Used More than once', 'Same Operator Used More than once')
# def test_MultipleOperator(self):
# multiple_operators = self.multiple_operators.evaluate()
# self.assertEqual(multiple_operators, 'Operators Used Multiple times', 'Operators Used Multiple times')
# def test_operator(self):
# invalid_operator = self.invalid_operator.evaluate()
# self.assertEqual(invalid_operator, 'Operator Invalid', 'Operator Invalid')
if __name__ == '__main__':
unittest.main()
| true |
5f6797b83a31490fc810a4b1166c1c493eacb966 | etasycandy/Python | /Workshop5/Exercise_page145/Exercise_04_page_145.py | 474 | 4.1875 | 4 | """
Author: Tran Dinh Hoang
Date: 07/08/2021
Program: Exercise_04_page_145.py
Problem:
4. What is a mutator method? Explain why mutator methods usually return the value None.
* * * * * ============================================================================================= * * * * *
Solution:
Display result:
95
"""
data = [21, 12, 20, 5, 26, 11]
# print(sum(data))
total = 0
for value in data:
total += value
print(total)
| true |
95d6dcd12399be4abdc5ad634ebae1538d35a5cd | etasycandy/Python | /Workshop4/Exercise_page125/Exercise_01_page_125.py | 811 | 4.21875 | 4 | """
Author: Tran Dinh Hoang
Date: 31/07/2021
Program: Exersice_01_page_125.py
Problem:
1. Write a code segment that opens a file named myfile.txt for input and prints the number of lines in the file.
* * * * * ============================================================================================= * * * * *
Solution:
Display result:
Content first 5 characters: Hoàng
"""
textFile = open("../fileTest/myfile.txt", 'w', encoding='utf-8')
textFile.write("Hoàng là nhất"
"\nFirst line"
"\nSecond line"
"\nThird line")
textFile = open("../fileTest/myfile.txt.txt", 'r', encoding='utf-8')
print(textFile)
count = 0
for line in textFile:
count += 1
print("The number of lines: ", count)
textFile.close()
| true |
1bd0168a2ecbcbea039c1ff5000c669dc77b9a20 | etasycandy/Python | /Workshop3/Exercise_page73/Exercise_02_page_73.py | 391 | 4.21875 | 4 | """
Author: Trần Đình Hoàng
Date: 17/07/2021
Program: Exercise_02_page_73.py
Problem:
2. Write a code segment that displays the values of the integers x, y, and z on a single
line, such that each value is right-justified with a field width of 6.
Solution:
Display result:
123 234 432
"""
x = 123
y = 234
z = 432
print("%6s %6s %6s" % (x, y, z))
| true |
c6d9e63b81115c0185e73a6e2a7018a58e4388b7 | etasycandy/Python | /Workshop3/Project_page_99-101/project_02_page99.py | 1,044 | 4.46875 | 4 | """
Author: Trần Đình Hoàng
Date: 17/07/2021
Program: project_02_page99.py
Problem:
2. Write a program that accepts the lengths of three sides of a triangle as inputs.
The program output should indicate whether or not the triangle is a right triangle.
Recall from the Pythagorean theorem that in a right triangle, the square of one side
equals the sum of the squares of the other two sides.
Solution:
Display result:
Enter the lengths of three sides of a triangle:
Edge A = 3
Edge B = 4
Edge C = 5
Is a right triangle
"""
print("Enter the lengths of three sides of a triangle: ")
a = int(input("Edge A = "))
b = int(input("Edge B = "))
c = int(input("Edge C = "))
if a + b > c and b + c > a and a + c > b:
if pow(a, 2) == pow(b, 2) + pow(c, 2) or pow(b, 2) == pow(a, 2) + pow(c, 2) or pow(c, 2) == pow(b, 2) + pow(a, 2):
print("Is a right triangle")
else:
print("Not a right triangle")
else:
print("Not a triangle")
| true |
22453bdf9e8e69d67aef0269e9050c7cef05da9f | etasycandy/Python | /Workshop6/Exercise_page182/Exercise_01_page_182.py | 808 | 4.34375 | 4 | """
Author: Tran Dinh Hoang
Date: 30/08/2021
Program: Exercise_01_page_182.py
Problem:
1. In what way is a recursive design different from top-down design?
* * * * * ============================================================================================= * * * * *
Solution:
Result:
- The first priority point is to approach solving problems with clean, neat, easy to read and
understand code. The disadvantage of binding is the high-level memory (stack) Stack as explained
above.
- Although the top-down design has the advantage that we will not have to worry about the problem
of Stack overflow. But it also has a disadvantage compared to recursion that the processing code
will be longer and more complex.
""" | true |
867e07a73ae2ad1a2d5741dcee434f6f738a7345 | TanyoTanev/SoftUni---Python-Advanced | /ADV_Comprehensions - 06.Bunker.py | 1,760 | 4.21875 | 4 | '''
6. Bunker
Using comprehension write a program that finds all the amount of all items in a bunker and their average quantity.
On the first line you will be given all the categories of items in the bunker, then you will be given a number (n). On
the next "n" lines you will be given items in the following format: "{category} - {item_name} -
quantity:{item_quantity};quality:{item_quality}". Store that information, you will need it later. After
you received all the inputs, print the total amount of items (sum the quantities) in the format: "Count of
items: {count}". After that print the average quality of all items in the format: "Average quality:
{quality - formatted to the second digit}". Finally, print all of the categories with the items on
separate lines in it in the format: "{category} -> {item1}, {item2}…". For more clarification, see the
example below.
'''
categories = input().split(', ')
N = int(input())
bunker = {category: {} for category in categories}
for _ in range(N):
command = input().split(' - ')
items_info = command[2].split(';')
quantity = int(items_info[0].split(':')[1])
quality = int(items_info[1].split(':')[1])
category = command [0]
item = command[1]
if command[0] in bunker:
bunker[category][item] = {'quantity': quantity, 'quality': quality}
#print(bunker)
count_quantity = [ bunker[key][y]['quantity'] for key in bunker for y in bunker[key] ]
count_quality = [ bunker[key][y]['quality'] for key in bunker for y in bunker[key] ]
print( f"Count of items: {sum(count_quantity)}")
print(f"Average quality: {sum(count_quality)/len(bunker):.2f}")
[print(f"{key} -> {', '.join(bunker[key].keys())}") for key in bunker.keys()] | true |
067cd409bf513de6c39b7a59cbc9375c9a81eb44 | TanyoTanev/SoftUni---Python-Advanced | /ADV_Comprehensions - 03.Diagonals.py | 1,157 | 4.3125 | 4 | '''3. Diagonals
Using nested list comprehension write a program that reads NxN matrix, finds its diagonals, prints them and their
sum as shown below.
'''
'''N = int(input())
matrix = []
diagonal_main = []
diagonal_second = []
def matrix_diagonals(matrix):# diagonal_main, diagonal_second ):
for row in range(len(matrix)):
diagonal_main.append(matrix[row][row])
diagonal_second.append(matrix[row][len(matrix)-row-1])
return diagonal_main, diagonal_second
for _ in range(N):
matrix.append(list(map(int, input().split(', '))))
diagonals = matrix_diagonals(matrix)
print(sum(diagonals[0]))
print(diagonals[1])'''
N = int(input())
matrix = []
diagonal_main = []
diagonal_second = []
matrix = [list(map(int, input().split(', '))) for _ in range(N)]
diagonal_main = [ matrix[row][row] for row in range(len(matrix))]
diagonal_second = [(matrix[row][len(matrix) - row - 1]) for row in range(len(matrix))]
print(f"First diagonal: {', '.join([str(x) for x in diagonal_main])}. Sum: {sum(diagonal_main)}")
print(f"Second diagonal: {', '.join([str(x) for x in diagonal_second])}. Sum: {sum(diagonal_second)}") | true |
1faf3ac1f4fb77179e3e0198eb7f12771a8b7f19 | TanyoTanev/SoftUni---Python-Advanced | /ADV_Tuples and sets - 06.Longest Intersection.py | 1,149 | 4.28125 | 4 | '''6.
Write a program that finds the longest intersection. You will be given a number N. On the next N lines you will be given two ranges in the format:
"{first_start},{first_end}-{second_start},{second_end}". Find the intersection of these two ranges and save the longest one of all N intersections.
At the end print the numbers that are included in the longest intersection and its length in the format:
"Longest intersection is {longest_intersection} with length {length_longest_intersection}"
Note: in each 2 ranges there will always be intersection. If there are two equal intersections, print the first one.
'''
count = int(input())
set_4 = set()
for i in range(count):
command = input().split('-')
first_beg, first_end = command[0].split(',')
second_beg, second_end = command[1].split(',')
set_1 = set(range(int(first_beg), int(first_end)+1))
set_2 = set(range(int(second_beg), int(second_end) + 1))
set_3 = set_1.intersection(set_2)
longest = len(set_3)
if len(set_3) > len(set_4):
set_4 = set_3
#print(set_1)
#print(set_4)
print(f"Longest intersection is {list(set_4)} with length {len(set_4)}") | true |
ea90b5df59ee7daada02915ba3731dd82935e978 | TanyoTanev/SoftUni---Python-Advanced | /ADV_Comprehensions - 01.Words Lengths.py | 584 | 4.40625 | 4 | '''
Using list comprehension, write a program that receives some strings separated by comma and space ", " and
prints on the console each string with its length in the format: "{first_str} -> {first_str_len},
{second_str} -> {second_str_len}…"
'''
#string_list = input().split(', ')
#list1 = []
#for i in range(len(string_list)):
# list1.append(f"{string_list[i]} -> {len(string_list[i])}")
#print(', '.join(list1))
#print([(f"{i} -> {len(i)}") for i in (input().split(', '))])
print(', '.join([(f"{i} -> {len(i)}") for i in (input().split(', '))])) | true |
523d5a682363fa4b0ad6807d38a9d69bbee4e389 | KantiMRX/calculator | /calc.py | 496 | 4.1875 | 4 | print("პროგრამა შექმნილა Kanti-ის მიერ, ისიამოვნეთ.")
x = "symbols"
x = float(input("შეიტანეთ x: "))
oper = input("აირჩიეთ ოპერაცია: +, -, /, * ...> ")
y = float(input("აირჩიეთ y: "))
if oper == "+":
print(x + y)
elif oper == "-":
print(x - y)
elif oper == "/":
print(x / y)
elif oper == "*":
print(x * y)
else:
print("შეცდომა")
| false |
25c115c8e95113ce345c35371a8c256387e64564 | marclen/Python | /maximumConsecutiveSequence.py | 2,712 | 4.28125 | 4 | # Determining the maximum number of sequential numbers in a list
# Using a loop in a loop, as we need to iterate through a list while keeping track of all the sequential numbers
# Outer loop keeps track of where we currently are in the loop and instantiates sequence details
# Inner loop keeps track of sequence details and records them
# I wanted to record the details of each sequence, so I created an object and recorded them in a list
class Sequence:
def __init__(self, minimum_value, maximum_value, length):
self.minimum_value = minimum_value
self.maximum_value = maximum_value
self.length = length
provided_list = [5, 2, 99, 3, 4, 1, 100, 11, 9, 14, 12, 10, 13, 15]
# code works whether your sort it or not of course
provided_list.sort()
sequence_list = []
loop_count = 0
while loop_count < len(provided_list):
current_minimum_value = provided_list[loop_count]
current_maximum_value = provided_list[loop_count]
sequence_bool = False
current_sequence_length = 0
if loop_count == len(provided_list) - 1:
# you're at the last value, don't think anything needs to be done here
break
# code to determine if the next item in list is a sequential number, and iterates until it no longer is
elif provided_list[loop_count + 1] - provided_list[loop_count] == 1:
sequence_bool = True
# Keeps iterating until the next number is not sequential OR you're at the end of the list
while sequence_bool and loop_count < len(provided_list):
current_sequence_length += 1
if current_minimum_value > provided_list[loop_count]:
current_minimum_value = provided_list[loop_count]
if current_maximum_value < provided_list[loop_count]:
current_maximum_value = provided_list[loop_count]
if loop_count == len(provided_list) - 1:
# We want to be in here when we're at the last digit to record sequence information
# but we need to break before the next if statement, because it will throw out of range exception
break
if provided_list[loop_count + 1] - provided_list[loop_count] != 1:
sequence_bool = False
loop_count += 1
# recording sequence details
sequence_list.append(Sequence(current_minimum_value, current_maximum_value, current_sequence_length))
else:
loop_count += 1
sequence_list.sort(key=lambda x: x.length, reverse=True)
for i in sequence_list:
print(f'Sequence: Run: {i.length}, Min: {i.minimum_value}, Max: {i.maximum_value}')
| true |
ae2539e23feac594064b8b9ab013b44a482c8c67 | manasRK/algorithms-practice | /hackerrank/nlp/paragraphs-to-sentences.py | 953 | 4.1875 | 4 | """
https://www.hackerrank.com/challenges/from-paragraphs-to-sentences
BRIEF:
Sentence segmentation, means, to split a given paragraph of text into sentences, by identifying the sentence boundaries. In many cases, a full stop is all that is required to identify the end of a sentence, but the task is not all that simple.
This is an open ended challenge to which there are no perfect solutions. Try to break up given paragraphs into text into individual sentences. Even if you don't manage to segment the text perfectly, the more sentences you identify and display correctly, the more you will score.
Achieved Score: 29.38/40
"""
import re
S = raw_input().strip()
chars = re.findall('\W+|\w+',S)
puncs = ["!", ".", "?"]
print chars
sent = ""
sentences = []
for char in chars:
if char.strip() in puncs:
sent+=char
sentences.append(sent)
sent=""
else:
sent+=char
for s in sentences:
print s.strip()
| true |
19f88c2f8672ad03c83d3ebd31dd276b1508ba83 | kuntalnr/python | /lists_and_listsfunctions.py | 859 | 4.28125 | 4 | grocery = ["harpic", "vim bar", "deodrant", "bhindi", "lollypop", 56] # creates a list
# print(grocery)
# accesing the list
# print(grocery[0])
# numbers = [2, 7, 9, 11, 3]
# numbers.sort() # sorts the number
# numbers.reverse() # reverses the number
# print(numbers[::])
# print(len(numbers))
# print(max(numbers))
# print(numbers.append(7)) # add 7 at the end
# numbers.insert(1, 45) # insert 45 at 1 index
# numbers.remove(9) # removes a number (not index)
# numbers.pop() # removes the last element
# print(numbers)
# numbers = [] # create a blank list
# numbers[1] = 98
# print(numbers)
# mutable - can change (mutable); imutable - cannot change (for e.g. tuple)
# tp = (1, 2, 3) # creates a tupple. cannot be changed
# tp = (1, ) # for a single object tupple, add an exteaa column
# print(tp)
a = 1
b = 1
a, b = b, a # interchanges the values of a and b | true |
9aa0a86f4599bde2d04e4fa0b4ed5a0e41e16e31 | NandoTheessen/Python-Fundamentals | /Dictionaries/dicts.py | 1,915 | 4.4375 | 4 | '''A script showing examples of how to mutate list'''
m = [9, 15, 24]
def modify(k):
'''appends the item 39 to given list
Args:
list k
'''
# In this case the original list gets mutated as we are only passing it's
# reference into the modify function
k.append(39)
print("k =", k)
f = [14, 23, 37]
def replace(g):
'''This function "replaces" the object g
correctly, you'd say "this function moves the reference pointer of
variable g to the newly defined array!"
Args:
list g
'''
# This function does not actually replace our passed array, as the
# reassignment below simply moves the reference for g (orginally on our
# passed in array) to the newly defined array
g = [17, 28, 45]
print("g =", g)
def banner(message, border='-'):
'''Function showing off the default value for arguments
printing a border with the given sign that is as long
as the message passed in to the function!
Args:
message: A message the user wants printed
border: the char that the user wants used for the border
default is "-"
returns:
prints the message acompagnied by 2 borders top & bottom
'''
line = border * len(message)
print(line)
print(message)
print(line)
def add_spam(menu=None):
'''This function shows the correct use of default values,
which should be immutable and only be replaced in the function
itself to avoid adding to the same default value again and again!
Args:
list of menu items, if provided
returns:
a menu-list'''
if menu is None:
menu = []
menu.append('spam')
return menu
def main():
'''automatically executes all functions within objects.py
when called via cli'''
modify(m)
replace(f)
banner('standard message')
add_spam()
if __name__ == '__main__':
main()
| true |
f5de30c0d4ca9675de683dd3dffb878238ec3838 | PriyadarsiniSivaraj/Assignment_3 | /A3.Q3.py | 380 | 4.34375 | 4 | #Input List
myList = ['Cat','Manhattan','Oncologist','That','Precipitation' ]
#Function to find the longest word in a given list
def longestWord(lst):
longest_word = ""
longest_length = 0
for word in lst:
if len(word)>longest_length:
longest_word = word
longest_length = len(word)
return longest_word
print(longestWord(myList))
| true |
3f8265d3495e091aee6c7f6cea82901b663f7927 | silveira/playground | /python/misc/merge_sort.py | 798 | 4.28125 | 4 | #!/usr/bin/env python
def merge(left, right):
"""
>>> merge([2,3,7], [1,4,5])
[1,2,3,4,5,7]
"""
result = []
i ,j = 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
def mergesort(array):
"""
>>> mergesort([3,1,4,1,5,9,2,6,5])
[1, 1, 2, 3, 4, 5, 5, 6, 9]
"""
if len(array)==0 or len(array)==1:
return array
elif len(array)==2:
if(array[0]>array[1]):
return [array[1], array[0]]
else:
return array
else:
mid = len(array)/2
left = mergesort(array[:mid])
right = mergesort(array[mid:])
return merge(left, right)
if __name__=="__main__":
# print merge([2,3,7], [1,4,5])
print mergesort([3,1,4,1,5,9,2,6,5])
| false |
807e8df23e0db141e69751b2d37be380fb52c7c8 | silveira/playground | /python/misc/merge_sorted_lists.py | 1,581 | 4.375 | 4 | #!/usr/bin/env python
"""
Problem: merge k sorted lists of size up to n.
Solution: two approaches, functions merge_and_sort and merge_many.
"""
"""
A trivial solution, put all lists together and sort it.
Time complexity: O(log(nk))
( without making any assumptions about how the python's sort take advantage of
pre-sorted ranges in the list )
"""
def merge_and_sort(lists):
retlist = []
for list in lists:
retlist.extend(list)
retlist.sort()
return retlist
"""
Merge two sorted lists in a sorted list.
This function is used by the function merge_many.
Time complexity: O(len(first)+len(second))
"""
def merge_two(first, second):
merged = []
i = 0
j = 0
while i<len(first) and j<len(second):
if first[i]==second[j]:
merged.append(first[i])
merged.append(second[j])
i += 1
j += 1
elif first[i]>second[j]:
merged.append(second[j])
j += 1
else:
merged.append(first[i])
i += 1
if i==len(first):
merged.extend(second[j:])
break
if j==len(second):
merged.extend(first[i:])
break
return merged
"""
Merge sorted lists, two by two.
Time complexity: O(nlog(k))
"""
def merge_many(lists):
queue = lists[:]
while(len(queue)>1):
first = queue.pop(0)
second = queue.pop(0)
queue.append(merge_two(first, second))
return queue.pop(0)
if __name__ == '__main__':
print merge_and_sort([[2,10,30,40],[9,11],[3,5,9,10]])
print merge_many([[2,10,30,40],[9,11],[3,5,9,10]])
| true |
6fd79fb09956a634e964ad980c3f9e4d5b98d2d3 | oibe/Interview-Questions | /regex.py | 1,590 | 4.5625 | 5 | """
Implement a simple regex parser which, given a string and a pattern, returns a boolean indicating whether the input matches the pattern. By simple, we mean that the regex can only contain one special character: * (star). The star means what you'd expect, that there will be zero or more of any character in that place in the pattern. However, multiple consecutive stars are allowed. Some examples of valid input (and expected output):
f(a*b, acb) => true
f(abc*, abbc) => false
f(**bc, bc) => true
"""
def match(pattern, text):
if pattern == "" and text != "":
return False
if pattern != "" and text == "":
return False
if pattern == "" and text == "":
return True
# matches will be printed in reverse order
# because recursion makes the last matches
# print first.
if pattern[0] == text[0]:
result = match(pattern[1:], text[1:])
# if result:
# print "matched %s" % text[0]
return result
elif pattern[0] == "*":
for i in range(len(text) + 1):
result = match(pattern[1:], text[i:])
# if result:
# print "matched %s" % text[:i]
if result:
return True
return False
def print_match_result(pattern, text):
print "%s, %s = %s" % (pattern, text, match(pattern, text))
print_match_result("a*b", "acb")
print_match_result("abc*", "abbc")
print_match_result("**bc", "bc")
print_match_result("ba**", "badfg")
print_match_result("abc", "abcdef")
print_match_result("abcdef", "abc")
print_match_result("", "")
| true |
301986fa28db9c2dc6dd88a50f97c8d025f3af51 | Kimbsy/project-euler | /python/problem_009.py | 491 | 4.375 | 4 | import math
"""A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
target = 1000
for i in range(1, target):
for j in range(i, target):
sum_of_squares = math.pow(i, 2) + math.pow(j, 2)
k = math.sqrt(sum_of_squares)
if i + j + k == target:
print(int(i * j * k))
| true |
5cadb7e9d3d2226d6babe292e8017772ace4472b | wanng-ide/Algorithms-and-Data-Structures | /insertion_sort.py | 361 | 4.15625 | 4 | def insertion_sort(array):
length = len(array)
if length <= 1:
return array
for i in range(1, length):
flag = array[i]
j = i- 1
while j>=0 and array[j]>flag:
array[j+1] = array[j]
j -= 1
array[j+1] = flag
return array
test_array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
insertion_sort(test_array)
print(test_array) | true |
611c151f700d3aa222864a68e7c3dfd27cb681b9 | asarama/python_workspace | /closures and decorators/decorators.py | 2,941 | 4.21875 | 4 | import functools
# Example 1
# Apply a decorator which updates the return logic for all function below
def escape_unicode(function_reference):
def wrap(*args, **kargs):
function_return = function_reference(*args, **kargs)
return ascii(function_return)
return wrap
@escape_unicode
def vegetable():
return 'carrot'
@escape_unicode
def animal()
return 'cat'
@escape_unicode
def mineral():
return 'limestone'
# Example 2
# Classes can be used as decorators as well. Here when we use the say_hello method the dunder call method of our CallCount class is executed.
# Using classes to decorate functions can add attributes to the function definition. Here we add the count attribute which keeps track of how many
# times it's function is called.
class CallCount:
def __init__(self, function_reference)
self.function_reference = function_reference
self.count = 0
def __call__(self, *args, **kargs):
self.count += 1
return self.function_reference(*args, **kargs)
@CallCount
def say_hello(name):
print(f'Hello {name}')
# say_hello('a')
# Hello a
# say_hello('b')
# Hello b
# say_hello.count
# 2
# Example 3
# Class instances can also be used as decorators. They instead need the function reference in the dunder call method.
# This gives more flexibility to the decorator since we can set and mutate class parameters.
# To turn off tracing in this example all we need to do is set tracer.enabled = False
class Trace:
def __init__(self, enabled = True):
self.enabled = enabled
def __call__(self, function_reference):
def wrap(*args, **kargs):
if self.enabled:
print(f'Tracing {function_reference}')
print(f'args {args}')
print(f'kargs {kargs}')
return function_reference(*args, **kargs)
return wrap
tracer = Trace()
@tracer
def some_function(list):
return zip(*list)
# Example 4
# Maintaining function attributes
def some_decorator(function_reference):
def wrap(*args, **kargs):
return function_reference(*args, **kargs)
wrap.__name__ = function_reference.__name__
wrap.__doc__ = function_reference.__doc__
return wrap
def some_better_decorator(function_reference):
@functools.wraps(function_reference)
def wrap(*args, **kargs):
return function_reference(*args, **kargs)
return wrap
# Example 5
# Simple decorator factory
def check_even(parameter_index):
def validator(function_reference):
@functools(function_reference)
def wrap(*args, **kargs):
return function_reference(*args, **kargs)
if args[parameter_index] % 2 != 0:
raise ValueError(
f'Argument parameter_index must be even.'
)
return wrap
return validator
@check_even(0)
def print_even_only(even_number):
print(even_number) | true |
9cada2bef983f63c5aadf92ffb4b725fb382e35a | vshypko/coding_challenges | /problems/misc/anagrams.py | 1,576 | 4.21875 | 4 | # Note that we can reuse the result from this function after calling it once by saving the data.
# So, there is no need to compute the hashmap each time we call get_capitalized_anagrams.
def get_hashmap(dictionary):
# create a hashmap for each word in dictionary
hashmap = {}
for w in dictionary:
# key is the lowercase sorted word (so that we can assign anagrams to the same bucket)
key = ''.join(sorted(w.lower()))
if key not in hashmap.keys():
hashmap[key] = list()
hashmap[key].append(w.lower())
return hashmap
def get_capitalized_anagrams(word):
# word is a randomly selected word from the English dictionary
# (function written by the colleague)
sorted_word = ''.join(sorted(word.lower()))
capitalized_indices = set()
for i in range(len(word)):
if word[i].isupper():
capitalized_indices.add(i)
# See note above. After the first call to get_hashmap, we can access the saved data
# instead of recomputing every time.
dictionary = list()
# assuming dictionary is English dictionary
# dictionary = EnglishDictionary
# to make sure there are no repetitions (which should not normally happen anyway)
anagrams = list(set(get_hashmap(dictionary)[sorted_word]))
if capitalized_indices:
for i in range(len(anagrams)):
word_list = list(anagrams[i])
for index in capitalized_indices:
word_list[index] = word_list[index].upper()
anagrams[i] = ''.join(word_list)
return anagrams
| true |
9774c509431cac266cab083529c5153c78832c8b | deepakduggirala/leetcode-30-day-challenge-2020 | /April/week-04-day-07-First-Unique-Number.py | 2,515 | 4.15625 | 4 | '''
You have a queue of integers, you need to retrieve the first unique integer in the queue.
Implement the FirstUnique class:
FirstUnique(int[] nums) Initializes the object with the numbers in the queue.
int showFirstUnique() returns the value of the first unique integer of the queue, and returns -1 if there is no such integer.
void add(int value) insert value to the queue.
Example 1:
Input:
["FirstUnique","showFirstUnique","add","showFirstUnique","add","showFirstUnique","add","showFirstUnique"]
[[[2,3,5]],[],[5],[],[2],[],[3],[]]
Output:
[null,2,null,2,null,3,null,-1]
Explanation:
FirstUnique firstUnique = new FirstUnique([2,3,5]);
firstUnique.showFirstUnique(); // return 2
firstUnique.add(5); // the queue is now [2,3,5,5]
firstUnique.showFirstUnique(); // return 2
firstUnique.add(2); // the queue is now [2,3,5,5,2]
firstUnique.showFirstUnique(); // return 3
firstUnique.add(3); // the queue is now [2,3,5,5,2,3]
firstUnique.showFirstUnique(); // return -1
'''
class DLNode:
def __init__(self, v):
self.value = v
self.prev = None
self.next = None
class FirstUnique:
def __init__(self, nums):
self.head = None
self.tail = None
self.set = set()
self.DLHash = {}
for n in nums:
self.add(n)
def showFirstUnique(self):
return self.head.value if self.head is not None else -1
def add(self, value):
if value in self.set: # no longer unique
if value in self.DLHash:
node = self.DLHash.pop(value)
self.remove(node)
else: #unique
self.set.add(value)
new_node = self.add_at_end(value)
self.DLHash[value] = new_node
def add_at_end(self, value):
new_node = DLNode(value)
if self.tail is None:
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
new_node.prev = self.tail
self.tail = new_node
return new_node
def remove(self, node):
if node.prev is None and node.next is None:
self.head = None
self.tail = None
elif node.prev is None: #head
n = node.next
self.head = n
n.prev = None
elif node.next is None: #tail
p = node.prev
self.tail = p
p.next = None
else:
p = node.prev
n = node.next
p.next = n
n.prev = p
obj = FirstUnique([2,3,5])
print(obj.showFirstUnique())
obj.add(5)
print(obj.showFirstUnique())
obj.add(2)
print(obj.showFirstUnique())
obj.add(3)
print(obj.showFirstUnique())
| true |
17e50056b8c62c4ef25f763c52db6105178410d9 | Sh3ddz/PythonDataStructures | /src/TestingDriver.py | 1,499 | 4.1875 | 4 | import DataStructures
linkedList = DataStructures.LinkedList()
linkedQueue = DataStructures.LinkedQueue()
linkedStack = DataStructures.LinkedStack()
node = DataStructures.Node(15)
node2 = DataStructures.Node("SIXTEEN")
node3 = DataStructures.Node(17)
print("------------------LINKED LIST TESTING------------------")
linkedList.add(node)
linkedList.add(node2)
linkedList.add(node3)
linkedList.add(DataStructures.Node(18))
print(linkedList)
print("AT INDEX 1:"+str(linkedList.get(1).getData()))
print("inserting at index 1")
linkedList.insert(DataStructures.Node(20),1)
print(linkedList)
print("AT INDEX 1:"+str(linkedList.get(1).getData()))
print("removing index 1")
linkedList.remove(1)
print(linkedList)
print("removing index 1")
linkedList.remove(1)
print(linkedList)
print("Clearing Linked List")
linkedList.clear()
print(linkedList)
print("------------------LINKED QUEUE TESTING------------------")
linkedQueue.add(node)
linkedQueue.add(node2)
linkedQueue.add(node3)
linkedQueue.add(DataStructures.Node(18))
print(linkedStack)
while(not linkedQueue.isEmpty()):
print("Removing one element from the queue.")
linkedQueue.remove()
print(linkedQueue)
print("------------------LINKED STACK TESTING------------------")
linkedStack.add(node)
linkedStack.add(node2)
linkedStack.add(node3)
linkedStack.add(DataStructures.Node(18))
print(linkedStack)
while(not linkedStack.isEmpty()):
print("Removing one element from the stack.")
linkedStack.remove()
print(linkedStack) | false |
a337d68a82ee905fd8c84493b6a753f71f3b343b | baranmcl/Project_Euler | /23_non_abundant_sums.py | 1,644 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
#For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28,
#which means that 28 is a perfect number.
#A number n is called deficient if the sum of its proper divisors is less than n
#and it is called abundant if this sum exceeds n.
#As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16,
#the smallest number that can be written as the sum of two abundant numbers is 24.
#By mathematical analysis, it can be shown that all integers greater than 28123
#can be written as the sum of two abundant numbers.
#However, this upper limit cannot be reduced any further by analysis
#even though it is known that the greatest number that cannot be expressed as the sum of two abundant
#numbers is less than this limit.
#Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
def abundantCheck(n):
return sum([i for i in xrange(1, int(n/2)+1) if n%i == 0]) > n
def abundantList():
abundantList = []
for i in xrange(12, 28123, 2):
if abundantCheck(i):
abundantList.append(i)
return abundantList
def nonAbundantSum():
abundants = abundantList()
possibleSums = set()
for i in xrange(len(abundants)):
for j in xrange(i, len(abundants)):
if abundants[i]+abundants[j] < 28123:
possibleSums.add(abundants[i]+abundants[j])
return sum([i for i in xrange(28123) if i not in possibleSums])
if __name__ == '__main__':
print(nonAbundantSum())
| true |
425b6403d1ea395942da315914ab70e6b67b5047 | bobpaw/adv-coding | /reverse.py | 250 | 4.15625 | 4 | #!/usr/bin/python3
##
## Reverse inputted text.
## Python 3
## Author: Aiden Woodruff <aiden.woodruff@gmail.com>
##
user_string = input("Gimme some characters: ")
user_list = list(user_string)
for i in range(0, len(user_string)):
print(user_list.pop(), end="")
print()
| true |
1f55eae6adb21e3d22758ad2fb25961633884ea5 | drewblik/Learn | /Lists.py | 354 | 4.1875 | 4 | #how to declare a list
a = [3, 10, -1]
print(a)
a.append(1)
print(a)
#lists can contain numbers and strings
a.append("hello")
print(a)
#list within a list
a.append([1, 2])
print(a)
a.pop() #deletes last item
print(a)
print(a[4])
a[0] = 100
print(a[0])
#practice
b = ["bananna", "apple", "microsoft"]
print(b)
temp = b[0]
b[0] = b[2]
b[2] = temp
print(b) | true |
0dfac2670f77403535ce0b429178ae2bc8f67432 | csula-students/cs4660-fall-2017-OnezEgo | /cs4660/tutorial/lists.py | 798 | 4.28125 | 4 | """Lists defines simple list related operations"""
def get_first_item(li):
"""Return the first item from the list"""
return li[0]
def get_last_item(li):
"""Return the last item from the list"""
i = len(li)
return li[i -1]
def get_second_and_third_items(li):
"""Return second and third item from the list"""
new_li = []
new_li.append(li[1])
new_li.append(li[2])
return new_li
def get_sum(li):
"""Return the sum of the list items"""
# sum = 0.0
# for i in range(len(li)):
# sum += li[i]
# return sum
return sum(li)
def get_avg(li):
"""Returns the average of the list items"""
# sum = 0
# size = len(li)
# for i in range(size):
# sum += li[i]
# return sum/size
return float(get_sum(li)) / len(li) | true |
f851bd4ad6acad8bc7b4ffaf8f6e6a5e79bbabff | aguandstrika/kicksandgiggles | /junkfood.py | 739 | 4.15625 | 4 | # Import Module
from tkinter import *
# create root window
root = Tk()
# root window title and dimension
root.title("junk foods")
# Set geometry(widthxheight)
root.geometry('350x200')
# adding a label to the root window
lbl = Label(root, text="random junk food")
lbl.grid()
# function to display text when
# button is clicked
def clicked():
#a simple junk food seceltor
junk_Food_randomizer = {'Pizza', 'Hot Dog', 'Hamburger'}
for e in junk_Food_randomizer:
print(e)
break
lbl.configure(text=e)
# button widget with red color text
# inside
btn = Button(root, text="Click me",
fg="red", command=clicked)
# set Button grid
btn.grid(column=1, row=0)
# Execute Tkinter
root.mainloop()
| true |
1d8821db13f44212b98864ff8eed10119889f7de | kreinberg/dsviz | /dsviz/decorators/validate_types.py | 828 | 4.21875 | 4 | '''Validate types decorator.'''
def validate_types(allowed_types):
'''A decorator for a data structure's constructor to validate the type of
data being stored.
Args:
allowed_types: A set of allowed types for the data structure.
Raises:
TypeError: If the data type is not supported by the data structure or if
there are missing positional arguments.
'''
def decorator(func):
def check_types(*args):
if len(args) < 3:
raise TypeError('Missing positional arguments: \'name\' and \'data_type\'')
data_type = args[2]
if data_type not in allowed_types:
raise TypeError('Data type is not supported by this data structure.')
return func(*args)
return check_types
return decorator
| true |
c1be67ba3a951437c52250b9bd6ab384e36ac74c | robinson-1985/mentoria_exercises | /lista_ex3.py/exercicio2.py | 565 | 4.125 | 4 | ''' 2. Faça um algoritmo que receba dois números e ao final mostre a soma, subtração,
multiplicação e a divisão dos números lidos.'''
numero1 = int(input('Declare o primeiro número: '))
numero2 = int(input('Declare o segundo número: '))
soma = numero1 + numero2
subtracao = numero1 - numero2
multiplicacao = numero1 * numero2
divisao = numero1 / numero2
print('O resultado da soma é: ', soma)
print('O resultado da subtração é: ', subtracao)
print('O resultado da multiplicação é: ', multiplicacao)
print('O resultado da divisão é: ', divisao) | false |
47f14694d09a90e76bb6532efded3cba801c8193 | robinson-1985/mentoria_exercises | /calculadora_v2.py | 849 | 4.375 | 4 | import sys
# Fazer uma calculadora com as quatro operações.
# This is the input
try:
print("Digite um número: ")
x = input()
x = float(x)
except Exception as error:
print("Voce deve informar apenas numeros")
sys.exit()
try:
print("Digite outro número:")
y = input()
y = float(y)
except Exception as error:
print("Informar apenas numeros")
sys.exit()
print("Escolha uma opção: ")
print("+ - para somar")
print("- - para subtrair")
print("* - para multiplicar")
print("/ - para dividir")
operation = input()
# This is the processing
if operation == "+":
print(x+y)
elif operation == "-":
print(x-y)
elif operation == "*":
print(x*y)
elif operation == "/":
if y != 0:
print(x/y)
else:
print("Operação não permitida \n")
else:
print("Operação Inválida")
| false |
2b06a2382872d264782c7d6757659492771ea24c | elzbietamal95/Python-tutorial | /Midterm_Exam/MidExam_Problem7.py | 492 | 4.21875 | 4 | def dict_invert(d):
'''
d: dict
Returns an inverted dictionary according to the instructions above
'''
inverse_dict = {}
for key in d.keys():
if d[key] in inverse_dict:
inverse_dict[d[key]].append(key)
else:
inverse_dict[d[key]] = [key]
for value in inverse_dict.values():
value.sort()
return inverse_dict
d = {4:True, 2:True, 0:True}
#d = {1:10, 2:20, 3:30, 4:30}
#d = {1:10, 2:20, 3:30}
print(dict_invert(d))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.