blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
818b175d73e30bdb9ea881060e5bdbcad876ae90 | chinnagit/python | /iterator.py | 648 | 3.859375 | 4 | class Iterator:
def __init__(self, list):
self.list = list
# __index will be treated as private variable of class
self.__index = 0
def haxnext(self):
if self.__index < len(list):
return True
else:
return False
def next(self):
value = list[self.__index]
self.__index += 1
return value
if __name__ == '__main__':
print('Iterator implementation')
list = [10, 20, 30, 40, 50]
iter = Iterator(list)
while iter.haxnext() :
# print("index value: ", iter.__index)
iter._somePrivateFunction()
print iter.next()
|
e59ad19d126050d7eac15d5fcf8f816d11cef1ee | serinamarie/CS-Hash-Tables-Sprint | /applications/crack_caesar/crack_caesar.py | 2,324 | 3.765625 | 4 | # Use frequency analysis to find the key to ciphertext.txt, and then
# decode it.
# Unable to solve this one at the moment :/
def crack(filename):
# open file
with open(filename, 'r') as f:
# set string text to variable
string = f.read()
# create an empty dict
letter_dict = {}
# for each character in our string
for letter in string:
# if character is a letter
if letter.isalpha():
# if letter not already in dict
if letter not in letter_dict:
# add new key/value pair
letter_dict[letter] = 1
# if letter in dict
else:
# increase count by 1
letter_dict[letter] += 1
# sort the letter frequencies
letter_frequencies_sorted = sorted(letter_dict.items(), key=lambda x: (-x[1]))
# create a caesar frequency list
caesar_frequency_list = []
for letter_desc in letter_dict.keys():
caesar_frequency_list.append(letter_desc)
real_world_frequencies = ['E', 'T', 'A', 'O', 'H', 'N', 'R', 'I', 'S', 'D', 'L', 'W', 'U', 'G', 'F', 'B', 'M', 'Y', 'C', 'P', 'K', 'V', 'Q', 'J', 'X', 'Z']
# goal: replace current letters in string with real_world letters
# we have caesar frequency list and real world frequency list, both in order
# if a letter in string matches a letter in real world frequency list
# find the real world frequency position (i) and replace it with the corresponding index in the caesar frequency list
# find real world index
for counter, value in enumerate(caesar_frequency_list):
string = string.replace(letter, real_world_frequencies[counter])
return string[:50]
# ID EWKKF WDQSMDU ID JCW JIEW XB XSU
# ET AOHHN
# print(value, real_world_frequencies[counter])
# for letter in string:
# # print(counter, value)
# # find index of letter within caesar freq
# if letter == value:
# print(letter, real_world_frequencies[counter])
# string = string.replace(letter, real_world_frequencies[counter])
if __name__ == '__main__':
print(crack('ciphertext.txt')) |
333e25d8cb6d3650af7e4a3b39b583c8f00254b5 | wargile/learning | /Python/ami_summer_camp/qsort/qsort.py | 789 | 3.734375 | 4 | import random
def qsort(s):
tn = random.randint(0, len(s) -1)
temp = s[tn]
#print(temp,'\n',s)
l = 0
r = len(s) - 1
a = 0
b = len(s) -1
#print(s)
while l <= r :
while s[l] > temp:
l += 1
while s[r] < temp:
r -= 1
if l<= r:
s[l],s[r] = s[r], s[l]
l += 1
r -= 1
#print(temp,' ',s,'\n')
if l < b:
s[l:b+1] = qsort(s[l:b+1])
if r > a:
s[a:r+1] = qsort(s[a:r+1])
#print(s,'\n')
return s
"""def main():
x = 0
s = []
while (x < 10):
s.append(random.randint(1,50))
x += 1
print(s,'\n')
qsort(s)
print(s)
input()
return 0
main()""" |
719c9346cec043c67df51d96c2088f1f274e5ea2 | sqq0216/testLearn | /pythonLearn/program/common/sort.py | 929 | 3.5625 | 4 | # 快速排序 时间复杂度为O(n)或O(n^2)平均时间复杂度为O(nlogn) 空间复杂度O(logn)/O(n)
import random
def qsort(l):
if len(l) < 2:
return l
else:
base = l[0]
left = [ele for ele in l[1:] if ele < base]
right = [ele for ele in l[1:] if ele > base]
return qsort(left) + [base] + qsort(right)
# 冒泡排序 时间复杂度为O(n^2)最佳为O(n)
def boublesort(l):
n = len(l)
for i in range(n):
for j in range(0, n-i-1):
if l[j] > l[j+1] :
l[j], l[j+1] = l[j+1], l[j]
if __name__ == "__main__":
test1 = []
num = random.randint(0,10)
for i in range(num):
test1.append(random.randint(0,5))
print(test1, num)
print(qsort(test1))
# l=[8,4,6,7,3]
# random.shuffle(l)
# boublesort(l)
# for i in range(len(l)):
# print(l[i])
|
33f7622211dd858d9606d55c02e3547bc89fabfd | galidor/PythonTutorialsSourceCode | /Exercise15.py | 293 | 4.28125 | 4 | def reverse_order(input_string):
words = input_string.split()
words = words[::-1]
output_string = ""
for i in words:
output_string = " ".join(words)
return output_string
sample_string = "I like bread but I prefer bananas to it"
print(reverse_order(sample_string)) |
ab8bcda8e43afa9dee575b15a5b6425bb8c1f6ce | ZoranPandovski/al-go-rithms | /math/GCD/Python/GCD_using_Euclidean.py | 252 | 3.875 | 4 | # Python code to demonstrate naive
# method to compute gcd ( Euclidean algo )
def computeGCD(x, y):
while(y):
x, y = y, x % y
return x
a = 60
b= 48
# prints 12
print ("The gcd of 60 and 48 is : ",end="")
print (computeGCD(60,48))
|
e8c3536f621ba78ccddc756b7080969baa481a45 | xCrypt0r/Baekjoon | /src/10/10810.py | 414 | 3.5 | 4 | """
10810. 공 넣기
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 64 ms
해결 날짜: 2020년 9월 16일
"""
def main():
N, M = map(int, input().split())
basket = [0] * N
for _ in range(M):
i, j, k = map(int, input().split())
for x in range(i - 1, j):
basket[x] = k
print(*basket, sep=' ')
if __name__ == '__main__':
main() |
dedb79af4860c6ec72e9ab7f65d5d14cc7608a23 | lettucemaster666/Python3_Bootcamp | /exception.py | 4,075 | 4.40625 | 4 | """
Purpose
-------
Introduction to Exception Handling in Python.
Summary
-------
Exception Handling is used to handle error when a code does not go as planned.
You can give a more specific error message depending on the type of error.
Structure of Exception Handling:
-------------------------------
try:
<code to execute> #Operation code that could potentially raise an exception.
except:
<code to execute> #When an error occurs in try block, print errors and useful messages only.
<code to execute> #If no errors in try block then except block is skipped.
<code to execute> #Can have multiple except blocks. Specific errors is first then generic errors at the bottom.
else:
<code to execute> #If no error in try block, the else block is executed.
finally:
<code to excute> #The code in this block is excuted no matter what happens in try, except, or else block.
"""
#Uncomment to run examples below.
"""
#Example 1: Division by zero error with no error handling.
#Prints a trace back with error "ZeroDivisionError: division by zero".
my_num = 10
division = 10 / 0
"""
"""
#Example 2: Division by zero error with generic error handling.
#Prints "Generic error, not sure what happened".
#This example catches all exception and it is very generic.
my_num = 10
try:
division = my_num / 0
except:
print("Generic error, not sure what happened")
"""
"""
#Example 3: Division by zero error with spefific error handling.
#Prints "Error: the number cannot be divided by 0!"
my_num = 10
try:
division = my_num / 0
except ZeroDivisionError:
print("Error: the number cannot be divided by 0!")
"""
"""
#Example 4: Division by zero error and type error.
#Prints "Error: the value input in my_num should be an integer or float."
#TypeError in the first except block was executed, ZeroDivisionError except block is skipped.
#It only runs an except block if the error matches and ignores the rest of except blocks just like if conditions.
my_num = "a"
try:
division = my_num / 0
except TypeError:
print("Error: the value input in my_num should be an integer or float.")
except ZeroDivisionError:
print("Error: the number cannot be divided by 0!")
"""
"""
#Example 5: Working division example, and else statement
#Prints "This block will execute if try block has no errors."
#The else block is executed when there are no errors in the try block, otherwise, is skipped.
my_num = 4
try:
division = my_num / 2
except TypeError:
print("Error: the value input in my_num should be an integer or float.")
except ZeroDivisionError:
print("Error: the number cannot be divided by 0!")
else:
print("This block will execute if try block has no errors.")
"""
"""
#Example 6: Working division example, else statement, and finally statement.
#Prints "This block will execute if try block has no errors" and "This block will execute no matter if there are exceptions or not."
#The finally block will execute no matter if there are exceptions or not.
my_num = 4
try:
division = my_num / 2
except TypeError:
print("Error: the value input in my_num should be an integer or float.")
except ZeroDivisionError:
print("Error: the number cannot be divided by 0!")
else:
print("This block will execute if try block has no errors.")
finally:
print("This block will execute no matter if there are exceptions or not.")
"""
"""
#Example 7: Division by zero error, type error, else statement, finally statement.
#Prints "This block will execute if try block has no errors." and "This block will execute no matter if there are exceptions or not."
my_num = 1
try:
division = my_num / 0
except TypeError:
print("Error: the value input in my_num should be an integer or float.")
except ZeroDivisionError:
print("Error: the number cannot be divided by 0!")
else:
print("This block will execute if try block has no errors.")
finally:
print("This block will execute no matter if there are exceptions or not.")
""" |
7ad327bdf7d981f3110ef4a14220f9b5a8488487 | cameliahanes/Hangman-Game | /Console.py | 2,477 | 3.578125 | 4 | class Console:
def __init__(self, controller):
self.__controller = controller
def run(self):
print('{: ^30}\n{:^29}\n{: ^32}'.\
format('=Hangman=',' add <sentence>\n play\n', ''))
while True:
try:
inp = input()
arg = self.argumented(inp)
if arg:
if arg['command'] == 'add':
self.__controller.add_sentence(" ".join(arg['args']))
elif arg['command'] == 'play':
self.game_menu()
except Exception as e:
print(e)
def argumented(self, inp):
argd = inp.strip().split(" ")
if len(argd) == 0:
return False
if argd[0] == "":
return False
argd = [a.strip() for a in argd]
#the spaces are removed
cmd = argd.pop(0).lower()
return {
'command':cmd,
'args':argd
}
def game_menu(self):
game = self.__controller.start_new_game()
print("".join(game.get_sentence()))
while True:
ip = input("letter: ")
if len(ip) > 1:
print("Enter only a letter!")
continue
result = game.play(ip)
print("\n".join(hangmans[result.trials]))
print("".join(result.sentence))
if result.state == -1:
print("Game failed!")
return
if result.state == 2:
print("Congratulations, you won the game!")
return
hangmans = [["__________","| |","| 0","| /|\\","| / \\","|","|", "hangman"],
["__________","| |","| 0","| /|\\","| / ","|","|","hangma"],
["__________","| |","| 0","| /|\\","| ","|","|","hangm"],
["__________","| |","| 0","| /|","| ","|","|","hang"],
["__________","| |","| 0","| /","| ","|","|","han"],
["__________","| |","| 0","| ","| ","|","|","ha"],
["__________","| |","| ","| ","| ","|","|","h"],
["__________","| ","| ","| ","| ","|","|"]
]
|
951bf78f90fb40b2bb5e8148e814ae42adf16329 | pele98/Object_Oriented_Programming | /OOP/Exercise3/Exercise3_8.py | 1,075 | 4.09375 | 4 | # File name: Exercise3_8
# Author: Pekka Lehtola
# Description: Creates cellphone class from user inputs
class Cellphone:
def __init__(self):
self.manufact = ""
self.model = ""
self.retail_price = 0
def set_manufact(self):
self.manufact = str(input("Enter the manufacturer : "))
def set_model(self):
self.model = str(input("Enter the model number : "))
def set_retail_price(self):
self.retail_price = float(input("Enter the retail price : "))
def get_manufact(self):
return print("Manufacturer:", self.manufact)
def get_model_number(self):
return print("Model number:", self.model)
def get_retail_price(self):
return print("Retail price:", self.retail_price)
def main():
my_cellphone = Cellphone()
my_cellphone.set_manufact()
my_cellphone.set_model()
my_cellphone.set_retail_price()
print("Here is the data that you provided :")
my_cellphone.get_manufact()
my_cellphone.get_model_number()
my_cellphone.get_retail_price()
main() |
2429e1fa66849a55e4c499fed987c3933ea77eb1 | itsmesravs/sravss | /amp.py | 138 | 3.8125 | 4 | n=raw_input(371)
temp=n
sum=0
while(n>0);
digit=n%10
sum=sum+digit**3
n=n//10
if(temp=sum):
print("yes")
else:
print("no")
|
eb245222e3ec0d84d1d9682ea598bbe46652dee1 | maru12117/python_practice | /210622_GUI_practice_1.py | 1,273 | 3.671875 | 4 | #GUI
import tkinter as tk
'''root=tk.Tk()
lbl = tk.Label(root, text="EduCoding",underline=3)
lbl.pack()
txt = tk.Entry(root)
txt.pack()
btn = tk.Button(root, text="OK", activebackground ="red", width=5)
btn.pack()
root.mainloop()'''
'''root=tk.Tk() #Tk 객체 인스턴스 생성 루트 자체(윈도우)
label = tk.Label(root, text="Hello World") #라벨 생성(lebel 위젯 사용)
label.pack() #라벨 배치
#root.mainloop() #root 표시'''
#버튼을 눌렀을때의 처리
'''def func1():
print('pushed') #메세지를 파이썬 셀에 출력
def func2():
print('Hi')
button1 = tk.Button(root, text="Push!", command= func1) #버튼 생성
button2 = tk.Button(root, text="Hi", command= func2)
button1.pack() #버튼 배치
button2.pack()
root.mainloop() #root표시'''
#
root=tk.Tk() #Tk 객체 인스턴스 생성 루트 자체(윈도우)
label = tk.Label(root, text="Push Button") #라벨 생성(lebel 위젯 사용)
label.pack() #라벨 배치
#root.mainloop() #root 표시'''
#버튼을 눌렀을때의 처리
def func():
label.config(text = "pushed") #label 표시변경(pushi button => pushed로 변경
button1 = tk.Button(root, text="Push!", command= func) #버튼 생성
button1.pack() #버튼 배치
root.mainloop() #root표시
|
4cb207df25c8c81e8296f8c68cf9164077be6e2c | SergeDmitriev/infopulse_university | /Lecture3/homework/task9.py | 1,233 | 4.40625 | 4 | # Даны четыре действительных числа: x1, y1, x2, y2. Напишите функцию distance(x1, y1, x2, y2),
# вычисляющую расстояние между точкой (x1, y1) и (x2, y2).
# Считайте четыре действительных числа от пользователя и выведите результат работы этой функции.
print('task9: ')
# def distance():
# try:
# x1 = x2 = y1 = y2 = 0
# x1 = float(input('Enter x1:'))
# y1 = float(input('Enter y1:'))
# x2 = float(input('Enter x2:'))
# y2 = float(input('Enter y2:'))
# except (ValueError, TypeError):
# x1 = x2 = y1 = y2 = 0
# print('Wrong coordinates! Pls, refill')
# distance()
#
# from math import sqrt
# result = sqrt((x2 - x1) ** 2 + (y2 - y1) **2 )
# return result
#
#
# dist = distance()
# print(dist)
def distance(x1,x2, y1, y2):
try:
from math import sqrt
result = sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
return result
except (ValueError, TypeError):
print('Wrong coordinates! Pls, refill! Result:')
return None
dis = distance('',5,6,8)
print(dis)
|
c5a760482d3eb93c5b692019ec75ac5af151fa7c | WanderAtDusk6/python- | /multiplication.py | 352 | 3.65625 | 4 | # -*- coding: gb2312 -*-
# ˷multiplication
'''
# version1
print()
for x in range(1,10):
for y in range(1,10):
print(x*y,end = '\t')
print()
'''
# version2
m = 1
while m <= 9:
n = 1
while n <= m:
print(m*n,end = '\t')
n = n+1
m += 1
print()
|
bd58209d68080355a362294a22a60bb2b1af05e8 | iamwhil/6.0001 | /ps1/ps1a.py | 721 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 12 10:12:23 2018
@author: Whil
"""
# Retrieve user input.
annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))
# Define state variables.
portion_down_payment = total_cost * 0.25
monthly_salary = annual_salary/12.0
# Rate of return
r = 0.04
current_savings = 0.00
months = 0
while current_savings <= portion_down_payment:
current_savings += current_savings * r/12
current_savings += monthly_salary * portion_saved
months += 1
print("Number of months:", months)
|
c03bb3952b8782404605a5b365b354d00001a106 | glyif/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 231 | 3.859375 | 4 | #!/usr/bin/python3
for i in range(0, 10):
for k in range(0, 10):
if i < k:
if i < 8:
print("{:d}{:d}, ".format(i, k), end="")
else:
print("{:d}{:d}".format(i, k))
|
1cf8e39394a45bb1f29a783bb5913c5d84339b52 | SunyoungHa/Python-Tableau-SQL-HTML | /Interactive_Dictionary/dictionary.py | 811 | 3.671875 | 4 | import json
from difflib import get_close_matches
data = json.load(open("data.json"))
def translate(word):
word = word.lower()
if word in data:
return data[word]
elif word.title()in data:
return[word.title()]
elif word.upper()in data:
return[word.upper()]
elif len(get_close_matches(word, data.keys()))>0:
yesNo= input("Did you mean %s instead? Enter Yes or No." %get_close_matches(word,data.keys())[0])
if yesNo == "yes":
return data[get_close_matches(word,data.keys())[0]]
elif yesNo == "no":
return "Try again"
else:
return "The word does not exist"
word = input("Enter word:")
output = translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print (output)
|
27eb2236cc7f43d9a05d93b2c3dfc45be5f3505e | dennisliuu/Coding-365 | /103/001.py | 933 | 3.9375 | 4 | A = []
B = []
while 1:
mov = int(input())
if mov == 0:
break
elif mov == 1:
A = []
print('A:%s B:%s' % (A, B))
elif mov == 2:
B = []
print('A:%s B:%s' % (A, B))
elif mov == 3:
insert = int(input())
A.append(insert)
print('A:%s B:%s' % (A, B))
elif mov == 4:
insert = int(input())
B.append(insert)
print('A:%s B:%s' % (A, B))
elif mov == 5:
remove = int(input())
if remove in A:
A.remove(remove)
print('A:%s B:%s' % (A, B))
elif mov == 6:
remove = int(input())
if remove in B:
B.remove(remove)
print('A:%s B:%s' % (A, B))
elif mov == 7:
print(sorted(list(set().union(A, B))))
elif mov == 8:
print(list(set(A).intersection(B)))
elif mov == 9:
print(0 if ''.join(map(str, B)) in ''.join(map(str, A)) else 1)
|
d423d154fce8421ef7211f6ddd0dee6c349814be | Aman221/HackHighSchool | /Parseltongue Piscine/Parseltongue Piscine Part 3/00_parentheses.py | 713 | 3.96875 | 4 | #first part
def everyother(s):
ret = ""
i = True
for char in s:
if i:
ret += char.upper()
else:
ret += char.lower()
if char != ' ':
i = not i
return ret
new_line = everyother(raw_input('Enter a phrase: '))
print new_line
#second part
newer_line = new_line.replace('A', '*')
brand_line = newer_line.replace('E', '*')
brander_line = brand_line.replace('I', '*')
brandest_line = brander_line.replace('O', '*')
final_line = brandest_line.replace('U', '*')
print final_line
#third part
open_par = final_line.count('(')
close_par = final_line.count(')')
if open_par == close_par:
print "Balanced? True"
else:
print "Balanced? False"
|
a3314374706d225d7b91155b62ab97bc12a88ac6 | ankitbhadu/cs204-riscv_simulator-1 | /pipelined/iag_dp.py | 1,245 | 3.65625 | 4 | #control signals pc_select, pc_enable, inc_select are assumed to be given and ra and imm are in binary
#if ra and imm are not in binary, we need to make a function to convert them into binary
#all values are represented as binary strings
# curr program counter is either passed or stored as a global variable(binary string)
def to_binary(a):
s = ""
while (a):
s += str(a%2)
a = a//2
return ("".join(reversed(s)))
def to_decimal(arr):
sum=0
for i in range(len(arr)):
sum+=(int(arr[i]))*(2**(len(arr)-1-i))
return sum
def to_list(s):
return [char for char in s]
def iag(pc_select, pc_enable, inc_select, imm, ra,curr_pc):#line number to which we have to jump is passed in imm
# print('got imm',imm)
temp_pc = ""
mux_inc = 4
mux_pc = 0
ra = to_decimal(ra)
if(pc_select == 0):
temp_pc = ra//4
else:
temp_pc = curr_pc
if(pc_enable == 1):
if(inc_select == 0):
mux_inc = 1
else:
# print('imm',imm)
mux_inc = imm//4
# print('imm//4',mux_inc)
mux_pc = temp_pc + mux_inc
# print('mux pc',temp_pc,mux_inc,mux_pc)
# returns mux_pc for mux y
return mux_pc
|
f6f1167ea05469281a566f57bb462dea9033dcc0 | julaluk801/Program-Translate | /Program Translate/module_checkfile.py | 821 | 3.671875 | 4 | #!/usr/bin/env python3
# Module check file of word
import listfile as fileloc
def main():
print("Start operation: Checkfile")
checkfile = Checkfile()
checkfile.checkFile()
class Checkfile(object):
def __init__(self):
self.filelist = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
def checkFile(self):
for i in self.filelist:
openfile = open(fileloc.FOLDER_WORD+i+".txt", "r+",encoding="utf8")
for line in openfile:
if line == "":
openfile.write("0\n")
break
openfile.close()
print("Check file %s: Founded" % i)
if __name__ == '__main__':
main() |
0d193fb4301920ae32b9298bd42f0bd273d795f8 | wisemonkey450/Boston | /boston.py | 1,697 | 3.9375 | 4 | #! /usr/bin/env python3
consonants =['b', 'c','d', 'f', 'g', 'h', 'j', 'k', 'l', 'm' ,'n' ,'p', 'q', 'r', 's', 't','v', 'w', 'x', 'z']
wicked_awesome_words = ["awesome", "good", "great", "fantastic", "weird", "strange", "patriots", "fenway", "red sox", "celtics", "bruins", "leominster", "peabody", "worcester", "boston", "dorchester", "Cape Cod"]
def main():
while True:
wicked = False
word = input("Give me a word!!")
if "Cape" in word or "Cod" in word or "cape" in word or "cod" in word:
print("The Cape")
continue
if "Patriots" in word or "patriots" in word:
print("The Pats")
continue
if word in wicked_awesome_words:
wicked = True
word.replace("re", "ah").replace("er","ah").replace("ing", "in")
wordlist = list(word)
for index,letter in enumerate(wordlist):
if letter == 'o' or letter == letter == 'O':
if index == 0:
continue
#if wordlist[index - 1] in consonants:
# wordlist[index - 1] = 'a'
# wordlist[index] = 'w'
# break
if index == len(word):
break
if wordlist[index+1] in consonants:
wordlist.insert(index, 'a')
wordlist.insert(index+1, 'w')
break
word = "".join(wordlist)
#Just get rid of the ahs
if 'r' in word:
word.replace('r','')
if wicked:
print("Wicked {}".format(word))
else:
print(word)
if __name__ == "__main__":
main()
|
5d93a457882489adfb683207dc35249142e85295 | WendyPeng1118/python-learning-project | /class5.py | 587 | 3.53125 | 4 | import math
coordinateAX = eval(input('輸入 A 點的 X 座標: '))
coordinateAY = eval(input('輸入 A 點的 Y 座標: '))
coordinateBX = eval(input('輸入 B 點的 X 座標: '))
coordinateBY = eval(input('輸入 B 點的 Y 座標: '))
distance = math.sqrt(
(coordinateAX - coordinateBX) ** 2 + (coordinateAY - coordinateBY) ** 2
)
resultA = 'A 點座標為 ({}, {})\t'.format(coordinateAX, coordinateAY)
resultB = 'B 點座標為 ({}, {})\t'.format(coordinateBX, coordinateBY)
resultDistance = '兩點距離為 {:.4f}'.format(distance)
print(resultA, resultB, resultDistance)
|
0c8153f27fb67a668ee75237e7cd43c5388cfa62 | Abu-Kaisar/Python3Programming--Coursera | /Chapter7. Iteration/loop.py | 459 | 3.859375 | 4 | # mylist = ["yo","mujju","salman","thuss"]
# for i in mylist:
# print("Hi", i ,"Dawat hai kheenchny aao")
# mylist = "dgsadafdua"
# for char in mylist:
# print("Hi", char )
s = "python rocks"
for ch in s:
print("HELLO")
import turtle # set up alex
wn = turtle.Screen()
mujju = turtle.Turtle()
for aColor in ["yellow", "red", "purple", "blue"]:
alex.color(aColor) # repeat four times
mujju.forward(50)
mujju.left(90)
wn.exitonclick()
|
f5dd157dc2328ddc8dd9d96a7fb4c669a08616a8 | raj5036/Project-Blockchain | /Code/blockchain.py | 538 | 3.546875 | 4 | import hashlib
from Block import Block
blockchain = []
genesis_block = Block("previous_hash_demo",["transaction1", "transaction2", "transaction3"])
second_block = Block(genesis_block.block_hash, ["transaction4", "transaction5"])
third_block = Block(second_block.block_hash, ["transaction6", "transaction7", "transaction8"])
print("Hash of genesis block is {}".format(genesis_block.block_hash))
print("Hash of second block is {}".format(second_block.block_hash))
print("Hash of third block is {}".format(third_block.block_hash))
|
f4912f766cae95160f51c71e346e725f0ec05d4e | Shreyankkarjigi/Python--Codes | /Basic programs/sum of n numbers.py | 280 | 4.1875 | 4 | #Code by Shreyank #Github-https://github.com/Shreyankkarjigi
#problem
'''
print sum of n numbers, take n from user
'''
n=int(input("enter range"))
sum=0
for i in range(n):
sum=sum+i
print("sum of n numbers is:",sum)
'''
output
enter range10
sum of n numbers is: 45
'''
|
a9764f8756270de62e2725ca3d5a210a27dbe693 | Shubhrima/TCS-Insight-Supermarket-System | /Sales.py | 3,090 | 4.0625 | 4 |
#Importing the libraries
import pandas as pd
#Storing column tables in a list
column_names = ['Date', 'prod_num', 'prod_name', 'quantity', 'price', 'total_cost']
#Creating a dataframe with these columns
database = pd.DataFrame(columns = column_names)
#Adding a sale to the record
def add_product(date, prod_num, prod_name, prod_type, price, quantity):
total_cost = price*quantity
dict ={'Date': date,
'prod_num': prod_num,
'prod_name': prod_name,
'prod_type': prod_type,
'price': price,
'quantity': quantity,
'total_cost': total_cost}
global database
database = database.append(dict, ignore_index=True)
print("Product added!!")
#Deleting a sale from the record
def del_prod(prod_num):
global database
database = database[database.prod_num != prod_num]
print('Deleted!!')
#Modifying a sale from the record and displaying the new entry
def modify_prod(prod_num):
global database
print("Enter the date ::")
database['Date'][database[database['prod_num'] == prod_num].index] = input()
print("Enter the product name ::")
database['prod_name'][database[database['prod_num'] == prod_num].index] = input()
print("Enter the product type ::")
database['prod_type'][database[database['prod_num'] == prod_num].index] = input()
print("Enter the price ::")
database['price'][database[database['prod_num'] == prod_num].index] = float(input())
print("Enter the quantity ::")
database['quantity'][database[database['prod_num'] == prod_num].index] = int(input())
database['total_cost'][database[database['prod_num'] == prod_num].index] = database['price'][database[database['prod_num'] == prod_num].index] * database['quantity'][database[database['prod_num'] == prod_num].index]
print('The new entry is :--\n\n')
display(prod_num)
#Display the fields of a particular sale
def display(prod_num):
global database
print('The date name is :: ', database['Date'][database[database['prod_num'] == prod_num].index].values[0])
print('The product name is :: ', database['prod_name'][database[database['prod_num'] == prod_num].index].values[0])
print("The product type is ::" , database['prod_type'][database[database['prod_num'] == prod_num].index].values[0])
print('The price of the product is ::', database['price'][database[database['prod_num'] == prod_num].index].values[0] )
print('The quantity of the product is ::', database['quantity'][database[database['prod_num'] == prod_num].index].values[0] )
print('The total cost of the product is ::', database['total_cost'][database[database['prod_num'] == prod_num].index].values[0] )
#Test
"""add_product(date = '1/1/1', prod_num = 1, prod_name = 'apple', prod_type = 'fruit', price = 1,quantity = 50)
add_product(date = '1/1/1', prod_num = 2, prod_name = 'banana', prod_type = 'fruit', price = 2,quantity = 50)
modify_prod(1)
display(2)""" |
f6adef84c4c40c0590918316a5ce41810f220c8f | velorett-i/pubele-aulas | /exercises/ex1-novo/ex1-2.py | 952 | 3.796875 | 4 | import re
import sys
def parse_file(filename):
res = dict()
with open(filename, 'r') as f:
#content = f.readlines()
content = f.read().splitlines()
content = content[3:]
in_def = False
word = ''
for line in content:
if line != '':
if not in_def:
word = line
res[word] = []
in_def = True
else:
res[word].append(line)
else:
in_def = False
return res
def search(word, dictionary):
for key, value in dictionary.items():
value = ' '.join(value)
if word in key or word in value:
print(key + ' :: ' + value)
def main():
filename = 'dicionario_medico_formatado.txt'
word = sys.argv[-1]
dicionario = parse_file(filename)
search(word, dicionario)
if __name__ == '__main__':
main() |
dc1aa5b14f64efe266e2ac176f2011ad19feb13d | shreysingh1/AddressBook | /address app/main.py | 2,264 | 3.6875 | 4 | from tkinter import *
import datetime
from mypeople import Mypeople
from addpeople import Addpeople
date = datetime.datetime.now().date()
date = str(date)
class Application(object):
def __init__(self, master):
# frames
self.master = master
self.top = Frame(master, height=150, bg='white')
self.top.pack(fill=X)
self.bottom = Frame(master, height=500, bg='#abd8eb')
self.bottom.pack(fill=X)
# top_frame_design
self.top_image = PhotoImage(file='icon/pb.png')
# bg is white by default and putting img on top frame
self.top_image_label = Label(self.top, image=self.top_image, bg='white')
self.top_image_label.place(x=25, y=25)
# creating label for heading
self.heading = Label(self.top, text="My PhoneBook App", font="arial 16 bold", bg="white", fg="#f57e42")
self.heading.place(x=180, y=40)
self.date_label = Label(self.top, text="Today's date:" + date, font="arial 12 bold", bg="white", fg="#f57e42")
self.date_label.place(x=300, y=125)
# creating button to perform operations such as add
# button1->add
self.addButton = Button(self.bottom, text="Add Person", fg="black",bg="white",font="arial 12 bold", width="10", command=self.addpeoplefunction)
self.addButton.place(x=200, y=30)
# button2->view
self.viewButton = Button(self.bottom, text="My People", fg="black",bg="white",font="arial 12 bold", width="11", command=self.my_people)
self.viewButton.place(x=200, y=80)
# button3->about
self.aboutButton = Button(self.bottom, text="About Us", fg="black",bg="white",font="arial 12 bold", width="10")
self.aboutButton.place(x=200, y=130)
def my_people(self):
people=Mypeople()
def addpeoplefunction(self):
addpeoplewindow = Addpeople( )
# creating main class to design the main GUI
def main():
root = Tk()
app = Application(root)
root.title("Phonebook App")
root.geometry("500x550+350+200")
root.resizable('false', 'false')
root.mainloop()
#whenever someone call this program the main function should be invoked
if __name__ == '__main__':
main() |
c8659240333d62ff8947cc40a42af9229c63d505 | thomasperrot/python_graphique | /structures/Vector.py | 1,292 | 3.9375 | 4 | #! /usr/bin/env python
# -*-coding: utf-8-*-
from math import sqrt
class Vector(object):
'''
classe définissant un vecteur dans l'espace caractérisé par
[*] sa coordonnée x (int ou float)
[*] sa coordonnée y (int ou float)
[*] sa coordonnée z (int ou float)
'''
def __init__(self, x, y, z):
self.xyz = [float(0) for i in xrange(3)]
self.xyz[0] = x
self.xyz[1] = y
self.xyz[2] = z
@property
def sqrNorm(self):
return self.xyz[0]*self.xyz[0] + self.xyz[1]*self.xyz[1] + self.xyz[2]*self.xyz[2]
@property
def getNormalized(self):
return Vector(self[0] * (1 / sqrt(self.sqrNorm)), self[1] * (1 / sqrt(self.sqrNorm)), self[2] * (1 / sqrt(self.sqrNorm)))
def __getitem__(self, i):
return self.xyz[i]
def __add__(v1, v2):
return Vector(v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2])
def __sub__(v1, v2):
return Vector(v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2])
def __mul__(self, a):
return Vector(a * self[0], a * self[1], a * self[2])
def __str__(self):
return "[%f,%f,%f]" % (self[0], self[1], self[2])
def dot(self, v2):
return self[0] * v2[0] + self[1] * v2[1] + self[2] * v2[2]
def cross(self, v2):
return Vector(
self[1] * v2[2] - self[2] * v2[1],
self[2] * v2[0] - self[0] * v2[2],
self[0] * v2[1] - self[1] * v2[0]
) |
53285a8a2c6b5fb7008af7210be3cf1b93bf5277 | blenature/python_advanced-1 | /modules/mod4.1.json/json_many_objects_different_types/timeclass.py | 1,279 | 3.765625 | 4 | class Time:
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
return f"{str(self.hour).zfill(2)}:" \
f"{str(self.minute).zfill(2)}:" \
f"{str(self.second).zfill(2)}"
class ZonedTime(Time):
def __init__(self, hour, minute, second, zone):
super().__init__(hour, minute, second)
self.zone = zone
def __str__(self):
return f"{str(self.hour).zfill(2)}:" \
f"{str(self.minute).zfill(2)}:" \
f"{str(self.second).zfill(2)} " + self.zone
def time_encoder(time):
if isinstance(time, ZonedTime):
return {"__ZonedTime__": True, "hour": time.hour, "minute": time.minute,
"second": time.second, "zone": time.zone}
elif isinstance(time, Time):
return {"__Time__": True, "hour": time.hour, "minute": time.minute,
"second": time.second}
else:
raise TypeError("Type should be Time")
def time_decoder(time):
if "__Time__" in time:
return Time(time["hour"], time["minute"], time["second"])
elif "__ZonedTime__" in time:
return ZonedTime(time["hour"], time["minute"], time["second"], time["zone"])
|
22ecae043eab30f4a44329a66ff9228ed09de0f1 | zxz2jj/CombinationPattern | /Mnist/test.py | 116 | 4.09375 | 4 | list1 = [[1, 2], [2, 2], [1, 2]]
temp = []
for i in list1:
if i not in temp:
temp.append(i)
print(temp) |
c403992e09d236585fb91c21b113b78f5b6640ae | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_2/KavinSub/b_pancake.py | 473 | 3.609375 | 4 | def all_happy(pancakes):
return len(pancakes) == pancakes.count(1)
def flip(pancakes, i):
for j in range(i, len(pancakes)):
if pancakes[j] == 0:
pancakes[j] = 1
else:
pancakes[j] = 0
T = int(input())
for i in range(T):
pancakes = input()
L = []
for pancake in pancakes:
if pancake == '-':
L.append(0)
else:
L.append(1)
L.reverse()
moves = 0
while not all_happy(L):
flip(L, L.index(0))
moves += 1
print("Case #{}: {}".format(i + 1, moves)) |
f63b61f006de8b09e8c36dbb0b30b9a1306422ba | norbieG/Algorithms | /Greedy Algorithms, Minimum Spanning Trees, and Dynamic Programming/knsapsack.py | 1,062 | 3.53125 | 4 | import numpy as np
def reconstruct(array, items):
vertices = []
i = NO_ITEMS
j = CAPACITY
while i >= 1:
if array[i-1,j] >= A[i,j]:
i -= 1
else:
vertices.insert(0, i)
j -= items[i][0]
i -= 1
print vertices
def read_data():
items = {}
file = open('task1.txt')
for i, line in enumerate(file):
if i >= 1:
line = [int(number) for number in line.strip().split()]
items[i] = (line[1] / 367,line[0]) #tuples (weight, value)
else:
line = [int(number) for number in line.strip().split()]
knapsack_size = line[0]
number_of_items = line[1]
return items, knapsack_size, number_of_items
if __name__ == "__main__":
items, CAPACITY, NO_ITEMS = read_data()
# CAPACITY /= 367
# print CAPACITY
A = np.zeros((NO_ITEMS+1, CAPACITY+1))
for i in xrange(1, NO_ITEMS+1):
for w in xrange(CAPACITY+1):
if w < items[i][0]:
A[i,w] = A[i-1,w]
else:
A[i,w] = max(A[i-1,w], A[[i-1],w-items[i][0]] + items[i][1])
print A[NO_ITEMS,CAPACITY]
print A
reconstruct(A, items)
# answer 2493893 |
c03280cb65657d5c7561dd1fe0beb797c791dce8 | Rahima-web/Hamiltonien | /TP4/brouillon1.py | 6,849 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 14:44:44 2020
@author: rahimamohamed
"""
import random as rd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
""" VARIABLE DECLARATION """
#number of parkinks
N = 3
#p_max = 0.5
#p_min = 0.2
#size_min=40
#size_max=300
p=0.3
#size = 400
""" QUESTION 1 : Generate several maps with different parking-space distributions. """
def Parking_Creation(size,p):
# The probability p that a qpace is free :
#p = rd.uniform(p_max,p_min)
# Define the size of the parking :
#size = int(rd.uniform(size_min,size_max))
# Create the parking : x=0 => space is not free && x=1 => space is free :
availability = rd.choices([0,1] , [1-p,p] , k=size)
return availability,p,size
def create_all_parkings(n,p):
# print("veuillez entrer le nombre de parking souhaité")
# n=input()
# n=int(n)
Liste_of_Parking=[]
size=50
#p=0.1
for i in range(0,n):
Liste_of_Parking.append(Parking_Creation(size,p))
size+=100
#p+=0.4
return Liste_of_Parking
#L=create_all_parkings(3,0.1)
""" QUESTION 2 : Implement the parking strategy shown in class for the generated maps."""
def Parking_Strategy(availability,p,size):
D = size+50 #Cost of passing your destination without parking
S,X,STOP,A = [],[],[],[] #S: space; X: availability, STOP : cost of stopping; A: action to do
for index,x in enumerate(availability) :
s = size-index #space number
S += [s]
X += [x]
if x==0:
STOP += [float('nan')] #the space is not free
A += ['Continue']
else :
stop = (D*p+1) * ((1-p)**s)
STOP += [stop]
if stop >= 1:
A += ['PARKING']
return S,X,STOP,A
else:
A += ['Continue']
def All_parking_strategy(n,p):
H=[]
L=create_all_parkings(n,p)
for i in range (0,len(L)):
H.append(Parking_Strategy(L[i][0],L[i][1],L[i][2]))
return H
H=All_parking_strategy(N,p)
for i in range (0,len(H[0][3])):
if H[0][3][i]=='PARKING':
print("the index is:",i)
""" QUESTION 3 : Discuss your results. """
sns.set_style('darkgrid')
def traces(X,Y):
plt.scatter(X,Y)
plt.plot(X,[1]*len(X), 'b--')
#plt.xlim(X[len(X)-40], 0) # decreasing S
plt.title('STOP CONTROLLER EVOLUTION AS A FUNCTION OF PLACE S')
plt.xlabel('S')
plt.ylabel('STOP CONTROLER VALUE')
plt.tight_layout()
plt.show()
print("\n--------------------COMPARISON: FOR DIFFERENT P AND SIZE------------------\n")
""" pour p =0.1 """
print(" -----------IF P=0.1----------- \n")
p=0.1
L=create_all_parkings(N,p)
H=All_parking_strategy(N,p)
for i in range(0,len(L)):
print (" \nPARKING NUMBER :",(i+1)," , WITH SIZE:",L[i][2],"\n")
# L=create_all_parkings(N,p)
# H=All_parking_strategy(N,p)
traces(H[i][0],H[i][2])
for j in range (0,len(H[i][3])):
if H[i][3][j]=='PARKING':
print("\n The parking place is:",j+1,"\n")
""" pour p =0.5 """
print(" \n -----------IF P=0.5----------- \n")
p=0.5
L=create_all_parkings(N,p)
H=All_parking_strategy(N,p)
for i in range(0,len(L)):
print (" \nPARKING NUMBER :",(i+1)," , WITH SIZE:",L[i][2],"\n")
# L=create_all_parkings(N,p)
# H=All_parking_strategy(N,p)
traces(H[i][0],H[i][2])
for j in range (0,len(H[i][3])):
if H[i][3][j]=='PARKING':
print("\n The parking place is:",j+1,"\n")
""" pour p =0.9 """
print(" \n -----------IF P=0.9----------- \n")
p=0.9
L=create_all_parkings(N,p)
H=All_parking_strategy(N,p)
for i in range(0,len(L)):
print (" \nPARKING NUMBER :",(i+1)," , WITH SIZE:",L[i][2],"\n")
# L=create_all_parkings(N,p)
# H=All_parking_strategy(N,p)
traces(H[i][0],H[i][2])
for j in range (0,len(H[i][3])):
if H[i][3][j]=='PARKING':
print("\n The parking place is:",j+1)
#n=3
#
#def create_parking():
# # Define probability p of a place is free :
# p = rd.uniform(0.5,0.3)
#
# # Define the size of the parking :
# size = int(rd.uniform(40,300))
#
# # Create the parking : x=0 => occupied / x=1 => free :
# parking = rd.choices([0,1] , [1-p,p] , k=size)
#
# return parking,p,size
#
#
#def nb_park(n):
## print("veuillez entrer le nombre de parking souhaité")
## n=input()
## n=int(n)
# Liste_Parking=[]
# for i in range(0,n):
# Liste_Parking.append(create_parking())
# return Liste_Parking
#
##
##P1= create_parking()
##P2=create_parking()
##P3=create_parking()
#
#L=nb_park(n)
#
##Free =[]
##Not_Free =[]
##for i in range (0, len(L[0][0])):
## if L[0][0][i]==1:
## Free.append(L[0][0][i])
## if L[0][0][i]==0:
## Not_Free.append(L[0][0][i])
##
##X= [i for i in range (0,L[0][2])]
##plt.scatter(X,L[0][0])
##plt.plot(X[L[0][2]-40],L[0][0],colour = 'blue')
##plt.xlim(X[len(X)-40], 0)
##plt.tight_layout()
##plt.show()
#
#
#
#def se_garer(parking,p,size):
# D = size+1
# S,X,STOP,A = [],[],[],[]
# for index,x in enumerate(parking) :
# s = size-index
# S += [s]
# X += [x]
# if x==0:
# STOP += [float('nan')]
# A += ['Continue']
# else :
# stop = (D*p+1) * ((1-p)**s)
# STOP += [stop]
# if stop >= 1:
# A += ['Se gare']
# return S,X,STOP,A
# else:
# A += ['Continue']
#
#
#def h():
# H=[]
# for i in range (0,len(L)):
# H.append(se_garer(L[i][0],L[i][1],L[i][2]))
#
# return H
#H=h()
#
#
##se_garer(P1[0],P1[1],P1[2])
##se_garer(P2[0],P2[1],P2[2])
##se_garer(P3[0],P3[1],P3[2])
#
#
#sns.set_style('darkgrid')
#
#def traces(X,Y):
# plt.scatter(X,Y)
# plt.plot(X,[1]*len(X), 'b--')
# plt.xlim(X[len(X)-40], 0) # decreasing S
# plt.title('Évolution du stop-controleur en fonction de S')
# plt.xlabel('S')
# plt.ylabel('Valeur du stop-controleur')
# plt.tight_layout()
# plt.show()
#
################################################################################
#
#for i in range(0,len(L)):
# L=nb_park(n)
# H=h()
# traces(H[i][0],H[i][2])
#
#
#
#
##if __name__ == '__main__':
##
## park,p,s = create_parking()
## S,X,Stop,Action = se_garer(park,p,s)
##
## df = pd.DataFrame({'S':S,'État (x)':X,'Stop Controleur':Stop,'Action':Action})
## traces(S,Stop)
#
#
#
|
6d99e0e1912e028fca66bcc334d4db2e3d9f2f13 | alfiza-shaikh/Exercise-2 | /quick sort.py | 568 | 3.6875 | 4 | def divide(a,s,e):
i=s
pivot=a[e]
for j in range(s,e):
if a[j]<=pivot:
a[i],a[j]=a[j],a[i]
i+=1
a[i],a[e]=a[e],a[i]
return i
def sort(a,s,e):
if(s<e):
p=divide(a,s,e)
sort(a,s,p-1)
sort(a,p+1,e)
from array import *
n=int(input("Enter number of elements : "))
val=array('i',[])
print("Enter elements : ")
for i in range(n):
x=int(input())
val.append(x)
print("Array before sorting :")
for i in val:
print(i,end=" ")
print()
sort(val,0,n-1)
for i in val:
print(i,end=" ")
|
94c3f4b88a376928459df5fbc9d6304a50bc07cb | SilvesSun/learn-algorithm-in-python | /tree/235_二叉搜索树的公共祖先.py | 1,672 | 3.5625 | 4 | # 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
#
# 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(
# 一个节点也可以是它自己的祖先)。”
#
# 例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
#
#
#
#
#
# 示例 1:
#
# 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
# 输出: 6
# 解释: 节点 2 和节点 8 的最近公共祖先是 6。
#
#
# 示例 2:
#
# 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
# 输出: 2
# 解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
#
#
#
# 说明:
#
#
# 所有节点的值都是唯一的。
# p、q 为不同节点且均存在于给定的二叉搜索树中。
#
# Related Topics 树 深度优先搜索 二叉搜索树 二叉树
# 👍 670 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root: return root
if p.val > q.val: return self.lowestCommonAncestor(root, q, p)
if p.val <= root.val <= q.val: return root
if root.val < p.val: return self.lowestCommonAncestor(root.right, p, q)
if root.val > q.val: return self.lowestCommonAncestor(root.left, p, q)
|
df09c9557369b2f5c072a70d08f602b989b4effe | NanoRoss/Python-Automation | /Conceptos_Basicos/3_Herencia.py | 3,575 | 3.859375 | 4 | class Vehiculo:
def __init__(self,velocidad,marca,modelo,color,velocidad_max):
self.velocidad = velocidad
self.marca = marca
self.modelo = modelo
self.color = color
self.velocidad_max = velocidad_max
def acelerar(self,velocidad):
self.velocidad = self.velocidad + velocidad
if self.velocidad > self.velocidad_max:
print("Se Alcanzo la Velocidad Maxima del Vehiculo: " + str(self.velocidad_max))
self.velocidad = self.velocidad_max
else: print("Se Acelero, la velocidad es:" + str(self.velocidad))
def frenar(self,velocidad):
self.velocidad = self.velocidad - velocidad
if self.velocidad < 0:
self.velocidad = 0
print("Se Freno, la velocidad es:" + str(self.velocidad))
#----------------------------------------------------------------------------------------
class Auto(Vehiculo):
def __init__(self,velocidad,marca,modelo,color,velocidad_max,patente,ruedas): #Paso propiedades padres+propias
self.patente = patente
self.ruedas = ruedas
super().__init__(velocidad,marca,modelo,color,velocidad_max) #Paso Propiedades Padre
def arrancar(self):
print("Arrancando el Auto")
def apagar(self):
print("Apagando el Auto")
#----------------------------------------------------------------------------------------
class Moto(Vehiculo):
def __init__(self,velocidad,marca,modelo,color,velocidad_max,patente,color_casco): #Paso propiedades padres+propias
self.patente = patente
self.color_casco = color_casco
super().__init__(velocidad,marca,modelo,color,velocidad_max) #Paso Propiedades Padre
def arrancar(self):
print("Arrancando La Moto")
def apagar(self):
print("Apagando La Moto")
def HacerWilly(self):
print("Yeah! Estoy haciendo Willy!!")
#----------------------------------------------------------------------------------------
# Creo Objeto Auto que va a heredar propiedades y metodos de la clase Auto y su clase Padre Vehiculos.
Auto_1 = Auto(0,"Ford","Taunus","Azul",150,"AAA111",4) #Le paso al constructor de la clase los parametros de mi Objeto de clase Padre + Hija.
print("Auto 1:")
Auto_1.arrancar()
print("La velocidad Inicial es:" + str(Auto_1.velocidad))
Auto_1.acelerar(int(input("Ingrese Velocidad de Aceleracion:")))
Auto_1.acelerar(int(input("Ingrese Velocidad de Aceleracion:")))
Auto_1.acelerar(int(input("Ingrese Velocidad de Aceleracion:")))
Auto_1.frenar(int(input("Ingrese Velocidad de Frenado:")))
print("La velocidad Final es:" + str(Auto_1.velocidad))
Auto_1.color = "Rojo"
print("El color del Auto 1 es:" + Auto_1.color)
Auto_1.apagar()
#----------------------------------------------------------------------------------------
# Creo Objeto Moto que va a heredar propiedades y metodos de la clase Moto y su clase Padre Vehiculos.
Moto_1 = Moto(0,"yamaha","SZ-RR 2017","Azul",300,"AAA111","Amarillo") #Le paso al constructor de la clase los parametros de mi Objeto de clase Padre + Hija.
print("Moto 1:")
Moto_1.arrancar()
print("La velocidad Inicial es:" + str(Moto_1.velocidad))
Moto_1.acelerar(int(input("Ingrese Velocidad de Aceleracion:")))
Moto_1.acelerar(int(input("Ingrese Velocidad de Aceleracion:")))
Moto_1.acelerar(int(input("Ingrese Velocidad de Aceleracion:")))
Moto_1.HacerWilly()
Moto_1.frenar(int(input("Ingrese Velocidad de Frenado:")))
print("La velocidad Final es:" + str(Moto_1.velocidad))
print("El color de la Moto 1 es:" + Moto_1.color)
Moto_1.apagar()
|
3cdde904908316fb7ed05c6697b7a83105a349cc | LOVEBAROT/python-basic-programs | /primeno.py | 249 | 4.125 | 4 | def isPrime(n):
if n<2:
return False
for i in range(2,n//2+1):
if n%i==0:
return False
return True
no=int(input("enter no:"))
if isPrime(no):
print(no,"is prime no")
else:
print(no,"is not a prime no") |
3cf669aeba89632bc3c4f025473aa00209e9ad29 | NahalRasti/Python_accounts.py | /testAccounts.py | 660 | 3.640625 | 4 | from accounts import BankAccount
def balance():
total = 0
for i in range(len(accounts)):
print("Name:", accounts[i].name , "\tNumbers:", accounts[i].number,
"\tBalance: ", accounts[i].balance)
total = total + accounts[i].balance
print("\t\t\t\t\tTotal: ", total)
accounts = []
bank = BankAccount('Everyday','007',2000)
accounts.append(bank)
bank = BankAccount('Cheque A/C','008',3000)
accounts.append(bank)
bank = BankAccount('Term Deposit','009',20000)
accounts.append(bank)
balance()
print("\nDoing some transactions...\n")
accounts[0].deposit(100)
accounts[1].withdraw(500)
accounts[2].add_interest()
balance()
|
0264f0d9e9b792a1c3139af320e5284c44c3aabf | HannahTin/Leetcode | /二叉树/dp/687_Longest Univalue Path.py | 1,006 | 3.984375 | 4 | '''
最长同值路径
给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。
注意:两个节点之间的路径长度由它们之间的边数表示。
'''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
res = 0
def dfs(node):
nonlocal res
if not node: return 0
left = dfs(node.left)
right = dfs(node.right)
arrowLeft = arrowRight = 0
if(node.left and node.left.val == node.val): arrowLeft += left+1
if(node.right and node.right.val == node.val): arrowRight += right+1
res = max(res,arrowLeft+arrowRight)
return max(arrowLeft,arrowRight)
dfs(root)
return res |
271b04ed8fab9e2857f7a286f519f8f2aec9bb6f | Tekorita/Cursopython | /conviertehorasasegundos.py | 976 | 4.125 | 4 | #Convierte de horas a segundos
#En este ejercicio deberás programar un algoritmo encargado de convertir una
#determinada cantidad de horas a segundos. Para ello deberás programar el
# código necesario que solicite al usuario que introduzca 5 números (horas)
# e imprima por la consola la conversión a segundos.
#Si te fijas en los casos de prueba, cada línea de las entradas se corresponde
# con la misma línea de las salidas, es decir, la primera línea de los casos de
# prueba (cuyo valor es 1) se corresponde con la primera línea de la salida
# (cuyo valor es 3600), y así sucesivamente.
#Las entradas estarán formadas por números reales comprendido entre 0 y 100.
#Las salidas deberán ser números naturales.
#Casos de prueba
#entrada | salida
#1 |3600
#1.5 |5400
#2 |7200
i = 0
while i < 5:
valor = float(input("ingresa una hora a convertir en segundos: "))
resultado = valor * 3600
print(int(resultado))
i = i + 1
|
b0d9f2a11ce018b7b84213aeb7321e876664951d | UncleBob2/MyPythonCookBook | /tuple find an element.py | 1,435 | 4.3125 | 4 | def main():
# A tuple of numbers
tupleObj = (12, 34, 45, 22, 33, 67, 34, 56)
print("**** Find an element in tuple using 'in' & 'not in' *****")
# Check if element 34 exists in tuple
if 34 in tupleObj:
print("Element Found in Tuple")
else:
print("Element not Found in Tuple")
# Check if element 1001 doesn't exists in tuple
if 1001 not in tupleObj:
print("Yes, element NOT In tuple")
else:
print("Element is in Tuple")
print("\n**** Find the index of an element in Tuple *****")
# Find the index of 24 in tuple, if not found then handle the exception
try:
pos = tupleObj.index(24)
print("Element 24 Found at : ", pos)
except ValueError as e:
print(e)
# Find the index of 34 in tuple, if not found then handle the exception
try:
pos = tupleObj.index(34)
print("Element 34 Found at : ", pos)
except ValueError as e:
print(e)
print("\n**** Find the occurence count an element in the Tuple *****")
# Get the count of how many times 34 appears in tuple
count = tupleObj.count(34)
print("Occurance count of 34 in tuple is : ", count)
# Based on occurrence count check if element exists in tuple
if tupleObj.count(34) > 0:
print("element 34 Found in Tuple")
else:
print("element 34 Not Found in Tuple")
if __name__ == '__main__':
main() |
7ae837fc142bb636cea0571c85b7c3219d79b0db | oliverhuangchao/python_study | /string/reverseWordII.py | 340 | 4.09375 | 4 | # reverse word in a string
# both iterative and recursive solution
# recursive solution goes here
def func(str):
if len(str) == 0:
return str
a = 0
while a < len(str) and str[a] != " ":
a += 1
str = str[:a][::-1] + " " + func(str[a+1:])
return str
str = "hello world chaoh"
str = str[::-1]
print str
str = func(str)
print(str) |
443be62ca17bdcaf6a64f4c97305b299891c5037 | hotheadheather/Python | /GolfProgram/GolfProgram/GolfProgram.py | 1,331 | 4.15625 | 4 | #Program that reads each player's name and golf score as input
#Save to golf.txt
print(
"""
~~ Spring Fork Golf Club ~~
Save golfers name to a record in a file read the name and golf score into a file.
Then golfers will be printed for your convenience.
"""
)
outfile = open('golf.dat', 'w')
#Enter input, leave blank to quit program
while True:
name = input("Player's name(leave blank to quit):")
if name == "":
break
score = input("Player's score:")
#write to file golf.dat
outfile.write(name + "\n")
outfile.write(str(score) + "\n")
outfile.close()
#Golf Scores
# main module/function
def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
# reads the player array from the file
name = infile.readline()
while name != '':
# reads the score array from the file
score = infile.readline()
# strip newline from field
name = name.rstrip('\n')
score = score.rstrip('\n')
# prints the names and scores
print(name + " scored a " + score)
# read the name field of next record
name = infile.readline()
# closes the file
infile.close()
# calls main function
main() |
368abf9f87b378bf668247e40e5b9c759274b76e | alexferreiragpe/Python | /CursoModulo2/Jokenpo.py | 2,472 | 3.609375 | 4 | import random
from time import sleep
print('\033[1;34m-=-' * 20, '\n Jokenpô \n', '-=-' * 20)
verifica = 'S'
posicoes = ['Pedra', 'Tesoura', 'Papel']
contPc = 0
contEu = 0
while verifica == 'S':
computador = random.choice(posicoes)
print('\nVamos começar!')
print('\n\033[1;35mComputador: Estou pensando, espere!')
sleep(2)
print('\033[1;35mComputador: Pronto! Já tenho minha escolha, agora é você')
while True:
try:
minhaescolha = int(
input('\n\033[1;33mFaça sua escolha: \033[1;34m1- Pedra 2- Tesoura 3- Papel: \033[1;31m'))
if minhaescolha < 1 or minhaescolha > 3:
raise ValueError('Valor Inválido')
except ValueError as e:
print('Escolha Inválida! Digite Novamente.')
else:
break
if minhaescolha == 1:
minhaescolha = 'Pedra'
elif minhaescolha == 2:
minhaescolha = 'Tesoura'
elif minhaescolha == 3:
minhaescolha = 'Papel'
sleep(2)
if minhaescolha == 'Pedra' and computador == 'Tesoura':
print('\nVocê Ganhou! \n\n\033[1;35mComputador: {} \n\033[1;33mVocê: {}'.format(computador, minhaescolha))
contEu = contEu + 1
elif minhaescolha == 'Tesoura' and computador == 'Papel':
print('\nVocê Ganhou! \n\n\033[1;35mComputador: {} \n\033[1;33mVocê: {}'.format(computador, minhaescolha))
contEu = contEu + 1
elif minhaescolha == 'Papel' and computador == 'Pedra':
print('\nVocê Ganhou! \n\n\033[1;35mComputador: {} \n\033[1;33mVocê: {}'.format(computador, minhaescolha))
contEu = contEu + 1
elif computador == minhaescolha:
print('\nCaramba... \nEmpatamos! \n\n\033[1;35mComputador: {} \n\033[1;33mVocê: {}'.format(computador,
minhaescolha))
else:
print('\nEu venci... Sou um Computador experto! \n\n\033[1;35mComputador: {} \n\033[1;33mVocê: {}'.format(
computador, minhaescolha))
contPc = contPc + 1
computador = ''
minhaescolha = ''
print('\n\033[1;34mParciais\n\033[1;35mComputador: {}\n\033[1;33mVocê: {}\n'.format(contPc, contEu))
print('\033[1;34m-=-' * 20, '\n Jokenpô \n', '-=-' * 20)
verifica = str(input('\n\033[1;34mDeseja Jogar Novamente? \033[1;33mS--> Sim N--> Não : ').upper())
|
b7947630937453b315fc21d4d8fb67a00a526ede | eraserpeel/Project-Euler | /problem_30.py | 251 | 3.5 | 4 |
import operator
def main():
numbers = []
for num in range(0, 1000000):
total = reduce(operator.add, [(int(i)**5) for i in str(num)])
if total == num:
numbers.append(total)
print numbers
print sum(numbers)
if __name__=="__main__":
main() |
e6a89d2496e8b248bf1b2d4e34c8ba49eccbb51f | KyeongJun-Min/DataScience_Practice | /[Solving] Pandas_usingDF.py | 379 | 3.59375 | 4 | import pandas as pd
# 코드를 작성하세요.
data_list = [['Taylor Swift', 'December 13, 1989', 'Singer-songwriter'],
['Aaron Sorkin', 'June 9, 1961', 'Screenwriter'],
['Harry Potter', 'July 31, 1980', 'Wizard'],
['Ji-Sung Park', 'February 25, 1981', 'Footballer']]
my_df = pd.DataFrame(data_list, columns = ['name', 'birthday', 'occupation'], index = ['0', '1', '2', '3'])
# 정답 출력
my_df
|
cd7541bf26a07400d0f1a37a691719cab3ca1228 | hi0t/Outtalent | /Leetcode/1261. Find Elements in a Contaminated Binary Tree/solution2.py | 1,013 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class FindElements:
def __init__(self, root: TreeNode):
self.root = root
self.recover(self.root, 0)
def recover(self, root: TreeNode, val: int) -> None:
root.val = val
if root.left: self.recover(root.left, 2 * val + 1)
if root.right: self.recover(root.right, 2 * val + 2)
def find(self, target: int) -> bool:
return self.lookup(self.root, target)
def lookup(self, root: TreeNode, target: int) -> bool:
if not root: return False
if root.val > target: return self.lookup(root.left, target)
if root.val == target: return True
return self.lookup(root.right, target) or self.lookup(root.left, target)
# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)
|
fbb2f05b557b83b01175ab37e872fef4a74ae085 | Maniramez/python-codes | /beginner level/max.element array.py | 117 | 3.71875 | 4 | N=int(input(""))
list=[]
for i in range(0,N):
m=int(input())
list.append(m)
print(list)
k=max(list)
print(k)
|
76286cda83fe243920b193d03c337179d2147de4 | juancebarberis/algo1 | /pre-parcialito/5.py | 720 | 3.921875 | 4 | #Escribir una funci´on que reciba dos secuencias y devuelva una lista con los elementos
#comunes a ambas, sin repetir ninguno.
secA = [1, 2, 3, 4, 7, 8, 9]
secB = [5, 4, 1, 2, 5, 2]
#Resultado [1, 2, 4]
def valoresComunes(A, B):
"""Recibe dos secuencias y devuelve una lista con los elementos en común
en ambas secuencias (sin repetir)."""
resultado = []
for elementA in A:
for elementB in B:
print(f'Comparando {elementA} | {elementB}')
if elementA == elementB:
if elementA in resultado or elementB in resultado:
continue
else:resultado.append(elementA)
return resultado
print(valoresComunes(secA, secB)) |
1280d44cb829ab37c5d69340bc1a620ab49e7b53 | Lam-Git/Learn_oop | /004._RectangleArea.py | 799 | 3.703125 | 4 | class RectangleArea:
def __init__(self): # user can input their own numbers when variable = 0
self.length = 0
self.width = 0
def set_parameters(
self, input_length, input_width
): # instance method with the set rules
self.length = float(input_length)
self.width = float(input_width)
def get_area(self): # getter
return self.length * self.width
if __name__ == "__main__":
input_length = input("Please key in the length:")
input_width = input("Please key in the width:")
rectangle = RectangleArea() # assigning the variable to the Class
rectangle.set_parameters(
input_length, input_width
) # assigning the dot-notion to the new variable to the setter method
print(rectangle.get_area()) # print
|
88a802db6ac593580787a2bfb72909e9bfc383f1 | koten0224/Leetcode | /0896.monotonic-array/monotonic-array.py | 493 | 3.5 | 4 | class Solution:
def isMonotonic(self, A: List[int]) -> bool:
lastNum = None
moreThan = None
for num in A:
if lastNum==None:
lastNum = num
continue
if lastNum == num:
continue
elif moreThan == None:
moreThan = lastNum > num
elif (lastNum > num) != moreThan:return False
lastNum = num
return True
|
9d671993ff5494ef1130376523712a32d95c0ef8 | reeeborn/py4e | /py4e/chapter13/ex13_coursera2.py | 1,173 | 3.703125 | 4 | # Python for Everyone
# Chapter 13 Coursera week 4 assignment 2
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
# retrives and parses the html from url
# returns a tuple (url, contents) from the nth anchor tag where n = position
# returns None for bad parameters
def getNthLinkData(url,position):
if type(position) is not int:
try:
position = int(position)
except:
print("invalid paramaters: position cannot be converted to type int")
return None
html = urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")
tags = soup('a')
return [tags[position-1].get('href',None), tags[position-1].contents[0]]
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter starting url: ')
position = input ('Position of link to follow: ')
times = int(input ('How many links do you want to follow: '))
while times > 0:
response = getNthLinkData(url,position)
if response is None: break
url = response[0]
print("Name:",response[1],"Times:",times)
times -= 1
|
7e73c0c1722c5a3777d794ab8e481615b53dca43 | pedromerry/Michelin-project | /Src/acquisition.py | 1,072 | 3.546875 | 4 | def loadDataset():
import pandas as pd
import os
currentPath=os.getcwd().split("\\Src")
print(currentPath)
#We load the three datasets
sourcePathDataSet1Star = str(currentPath[0]) + "\\Input\\one-star-michelin-restaurants.csv"
sourcePathDataSet2Star = str(currentPath[0]) + "\\Input\\two-stars-michelin-restaurants.csv"
sourcePathDataSet3Star = str(currentPath[0]) + "\\Input\\three-stars-michelin-restaurants.csv"
df1Star = pd.read_csv(sourcePathDataSet1Star)
df2Star = pd.read_csv(sourcePathDataSet2Star)
df3Star = pd.read_csv(sourcePathDataSet3Star)
#We introduce a new column for the number of stars in each dataframe
df1Star.insert(0, "stars", [1 for i in range(df1Star.shape[0])], True)
df2Star.insert(0, "stars", [2 for i in range(df2Star.shape[0])], True)
df3Star.insert(0, "stars", [3 for i in range(df3Star.shape[0])], True)
#We merge the three data frames by stacking them one on top of the other
outputDf = pd.concat([df1Star, df2Star, df3Star]).reset_index(drop=True)
return outputDf |
c8d96b89885e5aa4949f0769b7bc4586caf2c8ec | sharewind/python-tools | /show_max_factor.py | 428 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from timeit import timeit
__author__ = 'Caijanfeng'
def show_max_factor(num):
count = num / 2
while count > 1:
if num % count == 0:
print 'largest factor of %d is %d' % (num, count)
break
count -= 1
else:
print num, ' is prime'
if __name__ =="__main__":
for i in xrange(20):
show_max_factor(i)
else:
print 'now i = ',i |
f8f2abdbe975eda0df4b79e3266d50ce7e077fd6 | aregmi450/MCSC202PYTHON | /Q3.py | 824 | 4.0625 | 4 | # Create an array of 9 evenly spaced numbers going from 0 to 29 (inclusive) and give it the
# variable name r. Find the square of each element of the array (as simply as possible).
# Find twice the value of each element of the array in two different ways:
# (i)
# using addition and
# (ii) using multiplication.
import numpy as np
def Q3():
arr = np.linspace(0,29,9)
sqArr = [x**2 for x in arr]
doubleArr = [2*x for x in arr]
doubleArrAdd = [x+x for x in arr]
return {
"Array": arr,
"SquaredArray": sqArr,
"DoubledArray": doubleArr,
"DoubleByAddition": doubleArrAdd
}
print('Linearly spaced array : ', Q3()['Array'] )
print('Squared array : ', Q3()['SquaredArray'] )
print('Doubled Array : ', Q3()['DoubledArray'] )
print('Double By Addition : ', Q3()['DoubleByAddition'] )
|
495560c533f9d749f561c0ee156033ccb291170b | campbellr/pymacco | /pymacco/logic.py | 9,468 | 4.15625 | 4 | """ This module contains the logic for a card game
"""
import random
from pymacco import util
import pymacco.rules as rules
class Card(object):
""" Representation of a single card.
"""
suits = ['Clubs', 'Spades', 'Diamonds', 'Hearts']
values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack',
'Queen', 'King', 'Ace']
def __init__(self, suit, value):
if suit not in self.suits:
raise ValueError("'suit' must be one of %s" % self.suits)
if value not in self.values:
raise ValueError("'value' must be one of %s" % self.suits)
self.suit = suit
self.value = value
def __str__(self):
return "Card(%s, %s)" % (self.suit, self.value)
def __repr__(self):
return str(self)
def __cmp__(self, card):
if not isinstance(card, Card):
raise TypeError("Cannot compare a %s to a Card." % type(card))
# 2 of Clubs < 3 of Clubs from the values.
# 2 of Clubs < 2 of Spades from the suits.
# Arbitrarly decide that suits are more important, making the default
# sort by suit of
# increasing values.
thisCard = (self.suits.index(self.suit),
self.values.index(self.value))
otherCard = (self.suits.index(card.suit),
self.values.index(card.value))
return cmp(thisCard, otherCard)
def __hash__(self):
return hash((self.suit, self.value))
class TomaccoCard(Card):
""" A card specifically for use in tomacco
"""
clearCards = ['10', 'Ace']
resetCards = ['2']
wildCards = ['2', '10']
def clearCards(self):
""" Return whether or not the card is a 'reset card'.
A 'reset card' is a card that resets the count of the cards on
the table.
"""
return self.value in self.resetCards
def isClear(self):
""" Return whether or not the card is a 'clear card'.
A 'clear card' will clear existing cards on the table.
"""
return self.value in self.clearCards
def isWild(self):
""" Return whether or not the card is a 'wild card'.
A 'wild card' can be played at any time.
"""
return self.value in self.wildCards
def __cmp__(self, other):
""" Arbitrarly, say that a return > 0 = card is a valid play.
Also say 'self' is being played on the 'other' card.
Example - get valid cards in hand:
validCards = [card for card in myHand if card > pile.topCard]
"""
if not isinstance(other, type(self)):
raise TypeError("Cannot compare a %s to %s" % (type(other),
type(self)))
if self.isWild():
return 1
thisCard = self.values.index(self.value)
otherCard = self.values.index(other.value)
return cmp(thisCard, otherCard)
def beats(self, card):
""" Returns whether or not this card beats the given card.
:param card: The card to compare this card to.
:type card: :py:class:`logic.TomaccoCard`
:return: True if this card can be played on the given card,
otherwise False.
"""
return self > card
class Deck(object):
""" Representation of a single deck of cards.
"""
def __init__(self, cardCls=Card, cards=None):
self.cardCls = cardCls
if cards:
# TODO: should I be validating this?
self.cards = cards
else:
self.cards = []
for suit in self.cardCls.suits:
for value in self.cardCls.values:
self.cards.append(self.cardCls(suit, value))
def shuffle(self):
""" Shuffle the deck.
"""
random.shuffle(self.cards)
def removeTopCard(self):
if len(self.cards) > 0:
return self.cards.pop()
return None
def __getitem__(self, key):
if isinstance(key, slice):
return Deck(cards=self.cards[key])
return self.cards[key]
def __add__(self, other):
return self.cards + other.cards
def __sub__(self, other):
return self.cards - other.cards
def __iadd__(self, other):
self.cards += other.cards
return self
def __isub__(self, other):
self.cards -= other.cards
return self
class TomaccoHand(object):
def __init__(self):
self.cardsInHand = []
self.cardsFaceUp = []
self.cardsFaceDown = []
def __str__(self):
return "Hand(InHand: %s, FaceUp: %s, FaceDown: %s)" % \
(self.cardsInHand, self.cardsFaceUp, self.cardsFaceDown)
def __repr__(self):
return str(self)
def __contains__(self, card):
allCards = self.cardsInHand + self.cardsFaceUp + self.cardsFaceDown
return card in allCards
def __getitem__(self, card):
for cards in [self.cardsInHand, self.cardsFaceUp, self.cardsFaceDown]:
if card in cards:
return cards.remove(card)
raise Exception("%s not in this hand!" % card)
def pickUp(self, cards):
""" Pick up one or more cards.
:param cards: One or more cards to pick up.
:type cards: :py:class:`logic.TomaccoCard` or
:py:func:`list` of :py:class:`logic.TomaccoCard`
"""
if not cards:
print "no cards to pickup"
return
if isinstance(cards, list):
self.cardsInHand.extend(cards)
else:
self.cardsInHand.append(cards)
class TomaccoPile(object):
def __init__(self):
self._pile = []
def getTopCard(self):
if len(self._pile) > 0:
return self._pile[len(self._pile) - 1]
return None
def canPlay(self, card):
""" Validate whether the given card can be played on the pile.
:param card: The card to check for playability.
:type card: :py:class:`logic.TomaccoCard`
:return: :py:func:`bool` True if the card can be played on this pile,
otherwise False.
"""
if not self.getTopCard():
return True
return card.beats(self.getTopCard())
def play(self, card):
""" Play a card on the top of the pile.
:param card: The card to play.
:type card: :py:class:`logic.TomaccoCard`
"""
self._pile.append(card)
def pickUp(self):
cards = self._pile[:]
self._pile = []
return cards
class TomaccoGame(object):
""" Represents a game of tomacco.
"""
def __init__(self, players, decks=None):
players, decks = self._validateArgs(players, decks)
self.deck = Deck(cardCls=TomaccoCard)
for i in range(decks - 1):
self.deck += Deck(cardCls=TomaccoCard)
self.deck.shuffle()
self.activePile = TomaccoPile()
self.players = players
for player in players:
player.game = self
# TODO: Choose the starting player as the player to the right of the
# dealer.
self.currentPlayer = random.choice(self.players)
def start(self):
self.deal()
def _validateArgs(self, players, decks):
""" Validates the args
"""
players = util.iterable(players)
if len(players) < 2:
raise ValueError("A Minimum of two players are required to play Tomacco")
if decks is None:
# 1 deck for every 5 players
decks = rules.getNumDecks(len(players))
return players, decks
def deal(self):
# TODO: pick a dealer randomly, deal starting to the right of the dealer.
numInHand = 6
numFaceDown = 3
hands = [TomaccoHand() for i in range(len(self.players))]
for i in range(numInHand):
for hand in hands:
card = self.deck.removeTopCard()
print card.value
hand.cardsInHand.append(card)
for i in range(numFaceDown):
for hand in hands:
hand.cardsFaceDown.append(self.deck.removeTopCard())
for player, hand in zip(self.players, hands):
player.hand = hand
def getNextPlayer(self):
return self.currentPlayer
def pickUp(self):
""" Remove and return the top card off the deck.
:return: (:py:class:`TomaccoCard`) The top card off the deck.
"""
return self.deck.removeTopCard()
def pickUpPile(self):
self._incrementPlayer()
return self.activePile.pickUp()
def playCard(self, player, card):
if not self.canPlay(card):
raise Exception("Player attempted to play a card that "
"cannot be played.")
self.activePile.play(card)
self._incrementPlayer()
def _incrementPlayer(self):
nextIndex = (self.players.index(self.currentPlayer) + 1) % len(self.players)
self.currentPlayer = self.players[nextIndex]
def canPlay(self, card):
""" Validate whether the given card can be played.
:param card: The card to check for playability.
:type card: :py:class:`logic.TomaccoCard`
:return: :py:func:`bool` True if the card can be played,
otherwise False.
"""
return self.activePile.canPlay(card)
|
0f4f8baa51eef7730e1333031966196f5207c4bd | gaivits/skill_lab | /anagram-170947.py | 227 | 3.71875 | 4 | a = int(input())
i = 0
while(i<a):
s1 = str(input())
s2 = str(input())
y = "".join(sorted(s1))
x = "".join(sorted(s2))
if(x == y):
print("ANAGRAM")
else:
print("NOT ANAGRAM")
i = i+1
|
60b456ee2339aa2be7bdf59f40293eadb8571680 | dinanrhyt/change-bg-opencv | /tugas2b.py | 609 | 3.578125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 19:47:42 2019
@author: Toshiba
"""
import cv2 as cv
import numpy as np
# Load the aerial image and convert to HSV colourspace
image = cv.imread("result.png")
image = np.array(image, dtype=np.uint8)
hsv=cv.cvtColor(image,cv.COLOR_BGR2HSV)
# Define lower and uppper limits of what we call "red"
lower = np.array([0,100,100])
upper = np.array([20,255,255])
# Mask image to only select browns
mask=cv.inRange(hsv,lower,upper)
# Change image to purple where we found red
image[mask>0]=(205,0,205)
cv.imwrite("result2.png",image) |
d2884b178bebc6010fde9632bd4ca03dd1deed3b | dmitrime/algorithmic-puzzles | /leetcode/079-word-search.py | 888 | 3.59375 | 4 | class Solution:
def dfs(self, x, y, b, w, idx):
if idx == len(w):
return True
if x >= 0 and x < len(b) and y >= 0 and y < len(b[0]) and b[x][y] == w[idx]:
b[x][y] = '#'
res = self.dfs(x+1, y, b, w, idx+1) or \
self.dfs(x, y+1, b, w, idx+1) or \
self.dfs(x-1, y, b, w, idx+1) or \
self.dfs(x, y-1, b, w, idx+1)
b[x][y] = w[idx]
return res
return False
def exist(self, board: List[List[str]], word: str) -> bool:
if not board or not word:
return False
N, M = len(board), len(board[0])
for i in range(N):
for j in range(M):
if board[i][j] == word[0]:
if self.dfs(i, j, board, word, 0):
return True
return False
|
2bc1cde2b28b90e7628cf8171ec7083ee9d9f57a | igabbita/Python-Practice-Code | /sequentialsearch.py | 546 | 4.0625 | 4 | #Input: Array of Elements, Number to be searched
#Output: Number found/ not found
#Description: Sequential Search
def seqsrch (m,n,arr):
for i in range(0,n-1):
if m== arr[i]:
print("Number found at ", i)
return ()
else:
print ("Number not found")
arr = []
n= int(raw_input("Enter the number of array elements: "))
for i in range(0,n):
arr.append(int(raw_input("Enter the array elements: ")))
m=int(raw_input("Enter the number to be found: "))
seqsrch(m,n,arr)
|
d8360b082c6e49b1526755762753a116c6a8a25a | Geothomas1/60-Days-of-Coding | /leap year.py | 150 | 4 | 4 | n=int(input("Enter Year:"))
if(n%4==0 and n%100!=0 and n%400!=0):
print("{} is leap year".format(n))
else:
print("{} Not leap Year".format(n)) |
296cccda87481470b972b37d393f15da88662647 | ucr-hpcc/hpcc_python_intro | /dictionary-type-variables.py | 708 | 4.28125 | 4 | #!/usr/bin/env python
dictionary = {'name':'John','code':6734,'dept':'sales',2:'a number'}
dictionary = {
'name':'John',
'code':6734,
'dept':'sales',
2:'a number'
}
print(dictionary['name']) # Prints value for 'name' key
print(dictionary[2]) # Prints value for 2 key
print(dictionary) # Prints complete dictionary
print(dictionary.keys()) # Prints all the keys
print(dictionary.values()) # Prints all the values
dictionary['name'] = 'Paul' # Changes the value of name to Paul
dictionary['company'] = 'Big Company' # Adds new key-value pair
print(dictionary) # Prints all the values
|
b462a21b9589c6f191d9a59f1d8cea0ea06ba22c | smartikaa/dice | /dice.py | 669 | 3.53125 | 4 | import random
import tkinter as tk
from tkinter import font as tkFont
r = tk.Tk()
helv36 = tkFont.Font(family='Arial', size=36, weight=tkFont.BOLD)
r.geometry("700x450")
r.configure(bg="#0C0F38")
r.title('Dice')
diceLabel=tk.Label(r,text="",font=("times",200),fg="#F8EEEE",bg="#0C0F38")
n=[]
n.append('\u2681')
def roll():
num=['\u2680','\u2681','\u2682','\u2683','\u2684','\u2685']
n.append(random.choice(num))
i=len(n)-1
if n[i] != n[i-1]:
diceLabel.config(text=n[i])
diceLabel.pack()
else:
roll()
button = tk.Button(r, text='ROLL IT!', width=250, command=roll, bg="#EE8D25",font=helv36)
button.pack()
r.mainloop() |
5aac7038f59c4bd62ca1f424fa3be746ac12b7fc | shanksms/python-algo-problems | /arrays/three-way-partionining-check.py | 1,018 | 4.15625 | 4 | ''' Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above. '''
# Your task is to complete this function
# function should a list containing the required order of the elements
def threeWayPartition(arr, n, lowVal, highVal):
A, B, C = [], [], []
i = 0
for c in range(i, len(arr)):
e = arr[c]
if e <= lowVal:
A.append(arr[c])
i += 1
else:
break
for c in range(i, len(arr)):
e = arr[c]
if lowVal < e <= highVal:
B.append(e)
i += 1
else:
break
for c in range(i, len(arr)):
e = arr[c]
if e > highVal:
C.append(e)
i += 1
else:
break
if len(arr) == (len(A) + len(B) + len(C)):
return 1
else:
return 0
if __name__ == '__main__':
print(threeWayPartition([1, 2, 3, 4, 5], 5, 1, 2))
|
94da434852228f80c4fdef6e8f7d1ec90faf9a6a | juandacd/ST0245-002 | /laboratorios/lab01/codigo/Ejercicio1_1.py | 520 | 3.515625 | 4 | def Subcadena(cadena1, cadena2):
if((len(cadena1) == 0) or (len(cadena2) == 0)):
return 0
if(cadena1[len(cadena1)-1] == cadena2[len(cadena2)-1]):
w = cadena1[:-1]
z = cadena2[:-1]
return Subcadena(w, z) + 1
else:
x = cadena1[:-1]
y = cadena2[:-1]
return max(Subcadena(cadena1, y), Subcadena(x, cadena2))
print("La longitud de la subsecuencia común más larga entre las dos cadenas es: " + str(Subcadena("abcdefubcajp", "asdksdbcajñ")))
|
c96b902293a42500680afdf2d265ddeb6f400632 | arshad115/100-days-of-leetcode | /codes/2020-07-17-top-k-frequent-elements.py | 1,112 | 3.828125 | 4 | # -------------------------------------------------------
# Add Two Numbers - https://leetcode.com/problems/top-k-frequent-elements/
# -------------------------------------------------------
# Author: Arshad Mehmood
# Github: https://github.com/arshad115
# Blog: https://arshadmehmood.com
# LinkedIn: https://www.linkedin.com/in/arshadmehmood115
# Date : 2020-07-17
# Project: 100-days-of-leetcode
# -------------------------------------------------------
from typing import List
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if k == len(nums):
return nums
mostFrequent = {}
for x in nums:
if x in mostFrequent:
mostFrequent[x] += 1
else:
mostFrequent[x] = 1
# Sort list in descending order to get most frequent on top
mostFrequent = {k:v for k, v in sorted(mostFrequent.items(), key= lambda x: x[1], reverse=True)}
return list(mostFrequent.keys())[:k] # slicing top k
nums = [4,1,-1,2,-1,2,3]
k = 2
solution = Solution()
print(solution.topKFrequent(nums,k)) |
66d9fe7d730a07b361bf8621306fbfb6205aa31a | cj1597/python_part_2 | /part2_item4.py | 400 | 3.84375 | 4 | class Person:
"""Contains method for returning gender"""
gender = ''
def get_gender(self):
"""Returns person's gender"""
return self.gender
class Male(Person):
"""A Male person"""
gender = 'Male'
class Female(Person):
"""A Female person"""
gender = 'Female'
if __name__ == '__main__':
print(Male().get_gender())
print(Female().get_gender())
|
4e15a6639fe74c859903c04b60a19e56d7ca0a20 | Holmes-pengge/algo | /leetcode/editor/cn/[116]填充每个节点的下一个右侧节点指针.py | 2,359 | 3.984375 | 4 | # 给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
#
#
# struct Node {
# int val;
# Node *left;
# Node *right;
# Node *next;
# }
#
# 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
#
# 初始状态下,所有 next 指针都被设置为 NULL。
#
#
#
# 进阶:
#
#
# 你只能使用常量级额外空间。
# 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
#
#
#
#
# 示例:
#
#
#
#
# 输入:root = [1,2,3,4,5,6,7]
# 输出:[1,#,2,3,#,4,5,6,7,#]
# 解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由
# next 指针连接,'#' 标志着每一层的结束。
#
#
#
#
# 提示:
#
#
# 树中节点的数量少于 4096
# -1000 <= node.val <= 1000
#
# Related Topics 树 深度优先搜索 广度优先搜索 二叉树
# 👍 493 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
if not root:
return root
queue = [root]
while queue:
size = len(queue)
# 将队列中的元素串联起来
tmp = queue[0]
for i in range(1, size):
tmp.next = queue[i]
tmp = queue[i]
# 遍历队列中的每个元素,将每个元素的左右节点也放入队列中
for _ in range(size):
tmp = queue.pop(0)
if tmp.left:
queue.append(tmp.left)
if tmp.right:
queue.append(tmp.right)
return root
# leetcode submit region end(Prohibit modification and deletion)
|
92dca8295c017d0fc5407807ca899e6b293c9564 | KrishnaRauniyar/Python_assignment | /fun9.py | 467 | 4.09375 | 4 | # Write a Python function that takes a number as a parameter and check the
# number is prime or not.
# Note : A prime number (or a prime) is a natural number greater than 1 and that
# has no positive divisors other than 1 and itself.
def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x == 0):
return False
return True
print(test_prime(9)) |
137ffa9c2f60f50f747f196da570b44a775da2b9 | FIRESTROM/Leetcode | /Python/314__Binary_Tree_Vertical_Order_Traversal.py | 1,427 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
record = collections.defaultdict(list)
queue, result, min_i, max_i = [(0, root)], [], float("inf"), float("-inf")
while queue:
newq = []
for i, node in queue:
if node:
min_i = min(min_i, i)
max_i = max(max_i, i)
record[i].append(node.val)
newq.append((i - 1, node.left))
newq.append((i + 1, node.right))
queue = newq
for i in range(min_i, max_i + 1):
result.append(record[i])
return result
# More Simple Solution
class Solution(object):
def verticalOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
idx_dict = collections.defaultdict(list)
queue = [(root, 0)]
for node, i in queue:
if node:
idx_dict[i].append(node.val)
queue += (node.left, i - 1), (node.right, i + 1)
return [idx_dict[idx] for idx in sorted(idx_dict.keys())]
|
ec3e3ec39f3cbd3869dc86b45c03aeff273119e6 | pradeep122/LearnPython | /swetha/Tutorial_2/For_Loop/app.py | 726 | 4.25 | 4 | # For Loop is used to iterate over items of a collection such as string
# for string
for item in 'Python':
print(item)
# P
# y
# t
# h
# o
# n
# for array or list of names
for item in ['Swetha', 'Pradeep', 'Nirvaan']:
print(item)
# Swetha
# Pradeep
# Nirvaan
# for list of numbers
for item in [1, 2, 3, 4]:
print(item)
# 1
# 2
# 3
# 4
# Range is an object used to iterate range of numbers
for item in range(10):
print(item)
# range between 5 to 10
for item in range(5, 10):
print(item)
# we can also give a stem in range function
for item in range(5, 10, 2):
print(item)
# EXERCISE
prices = [10, 20, 30]
total = 0
for price in prices:
total = total + price
print(f"Shopping cart: {total}")
|
f7e69a6ef2301d337bc947d81f5ef473db39c48c | BiKodes/python-collectibles | /comprehensions/set/set.py | 2,264 | 3.78125 | 4 | # Initialize a Set:
empty_set = set()
# intialize a set with values:
dataScientist = set(['Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'])
dataEngineer = set(['Python', 'Java', 'Scala', 'Git', 'SQL', 'Hadoop'])
# Add and Remove Values from Sets.
# Initialize set with values:
graphicDesigner = {'InDesign', 'Photoshop', 'Acrobat', 'Premiere', 'Bridge'}
# Add Values to a Set:
graphicDesigner.add('Illustrator')
# Remove Values from a Set:
graphicDesigner.remove('Illustrator')
graphicDesigner.discard('Premiere')
graphicDesigner.pop()
# Remove All Values from a Set:
graphicDesigner.clear()
# Iterate through a Set:
dataScientist = {'Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'}
for skill in dataScientist:
print(skill)
# Transform Set into Ordered Values:
type(sorted(dataScientist))
sorted(dataScientist, reverse=True)
# Remove Duplicates from a List:
print(list(set([1, 2, 3, 1, 7])))
# Use a list comprehension to remove duplicates from a list:
def remove_duplicates(original):
unique = []
[unique.append(n) for n in original if n not in unique]
return(unique)
print(remove_duplicates([1, 2, 8, 3, 5, 1, 7, 8, 5]))
# The performance difference can be measured using the the timeit library which allows you to time your Python code.
import timeit
#Approach 1: Execution time
print(timeit.timeit('list(set([1, 2, 8, 3, 5, 1, 7, 8, 5]))', number=10000))
# Approach 2: Execution time
print(timeit.timeit('remove_duplicates([1, 2, 8, 3, 5, 1, 7, 8, 5])', globals=globals(), number=10000))
# Set Operation Methods:
dataScientist = set(['Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'])
dataEngineer = set(['Python', 'Java', 'Scala', 'Git', 'SQL', 'Hadoop'])
# union:
dataScientist.union(dataEngineer)
dataScientist | dataEngineer
# intersection:
dataScientist.intersection(dataEngineer)
dataScientist & dataEngineer
# You can test for disjoint sets by using the isdisjoint method:
graphicDesigner = {'Illustrator', 'InDesign', 'Photoshop'}
dataScientist.isdisjoint(dataEngineer)
dataScientist.isdisjoint(graphicDesigner)
# difference:
dataScientist.difference(dataEngineer)
dataScientist - dataEngineer
# symmetric_difference:
dataScientist.symmetric_difference(dataEngineer)
# Equivalent Result:
dataScientist ^ dataEngineer
|
0a7dc15098a11e2585324fc2d0969841cf17bb22 | 616049195/random_junks | /random_games/python_syntax.py | 1,645 | 4.15625 | 4 | """
Python syntax...
"""
# list comprehension
## syntax
new_list = [x for x in range(1,6)]
# => [1, 2, 3, 4, 5]
##
## examples
even_squares = [x**2 for x in range(1,11) if (x)%2 == 0]
##
# dictionary
my_dict = {
'name' : "Hyunchel",
'age' : 23,
'citizenship' : "Republic of Korea"
}
print my_dict.keys()
print my_dict.values()
for key in my_dict:
print key, my_dict[key]
#
# list slicing
## syntax
[start:end:stride]
same with range() syntax.
[inclusive: exclusive: inclusive]
# if you omit, you can default value [first:last:1]
# negative values change direction (reverse...)
##
l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print l[0:9:2]
## omitting
my_list = range(1, 11) # List of numbers 1 - 10
# Add your code below!
print my_list[::2]
##
## reverseing
my_list = range(1, 11)
# Add your code below!
backwards = my_list[::-1]
print backwards
##
# lambda
## syntax
# lambda variable: expression
##
squares = [x**2 for x in range(1, 11)]
print filter(lambda x: x >= 30 and x <= 70, squares)
#
## file i/o
#----__enter__() and __exit__() invocation "with" and "as" syntax
#syntax
with open("file", "mode") as variable:
# Read or write to the file
#
#### "variable" is created for good. it can be used after the statement. ###
#examples
with open("text.txt", "w") as textfile:
textfile.write("Success!")
#
#_---- File's memeber variable "closed" is set to True/False depending the file's open status
with open("text.txt", "r+") as my_file:
my_file.write("HONEY")
if not my_file.closed:
my_file.close()
print my_file.closed
#
## |
03b6ca945bd30847c80ca2cac94702211392d061 | ZhangYet/vanguard | /myrtle/befor0225/longest_common_prefix.py | 760 | 3.625 | 4 | # https://leetcode.com/problems/longest-common-prefix/
from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
if len(strs) == 1:
return strs[0]
records = set()
standard = strs[0]
prefix = ""
for i in range(len(standard) + 1):
prefix = standard[:i]
records.add(prefix)
for s in strs[1:]:
if len(s) < i:
return standard[: i - 1]
if s[:i] not in records:
return standard[: i - 1]
return prefix
def test_case(strs: List[str], res: str):
s = Solution()
assert s.longestCommonPrefix(strs) == res
|
fb1b21e04944c0b6b7a7689aa2fcedf41d944c45 | brackengracie/CS-1400 | /week-1/thermometer.py | 718 | 4.03125 | 4 | # Thermometer by: Gracie Bracken
def main() :
#instructions
print("---------------------------------------------")
print("Hey Dipper, remember your thermometer next time.")
print("I'll help for now! Use your stopwatch, count how ")
print("many times the cricket chirps in 13 seconds.")
print("")
# get the "chirps" from the user
chps=input("How many times did the crickets chirp? ")
chps=int(chps)
print("")
# caculations and print
ct=40
temp=ct+chps
if temp<50:
print("It's way too cold for crickets.")
else:
print("By my AWESOME caculations, the temperature is",temp)
print("---------------------------------------------")
main()
|
cc78cfeea4805a0557011196a9bcdd159724acfc | SiranushSevoyan/Intro-to-Python | /Lecture 2/Homework 2/Problem2.py | 348 | 3.90625 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("Text", type=str)
args = parser.parse_args()
b=int((len(args.Text)-3)/2)
c=int((len(args.Text)+3)/2)
print ("The old string:: ", args.Text)
print ("Middle 3 characters: ", args.Text[b:c])
print ("Middle 3 characters: ", args.Text[:b]+args.Text[b:c].upper()+args.Text[c:]) |
6fdc7d16748a875d535dfb8070eb8b69568bdb37 | IrwinLai/LeetCode | /876. Middle of the Linked List.py | 625 | 3.828125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
'''
l = []
tem = head
while tem:
l.append(tem.val)
tem = tem.next
index = (len(l))//2
while index > 0:
index -= 1
head = head.next
return head
''' |
c1f040ae4c4323053e6bfac3bd63436944617109 | BLewis739/MarkovTextGenerator | /Markov Text Generator.py | 4,295 | 3.75 | 4 | # Markov Text Generator.py
# Adapted from problem set question in Boston University course CS111
# Professor David Sullivan, PhD
# This version written by Brad Lewis 9/22/21
import random
'''
create_dictionary takes in a string that refers to the name
of a text file in the folder of the program. It returns d,
which is a dictionary containing the text of the program.
'''
def create_dictionary(filename):
nfile = open(filename, 'r', encoding='utf8')
d = {'$': []} #Create dictionary with $ as key to refer to sentence starters
for line in nfile:
line = line[:-1] #eliminate the \n character
words = line.split(" ") #create a list by removing the spaces
if line != '': #only adds words for non-null lines
d['$'].append(words[0]) #First word of line assigned to $ key
for i in range(len(words)): #scan word-by-word to add
if i + 1 != len(words) and words[i+1] != '': #Only adds words if there is a word after AND the word after isn't null
if words[i] == '': #Assigns starts of sentences after nulls to $
d['$'].append(words[i+1])
elif words[i] in d: #Assigns words already in d a new key
d[words[i]].append(words[i+1])
else: #Makes new keys
d[words[i]] = [words[i+1]]
nfile.close() #close the file
return d
def generate_text(d,num_words): #d is the dictionary inputted, num_words is desired length of the output
count = 0
text = ''
pun_list = ['.', '?', '!', ':']
abbrev_list = ['Mr.', 'Ms.', 'Mrs.', 'Dr.', 'etc.', 'vs.', 'Vs.']
while count < num_words: #Continues adding text as long as output hasn't yet hit the desired length
sent = [] #sentence
first_word = ''
while first_word == '':
first_word = random.choice(d['$']) #Pick the first word
sent.append(first_word) #First word is added to the empty sentence
if first_word in d:
if len(d[first_word]) > 1: #Applied to keys that have multiple possible values
next_word = random.choice(d[first_word])
else:
one_word_list = d[first_word] #For keys that have only one possible option
next_word = one_word_list[0]
sent.append(next_word) #next_word is determined above, appended to sentence here
while next_word in d: #Continues adding words as long as next_word is a key in d
if len(d[next_word]) > 1: #Randomly chooses value if key has multiple values
next_word = random.choice(d[next_word])
else: #If key has only one value, it is automatically picked
one_word_list = d[next_word]
next_word = one_word_list[0]
sent.append(next_word)
#Check for punctuation
if next_word not in abbrev_list: #Ignore punctuation on common abbreviations
if next_word[-1] in pun_list: #Identify punction that ends sentences
break
for i in sent: #Convert list of text into a string
text = text + i + " "
count += len(sent) #Update count based on the number of words added
text += '\n' #Add a newline character to the end for better readability
print(text)
d = create_dictionary("NepWxT.txt")
generate_text(d, 150)
|
43fd7a56513cc9e37d92463f28b10cc941aa981a | thekingmass/OldPythonPrograms | /aktuwhileeven.py | 221 | 4.25 | 4 | while 1:
x=int(input('please provide any input or zero to terminate\n'))
if x!=0:
if x%2==0:
print(x,'is an even number')
else:
print(x,'is not an even it is an odd number ')
|
0219070377c3f413f9fa5d44fb38387695d2edea | Samyak2607/CompetitiveProgramming | /Codechef/Find Your Gift.py | 615 | 3.578125 | 4 | def grid(j, x, y):
if j=='L':
x-=1
elif j=='R':
x+=1
elif j=='U':
y+=1
else:
y-=1
return (x,y)
for _ in range(int(input())):
n=int(input())
s = input()
l=[]
dict1={}
x,y=0,0
dict1['L']=0
dict1['R']=0
dict1['U']=1
dict1['D']=1
for i in range(n):
if not l:
l.append(s[i])
x,y=grid(s[i],x,y)
else:
if dict1[s[i]]==dict1[l[-1]]:
continue
else:
l.append(s[i])
x,y=grid(s[i],x,y)
print(x,y)
|
067f9d1c7e6778533982b64e38dacd73ef7260d8 | ajcepeda/Calculator | /calc_gui.py | 4,738 | 3.71875 | 4 | from tkinter import *
values = ''
# event function when any button is pressed (except equal and clear button)
def press(num):
global values
values = values + str(num)
equation.set(values)
# event function when equal button is pressed
def equal():
try:
global values
total = str(eval(values))
equation.set(total)
values = ''
except:
equation.set(' error ')
values = ''
def clear():
global values
values = ''
equation.set('0')
calc = Tk()
calc.geometry('355x475')
calc.configure(bg='#B9DDFF')
calc.title('Calculator')
calc.resizable(False,False)
button_frame = Frame(calc,bg='#B9DDFF')
button_frame.pack()
equation = StringVar()
equation.set('0')
expression_field = Entry(button_frame,textvariable=equation,justify='right',
font = ('arial',20,'bold'))
button1 = Button(button_frame,font= ('times new roman',12),text=' 1 ',bd=1,relief='ridge',
fg='black', bg='#e6ecff', command=lambda: press(1), height=3, width=8)
button2 = Button(button_frame,font= ('times new roman',12),text=' 2 ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press(2), height=3, width=8)
button3 = Button(button_frame,font= ('times new roman',12),text=' 3 ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press(3), height=3, width=8)
plus = Button(button_frame,font= ('times new roman',12),text=' + ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press("+"), height=6, width=8)
button4 = Button(button_frame,font= ('times new roman',12),text=' 4 ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press(4), height=3, width=8)
button5 = Button(button_frame,font= ('times new roman',12),text=' 5 ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press(5), height=3, width=8)
button6 = Button(button_frame,font= ('times new roman',12),text=' 6 ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press(6), height=3, width=8)
minus = Button(button_frame,font= ('times new roman',12),text=' - ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press("-"), height=3, width=8)
button7 = Button(button_frame,font= ('times new roman',12),text=' 7 ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press(7), height=3, width=8)
button8 = Button(button_frame,font= ('times new roman',12),text=' 8 ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press(8), height=3, width=8)
button9 = Button(button_frame,font= ('times new roman',12),text=' 9 ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press(9), height=3, width=8)
multiply = Button(button_frame,font= ('times new roman',12),text=' * ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press("*"), height=3, width=8)
button0 = Button(button_frame,font= ('times new roman',12),text=' 0 ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press(0), height=3, width=8)
decimal= Button(button_frame,font= ('times new roman',12),text='.',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press('.'), height=3, width=8)
clear = Button(button_frame,font= ('times new roman',12),text='C',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=clear, height=3, width=8)
divide = Button(button_frame,font= ('times new roman',12),text=' / ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=lambda: press("/"), height=3, width=8)
equal = Button(button_frame,font= ('times new roman',12),text=' = ',bd=1,relief='ridge',
fg='black', bg='#e6ecff',command=equal,height=3)
expression_field.grid(row=0,column=0, columnspan=4, ipadx=9,ipady=20,pady=15)
button1.grid(row=3, column=0)
button2.grid(row=3, column=1)
button3.grid(row=3, column=2)
plus.grid(row=4, column=3, rowspan = 2, sticky='ns')
button4.grid(row=2, column=0)
button5.grid(row=2, column=1)
button6.grid(row=2, column=2)
minus.grid(row=3, column=3)
button7.grid(row=1, column=0)
button8.grid(row=1, column=1)
button9.grid(row=1, column=2)
multiply.grid(row=2, column=3)
button0.grid(row=4, column=1)
decimal.grid(row=4, column=0)
clear.grid(row=4, column=2)
divide.grid(row=1, column=3)
equal.grid(row=5, column=0,columnspan = 3,sticky='ew')
calc.mainloop()
|
12ad51e396e1ca5bffdd62957f8d07dd536b6972 | guadalupeaceves-lpsr/class-samples | /for.py | 580 | 3.921875 | 4 | icecreamflavors = ['Chocolate', 'Vanilla', 'Strawberry', 'Salted Caramel', 'Mint Chip']
print("These are our ice cream flavors:")
print(icecreamflavors)
print("Want to add an ice cream flavor? Enter it now:")
newicecreamflavor = raw_input()
newicecreamflavor = [newicecreamflavor]
newmenu = icecreamflavors + newicecreamflavor
print("Great! Here's our menu:")
print(newmenu)
import random
randomicecreamflavor = random.randint(0,5)
randomicecreamflavor = newmenu[randomicecreamflavor]
print("Your flavor for today has been chosen randomly. Enjoy " + randomicecreamflavor + "!")
|
b7c120355913e5233bf39134ab86914c8437f4d2 | yoonmyunghoon/JDI | /알고리즘/프로그래머스/코딩테스트 연습/멀쩡한 사각형.py | 219 | 3.640625 | 4 | from math import gcd
def solution(w, h):
answer = 1
gcd_ = gcd(w, h)
x = w//gcd_
y = h//gcd_
print(x, y)
x_ = x // 2
y_ = y // 2
print(x_, y_)
return answer
print(solution(8, 12))
|
179ee0ea253318533957be2e031ca67784e4990c | aferreira44/python-para-zumbis | /lista-02/exercicio-04.py | 193 | 3.828125 | 4 | a = float(input('A: '))
b = float(input('B: '))
c = float(input('C: '))
nums = [a, b, c]
maior = nums[0]
for n in nums:
if n > maior:
maior = n
print('O maior número é %.2f' % maior) |
c4e35c30b5d36634d10c8ce73b4320da5fe608bd | 311210666/Taller-de-Herramientas-Computacionales | /Clases/Programas/Tarea05/problema5S.py | 220 | 3.65625 | 4 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import problema5
from problema5 import spnn
n= input ("¿Del 1 al cuál quieres calcular la suma?\n")
print "La suma de los primeros %d naturales es %d" % (n, spnn (n))
|
96289ebb75fe896a1836d11faf5defba8f61ff9f | kodyellis/Python | /testingfinal/Kody Ellis Discrete Math Problem #1.py | 1,926 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 02 22:32:31 2017
@author: Kody Ellis
"""
# Program 1. Set operations
#Using Python to create a program that can identify and complete set operations:
# Set Operations:
#
# Union
# Intersect
# Difference
# Cross product
# Equality
# Subset
# Proper SUbset
# Complement
#import intertools, so we can use set oeprations methods
import itertools
A={1,2,3,4,7}
B={5,6,7,8,9}
#A U B = U
U={1,2,3,4,5,6,7,8,9,10}
#note to self, experiement and refactor this using tkinter(gui library) durign my christmas break
input1 = raw_input("Enter a command to continue: Union, Intersect, Difference, Cross product, Equality, Subset, Proper SUbset, Complement: ")
if input1.lower() == "union":
# using set operators
#union
print("Union=",A.union(B))
elif input1.lower() == "intersection":
#Intersection
print("Intersection",A.intersection(B))
elif input1.lower() == "difference":
#Difference
print("Difference A",A.difference(B))
print("Difference B",B.difference(A))
elif input1.lower() == "crossproduct":
##Crossproduct in a loop
for i in itertools.product(A,B):
print("Crossproduct",i)
elif input1.lower() == "equality":
#Equality,
print("Equality A",A==B)
print("Equality B",B==A)
elif input1.lower() == "subset":
#Returns True or False for subsest
print("SubsetA",A.issubset(B))
print("Subset B",B.issubset(A))
elif input1.lower() == "proper subset" or input1.lower() == "propersubset":
#Returns True or False for proper subset
print("Proper subset A",A.issuperset(B))
print("Proper subset B",B.issuperset(A))
elif input1.lower() == "complement":
#Complement
print("Complement of A",U-A)
print("Complement of B",U-B)
|
53e5b8c10dbe2889e37480077885e1ef64582438 | muryliang/python_prac | /try/if.py | 396 | 4.03125 | 4 | #!/usr/bin/python
b=raw_input("input your integer:")
'''
if a=='2':
print ' you are 2'
elif a=="3":
print 'you are 3'
else:
print 'your are nothing'
a = int(b)
while a > -20:
print 'now is ', a
a = a-1
else :
print 'now done'
'''
a = int(b)
for x in range(0,a+1):
if x % 3 == 0:
continue
print x,
if x == 10:
break
else:
print '\nover'
|
e839047637d3c6251883e3889ff355f88b345a39 | adityaronanki/pytest | /pythoncourse/assignment_01.py | 2,295 | 4.0625 | 4 | __author__ = 'Khali'
from placeholders import *
notes = '''
Fill up each of this methods so that it does what it is intended to do. Use
only the standard data types we have seen so far and builtin functions.
builtin functions: http://docs.python.org/2/library/functions.html
Do not use any control flow statements (if, for...) in this assignment.
Assume that inputs are valid and of expected type, so no checking required.
'''
def get_odds_list(count):
"""
This method returns a list of the first 'count' odd numbers in descending
order. e.g count = 3 should return [5,3,1]
"""
list = []
for x in range(1, count * 2):
if x % 2 == 1:
list.append(x);
list.sort(reverse=True);
return list
def get_sorted_diff_string(first, second):
"""
returns a string which contains letters in first but not in second.
e.g.s apple and pig returns ael.
"""
a=set(first)
b=set(second)
c=a-b;
d=list(c)
d.sort();
str1 = ""
for x in range(0, len(d)):
str1 = str1 + d[x]
return str1
#return d
def get_sorted_without_duplicates(input):
"""
returns a string in which characters are sorted and duplicates removed
e.g apple returns aelp, engine returns egin
"""
a = set(input)
b = list(a)
b.sort();
str1=""
for x in range(0, len(b)):
str1 = str1 + b[x]
return str1
three_things_i_learnt = """
-
-
-sets
"""
time_taken_minutes = 5
def test_odds_list():
assert [1] == get_odds_list(1)
assert [] == get_odds_list(0)
assert [5,3,1] == get_odds_list(3)
assert [9,7,5,3,1] == get_odds_list(5)
def test_sorted_diff_string():
assert "" == get_sorted_diff_string("apple", "apple")
assert "aelp" == get_sorted_diff_string("apple", "")
assert "do" == get_sorted_diff_string("dog", "pig")
assert "in" == get_sorted_diff_string("pineapple", "apple")
def test_sorted_without_duplicates():
assert "aelp" == get_sorted_without_duplicates("apple")
assert "eorz" == get_sorted_without_duplicates("zeroo")
assert "" == get_sorted_without_duplicates("")
assert "abcd" == get_sorted_without_duplicates("abcdabcd")
|
89428ff9765bf751ec62c9fce51b9e74e3b0c725 | luthfirrahmanb/purwadhika_data_science_module1 | /fundamental.py | 13,831 | 4.03125 | 4 | import math
"""
Basic
"""
# print('Halo')
nama = "andi"
# print(nama)
usia = 23
usia = 32
# print(usia)
jomblo = True
# Data Type
# print(jomblo)
# print(type(nama))
# print(type(usia))
# print(type(jomblo))
"""
Input
"""
# name = input('Nama kamu?: ')
# age = input('Umur kamu?: ')
# sex = input('Kelamin kamu?: ')
# occupation = input('Pekerjaan kamu?: ')
# print('Nama: ' + name)
# print('Umur: ' + age)
# print('Kelamin: ' + sex)
# print('Pekerjaan: ' + occupation)
"""
Arithmetic and Numbers
"""
usiaAndi = 40
usiaBudi = 20
# print(usiaAndi * usiaBudi)
# print(usiaAndi / usiaBudi)
# print(usiaAndi + usiaBudi)
# print(usiaAndi - usiaBudi)
# print(usiaAndi % usiaBudi)
# print(usiaBudi ** 2)
# usiaAndi += 3
# usiaBudi *= 4
# print(usiaAndi)
# print(usiaBudi)
"""
Math
"""
# print(math.pi) # pi
# print(math.fabs(-4.7)) # absolute math
# print(math.pow(7, 2)) # Kuadrat, dsb
# print(math.sqrt(64)) # Akar
"""
Strings
"""
# x = 'Halo Dunia Hello'
# print(len(x))
# print(x.index('D'))
# print(x.split())
# print(x.lower())
# print(x.upper())
# print(x.capitalize())
# print(x)
# x1 = "Luthfir"
# x2 = 21
# greet = f"Hi saya {x1}, dan umur saya {x2}"
# print(greet)
"""
Comparison Object & Logical Operator
"""
x = 5
y = '5'
# print(x == y)
# print(x > int(y))
# print(x < int(y))
# print(x >= int(y))
# print(x <= int(y))
# bool1 = x == y
# bool2 = x >= int(y)
# print(f"boolean 1 = {bool1} dan boolean 2 = {bool2}")
# print(bool1 and bool2)
# print(bool1 or bool2)
# print(not bool1 and bool2)
# if(False):
# print('Hello')
# else:
# print('Halo')
"""
For and While Loops
"""
# number = 1
# while(number <= 10):
# print(number)
# number+=1
# for i in range(1, 6):
# print(i)
# for i in range(10, 50, 10):
# print(i)
"""
Notes:
1. '//' bisa menjadi pengganti math.floor saat melakukan pembagian
"""
"""
Quiz
"""
# Solve it 1-1
# x = int(input("Masukkan nilai x: "))
# y = int(input("Masukkan nilai y: "))
# z = int(input("Masukkan nilai z: "))
# w = (x + y * z / x * y)
# result = math.pow(int(w), z)
# result = int(result)
# print(result)
# Solve it 2-1
# numberInput = int(input("Masukkan Angka: "))
# result = math.pow(numberInput, 2)
# result = int(result)
# print("Kuadrat dari " + str(numberInput) + " adalah " + str(result))
# Solve it 3-1
# def solveIt3(days):
# year = math.floor(days / 360)
# days1 = days % 360
# month = math.floor(days1/30)
# days2 = days1 % 30
# week = math.floor(days2/ 7)
# day = math.floor(days2 % 7)
# print("years = ",year,
# "\nmonths = ",month,
# "\nweeks = ",week,
# "\ndays = ",day)
# solveIt3(485)
# Solve it 4-1
# ratioAndi = 4/14
# ratioBudi = 10/14
# umurAndi = 49 * ratioAndi + 2
# umurBudi = 49 * ratioBudi + 2
# print(f"umur andi adalah {int(umurAndi)} dan umur budi adalah {int(umurBudi)}")
# Solve it 5-1
# sentences = "i'm a software developer on B corp"
# sentences = sentences.lower()
# countSentences = sentences.count('e')
# print(countSentences)
# Solve it 6-1
# jamAwal = 9
# jarak = 120
# kecepatanTotal = 100/3600
# detikTotal = jarak/ kecepatanTotal
# lamaJam = math.floor(detikTotal // 3600)
# lamaMenit = math.floor((detikTotal % 3600) / 60)
# lamaDetik = math.floor((detikTotal % 3600) % 60)
# print(f"lama Jam {lamaJam} dan lama menit {lamaMenit} dan lama detik {lamaDetik}")
# print(f"Mobil A dan B tertabrak pada pukul {jamAwal + lamaJam}, menit {lamaMenit}, dan detik {lamaDetik}")
# solve it! 1-2
# nilai = int(input("Masukkan angka: "))
# if(nilai % 2 == 0):
# print(f"Angka {nilai} adalah angka genap")
# else:
# print(f"Angka {nilai} adalah angka ganjil")
# Solve it! 2-2
# massa = int(input("masukan masa anda(kg): "))
# tinggi = int(input("masukan tinggi anda(cm): "))
# imt = massa/math.pow((tinggi/100), 2)
# if(imt < 18.5):
# print(f"berat badan anda kurang - {imt}")
# elif(imt >= 18.5 and imt <= 24.9):
# print(f"berat badan ideal - {imt}")
# elif(imt >= 25.0 and imt <= 29.9):
# print(f"BB berlebih - {imt}")
# elif(imt >= 30.0 and imt <= 39.9):
# print(f"BB sangat berlebih - {imt}")
# else:
# print(f"Obesitas - {imt}")
"""
For and While Loops
"""
# number = 1
# while(number <= 5):
# print(number)
# number+=1
# listItem = list(range(1, 11, 2))
# print(listItem)
# for x in listItem:
# print(x)
# Solve it For Loops
# for i in range(1, 11):
# print(f"Nomor urut {i}")
# Solve it For loops with 3 param
# for i in range(0, 21, 2):
# print(f"Nomor Urut {i}")
# for i in range(1, 20, 2):
# print(f"Nomor urut {i}")
# Solve it For loop drawing
# i = ''
# for item in range(5):
# for item1 in range(5):
# i += " * "
# i += "\n"
# print(i)
# Solve it draw
# i = ""
# for item in range(0, 5):
# for item1 in range(0, item+1):
# i += " * "
# i += "\n"
# print(i)
"""
Function and List
"""
# def contoh():
# print('Halo Dunia')
# contoh()
# x = 10
# y = 50
# def contoh():
# print(x+y)
# contoh()
# def myName(name):
# print(f"{name} susilo")
# myName('Luthfir')
# def data(x, y):
# print(f"{x} lahir tahun {y}")
# data('Adi', 1990)
# def total(x, y):
# z = x + y
# return z
# print(total(4, 9))
# def kali (x):
# if(x < 2):
# return 1
# else:
# return x * tiga()
# print(kali(5))
# def tiga():
# return 3
# Recursive Function
# def pangkat(x, y):
# if(y == 1):
# return x
# else:
# y -= 1
# return x * pangkat(x, y)
# print(pangkat(2, 4))
# def kali(x = 5, y = 2):
# return x * y
# print(kali(y=4))
listMobil = ['Alya', 'Xenia', 'Avanza']
# print(listMobil)
# print(listMobil[0])
# listMobil[1:] = ['Xpander', 'Livina']
# print(listMobil)
# for x in listMobil:
# print(x)
# print(listMobil[0:3])
# buah = ['Nanas', 'Apel', 'Jeruk', 'Pir', 'Melon']
# buah[0] = 'Buah Naga'
# buah.pop()
# print(buah)
# listTest = [1, 'hi', ['hello', 2, True, [0, 1]]]
# print(listTest[2][3][1:])
"""
Lambda Exp, Tuples, etc
"""
# Dictionaries
# d = {
# "key1": "item1",
# "key2": "item2",
# "kucing": [
# 3,
# "jerapah"
# ]
# }
# print(d["key1"])
# print(d["kucing"][0])
# Dictionaries inside Dictionaries
# d = {
# "key1": {
# "key2": "item2"
# },
# "kucing": [
# 3,
# "jerapah"
# ]
# }
# print(d["key1"])
# print(d["key1"]["key2"])
# Tuples
# t = (
# 1, # Data Pertama
# [
# 0,
# "test"
# ], # Data Kedua
# {
# "a1": True,
# "a2": [
# 1,
# "mark",
# "dark"
# ]
# }, # Data Ketiga
# (
# True,
# {
# "person1": "luthfir"
# }
# )
# )
# print(t)
# a = "test1"
# b = 20
# d = { "" + a + "": 5, "" + str(b) + "": 9, "maruk": [7, 8]}
# for item in d:
# print(item)
# for item in d:
# print(d[item])
# d["keren"] = 70
# print(d)
# Sets (didalam sets tidak bisa ada list atau dict, tetapi bisa ada tuples, karena bersifat hashable/ tidak bisa diubah)
# s = {1, 2, 3, 4, 3, 1, 3, 2}
# print(s)
# print(list(s))
# newList = [1, 3, 3, 2, 1, 2, "test1", "test1", "test2"]
# s = set(newList)
# print(s)
#List comprehension
# listNum = [1, 2, 3, 4, 5]
# listNum = [item * 2 for item in listNum]
# print(listNum)
# Lambda Expressions
# def times2(num):
# return num * 2
# print(times2(2))
# lambda num: num * 2
# map
# without lambda
# def times2(num):
# return num * 2
# listNum = [1, 2, 3, 4, 5]
# listNum = list(map(times2, listNum))
# print(listNum)
# with lambda
# listNum = [1, 2, 3, 4, 5]
# listNum = list(map(lambda num: num * 2, listNum))
# print(listNum)
# Filter
# without lambda
# def genap(num):
# return num % 2 == 0
# listNum = [1, 2, 3, 4, 5]
# listNum = list(filter(genap, listNum))
# print(listNum)
# with lambda
# listNum = [1, 2, 3, 4, 5]
# listNum = list(filter(lambda num: num % 2 == 0, listNum))
# print(listNum)
# numList = [1,2,3]
# input = 'x'
# check1 = input in numList
# check2 = 'x' in ['x','y','z']
# check3 = 'KA' in 'kurakas'
# print(check1)
# print(check2)
# print(check3)
"""
Algorithm
"""
# def fizzBuzz(integer):
# for x in range(1, integer+1):
# if x % 3 == 0 and x % 5 == 0:
# print("fizzbuzz")
# elif x % 3 == 0:
# print("fizz")
# elif x % 5 == 0:
# print("buzz")
# else:
# print(x)
# fizzBuzz(30)
# def fibo(urut):
# listData = [1, 1]
# for i in range(2, urut):
# listData.append(listData[i-2] + listData[i-1])
# return listData[urut-1], listData
# print(fibo(100))
# import math
# def reverseList(theList) :
# for i in range(math.floor(len(theList)/2)) :
# tempList = theList[i]
# theList[i] = theList[len(theList) - 1 - i]
# theList[len(theList) - 1 - i] = tempList
# return theList
# print(reverseList([6,4,5,2,3]))
# mean
theList = [1, 2, 3, 2, 5, 2, 7, 3, 3, 4, 4, 4]
#
# import statistics
# mode = statistics.mode(theList)
# print(mode)
# def mean(theList):
# hasil = 0
# for x in theList:
# hasil += x
# print(hasil/len(theList))
# mean(theList)
# median
# def median(thelist):
# thelist.sort()
# median = 0
# if len(thelist) % 2 != 0:
# median = thelist[math.floor(len(thelist)/2)]
# else:
# mid1 = thelist[(int(len(thelist) / 2)) - 1]
# mid2 = thelist[int(len(thelist) / 2)]
# median = (mid1 + mid2) / 2
# return median
# print(median(theList))
# Mode
# def mode(thelist):
# mostCommon = max(map(thelist.count, thelist))
# listSet = set(filter(lambda x: thelist.count(x) == mostCommon, thelist))
# check = list(listSet)
# if len(check) > 1:
# return "This Array have no mode"
# else:
# return check[0]
# print(mode(theList))
# Solve it 1-3
# number = int(input("Masukkan angka: "))
# i = ""
# for item in range(number, 0, -1):
# for item1 in range(0, item):
# i += " * "
# i += "\n"
# print(i)
# Solve it 2-3
# number = int(input("Masukkan angka: "))
# i = ""
# for item in range(number, 0, -1):
# for item1 in range(0, item):
# i += " * "
# i += "\n"
# for item in range(1, number):
# for item1 in range(0, item+1):
# i += " * "
# i += "\n"
# print(i)
# Solve it 3-3
# number = int(input("masukkan angka: "))
# z=""
# for num in range(number):
# for num1 in range(0, number-1-num):
# z+=" "
# for num in range(0, (num*2)+1):
# z+= "*"
# z+="\n"
# print(z)
# solve it 4-3
# space = 0
# for i in range(19, 0, -2):
# print(' '*space + i*'*')
# space +=1
# Solve it 5-3
# space = 9
# for i in range(1, 10, 2):
# print(' '*space + i*'*')
# space-=1
# for i in range(11, 0, -2):
# print(' '*space + i*'*')
# space+=1
# Solve it 1-4
# maself
# arrayList = [200, 10, 20, 3, 1, 8]
# newArray = []
# def sort(theList, sortType):
# if sortType.lower() == 'asc' and theList != []:
# while arrayList:
# minimumNumber = arrayList[0]
# for x in arrayList:
# if x < minimumNumber:
# minimumNumber = x
# newArray.append(minimumNumber)
# arrayList.remove(minimumNumber)
# elif sortType == 'desc' and theList != []:
# while arrayList:
# minimumNumber = arrayList[0]
# for x in arrayList:
# if x > minimumNumber:
# minimumNumber = x
# newArray.append(minimumNumber)
# arrayList.remove(minimumNumber)
# else:
# print('Value yg anda masukkan salah atau kurang!')
# sort(arrayList, 'awdaw')
# print(newArray)
# Bubble Sort
# def sort(listSort, sortType):
# if sortType.lower() == 'asc' and listSort != []:
# for i in range(len(listSort)):
# for x in range(i+1, len(listSort)):
# if listSort[i] > listSort[x]:
# temp = listSort[i]
# listSort[i] = listSort[x]
# listSort[x] = temp
# elif sortType.lower() == 'desc' and listSort != []:
# for i in range(len(listSort)):
# for x in range(i+1, len(listSort)):
# if listSort[i] < listSort[x]:
# temp = listSort[i]
# listSort[i] = listSort[x]
# listSort[x] = temp
# else:
# print('Value yg anda masukkan salah atau kurang!')
# array = [900, 20, 1000, 1, 8, 8, 7, 20]
# sort(array, 'desc')
# print(array)
# Solve it 2-4
# anotherArray = [400, 1000, 900, 250, 125, 110]
# anotherList = []
# def searchMaxandMinValue(theList):
# maxValue = theList[0]
# minValue = theList[0]
# for x in theList:
# if x < minValue:
# minValue = x
# elif x > maxValue:
# maxValue = x
# anotherList[:] = [minValue, maxValue]
# searchMaxandMinValue(anotherArray)
# print(anotherList)
# solve it 1 - 5
# searchList = ['Merdeka', 'Hello', 'Hellos', 'sohib', 'Kari Ayam']
# print(searchList)
# searchValue = []
# searchInput = input("Search: ")
# def search():
# for x in searchList:
# check = searchInput.lower() in x.lower()
# if check:
# searchValue.append(x)
# else:
# print('Tidak ada data')
# break
# print(searchValue)
# search()
# Mr. Baron
# listData = ['Merdeka', 'Hello', 'Hellos', 'sohib', 'Kari Ayam']
# print(listData)
# inputUser = input('Search: ')
# def searchList(keyword, theList):
# newList = list(filter(lambda item: keyword.lower() in item.lower(), theList))
# return newList
# searchedList = searchList(inputUser, listData)
# print(searchedList)
|
d25f80cc00da4d3500b1e1dc60ce75e4e8d3937f | edwardjs55/Python | /OOP/Bike.py | 948 | 4.3125 | 4 | class Bike(object):
def __init__(self,price,speed):
self.price = price
self.max_speed = speed
self.miles = 0
def displayInfo(self):
print "Bike Price: $",self.price," Max Speed: ",self.max_speed," Miles: ",self.miles
return self
def ride(self):
self.miles += 10
print "Riding is a Breeze.."
return self
def reverse(self):
self.miles -= 5
print "Bamm..In Reverse.."
return self
myBike = Bike(250,"100mph")
yourBike = Bike(10,"10mph")
MikesBike = Bike(300,"300mph")
myBike.ride()
myBike.ride()
myBike.ride()
myBike.reverse()
myBike.displayInfo()
yourBike.ride().ride().reverse().reverse().displayInfo()
MikesBike.reverse().reverse().reverse().displayInfo()
# prevent Negatives miles by coding logic in Reverse Method
# All methods should return self Or else it will return null by default
# which will alsso prevent chaining...
|
86f198da1d645c01fc516e11cd27c075e3daba8b | nobe0716/problem_solving | /codeforces/contests/1241/B. Strings Equalization.py | 187 | 3.828125 | 4 | def is_possible(s, t):
st = set(t)
return any(e in st for e in set(s))
for _ in range(int(input())):
s, t = input(), input()
print('YES' if is_possible(s, t) else 'NO')
|
fa69f2f19750b3c8f07d941d68698b5091fc483d | zhenggang587/code | /leetcode/SameTree2.py | 863 | 3.828125 | 4 |
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param p, a tree node
# @param q, a tree node
# @return a boolean
def isSameTree(self, p, q):
if not p and not q:
return True
if not p or not q:
return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
if __name__ == "__main__":
s = Solution()
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(2)
node1.left = node2
node1.right = node3
node4 = TreeNode(1)
node5 = TreeNode(2)
node6 = TreeNode(2)
node7 = TreeNode(3)
node4.left = node5
node4.right = node6
node6.left = node7
print s.isSameTree(node1, node4)
|
13a1ec9f3d69d61fc94ff3883f576395ca6cad7e | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/binarySearch.py | 569 | 3.859375 | 4 | #Uses mid element to narrow array value down until found
import random
def binarySearch(list,element):
list.sort()
top = len(list)
bottom = 0
while top > bottom:
middle = (top + bottom) // 2
if element == list(middle):
return middle
elif element < list[middle]:
top = middle
elif element > list[middle]:
bottom = middle
return -1
list = [int(1000*random.random()) for i in range (1000)]
print(binarySearch,list,list[random.randrange(0, len(list))]
|
ac3134b71a42b889bc513019293c735a4f297bc2 | majf2015/python_practice | /test_proj/class.py | 1,964 | 4.21875 | 4 | class dog():
def eat(self,food):
self.__foo = "dog eat," + food
print self.__foo
def __init__(self, color):
self.__coor = color
def bar(self):
print self.__coor, " dog barking"
#def __len__(self):
# return 23
d = dog("black")
d.eat("qwe" )
d.bar()
#print "len of dog:" + str(len(d))
class BigDog(dog):
def __init__(self, weigth):
dog.__init__(self, "white")
self.__w = weigth
def bar(self):
dog.bar(self)
print " big dog is barking, weight:", self.__w
print "now big dog"
bd = BigDog(23)
bd.bar()
class animal():
def __init__(self):
print 'this is an animal'
def walk(self, str):
self.__s = str
print self.__s
print str
class cat(animal):
def __init__(self, color):
animal.__init__(self)
self.__c = color
def eat(self, food):
self.__foo = 'cat, ' + food
print self.__foo
def __str__(self):
return "cat string"
class lion(dog, cat):
def __init__(self):
cat.__init__(self, 'red')
#dog.__init__(self, 'black')
print "now lion"
l = lion()
l.eat('meat')
a = animal()
a.walk("I can walk")
c = cat('red')
c.walk("red cat")
c.eat('food')
c.new_name ="whatever"
#vim
#dd
# i ->i
c2 = cat("red2")
print hasattr(c2, 'new_name')
print hasattr(c, 'new_name')
def set_name(self,name):
self.name = name
#alt + f12
#from types import MethodType
import types
animal.set_name = types.MethodType(set_name,None,animal)
c.set_name("feng")
c.set_name = set_name
c.set_name(c, "feng")
print c.name
print c
class human(object):
def __init__(self, age):
self._a = age
def __str__(self):
return "xxxx human"
print "now, human"
h = human(23)
#print h.__str__()
print h
#print "2" + h
#print h.get_age
#h.set_age = 27
#print h.get_age
class dummy2(object):
def __init__(self):
pass
def __str__(self):
return "xxxx"
d = dummy2()
print str(d)
print " 2 " + '%s' % dummy2()
|
9344ef8b51ae68b5ece4078de5642af1c783c7ca | chikchengyao/advent_of_code_2017 | /07/b7.py | 4,776 | 3.5625 | 4 | ##########################################################
## Disgusting hacky code pls don't judge ##
##########################################################
# legit this will give you a fucking headache to read
#
# ABANDON HOPE ALL YE WHO ENTER HERE
#
# no, seriously, ask me to explain IRL it'll probably be easier
from input import input
from py7a import root
raw = input.split("\n")
for i in range(len(raw)):
raw[i] = raw[i].split()
raw[i][1] = int(raw[i][1][1:-1])
for j in range(3, len(raw[i]) - 1):
raw[i][j] = raw[i][j][0:-1]
total_weight = {}
nodes = {}
# Populate `nodes`
for node in raw:
nodes[node[0]] = node
# get weight, memoising along the way
def get_total_weight(name):
if name in total_weight:
pass
elif len(nodes[name]) <= 2:
total_weight[name] = nodes[name][1]
else:
sum = nodes[name][1]
for i in range(3, len(nodes[name])): #i.e., for each child of this node
sum += get_total_weight(nodes[name][i])
total_weight[name] = sum
return total_weight[name]
root_name = root()
def all_equal(xs):
if xs == []:
return True
else:
return max(xs) == min(xs)
def is_balanced(name):
# Returns bool
# Finds weights of current children and checks if they're all equal.
weight_list = []
for i in range(3, len(nodes[name])):
weight_list.append(get_total_weight(nodes[name][i]))
return all_equal(weight_list)
def odd_one_out(xs):
if len(xs) <= 2:
print("STOP AT TWO!")
else:
xs.sort()
if xs[0] == xs[1]:
return xs[-1]
else:
return xs[0]
def find_unbalanced(name):
if len(nodes[name]) == 5:
print("STOP AT TWO")
if is_balanced(name):
print("%s is balanced, returning True"%(name))
return True
else:
# look for the odd one out and return find_unbalanced on it
weight_list = []
for i in range(3, len(nodes[name])):
weight_list.append(get_total_weight(nodes[name][i]))
print("weight_list of %s is"%(name), weight_list)
odd_weight = odd_one_out(weight_list)
print("Odd weight is", odd_weight)
for i in range(3, len(nodes[name])):
if odd_weight == get_total_weight(nodes[name][i]):
print("Found odd node is %s"%i)
if find_unbalanced(nodes[name][i]) == True:
print("Return value is True, performing one-off operations")
for j in range(3,len(nodes[name])):
if j != i:
print("Found some j = %d not equal to i = %d"%(j,i))
diff = get_total_weight(nodes[name][j]) - get_total_weight(nodes[name][i])
return nodes[nodes[name][i]][1] + diff
else:
return find_unbalanced(nodes[name][i])
return "FATAL ERROR"
print(find_unbalanced(root_name))
#############################################################
# THE FOLLOWING ARE ALL DEPRECATED
#############################################################
# from input import input
# #print(input)
# nodes = input.split("\n")
# for i in range(len(nodes)):
# nodes[i] = nodes[i].split()
# total_weights = {} #memo table for weights
# def getTotalWeight(index):
# if index in total_weight:
# pass
# elif len(nodes[index]) <= 2: # i.e., has no children
# total_weights[index] = int(nodes[index][1][1:-1])
# print("Weight of %s at index %d is %d"%(nodes[index][0],index,total_weights[index]))
# else
# sum = int(nodes[index][1][1:-1])
# for i in range(3, len(nodes[index])):
# return total_weight[index]
# calculateWeight(2)
# Procedure
# Read list of nodes
# run checkBalanced
# part of checkBalanced is a recursive memoising function called calculateWeight
# #SETUP
# f = open("input2.txt")
# # The set of nodes
# # Structure: Takes a string (the name of the node) and returns an object, which has the properties:
# # name: string name
# # parent: None OR string name
# # children: list of string name
# # weight : int weight
# # total_weight: int total_weight
# # balanced: None OR bool is_balanced
# # Construct two trees represented by dicts, one giving the name of its parent, other giving a list of
# # its children.
# parent_of = {}
# children_of = {}
# weight_of = {}
# for line in f:
# # Parse line info into node details and children
# line = line[:-1] # Get rid of trailing newline
# line = line.split(" -> ")
# details = line[0].split()
# children = []
# if len(line) > 1:
# children = line[1].split(", ")
# # Point parent_of[child] to parent
# for child in children:
# parent_of[child] = details[0]
# # Point children_of[parent] to [children]
# children_of[details[0]] = children
# # Save weight
# weight = int(details[1][1:-1])
# # Walk up parent_of to find root
# # First get any element of the tree
# root = next(iter(parent_of.keys()))
# while root in parent_of:
# root = parent_of[root]
# # Approach: Traverse the tree, at each node flag it as balanced or not. |
76f932b3c7ebaaf9afca41a35bd952724e4a4832 | Aasthaengg/IBMdataset | /Python_codes/p03252/s568934327.py | 322 | 3.625 | 4 | if __name__ == '__main__':
S = input()
T = input()
set_S = set(S)
set_T = set(T)
if len(set_S) != len(set_T):
print("No")
exit()
dic = dict()
flg = True
for x,y in zip(S,T):
if x not in dic:
dic[x] = y
else:
if dic[x] != y:
flg = False
break
if flg :
print("Yes")
else:
print("No") |
faab9a9fbc2df3b1a8524edcc2a6385866812b4e | anaselmi/simple_python | /simple/up_arrow.py | 816 | 4.3125 | 4 | def parser(xpr: str):
""" Parses an up-arrow expression into a tuple containing the parsed expression.
Notes:
↑ is used to denote the up-arrow.
:param str xpr: Expression. Must be an int, n amount of arrows, and an int, separated by spaces.
:return tuple: Parsed expression, represented by three numbers.
0) int a.
1) int arrow. The amount of arrows.
2) int b. The amount of iterations.
"""
xpr = xpr.split(" ")
return int(xpr[0]), len(xpr[1]), int(xpr[2])
def calc(a, arrow, b):
assert(arrow >= 0 and b >= 0)
if arrow == 0:
return a*b
if b == 0:
return 1
return calc(a, arrow-1, calc(a, arrow, b-1))
def up_arrow(xpr: str):
a, arrow, b = parser(xpr)
return calc(a, arrow, b)
|
3a42f465d154eb4910fa3727c657ad129ca3bc0e | rowan-jansens/triangle_distribution | /simple_ca.py | 6,486 | 3.5625 | 4 | #! /usr/bin/env python3
"""Take an initial row and a cellular automaton rule and run the
automaton for a given number of iterations. Then look at the
triangle size distibution"""
import random
import math
def main():
n_cells = 700
n_steps = 800
distribution = {}
simple_distribution(n_steps, n_cells, distribution)
surface_steps(n_cells, distribution)
surface_cells(n_steps, distribution)
def print_distribution(distribution):
for key, value in sorted(distribution.items()):
print(key, value)
#a function to generate a datafile for a simple distribution plot
def simple_distribution(n_steps, n_cells, distribution):
f = open("gnuplot/simple_distribution.dat", "w")
single_run(n_steps, n_cells, distribution)
for key, value in sorted(distribution.items()):
f.write(str(key) + ' ' + str(value) + '\n')
f.close()
#a function to generate a datafile for a more complex suface plot
#of distribution across different n_steps
def surface_steps(n_cells, distribution):
s = open("gnuplot/surface_steps.dat", "w")
for j in range (20):
n_steps = (j+1) * 50 #increment step size by 50
single_run(n_steps, n_cells, distribution)
for key, value in sorted(distribution.items()):
s.write(str(key) + ' ' + str(n_steps) + ' ' + str(value) + '\n')
s.write('\n')
distribution.clear() #clear the dict for next itteration
s.close()
#a function to generate a datafile for a more complex suface plot
#of distribution across different n_cells
def surface_cells(n_steps, distribution):
s = open("gnuplot/surface_cells.dat", "w")
for j in range (20):
n_cells = (j+1) * 50 #increment step size by 50
single_run(n_steps, n_cells, distribution)
for key, value in sorted(distribution.items()):
s.write(str(key) + ' ' + str(n_cells) + ' ' + str(value) + '\n')
s.write('\n')
distribution.clear() #clear the dict for next itteration
s.close()
#runs the simple_ca one time
def single_run(n_steps, n_cells, distribution):
row = set_first_row_random(n_cells)
#row = set_first_row_specific_points(n_cells, [250])
#row = set_first_row_specific_points(n_cells, [200, 600])
#print_row(row)
rule = '01101000' # the basic rule
#rule = '00011110' # the famous rule 30
#rule = '01101110' # the famous rule 110
#rule = '10011001'
for i in range(n_steps):
old_row = row
row = take_step(rule, row)
#print_row(row)
get_distribution(n_cells, old_row, row, distribution)
def take_step(rule, row):
"""a single iteration of the cellular automaton"""
n_cells = len(row)
new_row = [0]*n_cells
for i in range(n_cells):
neighbors = [row[(i - 1 + n_cells) % n_cells], row[i], row[(i + 1) % n_cells]]
# new_row[i] = new_cell(neighbors)
## NOTE: new_cell_with_rule() is part of the extended code (at
## the bottom)
new_row[i] = new_cell_with_rule(rule, neighbors)
return new_row
def new_cell(neighbors):
"""looks at the neighborhood of three cells and determine what the
successor of the central cell should be"""
## this simple approach decides on the next cell based on the sum
## of the neighbors -- if both neighbors are active we are
## overcrowded and we die; if one is active then we come to life;
## if none are active we starve and die.
if neighbors[0] + neighbors[2] == 2: # try [0] and [1] for a different pattern
new_cell = 0
elif neighbors[0] + neighbors[2] == 1:
new_cell = 1
else:
new_cell = 0
return new_cell
def set_first_row_random(n_cells):
"""sets the first row to random values"""
row = [0]*n_cells
for i in range(n_cells):
row[i] = random.randint(0, 1)
return row
def set_first_row_specific_points(n_cells, active_pts):
"""takes a list of specific cells to be activated in the first row"""
row = [0]*n_cells
for pt in active_pts: # only activate the given cells
print(pt)
row[pt] = 1
return row
def print_row(row):
"""prints a row, represented as a blank if the cell is 0 or a special
symbol (like a period) if it's 1"""
on_marker = ' '
row_str = ''
for cell in row:
if cell:
symbol = on_marker
else:
symbol = '0'
print(symbol, end="")
print()
#builds a dict with the triangle distibution of a given run
def get_distribution(n_cells, old_row, row, distribution):
triangle_size = 0
num_triangles = 0
for i in range(n_cells):
left = old_row[(i - 1 + n_cells) % n_cells]
top = old_row[i]
right = old_row[(i + 1) % n_cells]
#Initiate a new triangle as long as the top 3 neighbors are not also "0"
#EG: A single "1" in any of the top three neighbors indicate a new tringle
if row[i] == 0 and (left != 0 or top != 0 or right != 0) and triangle_size == 0:
triangle_size += 1
#Increment the size counter for each additional 0 after a new
#triangle has been identified
elif row[i] == 0 and triangle_size > 0:
triangle_size += 1
#Terminate the triangle counter when a 1 is reached in the row
#If the triangle size is already in the dictionary, increment the value by 1
#Else, add the size as a new key in the dict and set the vaule as 1
#Then reset the size_counter
elif row[i] == 1 and row[(i - 1 + n_cells) % n_cells] == 0 and triangle_size > 0:
distribution[triangle_size] = distribution.get(triangle_size, 0) + 1
num_triangles += 1
triangle_size = 0
## NOTE: new_cell_with_rule() is extended code; you can skip it on a
## first implementation
def new_cell_with_rule(rule, neighbors):
"""Applies a rule encoded as a binary string -- since a neighborhood
of 3 binary cells can have 8 possible patterns, it's a string of 8
bits. You can modify it to be any of the 256 possible strings of
8 bits. I provide a couple of examples, and you can try many others."""
if not rule:
rule = '01101000' # the default rule
rule_index = neighbors[0] + 2*neighbors[1] + 4*neighbors[2]
cell = int(rule[rule_index])
return cell
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.