blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e69ec9688ec8b3cc2d1c48dd0d44c8332b19fcfe | storans/as91896-virtual-pet-jemimagregory | /exit_to_main_menu.py | 2,351 | 4.625 | 5 | # including the list items function and welcome screen function for testing
# This function is used after the main explanation of how the program works
def welcome_screen(pet_name):
# displays an introduction of the pet rabbit to the user
print("This is your pet, {}!".format(pet_name))
print(" _________ ________ \n"
" / \ / \ \n"
" / /~~~~~\ \ / /~~~~~\ \ \n"
" | | | | | | | | \n"
" | | | | | | | | \n"
" | | | | | | | | / \n"
" | | | | | | | | // \n"
"(O O) \ \_____/ / \ \_____/ / \n"
" \__/ \ / \ / \n"
" | ~~~~~~~~~ ~~~~~~~~ \n"
" ^")
def list_items(list_name):
# sets the number the list begins with to 1
number = 1
# uses the 'list' argument to assess what dictionary to take the items from to display. (eg. if the argument given in the main routine was FOOD_DICTIONARY then the program lists the food.)
for item in list_name:
# displays the dictionary of items in an ordered list for the user to choose from. (formats the dictionary)
print("{}. {}".format(number, item))
# makes the number increase as the list items increase
number += 1
# this is the function this component is centred around
def exit_to_main_menu(back_to_function, pet_name, list_name):
# asks the user if they would like to continue to the main menu
leave = input("Would you like to return to the main menu? ENTER to exit, or PRESS ANY KEY to return to what you were just doing")
# (using an if statement to move onto the function listing the main menu items (by entering) if the user chooses to move to the main menu [if leave == ""]
if leave == "":
list_items(list_name)
# else, go back to [back_to function])
else:
back_to_function(pet_name)
# Main Routine
MAIN_MENU_ITEMS = ["Check Pet's Weight", "Feed Pet", "Exercise Pet", "See Help Information", "Exit Game"]
# calling the function to test it, using the welcome_screen function screen as a test of what the user may have been doing before deciding the wanted to exit
exit_to_main_menu(welcome_screen, "Slip", MAIN_MENU_ITEMS)
|
772f2f3d721ab934884e9a366380be5739e0f3f5 | guam68/class_iguana | /Code/nathan/pythawn/lab_07_rpc.py | 959 | 3.921875 | 4 | import random
intro_txt = input('WE ARE PLAYING ROCK PAPER SCISSORS\n your choices are >r >p or >s\n Press ENTER to continue ')
choices = ['r', 'p', 's']
player_choice = ''
computer_choice = random.choice(choices)
player_choice = input('name your weapon\n >')
if player_choice == 'r' and computer_choice == 'r':
print('r v r = TIE')
if player_choice == 'r' and computer_choice == 'p':
print('r v p = LOSE')
if player_choice == 'r' and computer_choice == 's':
print('r v s = WIN')
if player_choice == 's' and computer_choice == 'p':
print('s v p = WIN')
if player_choice == 's' and computer_choice == 'r':
print('s v r = LOSE')
if player_choice == 's' and computer_choice == 's':
print('s v s = TIE')
if player_choice == 'p' and computer_choice == 'p':
print('p v p = TIE')
if player_choice == 'p' and computer_choice == 's':
print('p v s = LOSE')
if player_choice == 'p' and computer_choice == 'r':
print('p v r = WIN')
|
fe8302d75ca11c46b9aff46ed816c3f536a26220 | mmarano25/collatz-graph | /prototype.py | 931 | 3.65625 | 4 | import plotly as plt
import plotly.graph_objs as go
TESTS_ON = False
def collatz_steps(num: int) -> int:
"""runs the collatz conjecture on num, returns number of steps"""
if num == 0:
return 0
n = 0
while num != 1:
n += 1
if (num % 2) == 0:
num /= 2
else:
num = (num * 3) + 1
return n
# tests:
if TESTS_ON:
assert collatz_steps(0) == 0
assert collatz_steps(10) == 6
assert collatz_steps(1000) == 111
assert collatz_steps(123214) == 211
def collatz_from_one_to_x(x: int) -> list:
"""returns number of steps of collatz from numbers 1 to x"""
result = list()
for num in range(1,x):
result.append(collatz_steps(num))
return result
collatz_data = collatz_from_one_to_x(100000)
plotly_data = [
go.Histogram(
x=collatz_data,
nbinsx=len(set(collatz_data))
)
]
plt.offline.plot(plotly_data)
|
416ad983720100d66aa98e45711a352792c85cc9 | babuhacker/python_toturial | /input_output/test.py | 664 | 3.59375 | 4 | import os
file = []
while True:
option = input("what you want to do?\n")
if option == 'file':
user = input("now you want to\n""1.read.\n" "2.delete.\n" "3.append.\n")
if user == 'read':
name = input("tell me the file name")
outputfile = open(name, "r")
file_content = outputfile.read()
print(file_content)
if user == "delete":
os.remove('file.abc')
if user == "append":
name1 = input("tell me the file name")
outputfile = open(name1, "a")
outputfile.write(input("what you want to write. "))
outputfile.close()
|
18212efbeffea53b13a5ff9fbbc8c1e682c82d18 | mholmes21/Project-Euler | /zComplete-Problem58.py | 894 | 4.03125 | 4 | import time
def isPrime(n):
if n < 2:
return 0
elif n == 2:
return 1
elif n % 2 == 0:
return 0
else:
for x in range(3, int(n**0.5) + 1, 2):
if n % x == 0:
return 0
return 1
def calc_corners(s):
tmp = list()
tmp.append(s**2)
tmp.append(s**2 - s + 1)
tmp.append(s**2 - 2*s + 2)
tmp.append(s**2 - 3*s + 3)
return tmp
def count_primes(corners):
tmp = [0]*len(corners)
return sum([isPrime(x) for x in corners])
start = time.time()
# Start with side length 1
# Temp variable for counting number of primes
s = 1
p = 0
while (s):
corners = calc_corners(s)
p += count_primes(corners)
s += 2
# Check if #primes/#total is less than 10%
if (s > 7) and (p/(2*s - 1) < 0.10):
break
end = time.time()
print("The value of s is:", s, "in", end-start, "seconds")
|
428a1df46295ee5b127a9a89a012ee15dee75d7d | artorious/python3_dojo | /phone_list.py | 1,191 | 4.25 | 4 | #/usr/bin/env python3
""" A simple telephone contact list.
Uses Python dictionary to implement a simple telephone contact database with
a rudimentary command line interface.
The contact list associates a name with a telephone number.
A person or company’s name is a unique identifier for that contact.
The name is a key to that contact.
"""
contacts = {} # Init global telephone contact list
running = True
while running:
command = input('A)dd D)elete L)ook-up Q)uit: ')
if command == 'A' or command == 'a':
name = input('Enter new name: ')
print('Enter phone number for {0}: '.format(name))
number = input('>>> ')
contacts[name] = number
elif command == 'D' or command == 'd':
name = input('Enter name to DELETE: ')
del contacts[name]
elif command == 'L' or command == 'l':
name = input('Enter name to Look-up: ')
print('Name: {0} - Tel: {1}'.format(name, contacts[name]))
elif command == 'Q' or command == 'q':
running = False
elif command == 'dump':
print(contacts)
else:
print('Oops... {0} - NOT a valid command....Try again')
|
57eab3aa9a4cab151583d91ee20ec31c0ffd396d | Anondo/algorithms.py | /BlockChain/main.py | 286 | 3.546875 | 4 | from blockchain import BlockChain
myChain = BlockChain()
myChain.addBlock("first block")
myChain.addBlock("second block")
myChain.addBlock("third block")
myChain.addBlock("forth block")
for block in myChain.getBlocks():
print block.getData()
print myChain.getBlock(1).getData()
|
c6c07a7f873449f0cf8aa10223944a4737ce8194 | tyamz/CPS3310---PL | /Project3.py | 456 | 3.703125 | 4 | def main():
spam = ['apples', 'bananas', 'tofu', 'cats']
test = ['oranges', 'tomatoes', 'sushi', 'dogs']
def printList(lst):
str = ""
for i in range(len(lst)):
if i == len(lst) - 1:
str = str + ", and " + lst[i]
elif i == 0:
str = str + lst[i]
else:
str = str + ", " + lst[i]
print(str)
printList(spam)
printList(test)
main()
|
139f549a28e8e4679313f938946ce4f5173e4efd | wangjinyu124419/leetcode-python | /169. 多数元素.py | 402 | 3.640625 | 4 | """
169. 多数元素
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
"""
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums.sort()
return nums[len(nums)//2] |
7ce1b0d93ddc34fa89277b150d7143b6fbd700f4 | olsen601/guess_the_number | /Capstone_lab1_part1.py | 345 | 4 | 4 | from random import randint
answer = randint(1,11)
guess = input("Guess a number between 1 & 50:")
g = int(guess)
while g != answer:
print("guess again")
if g > answer:
print("too high")
elif g < answer:
print("too low")
guess = input("Guess a number between 1 & 50:")
g = int(guess)
print("correct!")
|
cc8fead178eb8ed27db84ce5184bb83b49914d6c | yuanlyainihey/review | /treeAndGraph/treeFunc.py | 4,657 | 4.0625 | 4 | class Node(object):
def __init__(self, val=-1):
self.val = val
self.left = None
self.right = None
class Tree(object):
def __init__(self):
self.root = Node()
def isEmpty(self):
if self.root is None:
return True
else:
return False
def addNode(self, val):
newNode = Node(val)
if self.root.val == -1:
self.root = newNode
else:
queue = [self.root]
while queue:
node = queue.pop(0)
if node.left is None:
node.left = newNode
return
elif node.right is None:
node.right = newNode
return
else:
queue.append(node.left)
queue.append(node.right)
def getParent(self, val):
if self.root.val == val:
print('根节点无父母')
return
tmp = [self.root]
while tmp:
node = tmp.pop(0)
if node.left and node.left.val == val:
print(node.val)
return
if node.right and node.right.val == val:
print(node.val)
return
if node.left is not None:
tmp.append(node.left)
if node.right is not None:
tmp.append(node.right)
print('树中无该节点')
return
def preOrder(self, node):
if node is None or node.val == -1:
return
print(node.val)
self.preOrder(node.left)
self.preOrder(node.right)
def inOrder(self, node):
if node is None or node.val == -1:
return
self.inOrder(node.left)
print(node.val)
self.inOrder(node.right)
def postOrder(self, node):
if node is None or node.val == -1:
return
self.postOrder(node.left)
self.postOrder(node.right)
print(node.val)
def getHeight(self, node):
if node is None or node.val == -1:
return 0
else:
return max(self.getHeight(node.left), self.getHeight(node.right)) + 1
def minDepth(self):
if self.root is None:
return 0
queue = [self.root]
minHeight = 1
while queue:
popNode = queue.pop(0)
if popNode.left is None or popNode.right is None or popNode.left.val == -1 or popNode.right.val == -1:
return minHeight
if popNode.left is not None and popNode.left.val != -1:
queue.append(popNode.left)
if popNode.right is not None and popNode.right.val != -1:
queue.append(popNode.right)
minHeight += 1
return minHeight
def isBalance(self, node):
if node is None or node.val == -1:
return True
leftHeight = self.getHeight(node.left)
rightHeight = self.getHeight(node.right)
if abs(leftHeight-rightHeight) > 1:
return False
return self.isBalance(node.left) and self.isBalance(node.right)
def BFSTree(self):
if self.root is None:
return []
result = []
queue = [self.root]
while queue:
popNode = queue.pop(0)
result.append(popNode.val)
if popNode.left is not None and popNode.left.val != -1:
queue.append(popNode.left)
if popNode.right is not None and popNode.right.val != -1:
queue.append(popNode.right)
return result
def isCompleteness(self):
if self.root is None:
return True
nodes = [self.root]
val = [self.root.val]
while nodes:
node = nodes.pop(0)
if node.left:
nodes.append(node.left)
val.append(node.left.val)
if node.right:
nodes.append(node.right)
val.append(node.right.val)
try:
val.index(-1)
return False
except:
return True
if __name__ == '__main__':
tree = Tree()
treeVal = [1, 2, 3, -1, 4, 5, 6, -1, -1, 7]
for i in treeVal:
tree.addNode(i)
# 树的DFS的三种方式:preOrder,inOrder,postOrder
# tree.preOrder(tree.root)
# tree.inOrder(tree.root)
# tree.postOrder(tree.root)
# tree.getParent(7)
# print(tree.getHeight(tree.root))
# print(tree.isBalance(tree.root))
# 树的BFS
# print(tree.BFSTree())
# print(tree.minDepth())
print(tree.isCompleteness) |
902745e015ef300425b438ce60fbe31d68721429 | husseinberk/python | /Problem 1 ( Beden Kitle İndeksi ).py | 428 | 3.84375 | 4 | print("Beden Kitle Endeksi Hesaplama Programı")
kilo = int(input("Lütfen Kilo Değerinizi Giriniz: "))
boy = float(input("Lütfen Boy Değerinizi Giriniz: "))
bki = kilo / ( boy ** 2)
print("Beden Kitle İndeksiniz: {} ".format(bki))
print("Kilo Durumunuz: ")
if (bki <= 18.5):
print("Zayıf")
elif (bki <= 25):
print("Normal")
elif (bki <= 30):
print("Fazla Kilolu")
else:
print("Obez")
|
c56fae91eaf2a9d13fb0decdfa89d03b8f86465c | wf-Krystal/TestDemo | /PTestDemo/dictTest/dictDemo2.py | 918 | 3.59375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
info = {
'stu1101': "zhangsan",
'stu1102': "wangwu",
'stu1103': "lisi"
}
b = {
'stu1101': "wangsui",
1: 3,
2: 5
}
c = dict.fromkeys([6, 7, 8]) #初始化一个字典,初始化keys
print(info.values()) #输出字典中的值
print('-------分隔线-------')
print(b.keys()) #输出字典中的key
print('-------分隔线-------')
info.setdefault('stu1101', 'abc') #如果key存在,不改变任何值;如果key不存在,则创建key并赋值
info.update(b) #合并字典,并且更新对应的key的值
print(info)
print('--------分隔线------')
print(c)
print('--------分隔线------')
#字典循环
#example1 推荐方法
for i in info:
print(i, info[i])
print('--------分隔线------')
#example2 不推荐使用,先要把字典转成列表,如果数据量大,效率大大降低
for k, v in info.items():
print(k, v) |
2b8501be5b877b150ba440d03fc3deddd25944d1 | Xiaoctw/LeetCode1_python | /字符串/比较含退格的字符串_844.py | 549 | 3.515625 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
list1 = []
list2 = []
for c in S:
if c != '#':
list1.append(c)
elif list1:
list1.pop()
for c in T:
if c != '#':
list2.append(c)
elif list2:
list2.pop()
if len(list2) != len(list1):
return False
for i in range(len(list1)):
if list1[i]!=list2[i]:
return False
return True |
14aad4c7bbabb44a323926346881304d35f3dba7 | maydan90/udacity_algorithms | /problem_6.py | 860 | 4.0625 | 4 | import random
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if not ints:
return None, None
min_value = ints[0]
max_value = ints[0]
for number in ints:
if number < min_value:
min_value = number
elif number > max_value:
max_value = number
return min_value, max_value
# Example Test Case of Ten Integers
values = [i for i in range(0, 10)] # a list containing 0 - 9
random.shuffle(values)
print("Pass" if ((0, 9) == get_min_max(values)) else "Fail")
values = [i for i in range(0, 1000)] # a list containing 0 - 999
random.shuffle(values)
print("Pass" if ((0, 999) == get_min_max(values)) else "Fail")
print(get_min_max([1]))
print(get_min_max([]))
|
a141a8197b93fdd1adc4fc2ddcb9182e89875f81 | danielfernandezexposito/cursopython | /fechas.py | 540 | 3.921875 | 4 | # Tipo de dato "date"
# Ejemplo de resta de fechas
# Calculo de dias restantes para cumple
from datetime import date
from datetime import datetime
print("¿Cuando es tu cumpleanyos?")
print("Dia: ")
dia = int(input())
print("Mes: ")
mes = int(input())
hoy = datetime.now()
anyocumple = hoy.year
if(hoy.month > mes):
anyocumple = anyocumple + 1
elif (hoy.month == mes and hoy.dia > dia):
anyocumple = anyocumple + 1
resta = abs(hoy - datetime(anyocumple, mes, dia))
print(f"quedan " + str(resta.days) + " dias para tu cumple")
|
c508880949428409c825a3571d97a1859090919b | rcampbell1337/secret-santa-generator | /GUI/email_sender.py | 4,057 | 3.578125 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter.font import Font
from tkinter import messagebox
import webbrowser
from Logic.pass_hasher import encrypt_pass
from database import DatabaseTables
from GUI.email_list import EmailList
# This class sets the email and app password of the sender device
class Sender:
def __init__(self):
self.root = tk.Tk()
self.font = Font(family="helvetica", size=9, weight="bold")
self.font_alt = Font(family="helvetica", size=14, weight="bold")
self.root.title("Set Email For Send")
self.root.resizable(False, False)
self.root.geometry("+750+250")
self.frame = tk.Frame(master=self.root).grid()
text = "Thank you for using the secret santa generator! Before we start you have to" \
" enter a few details, there is information on how to set this up here:"
# Links the user to documentation to set up a gmail account for this service
self.information = tk.Label(self.frame, font=self.font, padx=20, pady=10, text=text, wraplength=300)
self.information.grid(row=0, column=0, columnspan=2)
self.link = tk.Button(self.frame, font=self.font_alt, padx=5, pady=5, bg="black", text=r"DOCUMENTATION",
fg="white", cursor="hand2")
self.link.grid(row=1, column=0, columnspan=2)
self.link.bind("<Button-1>", lambda e: webbrowser.open_new("https://realpython.com/python-send-email/#option-1-"
"setting-up-a-gmail-account-for-development"))
self.prompt1 = tk.Label(self.frame, pady=10, text="But without further ado, please enter the email and password"
" of your gmail account: ", font=self.font, wraplength=300).grid(row=2, column=0, columnspan=2)
# Get the email and app password of the user
self.prompt2 = tk.Label(self.frame, text="Enter email:", font=self.font).grid(row=3, column=0)
self.prompt3 = tk.Label(self.frame, text="Enter Generated App Password:", font=self.font).grid(row=3, column=1)
self.email_input = tk.StringVar()
self.email = ttk.Entry(self.frame, width=30, textvariable=self.email_input)
self.email.grid(row=4, column=0)
self.password_input = tk.StringVar()
self.password = ttk.Entry(self.frame, width=30, textvariable=self.password_input, show="*")
self.password.grid(row=4, column=1)
# Submit Email and app password
self.submit = tk.Button(self.frame, pady=15, text="SUBMIT SENDER INFO", bg="black", fg="white",
command=self.submit_sender_acc, font=self.font_alt)
self.submit.grid(row=5, column=0, columnspan=2, sticky="w"+"e")
self.root.mainloop()
self.root.quit()
# Confirms with the user that they are happy with entered details
def submit_sender_acc(self):
result = tk.messagebox.askquestion("Are you sure?", "Are you happy with the email sender details of "
+ self.email_input.get(), icon='warning')
if result == 'yes':
# Makes sure the email address is a valid one
if self.email_input.get().__contains__("@gmail.com"):
database = DatabaseTables()
database.clear_sender_info()
# Enters data into database with encryption
sender_details = (self.email_input.get(), encrypt_pass(self.password_input.get()))
database.create_sender(sender_details)
database.close_db()
tk.messagebox.showinfo("Success!", "Sender email entered successfully!", icon="info")
self.root.destroy()
# Open the email list gui
EmailList()
else:
tk.messagebox.showinfo("Enter a valid address!", "That isn't a gmail account!")
return
else:
return
if __name__ == "__main__":
Sender()
|
8a25ebd7c54b0d5e907122d7913a51c1623feaec | mareaokim/lotto_hee | /jaggy&minggy.py | 705 | 3.78125 | 4 | #UP&DOWN게임
import random
#게임을 위한 숫자 생성
rn = random.randrange(1,101,1)
num = -1
t_cnt = 0 #시도횟수
print("1~100 숫자 재기&민기 게임을 시작합니다. !!!")
print("재기재기재기 민기민기민기")
while (rn != num):
num = int(input("1~100 사이의 숫자를 입력하세요 : "))
if (num > rn):
print("재기!")
elif (num < rn):
print("민기!")
t_cnt +=1
print("-------------------------------------")
print(t_cnt,"축하합니다. 철근과 밧줄 세트를 드립니다.")
|
929d2dbb0174476f6d396e2328e6cfe70984a7b0 | mrayirebi/Python-projects | /Geometric pattern.py | 440 | 3.890625 | 4 | from turtle import *
import random
#create a screen
screen = Screen()
screen.screensize(600,600,'black')
#create a pen to draw geometric pattern
pen = Pen()
pen.speed(150)
size = 20
for i in range(150):
r = random.randint(0,225)
g = random.randint(0,225)
b = random.randint(0,225)
randcol = (r,g,b)
colormode(255)
pen.color(randcol)
pen.circle(size,steps = 4)
pen.right(55)
size = size +3
|
bb4bcf45710620042fe310048a71c3056efcad01 | ajioka-fumito/kyopro | /2_ant_book/2-1 全探索/02_stackとqueue.py | 952 | 4.0625 | 4 | # スタック
"""
最後に追加された要素を最初に(O(1)で)取り出すことができるデータ構造
LIFO : last in first out
python では標準Listが対応しているが後述するcollections.dequeで実装することも可能
"""
def sample_stack():
stack = [1,2,3]
print("stack:",stack)
stack.append(4)
print("stack:",stack)
stack.append(5)
print("stack:",stack)
stack.pop()
print("stack:",stack)
# キュー
"""
要素を最後尾に追加し,先頭の要素を取り出すことができるデータ構造
FIFO : first in first out
python ではcollections.dequeで実装
"""
from collections import deque
def sample_queue():
queue = deque([1,2,3])
print("queue:",queue)
queue.append(4)
print("queue:",queue)
queue.append(5)
print("queue:",queue)
queue.popleft()
print("queue:",queue)
if __name__ == "__main__":
sample_stack()
print()
sample_queue() |
307d2fd9bfd02fe100f4316377beb791f7b95f1d | nkkodwani/arul-naveen-c2fo-2021 | /PracticeProjects/ArulFiles/read_from_file.py | 446 | 3.546875 | 4 | #READ FROM FILE: Excercise 22 from practicepython.org
darth = 0
luke = 0
lea = 0
with open('/Users/arul.sethi/Desktop/nameslist.txt', 'r') as open_file:
line = open_file.readline()
while line:
if 'Darth' in line:
darth += 1
elif 'Luke' in line:
luke += 1
elif 'Lea' in line:
lea += 1
line = open_file.readline()
print(f"Darth: {darth}\nLuke: {luke}\nRea: {lea}")
|
881640cd68e2feb05993d44cf56c9db372450cb8 | achmaddidhani/labpy03 | /LATIHAN2.py | 301 | 3.953125 | 4 | print("*****lathan2*********")
print("menampilkan bilangan, berhenti ketika bilangan 0, dan menampilkan bilangan terbesar")
max = 0
while True:
a=int(input("masukan bilangan = " ))
if max < a :
max = a
if a==0:
break
print("bilangan terbesarnya adalah = ",max)
|
229b9eea5a5c5e63f949b6eacd626e0fdc91eb64 | MatheusOlegarioDev/Python_Crie_Seus_Primeiros_Programas | /Fundamentos/Ambiente.py | 691 | 3.59375 | 4 | Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 1 #Inteiro
1
>>> 1.0 #Float
1.0
>>> 1. #Float
1.0
>>> 1 + 2j #Complex
(1+2j)
>>> #Gerando Números por meio de funções
>>> int(1.0)
1
>>> int('9')
9
>>> float(1)
1.0
>>> float('9.2')
9.2
>>> float('-inf')
-inf
>>> float('+inf')
inf
>>> float('nan')
nan
>>> complex(1, 2)
(1+2j)
>>> # Teste de Ambiente
>>> 3 + 2
5
>>> 3 + 4.2
7.2
>>> 4 / 2
2.0
>>> 5 / 2
2.5
>>> 5 // 2
2
>>> complex(1, 2)
(1+2j)
>>> complex(1, 2) + 2
(3+2j)
>>> complex(2, 0) + 0 +1j
(2+1j)
>>> 2 + 0+1j
(2+1j)
>>>
|
1245680845d0f6e4102053fae45f59d94e1580e3 | anEffingChamp/compSci321 | /chapter6/17.py | 1,102 | 4.46875 | 4 | # Jonathan Smalls
# computer science 321
# 6.17 myTriangle module
# returns true if sum of any two sides is greater than third
import sys
import math
def isValid(side1, side2, side3):
for side in [side1, side2, side3]:
lengthsTemp = [side1, side2, side3]
lengthsTemp.remove(side)
if (sum(lengthsTemp) > side):
continue
return False
# returns area of triangle
def area(side1, side2, side3):
# https://en.wikipedia.org/wiki/Triangle#Computing_the_area_of_a_triangle
# We use Herons formula to calculate.
areaSemi = (side1 + side2 + side3) / 2
area = math.sqrt(areaSemi * (areaSemi - side1) * (areaSemi - side2) * (areaSemi - side3))
print('The area of the triangle is ' + str(area))
return
print('We will calculate the area of a triangle.')
sides = []
for loop in range(0, 3):
side = eval(input('Please enter the length of side ' + str(loop + 1) + ': '))
sides.append(side)
if False == isValid(sides[0], sides[1], sides[2]):
print('These side lengths can not form a triangle.')
sys.exit
area(sides[0], sides[1], sides[2])
|
aa6a5a63c40ab696091f5a333ceba8333fbbb09f | shamsherrathore/Python | /student_marks.py | 982 | 4.0625 | 4 | student_name = str(input("enter the student name:"))
print('<<<<<<<<<wecome to the RANA group of college>>>>>>>>>')
n = int(input("enter the the subjects:"))
total_marks = 0
print("enter marks")
for i in range (1, n+1):
marks = float(input("subject"+str(i)+":"))
assert marks>=0 and marks<=100
total_marks += marks
print('*******************************************************************')
print('student name:', student_name,' total marks scored:',total_marks)
percentages = total_marks/n
print("total percentage of student is:",percentages)
if percentages>90 and percentages<=100:
prize = "ferrari"
print("congrats you won:",prize)
elif percentages>80 and percentages<=90:
prize = "audi"
print("congrats you won:",prize)
elif percentages >50 and percentages<=80:
prize = "bullet"
print("congrats you won:",prize)
else:
print("congrats you won: auto")
print("\n>>>>>end of the result<<<<<")
|
771da37cb71ba3676a87a897743299f4e77ba33f | cleosilva/desafios_Python | /9_notasAlunos.py | 1,110 | 4.25 | 4 | # Dados um número inteiro n, n > 0, e uma sequência com n notas finais de MAC2166, determinar quantos alunos:
# estão de recuperação: nota final maior ou igual a 3 e menor do que 5;
# foram reprovados: nota final menor do que 3;
# foram aprovados: nota final maior ou igual a 5;
# tiveram um desempenho muito bom: nota maior que 8;
alunos = int(input('Digite o número de alunos: '))
contaAlunosReprovados = 0
contaAlunosAprovados = 0
contaAlunosRecuperacao = 0
contaAlunosBomDesempenho = 0
i = 1
while i <= alunos:
nota = float(input('Digite a nota do aluno: '))
if nota < 3:
contaAlunosReprovados += 1
if nota >= 5:
contaAlunosAprovados += 1
if nota >=3 and nota < 5:
contaAlunosRecuperacao += 1
if nota > 8:
contaAlunosBomDesempenho += 1
i += 1
print('Total de alunos',alunos)
print('Número de alunos reprovados:',contaAlunosReprovados)
print('Número de alunos em recuperação:',contaAlunosRecuperacao)
print('Número de alunos aprovados:',contaAlunosAprovados)
print('Numero de alunos com bom desempenho:',contaAlunosBomDesempenho)
|
29199c16bceec77469cfda0acaaf19605c0f397f | Gaurav3099/Python | /L1/prac5.py | 149 | 3.859375 | 4 | #calcius to Fahrenheit
s=input("enter temp in celcius ")
cel = float(s)
fah = cel*1.8+32
print("Fahrenheit ",fah)
print("fahrenheit %4.2f"%fah) |
bacf076749e9fa84b22c54de47a3a4259975f690 | prateeksha29/DSA--Python | /Medium level/Arrays/LeetCode 75 - Sort Colors.py | 971 | 4.3125 | 4 | """
Given an array nums with n objects colored red, white, or blue, sort them in-place
so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
"""
# Three pointers
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
p0 = curr = 0
p2 = len(nums) - 1
while curr <= p2:
if nums[curr] == 0:
nums[p0], nums[curr] = nums[curr], nums[p0]
p0 += 1
curr += 1
elif nums[curr] == 2:
nums[curr], nums[p2] = nums[p2], nums[curr]
p2 -= 1
else:
curr += 1
|
fb16a1e130461cbc9a045c35c29d71efdad7c147 | reiterative/aoc2019 | /calc-fuel.py | 531 | 3.640625 | 4 | import math
def fuel_required(mass):
f = (mass / 3) - 2
if f < 0:
f = 0
return math.floor(f)
cnt = 1
fuel_total = 0
with open('input-day1') as fp:
line = fp.readline()
while line:
print("Line {}: {} ( {} )".format(cnt, line.strip(), fuel_total))
m = int(line)
fr = fuel_required(m)
while fr > 0:
fuel_total += fr
fr = fuel_required(fr)
line = fp.readline()
cnt += 1
print ("Total fuel required: {}".format(int(fuel_total)))
fp.close()
|
9494f6ba527faea030a0f7f7d427fbfa3034259b | cicihou/LearningProject | /leetcode-py/leetcode279.py | 721 | 3.625 | 4 | '''
代码+图解:https://leetcode-cn.com/problems/perfect-squares/solution/hua-jie-suan-fa-279-wan-quan-ping-fang-shu-by-guan/
最差的情况就是
dp[i] = i,也就是说要构成 5 的完全平方差,需要 5个 1
优化的情况就是,创造一个 j,在 j 的平方小于当前所需要的数的情况下,用j 来优化我们所需要的正方形平方的个数
'''
class Solution:
def numSquares(self, n: int) -> int:
dp = [0] * (n+1)
for i in range(1, n+1):
dp[i] = i # 最坏情况
j = 1
while i - j**2 >= 0:
dp[i] = min(dp[i], dp[i-j**2] + 1) # 将当前的正方形个数优化
j += 1
return dp[n]
|
dc9295f5b0aaad9d9eb040afaa0a7909b9c278bc | niranjan-nagaraju/Development | /python/algorithms/arrays/sums/two_sums.py | 637 | 4.125 | 4 | '''
Find and return all pairs that add upto a specified target sum
'''
# Return all pairs with sum in a sorted array
def two_sums_sorted(a, target):
pairs = []
i, j = 0, len(a)-1
while i < j:
curr_sum = a[i]+a[j]
if curr_sum == target:
pairs.append((a[i], a[j]))
i += 1
j -= 1
elif curr_sum < target:
# Move left pointer so current sum increases
i += 1
else: # curr_sum > target:
# Move right pointer so current sum decreases
j -= 1
return pairs
if __name__ == '__main__':
assert two_sums_sorted([1,2,3,4,5,6,7], 8) == [(1,7), (2,6), (3,5)]
assert two_sums_sorted([1,2,3,4,5], 7) == [(2,5), (3,4)]
|
cec0b6cb5e29ff1687dcdafe3950d4bef8675ef0 | Ushravan/Programming-Foundations-With-Python | /Conditional Statements/String_Repetition_3.py | 532 | 4.40625 | 4 | #String Repetition 3
#Given a word and a number (N), write a program to print the last three characters of the word N times in a single line.
#Explanation
#For example, if the given input is "Transport" and the given number is 2.
#The last three characters of the given word are "ort", which have to be repeated 2 times, so the output should be "ortort"
Word =input()
N = int(input())
length = len(Word)
start_from = length-3
repeatation_of_characters = Word[start_from:]
massage = repeatation_of_characters*N
print(massage)
|
74efec896366d743a740aa901ac874e405d7d1a5 | ankit595/tathastu_week_of_code | /Day 1/Program 4.py | 189 | 3.828125 | 4 | cost_price=int(input("Enter cost price:-"))
sell_price=int(input("Enter selling price:-"))
profit=sell_price-cost_price
sell_price=sell_price+profit*.05
print(profit)
print(sell_price)
|
f16b9e2a1301061421ef0c7e8ec64cfe0ff400b0 | idkwim/ctf-10 | /crypto/0003_2017_BugsBunny_Crypto15/crypto15.py | 641 | 3.671875 | 4 | # -*- coding: utf-8 -*-
#/usr/bin/env python
import string
# Flag : Piug_Pibbm{Q35oF_3BQ0R3_4F3_B0H_G3QiF3_OH_4ZZ}
def encode(story, shift):
return ''.join([
(lambda c, is_upper: c.upper() if is_upper else c)
(
("abcdefghijklmnopqrstuvwxyz"*2)[ord(char.lower()) - ord('a') + shift % 26],
char.isupper()
)
if char.isalpha() else char
for char in story
])
def decode(story,key):
pass
if __name__ == '__main__':
print ord('n') - ord('b')
exit()
key = [_YOUR_KEY_HERE_]
print decode("Piug_Pibbm{Q35oF_3BQ0R3_4F3_B0H_G3QiF3_OH_4ZZ}",key) |
c05858ba61e68c91bb2d0d92bdb673f39d81f0d0 | martapastor/GIW-Practicas | /Practica1/ejercicio3.py | 4,125 | 4 | 4 | import sys
# We declare the name for the output file where the results will be written
output_file = "output.txt"
def count_words(lines_in_file):
# We create an empty dictionary to save the words and the number of times it appears in the text
# As the words are not sorted in the text, using a dictionary with a key -> value relation is the
# most efficient way to do it, as we can also search in the dictionary by the word itself and not
# necessarely by index
words_dic = {}
for each_line in lines_in_file:
# We select the words such as prepositions and conjuntions that we don't
# to count during the process...
discarded_special_chars = ['', '-', '&', '/']
discarded_articles = ['el', 'la', 'los', 'las', 'un', 'uno', 'una', 'unos', 'unas', 'mi', 'mis', 'tu', 'tus', 'su', 'sus', 'nuestro', 'nuestros', 'vuestro', 'vuestros']
discarded_prepositions = ['a', 'ante', 'bajo', 'cabe', 'con', 'contra', 'de', 'desde', 'en', 'entre', 'hacia', 'hasta', 'para', 'por', 'segun', 'sin', 'so', 'sobre', 'tras']
discarded_conjunctions = ['y', 'e', 'ni', 'que', 'pero', 'aunque', 'sino', 'sea', 'pues', 'porque']
# ... and we add all different arrays in a unique list of discarded
# words (to avoid having to write again all of different arrays in the
# if condition of the loop while checking words of the file one by one)
discarded_words = discarded_prepositions + discarded_special_chars + discarded_articles + discarded_conjunctions
# We split the words read and save them into a list
words = each_line.split(' ')
for each_word in words:
# The method strip() returns a copy of the string in which all chars have been stripped from
# the beginning and the end of the string. As no value is passed as argument, by default the
# whitespace char is the one removed. The function lower() also converts all chars in the
# string to lowercase so the program will not count as two different words those who start
# uppercase for example in the beginning of a sentence:
each_word = each_word.strip().lower()
# If the word already exists in our dictionary as a key, we increment the counter by 1
if each_word in words_dic:
words_dic[each_word] += 1
# Otherwise, we create a new entry in the dictionary and initialize it to 1...
else:
# ... only if the word is not in the discarded_words list
if (each_word not in discarded_words):
words_dic[each_word] = 1
# We open the output file where we are going to write and save the results
f = open(output_file, 'w')
# For each word stored in the dicitonary, we write the word itself (corresponding to the ley of the
# dicitonary) and the number of times it appear (corresponding to the value attached to the key)
for key, value in words_dic.items():
f.write(key + ": " + str(value) + '\n')
f.close()
if __name__ == "__main__":
# As we are executing our code directly from Jupyter notebook, we have decided to comment the code
# used to import the filename as a parameter in case we want to execute our program from the terminal,
# using the sys module we import at the beginning of the code. The file from where our program read the
# text to count its words must be called 'example.txt'
# if len(sys.argv) == 2:
# We try to open the file passed by argument
# file_to_read = open(sys.argv[1])
file_to_read = open('example.txt')
if (file_to_read):
# We read each line of the given file and save them in a list returned by the readlines() function
lines_in_file = file_to_read.readlines()
count_words(lines_in_file)
print("The output file has been succesfully created.")
file_to_read.close()
else:
print("The file does not exist.")
# else:
# print("Usage: python " + sys.argv[0] + " filename")
|
1973c363f63090bf0aec6fb0900fc88bc92ca336 | ami225/python-practice | /sample.py | 255 | 4.09375 | 4 | x = 10
print(x / 3) #3.33...
print(x // 3) #3
print(x % 3) #1
print(x ** 2) #100 2乗
y = 4
y += 12
print(y)
#and or not
print(True and False) # False
print(True or False) # True
print(not True) #False
# + *
print("hello" + "world")
print("hello" * 3)
|
f10e516974a5b76c49e4158f4051b807d3682877 | Chithra-Lekha/pythonprogramming | /prgm2.py | 120 | 3.828125 | 4 | yr=int(input("enter the future year"))
for i in range(2021,yr+1):
if i%4==0 and i%100!=0 or i%400==0:
print(i) |
047e78d6364dee581c93e2e1f30176a646937f30 | danagilliann/coding_practice | /python/add_digits.py | 459 | 3.625 | 4 | num = 6345
my_int = 0
def add_total(num):
total = 0
string_of_num = str(num)
for i in range(0, len(string_of_num)):
total += int(string_of_num[i])
return total
total = add_total(num)
def add_digits(num, total):
if total <= 10:
print total
else:
num = total
total = add_total(num)
add_digits(num, total)
add_digits(num, total)
|
61eba586696216e85fd24f28b8058a64d353accb | tranphibaochau/LeetCodeProgramming | /Easy/pivot_index.py | 1,324 | 3.8125 | 4 | #############################################################################################################################################################
# Given an array of integers nums, write a method that returns the "pivot" index of this array.
# We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
# If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
# Input:
# nums = [1, 7, 3, 6, 5, 6]
# Output: 3
# Explanation:
#. The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
#. Also, 3 is the first index where this occurs.
#############################################################################################################################################################
#Solution: calculate the sum of the whole array, then as we go through each number in the array, calculate the sumL and sumR as we see below
def pivotIndex(self, nums):
sumL = 0
sumR = sum(nums)
for i in range(len(nums)):
sumR -= nums[i]
if sumL == sumR:
return i
sumL += nums[i]
return -1 |
4625a6aad4dbe2728b45f507078abb4a1479b139 | xxxzc/public-problems | /PythonBasic/BuiltInFunctions/Object/attr/template.py | 368 | 3.78125 | 4 | class Student:
def __getattr__(self, name):
if name == 'info':
return '\n'.join([
'姓名: ' + getattr(self, 'name'),
'学号: ' + getattr(self, 'sno'),
'年级: ' + getattr(self, 'grade')])
return ''
name, sno, grade = input().split()
student = Student()
# TODO
print(''' TODO ''') |
422fecef6b968d55e318bcf42de118837de10ba1 | powermano/pycharmtest | /for_test.py | 1,337 | 3.640625 | 4 | # from enum import Enum, unique
#
# @unique
# class Weekday(Enum):
# Sun = 0 # Sun的value被设定为0
# Mon = 1
# Tue = 2
# Wed = 3
# Thu = 4
# Fri = 5
# Sat = 6
#
# day1 = Weekday.Mon
#
# print(day1)
# print(day1.value)
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name, member in Month.__members__.items():
print(name, '=>', member, ',', member.value)
class Color(Enum):
red = 1
orange = 2
yellow = 3
green = 4
blue = 5
indigo = 6
purple = 7
###test the type of the input data
# if __name__=='__main__':
# a = input('choose the n:')
# print(a)
# print(type(a))
## test for read file
# file = open('D:/myFile.txt','r')
# read_file = file.read().strip().split()
# print(read_file)
### test for def __new__():
#
# class A(type):
# pass
#
#
# class ListMetaclass(type):
# def __new__(cls, name, bases, attrs):
# attrs['add'] = lambda self, value: self.append(value)
# return type.__new__(A, name, bases, attrs)
#
# # def __init__(self):
# # print('base class work')
#
# class MyList(list, metaclass=ListMetaclass):
# # def __init__(self):
# # print('it works')
# pass
#
# L = MyList()
# # L.add(1)
# print(type(L))
|
70ca19b3a39bd60cc546450ba5b33ac6732acf77 | MonikaMudr/pyladies | /04/ukoly/ukol_7.py | 1,005 | 3.625 | 4 | rodne_cislo = input('Zadej rodne cislo: ')
# a) je ve spravnem formatu, 6 cislic/4 cislice?
cislo_seznam = rodne_cislo.split('/')
if len(cislo_seznam[0]) == 6 and len(cislo_seznam[1]) == 4:
print("Rodne cislo ma spravny format.")
cislo_bez_lomitka_string = ''.join(cislo_seznam)
cislo_bez_lomitka = int(cislo_bez_lomitka_string)
#b) je delitelne 11?
if cislo_bez_lomitka % 11 == 0:
print('Zadane rodne cislo je delitelne 11')
#c) jake je datum narozeni (den, mesic, rok)
den = cislo_bez_lomitka_string[4:6]
mesic_string = cislo_bez_lomitka_string[2:4]
mesic = int(mesic_string)
if mesic > 50:
mesic_zena_muz = mesic - 50
else:
mesic_zena_muz = mesic
rok_string = cislo_bez_lomitka_string[0:2]
rok = int(rok_string)
if rok > 84:
cely_rok = '{}{}'.format(19, rok)
else:
cely_rok = '{}{}'.format(20, rok)
print("Datum narozeni je: " + '{}.{}.{}'.format(den, mesic_zena_muz, cely_rok))
#d) Pohlavi
if mesic > 50:
print('Pohlavi: ' + 'zena')
else:
print('Pohlavi:' + 'muz')
|
a060eb9e7f0c9c949cb3c08c9c15d85d8cf46f82 | sky-tanaka/GitVsc | /module-sample1.py | 143 | 3.6875 | 4 | import calc
a=2
b=3
ans1=calc.add(2,3)
ans2=calc.sub(2,3)
print("{}+{}={} ".format(a,b,ans1))
print("{}-{}={} ".format(a,b,ans2))
|
63bbb1c441572a5f4cd6f47a98557abf2d8ee910 | rohit-mehra/basic_machine_learning_assignments | /kmeans.py | 5,700 | 3.890625 | 4 | #!/usr/bin/env python3
"""Assignment 1: UTSA CS 6243/4593 Machine Learning Fall 2017"""
import random
from statistics import mean
__author__ = 'Rohit Mehra'
class KMeans:
"""Basic KMeans Cluster Class"""
def __init__(self, num_clusters=3, max_iterations=900, random_seed=None):
self.num_clusters = num_clusters
self.max_iterations = max_iterations
self.random_seed = random_seed
self.labels_ = None
@staticmethod
def sim(x1, x2):
"""calculates distanc/similarity between two feature vectors
:param x1: first vector
:param x2: second vector
:returns dist: manhattan dist between two vectors"""
if not len(x1) == len(x2):
raise Exception("Vectors don't have same number of features")
dist = 0
for i, j in zip(x1, x2):
dist += abs(i - j)
return dist
def get_labels(self, X, centroids):
"""returns asssigned centroids to each vector in X
:param X: set of feature vectors
:param centroids: set of centroids
:return labels: set of size len(X), where label[i] is the centroid of i'th element in set X
"""
labels = []
for x in X:
distances = [(c, self.sim(x, c)) for c in centroids]
labels.append(min(distances, key=lambda t: t[1])[0])
return labels
@staticmethod
def get_centroids(X, labels):
"""get new centroids for the clusters
:param X: data points array
:param labels: corresponding labels for each data point, array
:return new_centroids: new centroid of the clusters
"""
xy = list(zip(X, labels)) # (x, x's centroid)
old_centroids = set(labels) # set of centroids
new_centroids = []
for c in old_centroids:
# list of similar features [(all xs), (all ys)]
feats = list(zip(*[x for x, l in xy if l == c]))
# tuple of features shape = (1, num_features) = (x1, x2)
centroid = tuple([mean(f) for f in feats])
assert len(centroid) == len(c)
new_centroids.append(centroid)
assert len(new_centroids) == len(old_centroids)
return new_centroids
def k_means(self, X, num_clusters=3, max_iterations=9000, random_seed=None, verbose=False):
""" Basic K-means clustering algorithm
:param X: set of feature vectors
:optional param num_clusters: number of cluster required
:optional param max_iterations: to cap max_iterations in optimization step
:optional param random_seed: to seed random init
:return centroids: set of centroids of clusters
:return labels: set of assigned centroids in same sequence as set of input data,
label[i] gives label for i'th data point in the input
:return iterations: iterations took to reach minima
"""
random.seed(random_seed)
# random vectors as centroids
centroids = random.sample(X, num_clusters)
# init labelling each vector to the cluster
labels = self.get_labels(X, centroids)
iterations = 0
# breaks when clusters stop changing
while True:
# to avoid infinite loop
if iterations > max_iterations:
break
if verbose:
print(self.transform(X, labels))
# counter
iterations += 1
# get new centroids based of clusters
new_centroids = self.get_centroids(X, labels)
# reassign data points to new centroids
new_labels = self.get_labels(X, new_centroids)
# check if new_labels(cluster assignment) are same to the previous assignment or not
if new_labels != labels:
labels = new_labels
centroids = new_centroids
else:
break
return centroids, labels, iterations
def fit(self, X, verbose=False):
"""execute kmeans algo on X, iteratively learn cluster centers from data
:param X: data for learning
:optional param verbose: True if you want to print clusters after each iteration of learning
"""
self.cluster_centers_, self.labels_, self.n_iter_ = self.k_means(
X, verbose=verbose)
return self
def transform(self, X, labels=None):
"""assign input points to their cluster, transform the data in center: [datapoints] format
:param X: data points to be transformed
:param labels: assigned cluster centers to the given points
:return transformed_data: format = {center: [list of datapoints in this cluster],...}
"""
if self.labels_: # if clusters set i.e. non intermediate stage
labels = self.labels_
if labels:
xy = list(zip(X, labels)) # (x, centroid)
centroids = set(labels) # set of centroids
transformed_data = dict()
for c in centroids:
transformed_data[c] = [x for x, l in xy if c == l]
return transformed_data
else:
raise Exception(
'Please use fit(X) to make the object learn the clusters first, then call transform(X)')
if __name__ == '__main__':
data_points = [(2, 10), (2, 5), (8, 4), (5, 8),
(7, 5), (6, 4), (1, 2), (4, 9)]
names = ['A' + str(i) for i in range(1, 9)]
km = KMeans().fit(data_points, verbose=False)
print(km.transform(names))
"""Output: {(1.5, 3.5): ['A2', 'A7'], (7, 4.333333333333333): ['A3', 'A5', 'A6'], (3.6666666666666665, 9): ['A1', 'A4', 'A8']}"""
|
e7fe8efe710d89ee0fcde959a292ad13e60da77c | Shen-xinliang/python-14 | /tianwei/week4/SearchBigThree.py | 352 | 3.703125 | 4 | #随机生成20个数字,并且筛选出其中最大的三个数
import random
lst=[random.randrange(0,101) for x in range(20)]
print(lst)
for i in range(3):
max=i
for j in range(i+1,20):
if lst[max]<lst[j]:
max=j
print(lst[max])
if max!=i:
temp=lst[i]
lst[i]=lst[max]
lst[max]=temp
|
1fd692b13f46d596236a91e765c8ae8016b50c4a | chengong825/python-test | /120三角形最小路径和.py | 773 | 3.8125 | 4 |
# 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
#
# 例如,给定三角形:
#
# [
# [2],
# [3,4],
# [6,5,7],
# [4,1,8,3]
# ]
# 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
#
class Solution:
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
deepth=len(triangle)
for i in range(deepth):
d=deepth-1-i
for j in range(d):
triangle[d-1][j]=triangle[d-1][j]+min(triangle[d][j],triangle[d][j+1])
return triangle[0][0]
solution=Solution()
triangle=[[2],[3,4],[6,5,7],[4,1,8,3]]
print(solution.minimumTotal(triangle=triangle)) |
37b095f48f41178c9ce7affba0d952e312a1d1f6 | mlubinsky/mlubinsky.github.com | /Flask/Flask_sqlite_d3/import_plaza_csv.py | 2,662 | 3.53125 | 4 | """
Read in BART ETD data from files and write to SQL.
"""
import sqlite3
import pandas as pd
import numpy as np
DATABASE = 'bart.db'
#FILES = ['plza.csv', 'mont.csv']
FILES = ['plza.csv' ]
def parse_time(timestamp):
"""Attempt to parse a timestamp (in seconds) into a pandas datetime in
Pacific time, return the timestamp is parsing is successful, NaT (not a
time) otherwise
:return: Pandas timestamp in Pacific time, or NaT
"""
try:
dt = pd.to_datetime(float(timestamp), unit='s')
return dt.tz_localize('UTC').tz_convert('US/Pacific')
except (AttributeError, ValueError):
return pd.NaT
def define_weekday(obs_time):
"""Return 0 if obs_time occurred on a weekday, 1 if a Saturday, 2 if a
Sunday.
:param obs_time: pandas timestamp
"""
if obs_time.weekday() < 5:
return 0
elif obs_time.weekday() == 5:
return 1
elif obs_time.weekday() == 6:
return 2
def parse_data(file_name, date_parser=parse_time, time_col=['time']):
"""Return a dataframe from csv file, with times parsed.
:param file_name: csv file
:param date_parser: function to convert time_col to datetime (default:
parse time)
:param time_col: the time of the column to parse as times
:return: DataFrame from csv file
"""
return pd.read_csv(file_name, parse_dates=time_col, date_parser=date_parser)
def time2minute_of_day(obs_time):
"""Return the minute of day (12:00 midnight = 0) of observation time
:param obs_time: pandas datetime object
"""
return obs_time.time().hour * 60 + obs_time.time().minute
def csv2sql(conn, files):
"""Read in BART ETD data from files and write that data to the SQL database
accessed by conn.
:param conn: SQL database connection
:param files: the files to read data from
"""
output_cols = ['dest', 'dir', 'etd', 'station', 'minute_of_day',
'day_of_week']
conn.execute("DROP TABLE IF EXISTS etd")
for sta_file in files:
df = parse_data(sta_file)
df['station'] = sta_file.split('.')[0]
df['day_of_week'] = df['time'].apply(lambda x: define_weekday(x))
df['etd'] = df['etd'].replace('Leaving', 0).dropna().astype(np.int)
df['minute_of_day'] = df['time'].apply(time2minute_of_day)
df[output_cols].to_sql('etd', conn, index=False, if_exists='append')
conn.cursor().execute(
"""CREATE INDEX idx1
ON etd(station, dest, minute_of_day, day_of_week)
"""
)
conn.commit()
conn.close()
if __name__ == '__main__':
conn = sqlite3.connect(DATABASE)
csv2sql(conn, FILES) |
0b02cad5c63a3c94e9de44b80f277b946731cdbe | AbirameeKannan/Python-programming | /Beginner Level/function.py | 734 | 3.703125 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: user
#
# Created: 20/02/2018
# Copyright: (c) user 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
print "Hello From My Function!"
if __name__ == '__main__':
main()
def my_function():
print "Hello From My Function!"
def my_function_with_args(first,sec):
print first + sec
my_function()
my_function_with_args("Your name ", "have a great year!")
total = 0
def sum( arg1, arg2 ):
total = arg1 + arg2
return total
sum( 10, 20 )
print "Total : ", total
|
65da6f97a9d33fad3102c8697f6858c8595d4743 | Shulin00/GreenPol | /telescope_control/examples/gui4_grid_layout.py | 535 | 3.875 | 4 | from tkinter import *
#creates a blank window
root = Tk()
label_1 = Label(root, text='name')
label_2 = Label(root, text='password')
#user input
entry_1 = Entry(root)
entry_2 = Entry(root)
#where to put it
label_1.grid(row=0, sticky=E) #sticky: N,S,W,E, alignment
label_2.grid(row=1, sticky=E)
entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)
cb = Checkbutton(root, text='Keep me logged in')
cb.grid(columnspan=2)
#keeps the window running, rather than shutting down right away
root.mainloop() |
4d257686fba7b000f03d4e7e81e0ad933cb78124 | dygksquf5/python_study | /Algorithm_python/조이스틱.py | 1,852 | 3.5 | 4 |
# 이런식으로 아스키로드로 하려고했는데, 문제를 ㅇ살짝 처음에 잘못 이해해서,... 다시 새롭게 접근하기 !
# def solution(name):
# print(int(ord("A")) - int(ord("J")))
# answer = -1
#
# nums = [0] * len(name)
#
# for i, n in enumerate(name):
# if n == "A":
# nums[i] = 1
# elif n != "A":
# nums[i] = abs(int(ord("A")) - int(ord(n)))
#
# print(nums)
# import string
#
#
# def solution(name):
# alpa = [i for i in string.ascii_uppercase]
#
# check = [min(alpa.index(i), alpa[::-1].index(i) + 1) for i in name]
#
# if 'A' not in name:
# answer = -1
# for i in name:
# answer += 1
# # 일반 인덱스, 뒤집힌 인덱스 = 더 A 로부터 거리가 짧은걸 반환
# minimum = min(alpa.index(i), alpa[::-1].index(i) + 1)
# answer += minimum
# return answer
# if 'A' in name:
# pass
# 이렇게 조금 검색해서 해결 완료. 쉽지않았따 ㅠ
import string
def solution(name):
alpa = [i for i in string.ascii_uppercase]
check = [min(alpa.index(i), alpa[::-1].index(i) + 1) for i in name]
print(check)
if 'A' not in name:
return (len(name) - 1) + sum(check)
if 'A' in name:
answer = 0
locat = 0
while True:
answer += check[locat]
check[locat] = 0
if sum(check) == 0: break
left = 1
right = 1
while check[locat + right] == 0:
right += 1
while check[locat - left] == 0:
left += 1
if left >= right:
locat += right
answer += right
else:
locat -= left
answer += left
return answer
|
e44eb20714520e49086392bccbc98f8d02184257 | kevinwkt/intelligentSystems | /a-star/main.py | 4,719 | 3.515625 | 4 | #! /usr/bin/python3
# Search Space:
# The search space for each movement would depend on two factors:
# 1. Which side the lamp is currently at.
# 2. Who is at the side where the lamp is at.
# Initial State:
# In the beginning we would have everyone on the left side and no one on the right side.
# Since we will represent the people present with a bit flip when on, they are present, the initial
# state would be (31, 0).
# Goal State:
# Since the goal state would be to have everyone on the right side of the bridge, the
# representation state would be (0, 31).
# Rules:
# - Only 2 people can be bit flipped at the same time where we take the max(cost1, cost2) as cost.
# - Cost can not exceed the hard limit of 30.
# -
# Cost Function:
# Heuristic Function:
# Search Tree Generation:
# Output by matplotlib+networkx
from collections import defaultdict
from networkx.drawing.nx_agraph import graphviz_layout
import math
import matplotlib.pyplot as plt
import networkx as nx
# Dijkstra map containing the minimum cost for different states.
visited = defaultdict(lambda:None)
# Fixed costs for the speed of individuals.
cost = [1, 3, 6, 8, 12]
# Log capturing list.
path_expl = []
# Hard-coded max limit.
max_cost = 30
# Hard-coded final state.
final_state = (0, 31)
# Graph for visualization.
G = nx.Graph()
all_edges = []
answer_edges = []
def min(a, b):
return a if a<b else b
def max(a, b):
return a if a>b else b
def cost_function():
return 1
def heuristic_function():
return 1
def bitflip(current_state, i, j=None):
bitmask = (1<<i)|(1<<j) if j else (1<<i)
new_left = current_state[0]^bitmask
new_right = current_state[1]^bitmask
return (new_left, new_right)
def handle_nx_graph():
red_edges = []
black_edges = []
G.add_edges_from(all_edges)
values = [0.25 for x in all_edges]
#pos = graphviz_layout(G, prog='dot')
pos = nx.spring_layout(G, k=5/math.sqrt(G.order()))
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'),
node_size = 800)
nx.draw_networkx_labels(G, pos)
red_edges_set = set(answer_edges)
for x in all_edges:
if x in red_edges_set:
red_edges.append(x)
else:
black_edges.append(x)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, edge_color='b', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
def dijkstra(current_state, lamp_left, current_cost):
if current_cost > max_cost:
return False
# Update visited with min()
visited[current_state] = min(visited[current_state], current_cost) if visited[current_state] else current_cost
# Check for final state to finish recursion.
if current_state == final_state:
return True
possible = []
# Create a list of possible moves.
if lamp_left:
for i in range(len(cost)-1):
if (current_state[0] & 1<<i):
for j in range(i+1, len(cost)):
possible.append((i, j))
else:
for i in range(len(cost)):
if (current_state[1] & 1<<i):
possible.append((i, None))
# Sort the possible combination based on cost+heuristic.
possible.sort(key=lambda t: cost_function()+heuristic_function())
# Recurse through the best costly and heuristical move.
for i, j in possible:
# Calculate new state.
new_state = bitflip(current_state, i, j)
all_edges.insert(0, (current_state, new_state))
if dijkstra(new_state, not lamp_left, current_cost+max(cost[i], cost[j] if j else -1)):
# Log what action was done.
if lamp_left:
path_expl.insert(0, 'Took %d %d to the right\t\tcurrent_cost: %d'%(cost[i], cost[j], current_cost+max(cost[i], cost[j])))
else:
path_expl.insert(0, 'Returned %d to the left\t\tcurrent_cost: %d'%(cost[i], current_cost+cost[i]))
# Include correct edge as answer.
answer_edges.insert(0, (current_state, new_state))
return True
return False
def main():
# Initial state.
initial_state = (31, 0)
# Initial lamp position; True is when lamp is on the left.
initial_lamp_position = True
# Initial cost.
initial_cost = 0
# This function should return True if it found a solution.
dijkstra(initial_state, initial_lamp_position, initial_cost)
# path_expl should be empty list if no solution was found.
for text in path_expl:
print(text)
# Handle graph generator.
handle_nx_graph()
# Show graph using matplotplt.
plt.show()
if __name__ == '__main__':
main() |
6bf47bda3c958001479dd4dd3aa17ad9a2a7265c | Boris-Rusinov/BASICS_MODULE | /Nested Loops/Ex02-Equal_Sums_Even_Odd_Position.py | 1,245 | 3.671875 | 4 | from math import floor
range_min_num = int(input())
range_max_num = int(input())
curr_num_no_changes = 0
curr_even_sum = 0
curr_odd_sum = 0
curr_position = 0
for curr_num in range(range_min_num, range_max_num + 1):
# Did this with a while loop just to see if I can make the code execution faster than 1.200 sec with it, instead of using enumerate()
curr_num_no_changes = curr_num
while True:
if curr_position % 2 == 0:
curr_even_sum += curr_num % 10
curr_num = floor(curr_num / 10)
else:
curr_odd_sum += curr_num % 10
curr_num = floor(curr_num / 10)
curr_position += 1
if curr_num == 0:
break
"""
Alternatively:
for curr_num in range(range_min_num, range_max_num + 1):
num_to_str = str(curr_num)
for index, digit in enumerate(num_to_str):
if index % 2 == 0:
curr_even_sum += int(digit)
else:
curr_odd_sum += int(digit)
"""
curr_num = curr_num_no_changes
if curr_odd_sum == curr_even_sum:
print(curr_num, end= " ")
curr_odd_sum = 0
curr_even_sum = 0
curr_position = 0 |
1597043fd7638e1c6711dbfad54cfe8876415d78 | Janardhanpoola/100exercises-carbooking | /test.py | 1,974 | 4.4375 | 4 | #1. Given a string, return a new string where "not " has been added to the front. However, if the
#string already begins with "not", return the string unchanged.
def not_string(str):
if str.startswith('not'):
return str
else:
return "not "+str
if __name__=="__main__":
str="candy"
print(not_string(str))
##############################
#2.Implement an appropriate Unit Test for the not_string method.
import unittest
class Test_not_string(unittest.TestCase): #python -m unittest test.py
def test_not_string(self):
self.assertEqual(not_string("candy"),"not candy") #pass case
self.assertNotEqual(not_string("not candy"),"candy") #pass case
#self.assertEqual(not_string('candy'),'candy') #fail case
#########################################
#3.Implement the unique_names method. When passed two lists of names, it will return a list
#containing the names that appear in either or both lists. The returned list should have no
#duplicates.
def uniq_names(ls1,ls2):
l3=ls1+ls2
return list(set(l3))
ls1=['Ava', 'Emma', 'Olivia']
ls2=['Olivia', 'Sophia', 'Emma']
print(uniq_names(ls1,ls2))
###############################
#4.In python code, given a JSON object with nested objects, write a function that flattens all the
#objects to a single key-value dictionary. Do not use the lib that actually performs this function.
import json
def make_it_flat(d):
k="".join(list(d.keys()))
dv=list(d.values())[0]
vals=list(dv.values())
keys=[k+'_'+i for i in list(dv.keys())]
res=dict((zip(keys,vals)))
return res
d={
"a": {
"b": "c",
"d": "e"
}
}
print(make_it_flat(d))
##########
# import sqlite3
# conn=sqlite3.connect('chinook.db')
# c=conn.cursor()
# c.execute('select * from tracks')
# data=c.fetchall()
# for (TrackId,Name,AlbumId,MediaTypeId,GenreId,Composer,Milliseconds,Bytes,UnitPrice) in data:
# print(TrackId)
###########
l=[1,2,3]
print(l[10:]) |
b2167cbace206711eceaeb7f3bf1c26b1ae3ac72 | bharaths30/HackerRank | /tree_test.py | 1,580 | 3.546875 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: sbhar
#
# Created: 07/01/2017
# Copyright: (c) sbhar 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
class Node:
def __init__(self,var):
self.var=var
self.left=None
self.right=None
def display(self):
print self.var
def buildTree(ptr,val):
if val<ptr.var:
if ptr.left==None:
ptr.left=Node(val)
return
else:
ptr=ptr.left
buildTree(ptr,val)
else:
if ptr.right==None:
ptr.right=Node(val)
return
else:
ptr=ptr.right
buildTree(ptr,val)
def iterFinder(root,val):
ptr=root
while(ptr!=None):
if val<ptr.var:
ptr=ptr.left
continue
elif val>ptr.var:
ptr=ptr.right
continue
else:
return True
return False
def recursiveFinder(ptr,val):
if ptr==None:
return False
if ptr.var==val:
return True
if val<ptr.var:
return recursiveFinder(ptr.left,val)
else:
return recursiveFinder(ptr.right,val)
def main():
vals=[5,3,9,1,4,6,8,10,12,14,16,18,-2,-4,-6,-8,0]
root=Node(vals[0])
ptr=root
for i in range(1,len(vals)):
buildTree(root,vals[i])
#print iterFinder(root,4)
print recursiveFinder(root,13)
if __name__ == '__main__':
main()
|
1864681f7a8b249d054ea08c269732c7533ded98 | Gingervvm/JetBrains_Hangman | /Problems/Preprocessing/task.py | 190 | 3.703125 | 4 | input_string = input()
to_replace = [",", ".", "!", "?"]
input_replace = input_string
for sign in to_replace:
input_replace = input_replace.replace(sign, "")
print(input_replace.lower()) |
ce1f28cf8310137f7633f2709b8251dd4d6e9395 | sp3006/MyPythonCoding | /GivenOpAddList.py | 846 | 3.9375 | 4 |
##Given a list of integers nums, a string op representing either "+", "-", "/", or "*",
##and an integer val, perform the operation on every number in nums with val and return the result.
Note: "/" is integer division.
class Solution:
def solve(self, nums, op, val):
nu = list()
if op == "+":
for num in nums:
num = num + val
nu.append(num)
return nu
elif op == "-":
for num in nums:
num = num - val
nu.append(num)
return nu
elif op == "/":
for num in nums:
num = num // val
nu.append(num)
return nu
elif op == "*":
for num in nums:
num = num * val
nu.append(num)
return nu
|
8ab9e1662c97df4ded047dc170394176f62dcb30 | yize11/1808 | /05day/10-上网.py | 161 | 3.890625 | 4 | age = int(input('请输入年龄'))
money = float(input('请输入钱'))
if age > 18 and money > 5:
print('可以上网')
else:
print('在宿舍待着')
|
ecb1f8a696a77f4bab73e462b0cc73db55a20ac7 | josiane-sarda/CursoPythonHbsisProway | /Aulas Marcello/exercicio 44.py | 375 | 4.03125 | 4 | #Modifique o exercício anterior para aceitar somente valores maiores que 0 para N.
# Caso o valor informado (para N) não seja maior que 0, deverá ser lido um novo valor para N.
print('Digite um valor N')
valor_n = int(input())
while (valor_n <= 0):
print('Valor invalido. Digite um novo valor')
valor_n = int(input())
for i in range(1, valor_n ):
print(i)
|
40af54f8f87bcee066b29ba6cd0abb20c0b451c3 | Daehyun-Bigbread/Bigbread-Python | /python_for_everyone/15A-typing.py | 1,329 | 3.65625 | 4 | # 프로젝트2: 타자 게임 만들기
import random
import time
# 단어 리스트: 여기에 단어를 추가하면 문제에 나옵니다.
w = ["cat", "dog", "fox", "monkey", "mouse", "panda", "frog", "snake", "wolf"]
n = 1 # 문제 번호
print("[타자 게임] 준비되면 엔터!")
input() # 사용자가 엔터를 누를 때까지 기다립니다.
start = time.time() # 시작 시간을 기록합니다.
q = random.choice(w) # 단어 리스트에서 아무거나 하나 뽑습니다.
while n <= 5: # 문제를 5번 반복합니다.
print("*문제", n)
print(q) # 문제를 보여줍니다.
x = input() # 사용자 입력을 받습니다.
if q == x: # 문제와 입력이 같을 때(올바로 입력했을 때)
print("통과!") # "통과!"라고 출력합니다.
n = n + 1 # 문제 번호를 1 증가시킵니다.
q = random.choice(w) # 새 문제를 뽑습니다.
else:
print("오타! 다시도전!")
end = time.time() # 끝난 시간을 기록합니다.
et = end - start # 실제로 걸린 시간을 계산합니다.
et = format(et, ".2f") # 보기 좋게 소수점 2자리까지만 표기합니다.
print("타자시간:", et, "초")
|
832e170046a34f969c8650717ff9201562533639 | PCMBarber/factorial | /Not_tests/notimportant.py | 2,505 | 4.1875 | 4 | import os
import time
def fact(num):
factorial = 1
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
if i == 0:
continue
factorial = factorial*i
return factorial
def reverse_fact(num):
count = 0
for i in range(num):
if i == 0:
continue
if num == 1:
count = str(count)
count = count + "!"
return count
break
elif num < 1:
return "NONE"
break
num = (num/i)
count += 1
def main():
while True:
print("Welcome!")
print("Please choose from the following options :")
print("Calulate a factorial (1)")
print("Find the factorial of a number (2)")
selection = input()
validation = False
if selection == "1":
while validation == False:
num = input("Please enter number to be factorialised: ")
validation = int_validator(num)
num = int(num)
result = factorial(num)
print("The factorial of",num,"is",result)
use_again()
elif selection == "2":
while validation == False:
num = input("Please enter number to find the original factorial: ")
validation = int_validator(num)
num = int(num)
result = reverse_fact(num)
if result == "NONE":
print(result)
else:
print(num,"'s factorial is: ",result)
use_again()
else:
print("Invalid input!")
continue
def use_again():
while True:
again = input("Do you want to enter another? (Y/N) : ").lower()
if again == "y":
main()
break
elif again == "n":
print ("Bye!")
exit()
else:
print("Invalid Input")
continue
def int_validator(num): #Auto validates int user inputs
try:
num = int(num)
if num < 0:
clear()
print("Input cannot ne negative number!")
return False
else:
return True
except ValueError:
clear()
print("Invalid input")
return False
def clear():
if os.name == 'nt':
os.system('CLS')
if os.name == 'posix':
os.system('clear')
if __name__ == "__main__":
main()
|
ef957817a5062e413678dc3b10f168fcc4284c97 | alexey-mazenkov/lenghtconverter | /main.py | 10,195 | 3.953125 | 4 | # Length converter v1.
# Objective: to develop a length measure converter.
import localization as lc # Import localization packages from "localization.py".
lc.lang = str() # Language selection.
print(lc.measures_list) # Print The list of supported measures of length.
length_unit = input(lc.length_unit_choose) # Choice of measures of length.
if length_unit == 'mm':
length = int(input(lc.input_length_in_mm)) # Enter a length in millimeters.
if length == 1:
print(length, lc.mm_in_cm1, length * 0.1) # Сonversion from millimeters to millimeters.
print(length, lc.mm_in_inch1, length * 0.039) # Сonversion from millimeters to inches.
print(length, lc.mm_in_dm1, length * 0.01) # Сonversion from millimeters to inches.
print(length, lc.mm_in_m1, length * 0.001) # Сonversion from millimeters to meters.
elif length == 2 or length == 3 or length == 4:
print(length, lc.mm_in_cm2, length * 0.1) # Сonversion from millimeters to millimeters.
print(length, lc.mm_in_inch2, length * 0.039) # Сonversion from millimeters to inches.
print(length, lc.mm_in_dm2, length * 0.01) # Сonversion from millimeters to decimeters.
print(length, lc.mm_in_m2, length * 0.001) # Сonversion from millimeters to meters.
else:
print(length, lc.mm_in_cm3, length * 0.1) # Сonversion from millimeters to millimeters.
print(length, lc.mm_in_inch3, length * 0.039) # Сonversion from millimeters to inches.
print(length, lc.mm_in_dm3, length * 0.01) # Сonversion from millimeters to decimeters.
print(length, lc.mm_in_m3, length * 0.001) # Сonversion from millimeters to meters.
if length_unit == 'cm':
length = int(input(lc.input_length_in_cm)) # Enter a length in centimeters.
if length == 1:
print(length, lc.cm_in_mm1, length * 10) # Сonversion from centimeters to millimeters.
print(length, lc.cm_in_inch1, length * 0.39) # Сonversion from centimeters to inches.
print(length, lc.cm_in_dm1, length * 0.1) # Сonversion from centimeters to decimeters.
print(length, lc.cm_in_m1, length * 0.01) # Сonversion from centimeters to meters.
elif length == 2 or length == 3 or length == 4:
print(length, lc.cm_in_mm2, length * 10) # Сonversion from centimeters to millimeters.
print(length, lc.cm_in_inch2, length * 0.39) # Сonversion from centimeters to inches.
print(length, lc.cm_in_dm2, length * 0.1) # Сonversion from centimeters to meters.
print(length, lc.cm_in_m2, length * 0.01) # Сonversion from centimeters to kilometers.
else:
print(length, lc.cm_in_mm3, length * 10) # Сonversion from centimeters to millimeters.
print(length, lc.cm_in_inch3, length * 0.3937) # Сonversion from centimeters to inches.
print(length, lc.cm_in_dm3, length * 0.1) # Сonversion from centimeters to decimeters.
print(length, lc.cm_in_m1, length * 0.01) # Сonversion from centimeters to meters.
print(length, lc.cm_in_km3, length * 0.00001) # Сonversion from centimeters to kilometers.
if length_unit == 'inch':
length = int(input(lc.input_length_in_inch)) # Enter a length in inches.
if length == 1:
print(length, lc.inch_in_mm1, length * 25.4) # Сonversion from inch to millimeters.
print(length, lc.inch_in_cm1, length * 2.54) # Сonversion from inch to centimeters.
print(length, lc.inch_in_dm1, length * 0.254) # Сonversion from inch to decimeters.
print(length, lc.inch_in_m1, length * 0.0254) # Сonversion from inch to meters.
elif length == 2 or length == 3 or length == 4:
print(length, lc.inch_in_mm2, length * 25.4) # Сonversion from inches to millimeters.
print(length, lc.inch_in_cm2, length * 2.54) # Сonversion from inches to centimeters.
print(length, lc.inch_in_dm2, length * 0.254) # Сonversion from inches to decimeters.
print(length, lc.inch_in_m2, length * 0.0254) # Сonversion from inches to meters.
else:
print(length, lc.inch_in_mm3, length * 25.4) # Сonversion from inches to millimeters.
print(length, lc.inch_in_cm3, length * 2.54) # Сonversion from inches to centimeters.
print(length, lc.inch_in_dm3, length * 0.254) # Сonversion from inches to decimeters.
print(length, lc.inch_in_m3, length * 0.0254) # Сonversion from inches to meters.
print(length, lc.inch_in_km3, length * 0.000025) # Сonversion from inches to kilometers.
if length_unit == 'dm':
length = int(input(lc.input_length_in_dm)) # Enter a length in decimeters.
if length == 1:
print(length, lc.dm_in_mm1, length * 100) # Сonversion from decimeter to millimeters.
print(length, lc.dm_in_cm1, length * 10) # Сonversion from decimeter to centimeters.
print(length, lc.dm_in_inch1, length * 3.94) # Сonversion from decimeter to inches.
print(length, lc.dm_in_m1, length * 0.1) # Сonversion from decimeter to meters.
print(length, lc.dm_in_km1, length * 0.0001) # Сonversion from decimeter to kilometers.
elif length == 2 or length == 3 or length == 4:
print(length, lc.dm_in_mm2, length * 100) # Сonversion from decimeters to millimeters.
print(length, lc.dm_in_cm2, length * 10) # Сonversion from decimeters to centimeters.
print(length, lc.dm_in_inch2, length * 3.94) # Сonversion from decimeters to inches.
print(length, lc.dm_in_m2, length * 0.1) # Сonversion from decimeters to meters.
print(length, lc.dm_in_km2, length * 0.0001) # Сonversion from decimeters to kilometers.
else:
print(length, lc.dm_in_mm3, length * 100) # Сonversion from decimeters to millimeters.
print(length, lc.dm_in_cm3, length * 10) # Сonversion from decimeters to centimeters.
print(length, lc.dm_in_inch3, length * 3.94) # Сonversion from decimeters to inches.
print(length, lc.dm_in_m3, length * 0.1) # Сonversion from decimeters to meters.
print(length, lc.dm_in_km3, length * 0.0001) # Сonversion from decimeters to kilometers.
if length_unit == 'm':
length = int(input(lc.input_length_in_m)) # Enter a length in meters.
if length == 1:
print(length, lc.m_in_mm1, length * 1000) # Сonversion from meter to millimeters.
print(length, lc.m_in_cm1, length * 100) # Сonversion from meter to centimeters.
print(length, lc.m_in_inch1, length * 39.4) # Сonversion from meter to inches.
print(length, lc.m_in_dm1, length * 10) # Сonversion from meter to decimeters.
print(length, lc.m_in_km1, length * 0.001) # Сonversion from meter to kilometers.
elif length == 2 or length == 3 or length == 4:
print(length, lc.m_in_mm2, length * 1000) # Сonversion from meters to millimeters.
print(length, lc.m_in_cm2, length * 100) # Сonversion from meters to centimeters.
print(length, lc.m_in_inch2, length * 39.4) # Сonversion from meters to inches.
print(length, lc.m_in_dm2, length * 10) # Сonversion from meters to decimeters.
print(length, lc.m_in_km2, length * 0.001) # Сonversion from meters to kilometers.
else:
print(length, lc.m_in_mm3, length * 1000) # Сonversion from meters to millimeters.
print(length, lc.m_in_cm3, length * 100) # Сonversion from meters to centimeters.
print(length, lc.m_in_inch3, length * 39.4) # Сonversion from meters to inches.
print(length, lc.m_in_dm3, length * 10) # Сonversion from meters to decimeters.
print(length, lc.m_in_km3, length * 0.001) # Сonversion from meters to kilometers.
if length_unit == 'km':
length = int(input(lc.input_length_in_km)) # Enter a length in kilometers.
if length == 1:
print(length, lc.km_in_mm1, length * 1000000) # Сonversion from kilometer to millimeters.
print(length, lc.km_in_cm1, length * 100000) # Сonversion from kilometer to centimeters.
print(length, lc.km_in_inch1, length * 39370) # Сonversion from kilometer to inches.
print(length, lc.km_in_dm1, length * 10000) # Сonversion from kilometer to decimeters.
print(length, lc.km_in_m1, length * 1000) # Сonversion from kilometer to meters.
elif length == 2 or length == 3 or length == 4:
print(length, lc.km_in_mm2, length * 1000000) # Сonversion from kilometers to millimeters.
print(length, lc.km_in_cm2, length * 100000) # Сonversion from kilometers to centimeters.
print(length, lc.km_in_inch2, length * 39370) # Сonversion from kilometers to inches.
print(length, lc.km_in_dm2, length * 10000) # Сonversion from kilometers to decimeters.
print(length, lc.km_in_m2, length * 1000) # Сonversion from kilometers to meters.
else:
print(length, lc.km_in_mm3, length * 1000000) # Сonversion from kilometers to millimeters.
print(length, lc.km_in_cm3, length * 100000) # Сonversion from kilometers to centimeters.
print(length, lc.km_in_inch3, length * 39370) # Сonversion from kilometers to inches.
print(length, lc.km_in_dm3, length * 10000) # Сonversion from kilometers to decimeters.
print(length, lc.km_in_m3, length * 1000) # Сonversion from kilometers to meters. |
7325d868d2d0b1288b5f91a30f9323173558a2cc | Brunoenrique27/Exercicios-em-Python | /desafio88 - Listas em python.py | 773 | 3.953125 | 4 | ## Faça um programa que ajude um jogador da MEGA SENA a criar palpites.
# O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo
# cadastrando tudo em uma lista composta.
from random import randint
from time import sleep
lista = []
jogos = []
print('*'*30)
print(' SORTEIO MEGA SENA ')
print('*'*30)
quantidade = int(input('Quantos sorteios voce deseja?'))
for c in range(0,quantidade):
c = 1
while c <= 6:
num = randint(1,60)
if num not in lista:
lista.append(num)
c += 1
lista.sort()
jogos.append(lista.copy())
lista.clear()
for v, c in enumerate(jogos):
print(f'O jogo {v+1}: {c}')
sleep(1)
print('*'*30)
print('-='*5,'BOA SORTE','-='*5) |
cf186f63b3fa31a4d87c56729e28c04cbf1141ff | evamc7/learn_python_the_hard_way | /ex11.py | 729 | 4.1875 | 4 | print "How old are you?"
age = raw_input (22)
print "How tall are you?"
height = raw_input (70)
print "How much do you weigh?"
weight = raw_input (53)
# en este caso he rellenado yo los parentes de raw_input, que seria lo que tendria que rellenar el usuario con los datos que deben aparecer
print "So, you're %r old, %r tall and %r heavy." % (
age,height, weight)
#raw_input sirve a la hora de crear una sentencia que solicite datos, La función input está destinada a la entrada de cualquier caracter, siempre y cuando este mismo sea notificado como es. Es decir, si ingresamos números, simplemente sera así lo que nos dirá Python
#normalmente se usa para que el usuario rellene el campo con los datos que deben salir |
2ebbdc8a6522508a8cb05d4b26425cfbd547ca9f | PengiunDoomsday/lab7 | /lab7.py | 1,453 | 3.796875 | 4 | """
Created on Fri Dec 7 21:04:34 2018
@author: Javier Soon
ID: 80436654
Professor: Diego Aguirre
T.A.: Manoj Saha
Description: Compare two words in which it would count the number of operations
needed to make either word be the same to the other.
"""
def edit_distance(word1, word2):
''' method takes two words, and returns the edit distance of the words '''
str1 = len(word1) + 1 # increases the size of the word by 1 for the "space"
str2 = len(word2) + 1
matrix = {} # creates a dictionary
for i in range(str1):
matrix[i,0] = i # makes the matrix work like this matrix[i][0]
for j in range(str2):
matrix[0,j] = j
for i in range(1, str1):
for j in range(1, str2):
if word1[i - 1] == word2[j - 1]: # if the char at the position are the same = 0
cost = 0
else:
cost = 1 # if the char at the position are different cost = 1
matrix[i,j] = min(matrix[i, j-1]+1, matrix[i-1, j]+1, matrix[i-1, j-1]+cost)
# looks at the surrounding three positions, finds the min and adds the cost which is either a 1 or 0
# depending if they the same or not.
return matrix[i,j]
def main():
word1 = "doing"
word2 = "hellos"
distance = edit_distance(word1, word2)
print(distance)
main() |
71e2eb5f6887e7739e435cd78d803f613293ba02 | AsherThomasBabu/AlgoExpert | /Arrays/Sorted-Squared-Array/optimised.py | 701 | 3.953125 | 4 | # Write a function that takes in a non-empty array of Integers that are sorted in ascending order and returns a new array of the same length with the squares of the original integers also sorted in ascending order.
def sortedSquaredArray(array):
sortedArray = [0 for i in range(len(array))]
leftInd = 0
rightInd = len(array)-1
arrayLen = len(array) -1
for i in range(arrayLen + 1):
leftVal = abs(array[leftInd])
rightVal = abs(array[rightInd])
if leftVal > rightVal:
sortedArray[arrayLen-i] = leftVal**2
leftInd += 1
else:
sortedArray[arrayLen-i] = rightVal**2
rightInd -= 1
return sortedArray
|
a921d09d209eab83956b4d6e675a37c9577e3d44 | BruceJohnJennerLawso/void | /app.py | 514 | 3.578125 | 4 | ## app.py ######################################################################
## central app file containing a main function #################################
## I still think a lot like C ##################################################
################################################################################
from vector import vector_III;
def main():
v1 = vector_III(1, 1, 1);
v2 = vector_III(-1, 1, -1);
print "dot product of (1,1,1) & (-1,1,-1) is " + str(v1.Dot(v2));
return 0;
main();
|
2b65897ee10090d9bb83817db9c671deac98592b | SteveDengZishi/ChickenFight | /JitteryChicken.py | 1,813 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 4 00:19:40 2017
@author: stevedeng
"""
"""
This file contains the JitteryChicken class, which is a sub-class of FuriousChicken
The make_your_move() function of FuriousChicken has been overidden here
Modified from original author Foo Barstein
Date: 31 May 2016
"""
#import the necessary modules
import random
from FuriousChicken import *
class JitteryChicken(FuriousChicken):
"""Template for a random decision-making chicken descended from the original Furious Chicken"""
#the only function you are allowed to override is the make_your_move function
def make_your_move(self):
"""Overriding the FuriousChicken class's function by the same name. This function randomly decides what this chicken should do each round"""
#EXAMPLE ONLY... YOUR CHICKEN SHOULD MAKE ITS OWN DECISIONS WHAT TO DO
#this chicken randomly decides whether it should attack, defend, or rest and recuperate
what_to_do = random.randint(1,3)
#randomly decide what body part to attack or defend
#added a if statement to prevent empty range for randrange() BUG
if len(self.get_body_parts()) != 0:
num = random.randint(0, len(self.get_body_parts())-1) #a random number from 1 to however many body parts this chicken has
body_part = self.body_parts[num] #select the random body part from the list of this chicken's body parts
else:
print("{} is dead now!!!".format(self.name))
return
if what_to_do == 1:
#attack!
self.attack(body_part)
elif what_to_do == 2:
#defend!
self.defend(body_part)
else:
#rest and recuperate
self.recuperate()
|
4cce146c40c875d9f52410016dc5ba5cf7930485 | TylerCrabtree/Connect4GUI | /c4GUI.py | 17,071 | 3.53125 | 4 | # Tyler Crabtree
# Csci 121
# Assignment 9
diameter = 50
spacing = 10
gutter = 50
import random # for win choices and message choices
from Tkinter import *
class Board:
def __init__( self, width, height ):
self.width = width
self.height = height
self.data = [] # this will be the board (b)
for row in range( self.height ):
boardRow = []
for col in range( self.width ):
boardRow += [' ']
self.data += [boardRow]
def __repr__(self): # designs board
s = ''
for row in range( self.height ): #makes rows
s += '|'
for col in range( self.width ):
s += self.data[row][col] + '|' # adds columns
s += '\n'
s+= '__'*self.width + '\n'
for col in range(self.width):
s+= ' ' + str(col%10)
return s # return it
def addMove(self, col, ox ):
if self.allowsMove(col):
for row in range( self.height ):
if self.data[row][col] != ' ':
self.data[row-1][col] = ox # add the space character
return
self.data[self.height-1][col] = ox
def addMoveRow(self, col, ox ): #for gui Ai
if self.allowsMove(col):
for row in range( self.height ):
if self.data[row][col] != ' ':
self.data[row-1][col] = ox # add the space character
return row -1
self.data[self.height-1][col] = ox
return self.height -1
def addMoveImproved(self, col, ox ):
if self.allowsMove(col):
for row in range( self.height ):
if self.data[row][col] != ' ':
self.data[row-1][col] = ox # add the space character
return row
def allowsMove(self,col): #checks to see move is allowed.
if 0 <= col < self.width:
return self.data[0][col] == ' '
def allowsMoveTrue(self,col): #checks to see move is allowed.
if 0 <= col < self.width:
return True
def clear(self): # clears board
for row in range(self.height):
for col in range(self.width):
self.data[row][col] = ' '
return
def delMove(self, col): # deletes one move
for row in range( self.height ):
if self.data[row][col] != ' ':
self.data[row][col] = ' '
return
#self.data[self.height][col] = ' '
def isFull(self): # basically checks to see if a draw
for col in range( self.width ):
if self.data[0][col] == ' ':
return False
return True
def setBoard( self, moveString ): # creates specific board
nextCh = 'X'
for colString in moveString:
col = int(colString)
if 0 <= col <= self.width:
self.addMove(col, nextCh)
if nextCh == 'X':
nextCh = 'O'
else:
nextCh = 'X'
def winsFor(self, ox):
for row in range(0,self.height-3): #vertical wins
for col in range(0,self.width):
if self.data[row][col] == ox:
if self.data[row+1][col] == ox:
if self.data[row+2][col] == ox:
if self.data[row+3][col] == ox:
return True
for row in range(0,self.height): #hoizontal wins
for col in range(0,self.width-3):
if self.data[row][col] == ox:
if self.data[row][col+1] == ox:
if self.data[row][col+2] == ox:
if self.data[row][col+3] == ox:
return True
for row in range(0,self.height-3): #Downward slope /
for col in range(3,self.width):
if self.data[row][col] == ox:
if self.data[row+1][col-1] == ox:
if self.data[row+2][col-2] == ox:
if self.data[row+3][col-3] == ox:
return True
for row in range(0,self.height-3): #Upward slope \
for col in range(0,self.width-3):
if self.data[row][col] == ox:
if self.data[row+1][col+1] == ox:
if self.data[row+2][col+2] == ox:
if self.data[row+3][col+3] == ox:
return True
return False
def input(self,ox): # basic layout
while True:
game = input(ox + ", choose your destiny: ")
if self.allowsMove(game):
return game
def hostGame(self): #actual game
print self
while True:
game = self.input('X')
self.addMove(game, 'X')
print self
if self.winsFor('X'):
print random.choice([ "X is vitorious!", "X, take your pride!",\
"X, you chose wisely", "Enjoy the taste of victoy X" ])
b.clear()
break
game = self.input('O')
self.addMove(game,'O')
print self
if self.winsFor('O'):
print random.choice([ "O, I do believe you won ", "O, you are unstoppable",\
"O, glory awaits for you.", "O is the champion!"])
b.clear()
break
if self.isFull():
print random.choice([ "It's a draw", "Sometimes a tie is worse than a loss" , \
"No one is the winner, that's life", "Maybe you should try again?"])
b.clear()
break
def playGameWith(self,aiPlayer): #actual game
print self
while True:
checker = 'X'
game = self.input('X')
self.addMove(game, 'X')
print self
if self.winsFor('X'):
print random.choice([ "X is vitorious!", "X, take your pride!",\
"X, you chose wisely", "Enjoy the taste of victoy X" ])
b.clear()
break
colNumber = aiPlayer.nextMove(self) #get move
self.addMove(colNumber,'O') #add move
print self
if self.winsFor('O'):
print random.choice([ "O, is the taste of victory sweet?", "O, you are unstoppable",\
"O, glory awaits for you.", "O is the champion!"])
b.clear()
break
if self.isFull():
print random.choice([ "It's a draw", "Sometimes a tie is worse than a loss" , \
"No one is the winner, that's life", "Maybe you should try again?"])
b.clear()
break
if checker == 'X':
checker = 'O'
else:
checker = 'X'
##############################################################
##############################################################
# Gui Portion
#############################################################
##############################################################
def quitGame( self): # works fine
self.window.destroy()
def postMessage(self,newText): #unsure
if self.message != None:
self.draw.delete(self.message)
self.message = self.draw.create_text(diameter/2, \
self.gutter + diameter/2, \
text = newText,anchor="w",font = "Times 48")
else:
self.message = self.draw.create_text(diameter/2, \
self.gutter + diameter/2, \
text = newText,anchor="w",font = "Times 48")
def mouse (self,event):
if self.ignoreEvents:
self.window.bell()
return
self.ignoreEvents = True
col= int((event.x - spacing/2) / (diameter + spacing))
#if self.allowsMove(col) == True:
#move = self.player.nextMove(self) # * correctly outputs Ai moves, \
# but functions one move behind
if self.allowsMove(col):
row = self.addMoveRow(col,'X') #knows row
self.gui(row,col,"red")
#print event.x," ", event.y
if self.winsFor('X'):
self.postMessage("Red wins!")
return
elif self.isFull():
self.postMessage("Draw")
return
self.postMessage("Thinking...")
move = self.player.nextMove(self) # if i add print statment, prints one turn behind
row = self.addMoveRow(move,'O')
if move == None:
self.postMessage("Pointlessness.")
return
self.gui(row, move,"black")# need to change! Changed to move
if self.winsFor('O'):
self.postMessage("Black wins!")
return
elif self.isFull():
self.postMessage("Tie")
return
self.postMessage(random.choice(["Bring it!?", "Let's go!", "Red's turn!"]))
self.ignoreEvents = False
else:
self.postMessage("Full.")
self.ignoreEvents = False
#while self.allowsMove(col) == False:
#col= int((event.x - spacing/2) / (diameter + spacing))
#if self.allowsMove(col) == True:
# break
#self.window.bell()
#return
#self.gui(row,col,"red") #took out row
def newGame(self):
for row in range(self.height):
for col in range(self.width):
self.data[row][col] = ' '
self.gui(row,col,"white")
self.postMessage(random.choice(["Go!", "Red's turn."]))
self.ignoreEvents = False
return
#def level(self):
#Level = Player.self.ply
#Level = Level +1
#playGui(6,Level)
def attachGUI(self,window,player):
self.ignoreEvents = True
self.player= player
self.message = None
self.window = window
self.frame = Frame(window) #remember Frame is uppercase
self.frame.pack() #pack finds a place for frame
self.qButton = Button(self.frame, text ="Quit",fg="red", \
command = self.quitGame) # quit button, fg = foreground color
self.qButton.pack(side = RIGHT)
self.newButton = Button(self.frame, text ="New Game",fg="green", \
command = self.newGame)
#self.Easy= Button(self.frame, text ="Difficulty Up",fg="green", \
# command = self.newGame)
#self.Easy.pack(side = RIGHT)
#self.Hard= Button(self.frame, text ="Difficulty Up",fg="green", \
# command = self.level)
#self.Hard.pack(side = RIGHT)
self.newButton.pack(side = RIGHT)
w = self.width * ( diameter +spacing) + spacing# """(self.width/2)"""
h = self.height * (diameter + spacing) + spacing + gutter
self.draw = Canvas(window, width = w,height = h, bg = "grey", \
borderwidth = 0, highlightbackground = "black", highlightthickness = 2)
self.draw.bind("<Button - 1>" , self.mouse)
self.draw.pack()
self.circles =[]
delta = diameter + spacing
y = spacing
for row in range(self.height):
boardRow = []
x = spacing
for col in range(self.width):
c = self.draw.create_oval(x,y, x+diameter, y +diameter,fill="white" )
boardRow += [c]
x += delta
self.circles += [boardRow] # changed from +
y += delta
self.gutter = y
self.postMessage(random.choice(["Red, go!", "Red's turn."]))
self.ignoreEvents = False
def gui(self,row,col,color):
c = self.circles[row][col]
self.draw.itemconfig(c, fill = color)
#############################################################
#############################################################
#end gui
#############################################################
#############################################################
#############################################################
#############################################################
#Start of AI
#############################################################
#############################################################
class Player:
def __init__ (self,checker,ply):
self.checker = checker
self.ply = ply
def nextMove(self, board):
scores = self.scoresFor (board,self.checker,self.ply)
board.allowsMove(scores)
best = max(scores)
#worst = random.choice(scores)
#randomElement = random.choice[col]
#randomScore = scores[col]
for col in range(board.width):
"""if randomScore == best:
print "Player %s moves[%i]" % (self.checker,col)
return col"""
if best == scores[col]:
#randomElement = random.choice[col]
#print "Player %s last move was [%i]" % (self.checker,col)
return col
# accumulated new list and randomly pick column
# read chp 14 and check python.prg
def scoresFor(self,board,ox,depth):
scoresList = []
for col in range(board.width): # -1?
if board.allowsMove(col): # checks if that wins
board.addMove(col,ox)
if board.winsFor(ox): # if you win
scoresList += [100.0]
elif depth <1: #ply is 1, append 50
scoresList += [50.0]
else:
if ox == 'X':
opp = 'O'
else:
opp = 'X'
oppList = self.scoresFor(board,opp,depth-1) #recursive ply
bestOpp = max(oppList)
#worstOpp = min(oppList)
#randomElement = random.choice(oppList)
invertedOppScore = random.choice( [.65,.66,.67,.68,.69,.70,.71,.77,.78,.79,.80,.81,.82,.83,.84,.85,.86,.87,.88,.89,.90,\
.91,.92,.93,.94,.95,.96,.97,.98,.99])*(100.0-bestOpp) # better way than original way below
#random.choice([(100.0 - bestOpp)*.75, (100.0 - bestOpp)*.9, (100.0 - bestOpp)*.6, (random.choice([.7,.8,.95])* (100.0 - bestOpp))])
scoresList += [invertedOppScore]
board.delMove(col) # gets rid of testing move
else:
scoresList += [-1.0]
return scoresList
def playText(size,ply):
t = Board(3)
p = Player('O', 3)
t.hostGame(p)
def playGui(size,ply):
t = Board(7,6)
p = Player('O',ply)
window = Tk() # base windowing system
window.title("Connect Four") #changed window.tile to windowVar.title
t.attachGUI(window,p)
window.mainloop()
#################################################
#call functions to call the Gui
#################################################
b = Board(7,6)
p = Player('O',6)
#b.playGameWith(p)
playGui(6,3)
#################################################
# attempted code durring the proccess
#################################################
''' def gui(self,col,row,color):
if color == "red":
self.ox = "X"
row = self.addMoveRow(col, "X" )
if color == "black":
row = self.addMoveRow(col, "X" )
c = self.circles[col][row]
#for height in range(row):
# for width in range(col):
#for row in range(self.height):
#for col in range(self.width):
if color == "red" :
self.draw.itemconfig(c,fill="red") # removed fill
if color == "black":
self.draw.itemconfig(c,fill="black")'''
# def guiAi(self, col,color):
#c = self.circles
#for height in range(row):
# for width in range(col):
#if color == "red":
# if self.circles != ' ':
# self.cirlces[row-1]
# self.draw.itemconfig(col+1,fill="red") # removed fill
# self.draw.itemconfig(col+1,fill="red") # removed fill
#if color == "black":
# self.draw.itemconfig(col+1,row+1,fill="black")
"""class player:
#ply = ?
def __init__( self, ox, col ):
return
# self.width = width
#self.height = height
#self.data = [] # this will be the board (b)
#for row in range( self.height ):
# boardRow = []
# for col in range( self.width ):
# boardRow += [' ']
#self.data += [boardRow]
def nextMove(self,board):
scores = self.scores(board,self.ox,self.ply)
moves = [[scores[i],i] for i in range(len(scores))]
best = max(moves)
return best[i]
def scoreFor(self,board,ox,depth):
scorelist =[]
for col in range(board.width):
if b.addMove(col) == True:
if b.winsFor(col) == True:
scores = 100
else:
scores = scores - 1
#append (100.0-max(l))
#for col in range(board.width)
#if Board.allowsMove('O') == True:
#return Board.addMove('O')
"""
"""
class Player:
def __init__ (self,checker,ply):
self.checker = checker
self.ply = ply
def nextMove(self, board):
scores = self.scoresFor(board,self.checker,self.ply)
best = max(scores)
move = best[1]
row = move[0]
col = move[1]
board.addMove(row,col,self.checker)
print "Player %s moves[%i.%i]" % (self.checker,row,col)
def scoresFor(self,board,ox,depth):
scoreList = []
moves = board.possibleMoves()
for move in moves:
row = move[0]
col = move[1]
board.addMove(row,col,ox)
if board.winsFor(ox):
scoresList += [[100.0,move]]
elif depth <1:
scoresList += [[50.0, move]]
else:
if ox == 'X':
opp = 'O'
else:
opp = 'X'
oppList = self.scoresFor(board,opp,depth-1)
bestOpp = max(oppList)
invertedOppScore = 100.0 - bestOpp[0]
scoresList += [invertedOppScore, move]
return scoresList
#row = int((event.y - spacing/2) / (diameter + spacing) ) #added int
#if event.x >0 and event.x < 65:
# col = 1
"""
#t = ticTacToe(3)
#p = Player('O', 3)
#t.hostGame(p)
'''
b.addMove(0,'x')
b.addMove(1,'x')
b.addMove(2,'x')
b.addMove(3,'x')
b.addMove(4,'x')
b.addMove(5,'x')
'''
#b.setBoard('000000')
#b.setBoard('01010101010')
#b.setBoard('01122123333')
#b.setBoard('21221103131213')
#b.setBoard('00020131234')
# for testing
#b.addMove(1,'X')
#print b
#print b.winsFor('X') |
59d0eda233767d5a6d0b7ede9490fe828a07548d | pymft/mft-vanak | /S12/decorators/what_is_decorator.py | 416 | 3.640625 | 4 | def echo(s):
return s
def echo_multiple_times(s, n):
return echo(s) * n
def get_echoer(n):
def f(s):
return echo_multiple_times(s, n)
return f
echo_twice = get_echoer(2)
# def echo_twice(s):
# return echo_multiple_times(s, 2)
echo_10 = get_echoer(10)
# def echo_10(s):
# return echo_multiple_times(s, 10)
print(echo("hello"))
print(echo_twice("hello"))
print(echo_10("hello")) |
3fa121a3b7e2b9bc9ab5389b4ae672f1ad8c8fac | MoKamalian/CSCI2202 | /Solutions for lab 1-B nd assing1 nd test/Test/Question3.py | 966 | 4.125 | 4 | # Question 3: Dice Rolling Probabilities
import random
# Set the number of simulations (default 100000).
N = 100000
# Set up counters for keeping track of the number
# of times each condition is met.
countSix = 0
countTwelve = 0
# Simulate the dice rolling N times.
for _ in range(N):
# Generate 12 dice rolls, where each die is a d6 (1-6).
dice = [random.randint(1, 6) for _ in range(12)]
# Look at the first six dice and see if there's at least
# one six. If yes, our count goes up by 1.
if dice[:6].count(6) >= 1:
countSix += 1
# Look at all twelve dice and see if there's at least two
# sixes. If yes, our count goes up by 1.
if dice.count(6) >= 2:
countTwelve += 1
# Print the final probability calculations.
print("Probability of getting at least one 6 in six dice rolls:", countSix/N)
print("Probability of getting at least two 6's in twelve dice rolls:", countTwelve/N)
|
b2968cfd083bc711abf0cc5b97730d01dc70b2e9 | scottr/tvinfo | /tvinfo/model.py | 7,289 | 3.75 | 4 | """ Data model for TV series, seasons and episodes.
"""
class Series:
""" A TV Series.
Generally, this class is not instantiated directly, but instead is
created by the series_search() method of the tvinfo module.
"""
def __init__(self):
self.__title = ""
self.__overview = ""
self.__language = ""
self.__first_aired = ""
self.__banner_uri = []
self.__actors = []
self.__seasons = {}
self.__backend_data = {}
def get_title(self):
""" Get the title of the series.
"""
return self.__title
def set_title(self, title):
""" Set the title of the series.
"""
self.__title = title
def set_language(self, language):
""" Set the language of the series.
"""
self.__language = language
def get_language(self):
""" Get the language of the series.
"""
return self.__language
def get_overview(self):
""" Get the overview/synopsis of the series.
"""
return self.__overview
def set_overview(self, overview):
""" Set the overview/synopsis of the series.
"""
self.__overview = overview
def get_first_aired_date(self):
""" Return the first aired date as a Python datetime.date object.
"""
return self.__first_aired
def set_first_aired_date(self, day, month, year):
""" Set the first aired date.
"""
self.__first_aired = datetime.date(year, month, day)
def get_banner_uris(self):
""" Get a list of URIs that describe "banners" for this series.
"""
return self.__banner_uri
def set_banner_uris(self, uris):
""" Set a list of URIs that describe "banners" for this series.
"""
self.__banner_uri = uris
def get_actor_list(self):
""" Get a list of actors in this series.
"""
return self.__actors
def set_actor_list(self, actors):
""" Set the list of actors in this series.
"""
self.__actors = actors
def get_backend_data(self, key):
""" Return an item from the backend's private data store.
For example, backends can use this to store season id's, etc.
"""
return self.__backend_data.get(key, None)
def set_backend_data(self, key, value):
""" Sets a key/value pair in the backend private data store.
"""
self.__backend_data[key] = value
def get_episode(self, season, episode):
""" Lookup an episode in this series.
Given a season and episode number, returns an Episode object
describing the episode. If the episode is not found, None is
returned, indicating that the cache may need to be updated.
"""
if self.__seasons == {}:
return None
if self.__seasons.has_key(season) == False:
return None
return self.__seasons[season].get_episode(episode)
def get_season(self, season_number):
""" Get the Season object for season_number.
"""
return self.__seasons.get(season_number, None)
def set_season(self, season_number, season):
""" Set the Season object for season_number.
"""
self.__seasons[season_number] = season
def get_seasons(self):
""" Return a sorted list of Season objects for this Series.
"""
return [ s for snum, s in sorted(self.__seasons.items()) ]
class Season:
""" Describes a TV season.
"""
def __init__(self):
self.__season_number = ""
self.__banner_uris = []
self.__episodes = {}
def get_season_number(self):
""" Return the season number of this season.
"""
return self.__season_number
def set_season_number(self, season_number):
""" Set the season number of this season.
"""
self.__season_number = season_number
def get_banner_uris(self):
""" Return a list of URIs describing banners for this season.
"""
return self.__banner_uris
def set_banner_uris(self, uris):
""" Set the list of URIs describing banners for this season.
"""
self.__banner_uris = uris
def set_episode(self, episode_number, episode):
""" Set the Episode object for episode_number.
"""
self.__episodes[episode_number] = episode
def get_episode(self, episode_number):
""" Get an Episode by episode number.
"""
return self.__episodes.get(episode_number, None)
def get_episodes(self):
""" Get the episodes for this season as a sorted list.
"""
return [ e for enum, e in sorted(self.__episodes.items()) ]
class Episode:
""" Describes a single TV episode.
"""
def __init__(self):
self.__title = ""
self.__overview = ""
self.__episode_number = ""
self.__banner_uris = []
def get_title(self):
""" Get the title of this episode.
"""
return self.__title
def set_title(self, title):
""" Set the title of this episode.
"""
self.__title = title
def get_banner_uris(self):
""" Get the list of URIs describing banners for this episode.
"""
return self.__banner_uris
def set_banner_uris(self, uris):
""" Set the list of URIs describing banners for this episode.
"""
self.__banner_uris = uris
def get_overview(self):
""" Get the overview/synopsis of this episode.
"""
return self.__overview
def set_overview(self, overview):
""" Set the overview/synopsis of this episode.
"""
self.__overview = overview
def get_episode_number(self):
""" Get the episode number of this episode.
"""
return self.__episode_number
def set_episode_number(self, episode_number):
""" Set the episode number for this episode.
"""
self.__episode_number = episode_number
|
c565c8e4dd693852e395897f738e3866403d38ba | hcshires/APCSP | /falling_rectangle.py | 1,591 | 3.5625 | 4 | import tkinter as tk
import random
xvel = 0
times_clicked = 0
yvel = -5
def clicked(event):
global times_clicked #use the global variable within this function
x = event.x # the x coordinate of your click
y = event.y # the y coordinate of your click
print(canvas.coords(1)) # print the coordinates of the rectangle when you click the screen (the rectangle has an ID of 1)
def move_rect():
global yvel
global xvel
width = window.winfo_width()
height = window.winfo_height()
pos = canvas.coords(1) # get current rectangle coordinates
new_y = pos[1]+yvel
new_x = pos[0]+xvel
if new_y <= height:
canvas.coords(1, new_x, new_y, new_x + rect_w, new_y + rect_h)
yvel += .25
canvas.after(100, move_rect) # call the move function again after .5 second
def up(event):
global yvel
yvel = yvel - 2
def left(event):
global xvel
xvel = xvel - 2
def right(event):
global xvel
xvel = xvel + 2
def collisionDetection():
window = tk.Tk( ) # create root window
window.geometry('700x400') # resize window
canvas = tk.Canvas(window, bg = "#ffffff") #create canvas to draw on
canvas.pack(fill = tk.BOTH, expand = 1) # make canvas fill window
rect_w = 100
rect_h = 50
player = canvas.create_rectangle(200, 100, 200 + rect_w, 100 + rect_h, fill="blue") # draws rectangle
landingRect = canvas.create_rectangle(0, 300, 700, 400, fill="black")
window.bind("<Button-1>", clicked) # set the event handler for when window is clicked
window.bind("<w>", up)
window.bind("<a>", left)
window.bind("<d>", right)
move_rect()
window.mainloop() # required line to start window |
0d02858b74f60409851b449388da228c0f89d420 | tioguil/LingProg | /-Primeira Entrega/Exercicio01 2018_08_14/atv8.py | 1,689 | 3.953125 | 4 | # 8 Faça um Programa que pergunte quanto você ganha por hora e o
# número de horas trabalhadas no mês. Calcule e mostre o total do
# seu salário no referido mês, sabendo-se que são descontados 11%
# para o Imposto de Renda, 8% para o INSS e 5% para o sindicato,
# faça um programa que nos dê:
# - salário bruto.
# - quanto pagou ao INSS.
# - quanto pagou ao sindicato.
# - o salário líquido.
# - calcule os descontos e o salário líquido, conforme a tabela abaixo:
# + Salário Bruto : R$
# - IR (11%8 : R$
# - INSS (8%8 : R$
# - Sindicato ( 5%8 : R$
# = Salário Liquido : R$
# Obs.: Salário Bruto - Descontos = Salário Líquido.
print("Informe Valor ganho por hora")
valor_hora = float(input())
print("Informe horas trabalhadas no mês")
horas_trabalhadas = float(input())
salario_bruto = valor_hora * horas_trabalhadas
inss = salario_bruto*0.08
sindicato = salario_bruto*0.05
ir = salario_bruto*0.11
total_descontos = inss+sindicato+ir
salario_liquido = salario_bruto - total_descontos
print("-------------------------------------------"
"\n| Salario Bruto ------------- %s R$"
"\n| "
"\n| ------------- "
"\n| INSS - %s R$"
"\n| Sindicato - %s R$"
"\n| IR - %s R$"
"\n| Total Descontos - %s R$"
"\n| ------------- "
"\n| "
"\n| Salario Liquido %s R$"
"\n--------------------------------------------" %(salario_bruto, inss, sindicato, ir, total_descontos, salario_liquido)) |
e75fe49f87c503c2d8e7fac3f6d253925d007afc | kvijayenderreddy/march2020 | /loops/NestedIfLoop.py | 137 | 4.03125 | 4 |
a = 30
b = 30
if (a<b):
print("a is greater than b")
elif (a>b):
print("b is greater")
else:
print("a and b are equal")
|
88dfe92ef26f3f4e34a85c0fae92bb0678e151c3 | alex9269/ECE351_Code | /lab2.py | 2,505 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 19:59:58 2019
@author: alexa
"""
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 14})
steps = 1e-2
t = np.arange(0,10+steps,steps)
def func1(t):
y = np.zeros((len(t),1))
for i in range(len(t)):
y[i] = np.cos(t[i])
return y
y = func1(t)
myFigSize = (10,8)
plt.figure(figsize=myFigSize)
plt.subplot(1,1,1)
plt.plot(t,y)
plt.grid(True)
plt.ylabel('y')
plt.xlabel('x')
plt.title('y(t)=cos(t)')
steps = 0.1
t = np.arange(-5,10+steps,steps)
def step(t):
y = np.zeros((len(t),1))
for i in range(len(t)):
if t[i] < 0:
y[i] = 0
else:
y[i] = 1
return y
def ramp(t):
y = np.zeros((len(t),1))
for i in range(len(t)):
if t[i] < 0:
y[i] = 0
else:
y[i] = t[i]
return y
def my_func(t):
y = np.zeros((len(t),1))
y = ramp(t-0) + 5*step(t-3) - ramp(t-3) - 2*step(t-6) - 2*ramp(t-6)
return y
y = step(t)
myFigSize = (10,20)
plt.figure(figsize=myFigSize)
plt.subplot(3,1,1)
plt.plot(t,y)
plt.grid(True)
plt.ylabel('Step Function')
plt.title('Step, Ramp, and User-Defined Functions')
y = ramp(t)
plt.subplot(3,1,2)
plt.plot(t,y)
plt.grid(True)
plt.ylabel('Ramp Function')
y = my_func(t)
plt.subplot(3,1,3)
plt.plot(t,y)
plt.grid(True)
plt.ylabel('User-Defined Function')
plt.xlabel('t')
plt.show()
t = np.arange(-10,5+steps,steps)
y = my_func(-t)
myFigSize = (10,40)
plt.figure(figsize=myFigSize)
plt.subplot(6,1,1)
plt.plot(t,y)
plt.grid(True)
plt.ylabel('Time Reversal')
plt.title('Shifted User-Defined Function Graphs')
t = np.arange(-1,15+steps,steps)
y = my_func(t-4)
plt.subplot(6,1,2)
plt.plot(t,y)
plt.grid(True)
plt.ylabel('t-4')
t = np.arange(-14,1+steps,steps)
y = my_func(-t-4)
plt.subplot(6,1,3)
plt.plot(t,y)
plt.grid(True)
plt.ylabel('-t-4')
t = np.arange(-5,20+steps,steps)
y = my_func(t/2)
plt.subplot(6,1,4)
plt.plot(t,y)
plt.grid(True)
plt.ylabel('t/2')
t = np.arange(-2,5+steps,steps)
y = my_func(2*t)
plt.subplot(6,1,5)
plt.plot(t,y)
plt.grid(True)
plt.ylabel('2t')
t = np.arange(-5,10+steps,steps)
dt = np.diff(t)
y = np.diff(my_func(t),axis=0)/dt
plt.subplot(6,1,6)
plt.plot(t[0:len(t)-1],y)
plt.grid(True)
plt.axis([-5,10,-10,20])
plt.ylabel('First Derivative')
plt.xlabel('t')
plt.show() |
6a081dbb1acef18695db4d27aae096682973d790 | Dissssy/AdventOfCode2020 | /09/2/code.py | 1,020 | 3.625 | 4 | import time
start_time = time.time()
#open the file and parse it into a list of strings on newlines
text_file = open("input.txt", "r")
lines = text_file.read().split('\n')
#every input text file has an empty newline at the end, delete it
lines.pop(-1)
def isvalid(i):
for j in range(i - 25, i):
for l in range(j + 1, i):
if(lines[j] + lines[l] == lines[i]):
return True
return False
def check():
for i in range(2, len(lines)):
for j in range(0, len(lines) - i):
check = [None]*i
sum = 0
for l in range(j, j + i):
check[l - j] = lines[l]
for l in range(0, len(check)):
sum += check[l]
if(sum == invalid):
return(min(check) + max(check))
for i in range(0, len(lines)):
lines[i] = int(lines[i])
for i in range(25, len(lines)):
if not isvalid(i):
invalid = lines[i]
print(check())
print("--- %s seconds ---" % (time.time() - start_time))
|
0847cb673c662e90446ddd484e19f141b07315be | jilee210/hello-world | /wcounter.py | 1,293 | 3.546875 | 4 | #!/usr/bin/python
# JL 081017 to simulate wordcount.py with High Performace collections container Counter availble >= version 2.7
# Note: python 2.7 and 3.x, Counter not available in 2.6
# ======================================================
import sys
from collections import Counter as C
if len(sys.argv) < 2:
print 'usage: ./counter.py file [topcount]'
sys.exit(1)
text = open(sys.argv[1]).read()
if text:
wc = C(text.lower().split())
#wc = C(text.split())
else:
print("text/file empty")
sys.exit(2)
if len(sys.argv) == 3:
topcount = int(sys.argv[2])
else:
topcount = 5
print("* most_common topcount %d: %s" % (topcount, wc.most_common(topcount))) # wc.most_common() will sort all by freq highest first
print("* complete count up to maxcnt 50 to limit output")
maxcnt = 0
for i in sorted(wc, key=wc.get, reverse=True):
# help(dict.get): D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
# the below two: print i as tuples(not dict) and wc[i] to 0, so need to print("{} {}".format(i[0], i[1]))
# for i in wc.most_common():
# for i in sorted(wc.items(), key=lambda t: t[1], reverse=True): # cf. wc as dict vs wc.items() tuple like most_common
#print('{} {}'.format(i, wc[i]))
print("%s : %d" % (i, wc[i]))
maxcnt += 1
if maxcnt == 50: break
|
9d86e750a6924e1996374d8e3ba860f374b87a7b | huhudaya/leetcode- | /LeetCode/546. 移除盒子.py | 686 | 3.546875 | 4 | '''
给出一些不同颜色的盒子,盒子的颜色由数字表示,即不同的数字表示不同的颜色。
你将经过若干轮操作去去掉盒子,直到所有的盒子都去掉为止。每一轮你可以移除具有相同颜色的连续 k 个盒子(k >= 1),这样一轮之后你将得到 k*k 个积分。
当你将所有盒子都去掉之后,求你能获得的最大积分和。
示例:
输入:boxes = [1,3,2,2,2,3,4,3,1]
输出:23
解释:
[1, 3, 2, 2, 2, 3, 4, 3, 1]
----> [1, 3, 3, 4, 3, 1] (3*3=9 分)
----> [1, 3, 3, 3, 1] (1*1=1 分)
----> [1, 1] (3*3=9 分)
----> [] (2*2=4 分)
提示:
1 <= boxes.length <= 100
1 <= boxes[i] <= 100
'''
|
fed249dd7b78521cf04f042016db001b0d8fc927 | jnovikov/patterns_examples | /computer.py | 927 | 3.515625 | 4 | class State(object):
allowed_states = []
state_description = None
def change_state(self, state):
if state.state_description in self.allowed_states:
return True
return False
class StateOn(State):
allowed_states = ["sleep", "off"]
state_description = "on"
class StateOff(State):
allowed_states = ["on"]
state_description = "off"
class StateSleep(State):
allowed_states = ["off", "on"]
state_description = "sleep"
class Computer(object):
def __init__(self, name):
self.name = name
self.state = StateOff()
def change_state(self, new_state):
if self.state.change_state(new_state):
self.state = new_state
else:
print("CANT CHANGE STATE")
def info(self):
print(self.state.state_description)
c = Computer("ibm")
c.info()
c.change_state(StateOff())
c.change_state(StateOn())
c.info() |
cc57c034de41a330f65ccc426c0331a4110f511c | TareqJudehGithub/Ardit_Sulce_Udemy | /Python_Mega/sec5_Basics_func_condtiton/section_recap.py | 1,028 | 4.4375 | 4 | # Cheatsheet (Functions and Conditionals)
# In this section, you learned to:
# Define a function:
def cube_volume(a):
return a * a * a
# Write a conditional block:
message = "hello there"
if "hello" in message:
print("hi")
else:
print("I don't understand")
# Write a conditional block of multiple conditions:
message = "hello there"
if "hello" in message:
print("hi")
elif "hi" in message:
print("hi")
elif "hey" in message:
print("hi")
else:
print("I don't understand")
# Use the and operator to check if both conditions are True at the same time:
x = 1
y = 1
if x == 1 and y==1:
print("Yes")
else:
print("No")
# Output is True since both x and y are 1.
# Use the or operator to check if at least one condition is True:
x = 1
y = 2
if x == 1 or y==2:
print("Yes")
else:
print("No")
# Output is Tue since x is 1.
# Check if a value is of a particular type with:
isinstance("abc", str)
isinstance([1, 2, 3], list)
# or
type("abc") == str
type([1, 2, 3]) == list
|
20b629f9355912044f6048f4f3a6abd9b8343f44 | olgarithms/advent_of_code_2019 | /Day05/task2.py | 2,761 | 3.78125 | 4 | filename = "input.txt"
result = None
def get_numbers():
with open(filename, 'r') as textfile:
line = textfile.readline().strip("\n")
return list(map(int, line.split(',')))
def get_parameter(mode, i, pos, numbers):
return numbers[get_address(mode, i, pos, numbers)]
def get_address(mode, i, pos, numbers):
# print("mode", mode, "i", i, "pos", pos)
address = 0
if mode == "1":
address = i+pos
elif mode == "0":
address = numbers[i+pos]
return address
def do_arithmetic_operation(addition, multiplication, mode, i, numbers):
# mode is a 3 digit string that gives modes for each parameter
param1 = get_parameter(mode[2], i, 1, numbers)
param2 = get_parameter(mode[1], i, 2, numbers)
if addition:
result = param1 + param2
elif multiplication:
result = param1 * param2
numbers[get_address(mode[0], i, 3, numbers)] = result
def do_jump(is_zero, mode, i, numbers):
param1 = get_parameter(mode[2], i, 1, numbers)
if ((param1 == 0) and is_zero) or ((param1 != 0) and not is_zero):
i = get_parameter(mode[1], i, 2, numbers)
else:
i += 3
return i
def do_comparisons(less_than, equals, mode, i, numbers):
param1 = get_parameter(mode[2], i, 1, numbers)
param2 = get_parameter(mode[1], i, 2, numbers)
param3 = get_address(mode[0], i, 3, numbers)
if (less_than and param1 < param2) or (equals and param1 == param2):
numbers[param3] = 1
else:
numbers[param3] = 0
return i + 4
def task2():
numbers = get_numbers()
i = 0
outputs = []
while i < len(numbers) - 1:
num_str = str(numbers[i])
zeros_to_add = 5-len(num_str)
instruction = zeros_to_add*"0" + num_str
opcode = instruction[-2:]
mode = instruction[:-2]
if opcode == "01":
do_arithmetic_operation(True, False, mode, i, numbers)
i += 4
elif opcode == "02":
do_arithmetic_operation(False, True, mode, i, numbers)
i += 4
elif opcode == "03":
numbers[get_address(mode[2], i, 1, numbers)] = 5
i += 2
elif opcode == "04":
out = numbers[get_address(mode[2], i, 1, numbers)]
outputs.append(out)
i += 2
elif opcode == "05":
i = do_jump(False, mode, i, numbers)
elif opcode == "06":
i = do_jump(True, mode, i, numbers)
elif opcode == "07":
i = do_comparisons(True, False, mode, i, numbers)
elif opcode == "08":
i = do_comparisons(False, True, mode, i, numbers)
elif opcode == "99":
break
else:
break
return outputs[-1]
print(task2())
|
020eac8e025e72936f95d556ffcef462f7c84a54 | dmr8230/UNCW-Projects | /CSC231-Python/Chp 10 - Recursive Sum/mySum.py | 2,375 | 4.25 | 4 | '''
Author: Dani Rowe
Date: October 13th, 2020
Description: This program implements a recursive sum operation on a list
'''
import random
def recSum1(someList):
'''
this function adds all the items in the list together
:param someList: takes the list
:return: the sum of the function
'''
if len(someList) == 1:
return someList[0]
else:
a = recSum1(someList[:len(someList) //2])
b = recSum1(someList[len(someList) // 2:])
return a + b
def recSum2(someList):
'''
Takes the sum of the funciton and adds it together
:param someList: the list
:return: all of the items added together
'''
if len(someList) == 1:
return someList[0]
else:
return someList[0] + recSum2(someList[1:])
def minvalues(someList):
'''
finds the minimum value in the function
:param someList: the list
:return: the minimum value in the list
'''
if len(someList) == 1:
return someList[0]
else:
firsthalf = minvalues(someList[:len(someList) //2])
secondhalf = minvalues(someList[len(someList) //2:])
if (firsthalf < secondhalf):
return firsthalf
else:
return secondhalf
def exponentfunc(x, n):
'''
recursivly finds the exponent of the function depending on if it is even or odd
:param x: one variable in the function
:param n: another variable in the function
:return: the result depending if it is even or odd
'''
if n <= 0:
return 1
else:
y = n // 2
m = exponentfunc(x, y)
if (y%2 == 0):
return m * m
else:
return m * m * x
def main():
N = 100
myList = [random.randint(-500, 500) for i in range(N)]
x = int((random.randint(1,10)))
n = int((random.randint(1,10)))
print("The x value is: " , x)
print("The n value is: " , n)
print(myList)
print("The sum of the numbers is: " + str(sum(myList)))
print("The sum of the numbers using recSum1 is: " + str(recSum1(myList)))
print("The sum of the numbers using recSum2 is: " + str(recSum2(myList)))
print("The minimum value is the smaller minimums of the two halves is: " + str(minvalues(myList)))
print("The recursive result for the xn problem is: " + str(exponentfunc(x,n)))
if __name__ == "__main__":
main() |
59e053a59597acb62aecb3b49e1fe1f650d24a5c | muyawei/DataAnalytics | /Pandas_Date/pandas_data/combine_first.py | 539 | 3.9375 | 4 | # -*- coding:utf-8 -*-
import pandas as pd
import numpy as np
# 用参数对象中的数据为调用者对象"打补丁"
df1 = pd.DataFrame({"a": [1, 3, np.NaN, 4],
"b": [2, np.NaN, 4, 6]
})
df2 = pd.DataFrame(np.arange(12).reshape((2, 6)))
df = df1.combine_first(df2)
print "df1"
print df1
print "df2"
print df2
print "df"
print df
df2 = pd.DataFrame(np.arange(12).reshape((6, 2)), columns=["a", "b"])
df = df1.combine_first(df2)
print "df1"
print df1
print "df2"
print df2
print "df"
print df
|
902b52a221512b1cbb284df287ac287ccf66f34c | gagan405/ProjectEuler | /p94.py | 756 | 3.84375 | 4 | sum = 0
limit = 1000000000
def getNextVal(a, b):
return ((2*a + 3*b), (a + 2*b))
def getTriangles():
global sum
x = 2
y = 1
# a = x**2 + y**2
# b = 2*(x**2-y**2)
while(True):
a3 = 2*x - 1
area3 = y*(x-2)
if(a3 > limit):
break
if (a3 > 0 and area3 > 0 and
a3 % 3 == 0 and area3 % 3 == 0):
a = a3 // 3;
sum += 3 * a + 1;
a3 = 2 * x + 1;
area3 = y * (x + 2);
if (a3 > 0 and area3 > 0 and
a3 % 3 == 0 and area3 % 3 == 0):
a = a3 // 3;
sum += 3 * a - 1;
x, y = getNextVal(x, y)
getTriangles()
print("Sum of perimeters : ", str(sum))
|
a7522bc846faa2b76b28167a3a9c2883d22dfb5e | dani-fn/Projetinhos_Python | /projetinhos/ex#24 - verificando as primeiras letras de um texto.py | 131 | 3.921875 | 4 | print('Será que sua cidade começa com Santo?')
cid = str(input('Em que cidade você nasceu? ')).upper()
print('SANTO' in cid)
|
e6c858b32f2be71af8baff8bab0ba94e88ef1f2c | abhijitdey/coding-practice | /facebook/arrays_and_strings/1_longest_substring_without_repeating_chars.py | 939 | 3.703125 | 4 | class Solution:
"""
1. Keep track of the index where you see each char
2. Whenever you find a repeating char, make sure you mark that index+1 as the start of a new substring
and start counting the length from there. last_valid_index keeps track from where the substring starts.
3. Store the value of the max substring as you loop through the main string.
"""
def lengthOfLongestSubstring(self, s: str) -> int:
seen_chars = {}
max_length = 0
current_length = 0
last_valid_index = -1
for i, char in enumerate(s):
if char in seen_chars and seen_chars[char] >= last_valid_index:
current_length = i - seen_chars[char]
last_valid_index = seen_chars[char] + 1
else:
current_length += 1
seen_chars[char] = i
max_length = max(max_length, current_length)
return max_length
|
832c6b1f8ba2ee1eec1d13419216bf5d669bf219 | ZoomQuiet/zoomquiet.tangle | /s5/070322-introPy/py/pythonic.py | 4,097 | 3.8125 | 4 | # coding : utf-8
''' prime = sieve [2..] ---改进后的素数数列
sieve (x:xs) = x : sieve (filter (\y ->y `rem` x /= 0) xs)
'''
#想将数组中大于某个数值的数选出来构成一个新的数列
li = range(3)
import random
random.shuffle(li)
[item for item in li if item > 3.5 ] #(注:source是一个List)
############### 数据类型
素数计算
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/162479
N = 40
[p for p in range(2,N) if 0 not in [p%d for d in range(2,p)]]
- replace 'range(2,p)' by 'range(2,p/2+1)',
- replace 'range(2,p)' by 'int(sqrt(p))+1)' (sqrt is imported from the math module),
- replace 'range(...)' by 'xrange(...)', in both places.
from math import sqrt
N = 100
[ p for p in range(2, N) if 0 not in [ p% d for d in range(2, int(sqrt(p))+1)] ]
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
| | | | | | | | | | +- 弥补
| | | | | | | | | +- 通过平方精简尝试
| | | | | | | | +- 组织所有 2~p 之间可能为公因子的数列
| | | | | | | +- 求余,尝试整除
| | | | | | +- 列表运算,直接将以上计算结果组成数组 返回
| | | | | +- 余数0 不在求余结果列表中
| | | | +- 即2~p 都不能整除 p 的p
| | | +- 提取运算
| | +- for..in 循环取数,从2~p 的连续数组中
| +- 素数!
+- 列表计算组织所有结果为数组返回!
就是判断是否有 2-p 之间的数可以整除 p ,如果有的话, 后面的列表中就会有一个余数为0, 所以要没有 0 存在才能判定为没有可整除他的(也就是素数)
############### 自省!
在一个函数中如何知道调用者(Python)
def fun():pass
这个函数如何知道是谁调用了它呢? 在C类语言中好像是很难的。但在 Python中却很简单
import traceback
def fun():
s = traceback.extract_stack()
print '%s Invoked me!'%s[-2][2]
这个 fun 函数就可以知道是谁调用了它,并打印出来, 我们来试一下:
>>> def a():fun()
>>> def b():fun()
>>> a()
a Invoked me!
>>> b()
b Invoked me!
>>>
ok! 怎么应用这个特性呢? 发挥各位的想象力了。
MixIn 技术 (感谢 limdou 的介绍)
def MixIn(pyClass, mixInClass):
print "Mix class:",mixInClass, " into: ",pyClass,'\n'
pyClass.__bases__ += (mixInClass,)
class A:
def __init__(self):
self.name = "Class A"
def fun(self):
print self.name
class B:
def __init__(self):
self.name = "Class B"
def add(self, a,b):
print 'function defined in B'
return a + b
obj_a = A()
print obj_a
print dir(obj_a),'\n'
MixIn(A,B)
print obj_a
print dir(obj_a),'\n'
print obj_a.add(3,5)
-----------------------------------------〉
执行结果:
>>>
<__main__.A instance at 0x00BB7F80>
['__doc__', '__init__', '__module__', 'fun', 'name']
Mix class: __main__.B into: __main__.A
<__main__.A instance at 0x00BB7F80>
['__doc__', '__init__', '__module__', 'add', 'fun', 'name']
function defined in B
8
解释一下 MixIn 技术,就是使 一个类成为另一个类的基类, 这样会使 被 MixIn 的那个类具有了新的特性。
在例子程序中, 我们将 B 类 MixIn 进 A 类, 成为 A 的基类,于是, A 类的实例便具有了 B 类的方法(add)
obj_a = A() obj_a 是 类 A 的一个实例
print obj_a <__main__.A instance at 0x00BB7F80>
print dir(obj_a),'\n' ['__doc__', '__init__', '__module__', 'fun', 'name']
MixIn(A,B) 将B MixIn 进 A
print obj_a <__main__.A instance at 0x00BB7F80>
print dir(obj_a),'\n' ['__doc__', '__init__', '__module__', 'add', 'fun', 'name']
注意,这时候,多了一个 add 方法(类B 中定义)
print obj_a.add(3,5) 现在 A 的实例可以使用 B 中的方法了
|
62d515e9d947726197ae8760d67871dd142ce497 | Miracle-cl/Algorithms | /Recursion/WordBreak.py | 1,223 | 3.578125 | 4 | from typing import List
from functools import lru_cache
# TLE Solution without lru_cache
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
return self.recursive(s, tuple(wordDict))
@lru_cache(maxsize=128)
def recursive(self, s, wordset):
if not s:
return True
for w in wordset:
if s.startswith(w) and self.recursive(s[len(w):], wordset):
return True
return False
# create memroy dict to save recursive info
class Solution2:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
memory = {w: 1 for w in wordDict}
memory[''] = 1
return self.recursive(s, set(wordDict), memory)
def recursive(self, s, wordset, memory):
if s in memory:
return memory[s]
for w in wordset:
if s.startswith(w) and self.recursive(s[len(w):], wordset, memory):
memory[s] = True
return True
memory[s] = False
return False
if __name__ == '__main__':
solu = Solution2()
s = 'leetcode'
wd = ['leet', 'code']
res = solu.wordBreak(s, wd)
print(res)
|
096ba953040c69fe2de0ea6181e16c45c187fbb5 | AMujeebDalal/python_bootcamp | /Podomora/km-mile_converter.py | 1,011 | 3.984375 | 4 | from tkinter import *
def calculate():
miles = float(miles_input.get())
km = round(1 / 1.6093 * miles, 3)
km_result.config(text=km)
window = Tk()
window.title("Miles-Km Converter")
window.minsize(width=200, height=150)
window.config(padx=20, pady=30)
is_equal = Label(text="is equal to", font=("Arial", 10, "bold"))
is_equal.grid(column=0, row=2)
is_equal.config(padx=20, pady=20)
# Entry
miles_input = Entry(width=10)
miles_input.grid(column=1, row=0)
miles_label = Label(text="Miles", font=("Arial", 10, "bold"))
miles_label.grid(column=2, row=0)
miles_label.config(padx=20, pady=20)
km_result = Label(text="0", width=10, font=("Arial", 10, "bold"))
km_result.grid(column=1, row=2)
km_result.config(padx=20, pady=20)
km_label = Label(text="Km", font=("Arial", 10, "bold"))
km_label.grid(column=2, row=2)
km_label.config(padx=20, pady=20)
# Button
button = Button(text="Calculate", command=calculate)
button.grid(column=1, row=4)
window.mainloop()
|
48e68203e86a00f32dacd993b0955441a50f90e6 | doortothe/kaggle_hash_code_2021 | /classes/__init__.py | 1,085 | 3.71875 | 4 | def validate_variable(var, var_check):
"""
Check if variable is within appropriate constraints
Return the variable if true
Otherwise, return an error
:param var: variable being checked
:param var_check: the variable to check
:return: var if within proper constraints. Otherwise, raise an error
"""
# Go through list of variables
if var_check == 'D' and 1 <= var <= 10 ^ 4:
return var
if (var_check == 'I' or var_check == 'S') and 2 <= var <= 100_000:
return var
if var_check == 'V' and 2 <= var <= 1_000:
return var
if var_check == 'F' and 1 <= var <= 1_000:
return var
raise Exception("Inappropriate value for " + var_check + ": " + str(var))
def find(array, idt):
"""
:param array: list of class has an id field for the id() method
:param idt: Id we are looking for
:return: if id is in id(list), return the index. -1 if not
"""
i = -1
for x in range(len(array)):
if array[x].get_id == idt:
i = x
return i
RED = 'red'
GREEN = 'green'
|
b8e41ef49175f2cda1bc9278271274425080f10d | Dagim3/MIS3640 | /quiz3_dagim.py | 1,354 | 3.8125 | 4 | # Upload quiz_3.py file to Blackboard - Session 13
def replace_even(data):
def replace_even(data):
for x in data:
if x%2 != int:
data.remove(x)
data.insert(x,0)
# Uncomment the following lines to test
ONE_TEN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
replace_even(ONE_TEN)
print(ONE_TEN)
# Expected output:
# [0, 2, 0, 4, 0, 6, 0, 8, 0, 10]
def remove_middle(data):
if len(data) % 2 == 0:
middle1= int((len(data)/2))
middle2 = int(len(data)/2 - 1)
del data[middle1]
del data[middle2]
else:
middle = int(len(data)/2)
del data[middle1]
# Uncomment the following lines to test
ONE_TEN = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
remove_middle(ONE_TEN)
print(ONE_TEN)
# Expected output:
# [1, 2, 3, 4, 7, 8, 9, 10]
def insert_integer(data, number):
for n in range(0, len(data)):
if (data[n] >= number):
data.insert(n, number)
break
return data
# Uncomment the following lines to test
data = [1, 3, 40, 75, 90, 2000, 2001, 2016]
new_data = insert_integer(data, 2015)
print(data)
# Expected output:
# [1, 3, 40, 75, 90, 2000, 2001, 2015, 2016]
def print_hist(data):
for x in sorted(data):
g= data[x]
print (x,": ",g*'*')
letter_counts={'C': 6, 'A': 3, 'B': 10, 'Z': 8}
print_hist(letter_counts) |
d771a924c87eec8b35ce3bc9c82011a654607a29 | Sanchi02/Dojo | /LeetCode/TreeTraverseProblems/EvenValuedGrandParents.py | 1,749 | 3.765625 | 4 | # Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.)
# If there are no nodes with an even-valued grandparent, return 0.
# Example 1:
# Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
# Output: 18
# Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
# Constraints:
# The number of nodes in the tree is between 1 and 10^4.
# The value of nodes is between 1 and 100.
# 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 sumEvenGrandparent(self, root: TreeNode) -> int:
curr_level = []
next_level = [root]
arrF = []
while(root and next_level):
curr_level = next_level
next_level = []
for node in curr_level:
if(node.val%2==0):
if(node.left):
if(node.left.left):
arrF.append(node.left.left.val)
if(node.left.right):
arrF.append(node.left.right.val)
if(node.right):
if(node.right.left):
arrF.append(node.right.left.val)
if(node.right.right):
arrF.append(node.right.right.val)
if(node.left):
next_level.append(node.left)
if(node.right):
next_level.append(node.right)
return sum(arrF) |
ceadeebcaa818f234ce6871394c5e7bb25568738 | tat2133/advent-of-code | /day01/part2.py | 405 | 3.6875 | 4 | frequency = 0
calibrated = False
frequency_history = set()
while not calibrated:
with open('input.txt', 'r') as f:
for line in f:
frequency += int(line)
if frequency not in frequency_history:
frequency_history.add(frequency)
else:
calibrated = True
break
print("calibrated frequency: {}".format(frequency))
|
c27854e0153d8e6e3984369175779e021e383f59 | dahaihu/standard | /studing/Fp-grouth/fpgrouth.py | 13,777 | 3.71875 | 4 | """
如何在一棵树上,挖掘频繁一项集,二项集,三项集等等
条件模式基:是以所查找元素项为结尾的路径集合,表示的是所查找的元素项与树根节点之间的所有内容。
"""
class treeNode:
# 名字,次数,父节点
def __init__(self, nameValue, numOccur, parentNode):
self.name = nameValue # 当前节点的名称
self.count = numOccur # 当前节点在此模式下的出现次数
self.nodeLink = None # 用来指向跟当前节点name相同的,别的支上的节点
self.parent = parentNode # needs to be updated #用来指向当前节点,在此支上的父节点
self.children = {} # 当前节点的孩子节点
def inc(self, numOccur): # 由于事务是含有次数的,所以,当前节点出现的频次可能是多余1的,所以加上numOccur
self.count += numOccur
def disp(self, ind=1): # 这个应该是通过“作图”(就是打印)来描述数,那么这个是如何打印的呢?拥有一个父节点的孩子,在同一层
print(' ' * ind, self.name, ' ', self.count)
for child in self.children.values():
child.disp(ind + 1)
# 创建Fpgrouth-Tree
# 传入的dataSet是一个字典,键是事务,值是事务出现的次数
def createTree(dataSet, minSup=1): # create FP-tree from dataset but don't mine
# 需要注意的是这个headerTable是个字典
# 首先,用来存储所有项目及其频次,然后对频次小于minSup的进行删除
# 然后进行修改,键是频繁项,值变成一个含有两项的列表,
# 第一项用来存储之前存储的当前频繁项的频次,
# 第二项用来当指针,用来指向构建的树种,与该节点的nameValue相同的节点
headerTable = {}
# go over dataSet twice 遍历两遍数据库
# 第一遍,统计频繁项出现的频次
for trans in dataSet: # first pass counts frequency of occurance
for item in trans:
headerTable[item] = headerTable.get(item, 0) + dataSet[trans] # 这个dataSet[trans] 有点让人摸不着头脑 传入的dataset是不是经过处理的。
# 字典不能边遍历,边删除吗?对的,字典是不能遍历的同事进行删除的
# for k in headerTable.keys(): #remove items not meeting minSup #我觉得出现错误的原因是,headerTable是中的值是可变的,这个headerTable.keys()
# if headerTable[k] < minSup:
# del(headerTable[k])
# 这个用filter会失败的,filter似乎只能滤除列表?????反正是不能用来滤除字典的(如果把字典当成iterable对象来看的话,里面返回的是全部键)
# filter可以滤除任何iterable对象
# headerTable=filter(lambda x:headerTable[x]>=minSup,headerTable)
# 将出现频次小于最低支持度的频繁项给删除
s = set(headerTable.keys())
for ind in s:
if headerTable[ind] < minSup:
del headerTable[ind]
# 对headerTable中的头结点进行排序
# 键为节点,值为节点出现的频次从大到小排序的索引
# 也就是说索引越小值越大
mark = {node:ind for ind, node in enumerate(sorted(headerTable, key=lambda x:headerTable[x], reverse=True))}
# 现在的这个headerTable中的键是频繁项,值是频繁项出现的次数
freqItemSet = set(headerTable.keys()) # 频繁项集,这个不用set函数处理,是不是也是可以的。??? freqItemSet=set(headerTable)即可
# print 'freqItemSet: ',freqItemSet
if len(freqItemSet) == 0: return None, None # if no items meet min support -->get out
for k in headerTable:
headerTable[k] = [headerTable[k], None] # reformat headerTable to use Node link
# 现在这个headerTable变成了,键依然是频繁项,但是值变成了,一个含有两个对象的列表,第一个对象是原来的值,即频繁项出现的次数;第二个对象是None
# print 'headerTable: ',headerTable
# treeNode的三个参数,名字,数量,父节点
# 现在开始建树了
retTree = treeNode('Null Set', 1, None) # create tree
# 第二遍过滤数据库,建树
for tranSet, count in dataSet.items(): # go through dataset 2nd time 一猜就知道dataSet是经过处理的数据集合
# tranSet是指事务,count是指当前事务的频次
# 对每个事务进行处理,然后添加到树中去
# localD是用来对当前事务进行处理
# 统计当前事务中每个频繁项出现的频次
# 对超过最小支持度的频繁项,通过从大到小的排序方式
# 整理成orderedItems
localD = {} # 这个是用来干什么的???用来获取当前事务中所含的频繁项集
for item in tranSet: # put transaction items in order
if item in mark:
localD[item] = mark[item]
# localD用来存放该事务记录中,每个频繁项的频次
if len(localD) > 0:
# 对频繁项按照出现的次数进行从大到小的排序
"""
这个地方是有问题的,觉得相同的数量的项,在不同的组合中,顺序可能是不一致的
最好前面统一制定排序
"""
orderedItems = [v[0] for v in sorted(localD.items(), key=lambda p: p[1])]
##总的应该是,对每个事物的项目,根据项目的频率,按照从大到小的排序
updateTree(orderedItems, retTree, headerTable, count) # populate tree with ordered freq itemset
return retTree, headerTable # return tree and header table
# 项目列表,项目列表应该在的根节点,表头,项目对应的数量
# items应该是频繁项中已经包含的项集
# 这个headerTable是inTree的对应
# 那么这个count指的是什么呢?
# 当前节点出现的频次
# 这个updateTree还是个递归,牛逼???
# 每个inTree都是一棵树,有孩子节点,有父节点,有出现的频次
def updateTree(items, inTree, headerTable, count):
# 如果items[0]在当前节点的孩子之中的话
if items[0] in inTree.children: # check if orderedItems[0] in retTree.children
inTree.children[items[0]].inc(count) # increment count
# 如果items[0]不在当前节点的孩子当中
else: # add items[0] to inTree.children
inTree.children[items[0]] = treeNode(items[0], count, inTree)
# 如果添加到当前树的节点,没有headerTable中的链接,则添加到其中
if headerTable[items[0]][1] is None: # update header table
headerTable[items[0]][1] = inTree.children[items[0]]
# 如果有的话,则需要更新headTable,那么是如何更新这个headerTable的呢?
# 一个个便利,直到找到最后一个,然后进行连接
else:
updateHeader(headerTable[items[0]][1], inTree.children[items[0]])
# 由于item[0]已经添加到树中,如果item的长度等于1,那么不需要往下添加了
if len(items) > 1: # call updateTree() with remaining ordered items
updateTree(items[1:], inTree.children[items[0]], headerTable, count)
def updateHeader(nodeToTest, targetNode): # this version does not use recursion
while (nodeToTest.nodeLink != None): # Do not use recursion to traverse a linked list! 为什么不要通过递归遍历一个链表
nodeToTest = nodeToTest.nodeLink
nodeToTest.nodeLink = targetNode
# 找节点的前缀,把当前节点包含在prefixPath之中的,这个后面会有提醒,需要注意的
# 这个和下面的findPrefixPath是什么关系呢?
def ascendTree(leafNode, prefixPath): # ascends from leaf node to root
if leafNode.parent != None:
prefixPath.append(leafNode.name)
ascendTree(leafNode.parent, prefixPath)
# 这个是用来干什么的呢?这个basePat是用来干什么的?我怎么没看见函数里面用着这个参数
# 返回的结果是以treeNode为尾的所有频繁项集
# 但是这个basePat到底是干嘛的呢?
# 既然命名为findPrefixPath,那么就只需要一个参数
# 这样的话,不就跟ascendTree功能是一样的
# 不是的,比ascendTree多些功能
# 找寻该条件的所有条件模式基
# 这个treeNode是一个链表,一直往下指向一个nodeName相同的节点
# 返回一个节点之上的模式?
# a5
# b3 c4
# c2
# 如果传入C节点,那么返回的就是{frozenset(a,b):2,frozenset(a):4}
# 这个传入的basePat是干嘛用的呢?
"""
这个傻逼的basePat是用来干嘛的
这个函数是用来找条件模式基的
然后基于这些条件模式基来构建一个新的树
找到输入的treeNode的条件模式基。。。。
这个里面传入的basePat有个jbd用
"""
def findPrefixPath(basePat, treeNode): # treeNode comes from header table 、treeNode是来自headerTable的
condPats = {}
# treeNode = headTable[basePat][1]
while treeNode != None:
prefixPath = []
ascendTree(treeNode, prefixPath)
if len(prefixPath) > 1:
# 为什么把找到的prefixPath之中第一个排除在外
# 因为通过ascendTree找寻prefixPath的时候,把当前的treeNode也包含在其中了
# 在一个字典中,可变对象是不能作为键的。出错的原因是not hashble
condPats[frozenset(prefixPath[1:])] = treeNode.count
treeNode = treeNode.nodeLink
return condPats
# 如何在一棵树中,寻找频繁项集呢?
# 在树种挖掘频繁项集吗?????
# 这个headerTable之前就存在吗?
# 这个inTree和这个headerTable是相对应的
# 这个preFix我觉得叫后缀更好
"""
代码似乎要写的好,写的精简,只能用递归
而自己写递归的话,要注意的地方很多,截止条件,,,,,
这个也是个递归
"""
def mineTree(inTree, headerTable, minSup, preFix, freqItemList):
# 这个bigL是根据按照频繁项的频率从小到大排序的频繁项
# 这个bigL是从headerTable中来的
# 这个bigL的顺序,影响结果吗?
# print("headerTable is {}".format(headerTable))
# print("preFix is {}".format(preFix))
# 每mineTree一次都得对headerTable中的键按照频次从小到大排序一次的吗?
# 而且,这个headerTable也是不变得的吧?????
# 这个地方sort一下有用吗?
# 从底部网上走,和乱序的走,有什么区别的吗
bigL = [v[0] for v in sorted(headerTable.items(), key=lambda p: p[1][0], reverse=True)] # (sort header table)
# print("bigL is {}".format(bigL))
# 这个basePat是单个项
for basePat in bigL: # start from bottom of header table
# newFreqSet = preFix.copy()
# newFreqSet.add(basePat) # 把当前的basePat加到这个newFreqSet中去
newFreqSet = preFix + [basePat]
# 但是呢,这个newFreqSet就是频繁项集吗???????
# print 'finalFrequent Item: ',newFreqSet #append to set
print("newFreqSet is {}".format(newFreqSet))
freqItemList.append(newFreqSet)
condPattBases = findPrefixPath(basePat, headerTable[basePat][1])
# print 'condPattBases :',basePat, condPattBases
# 2. construct cond FP-tree from cond. pattern base
myCondTree, myHead = createTree(condPattBases, minSup)
# print 'head from conditional tree: ', myHead
if myHead != None: # 3. mine cond. FP-tree
# print 'conditional tree for: ',newFreqSet
# myCondTree.disp(1)
mineTree(myCondTree, myHead, minSup, newFreqSet, freqItemList)
def loadSimpDat():
simpDat = [['r', 'z', 'h', 'j', 'p'],
['z', 'y', 'x', 'w', 'v', 'u', 't', 's'],
['z'],
['r', 'x', 'n', 'o', 's'],
['y', 'r', 'x', 'z', 'q', 't', 'p'],
['y', 'z', 'x', 'e', 'q', 's', 't', 'm']]
return simpDat
# 这个createIniSet是不是有点不好。假如有的有多个相同的事务,那么该事物数是不是可以是大于1的,如果都是1,那么这么做有什么意义呢?
# 看了上面这条评论,我是搞懂了,我之前是怎么的笨
def createInitSet(dataSet):
retDict = {}
for trans in dataSet:
retDict[frozenset(trans)] = retDict.get(frozenset(trans), 0) + 1
return retDict
# dataSet=createInitSet(loadSimpDat())
# print(dataSet)
def loadDataset(path, minSup):
dataset = []
with open(path, 'r') as file:
count = 0
for line in file:
# print(line.strip().split(' '))
dataset.append(line.strip().split(','))
count += 1
minSup = len(dataset) * minSup
return dataset, minSup
from time import time
def fp_test(path, minSup):
# start = time()
simpDat, minSup = loadDataset(path, minSup)
# minSup = 2
# simpDat = [{'A', 'B', 'C', 'D'}, {'C', 'E'}, {'C', 'D'}, {'A', 'C', 'D'}, {'C', 'D', 'E'}]
# simpDat = [['1', '3', '4'], ['2', '3', '5'], ['1', '2', '3', '5'], ['2', '5']]
initSet = createInitSet(simpDat)
print('数据集的长度为 {}'.format(len(initSet)))
myFPtree, myHeaderTab = createTree(initSet, minSup)
myFPtree.disp()
start = time()
myFreqList = []
print('minSup is {}'.format(minSup))
mineTree(myFPtree, myHeaderTab, minSup, [], myFreqList)
print("myFreqList is {}".format(len(myFreqList)))
# for items in myFreqList:
# print(items)
print('cost time is {}'.format(time() - start))
# fp_test(r'/Users/hushichang/mushroom.dat.txt', 0.2)
fp_test(r'/Users/hushichang/Downloads/groceries.csv', 0.0003) |
abe7cffd8f38462ff179a000cc6337059ab4078b | mnavaidd/Python-Practice | /if-else.py | 276 | 3.796875 | 4 | y = 3 + 3
print (y)
z = y * 2
print (z)
if (z == 12):
print ("great")
else:
print ("wrong")
person = input("enter your name")
print ("Hello", person)
if (person == "navaid"):
print ("Hurray: Navaid you earned", z, "points.")
else:
print("Hello", person)
|
68b9d35fa4e36820a4fdbe6156f256a9b4bd220c | RhysMurage/alx-higher_level_programming | /0x06-python-classes/6-square.py | 2,118 | 4.53125 | 5 | #!/usr/bin/python3
"""Creates a square class"""
class Square():
"""
Define a square
"""
def __init__(self, size=0, position=(0,0)):
"""
size initialization.
Args:
size: integer value
"""
if type(size) != int:
raise TypeError('size must be an integer')
if size < 0:
raise ValueError('size must be >= 0')
self.__size = size
self.position = position
def area(self):
"""
calculate area of square
"""
return self.__size**2
@property
def size(self):
"""
return size of square
"""
return self.__size
@size.setter
def size(self, value):
"""
set size of square
"""
if type(value) != int:
raise TypeError('size must be an integer')
if value < 0:
raise ValueError('size must be >= 0')
self.__size = value
def my_print(self):
"""
prints the square on the terminal
"""
if self.__size > 0:
for row in range(self.__position[1]):
print()
for row in range(self.__size):
for column in range(self.__position[0]):
print(" ", end="")
for column in range(self.__size):
print("#", end="")
print()
else:
print()
@property
def position(self):
"""
get the position of the square
"""
return self.position
@position.setter
def position(self, value):
"""
sets the position of the square
"""
if type(value) != tuple or len(value) != 2:
raise TypeError("position must be a tuple of 2 positive integers")
if type(value[0]) != int or type(value[1]) != int:
raise TypeError("position must be a tuple of 2 positive integers")
if value[0] < 0 or value[1] < 0:
raise TypeError("position must be a tuple of 2 positive integers")
self.position = value
|
2746e77b0c91a2d634bdc6fd276f2316054ef13a | lightning720z/belajar-python | /Elif.py | 281 | 3.953125 | 4 | # Belajar Elif else if
menu_pilihan = input("Silahkan pilih menu [1-3] : ")
if menu_pilahan == "1":
print("anda memilih 1")
elif menu_pilahan == "2":
print("anda memilih 2")
elif menu_pilahan == "3":
print("anda memilih 3")
else:
print("menu tidak ada") |
c825cd3abf3d97e5c82e829f49b76a4887ff44ea | fenixfurion/aoc2020 | /2020/day09/day9.py | 1,885 | 3.90625 | 4 | #!/usr/bin/env python
def check_valid(previous_list, check_value):
for i in range(0,len(previous_list)):
# print("i: {}".format(i))
search_value = abs(check_value-previous_list[i])
if search_value in previous_list[0:i] or search_value in previous_list[i:]:
print("Found values {} and {} in valid list {}".format(search_value, previous_list[i], valid_list))
return True
print("Did not find a pair in list {} to sum to {}.".format(previous_list, check_value))
return False
with open('input.txt', 'r') as fd:
data = [int(elem.strip()) for elem in fd.readlines()]
preamble_length = 25
valid_list = data[0:preamble_length]
print(valid_list)
for elem in data[preamble_length:len(data)]:
print("checking {}".format(elem))
if not check_valid(valid_list, elem):
print("{} is the first invalid value".format(elem))
invalid_num = elem
break
else:
print("Dropping {} from valid_list and appending {}".format(valid_list[0], elem))
valid_list.append(elem)
valid_list.pop(0)
# print("Valid list: {}".format(valid_list))
# part 2
found_range = False
for i in range(0,len(data)):
for j in range(i+1,len(data)):
data_range = data[i:j]
#print("i = {}, j = {}; list = {}".format(i, j, data_range))
#print("i = {}, j = {}".format(i, j))
if sum(data_range) == invalid_num:
print("Found range {} to {} with sum {}".format(i, j, invalid_num))
minval = min(data_range)
maxval = max(data_range)
print("Min: {}, Max: {}, min+max: {}".format(minval, maxval, minval+maxval))
found_range = True
break
if sum(data_range) > invalid_num:
# if sum(data[i:j]) > invalid num, continue i and reset j
break
if found_range:
break
|
c248504545472550f128d4ba776984db1432ef1e | shankarkrishnamurthy/problem-solving | /longest-mountain.py | 885 | 3.96875 | 4 | class Solution(object):
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
lm,i,cl = 0,1,-1
if len(A) < 3: return 0
print A
while i < len(A)-1:
if A[i] > A[i-1] and A[i] > A[i+1]:
# Found a mountain peak
r = i + 1
while r < len(A)-1 and A[r] > A[r+1]:
r += 1
if lm < r - cl :
lm = r-cl
i = r
print "new mountain ",cl,r, lm
cl = r-1
else:
if A[i-1] >= A[i]: cl = i-1
i += 1
return lm
print Solution().longestMountain([2,1,4,7,3,2,5])
print Solution().longestMountain([0,3,2,1,4,7,3,2,5])
print Solution().longestMountain([2,2,2])
print Solution().longestMountain([2,4,2])
|
09cad1f19bf0caeee98dc93996220faf67981143 | spice0xff/lear_php_laravel_test | /main.py | 1,108 | 3.59375 | 4 | import random
def task1():
number_list = ", ".join([str(int(100*random.random())) for index in range(100)])
with open("numbers.csv", "w") as file:
file.write(number_list)
def task2():
with open("numbers.csv", "r") as file:
data = file.read()
number_list = data.split(", ")
more_than_50_count = 0
for number in number_list:
more_than_50 = int(number) > 50
if more_than_50:
more_than_50_count += 1
print("{} {}".format(number, int(more_than_50)))
print("more than 50 count: {}".format(more_than_50_count, ))
def task3():
def fact(n):
if n == 0:
return 1
return n * fact(n-1)
number = None
while number is None:
print("input number [1..10]: ", end="")
number = input()
try:
number = int(number)
if number < 1 or number > 11:
raise ValueError
except ValueError:
number = None
print("fact({}) = {}".format(number, fact(number)))
if __name__ == '__main__':
task1()
task2()
task3()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.