blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2480357c4ebc466a648707ca61c3438472bbce77 | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/401-600/000477/TLE--000477.py | 811 | 3.75 | 4 | class Solution(object):
def totalHammingDistance(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 该函数出自 LC461
def hamming_distance(x, y):
res = 0
tmp = x ^ y
while tmp:
tmp &= tmp - 1
res += 1
return res
res = 0
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
res += hamming_distance(nums[i], nums[j])
return res
"""
https://leetcode-cn.com/submissions/detail/181519637/
35 / 46 个通过测试用例
状态:超出时间限制
"""
"""
注:即使用最快的计算两数之间汉明距离的实现都超时了,所以 “二重循环 + 每次计算” 肯定不行。
"""
|
382b82ca624a7a8e3245691fdf92347da0b229d2 | ivanezeigbo/statistics | /recursive simple.py | 590 | 4.15625 | 4 | #Recursive function to get largest number in list
list = [56, 345, 322, 6677, 798, 4, 322, 5667, 6676, 322, 7777, 566, 2322]
largest = list[0] #initially assigns the first term as the largest
x = 1 #index position
def large_num(largest, list, x):
if largest < list[x]: #compares with next
largest = list[x]
if x == (len(list) - 1):
print ("Largest number is", largest)
return (largest)
x += 1 #increments value of index
return (large_num(largest, list, x)) #checks largest against next value
large_num(largest, list, x) #runs function
|
0c7f7b1ff04528026aa8d273281d2b63d6b203a5 | mccarvik/cookbook_python | /14_testing_debugging_exceptions.py/13_profile_time_prog.py | 1,525 | 3.546875 | 4 | # timethis.py
import time
from functools import wraps
def timethis(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
r = func(*args, **kwargs)
end = time.perf_counter()
print('{}.{} : {}'.format(func.__module__, func.__name__, end - start))
return r
return wrapper
# use decorator to time runtime
@timethis
def countdown(n):
while n > 0:
n -= 1
countdown(10000000)
from contextlib import contextmanager
# to time a block of statements, can use a context manager
@contextmanager
def timeblock(label):
start = time.perf_counter()
try:
yield
finally:
end = time.perf_counter()
print('{} : {}'.format(label, end - start))
with timeblock('counting'):
n = 10000000
while n > 0:
n -= 1
# for small code fragments:
from timeit import timeit
print(timeit('math.sqrt(2)', 'import math'))
print(timeit('sqrt(2)', 'from math import sqrt'))
print(timeit('math.sqrt(2)', 'import math', number=10000000))
print(timeit('sqrt(2)', 'from math import sqrt', number=10000000))
# if you are interested in process time vs. wall clock time, use this:
from functools import wraps
def timethis(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.process_time()
r = func(*args, **kwargs)
# process_time()
end = time.process_time()
print('{}.{} : {}'.format(func.__module__, func.__name__, end - start))
return r
return wrapper
|
c32eb6c905fd540d5d1d28d43c52a591ecd0baeb | Jameslin810/pythonFun | /fibSeq.py | 241 | 3.875 | 4 | def fibSequence():
n = input('enter a number here: ')
if n <= 1 :
print n
return
case1 = 0
case2 = 1
print case1
print case2
for k in range (2, n):
x = case1 + case2
print x
case1 = case2
case2 = x
fibSequence() |
3ad775823457fd51e186ac0e30f45f48ac255c9a | hanpengwang/ProjectEuler | /37 (Truncatable primes).py | 955 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 14 15:58:43 2019
@author: hanpeng
"""
def primeFactor(n):
if n == 1:
return 10
mover = 2
count = 0
while mover<=n**0.5:
if n%mover==0:
count +=1
n = n/mover
mover = 2
else:
mover+=1
return(count)
def truncatablePrimes():
n = 11
count = 0
Sum = 0
while True:
innerCount = 0
for i in range(len(str(n))):
sliceRight = int(str(n)[i:])
sliceleft = int(str(n)[:i+1])
if primeFactor(sliceRight) !=0 or primeFactor(sliceleft) !=0:
break
else:
innerCount+=1
if innerCount == len(str(n)):
print(n)
count += 1
Sum += n
if count == 11:
break
n += 2
return(Sum)
print(truncatablePrimes()) |
bb9cd2155ef50183d7b3981cce85814d490cfd6b | pavoljuhas/xpd-python-bootcamp-test | /py05numpy/ex02.py | 1,469 | 4.0625 | 4 | #!/usr/bin/env python
import numpy
import numpy as np
'''this exercise is generally focusing on Broadcasting, element-wise operations,
slices, and ranges. You can write your script here then run it. It is better to
using a interactive shell, Ipython for example to do the task and see the
results immediately.
If you are using interactive shell like Ipython, you should first run this
script using %run command (In [x]: %run ex02.py). Then the example array
s1,s2,s3 will be available in your shell.
'''
s1 = np.array([1,4,9,16,25])
s2 = np.array([[1,2,3,4,5],
[1,4,9,16,25],
[1,8,27,64,125]])
'''Task1 Add s1 and s2 to observe broadcasting.
'''
def task1():
return
'''Get the second value from s1.
'''
def task2():
return
'''Get the third row from s2.
'''
def task3():
return
'''Get the second column from s2.
'''
def task4():
return
'''Generate a range of values from 1 to 20 in 0.5 step increments.
'''
def task5():
return
'''Generate a range of values from 5 to 30 with a total of 50 entries.
'''
def task6():
return
'''Use the np.log10() function to get the log values of ranges obtained from
task5 and task6
'''
def task7(x5, x6):
'''
x5: range got from task5
x6: range got from task6
'''
return
if __name__ == '__main__':
print task1()
print task2()
print task3()
print task4()
print task5()
print task6()
print task7(task5(), task6())
|
259d0a608c6fcfa3da872e059f499a98d72b49ba | Intelligence-Games/Connect_four | /Week 4 - Conecta 4/games.py | 981 | 3.671875 | 4 | """Games, or Adversarial Search. (Chapters 6)
"""
from utils import *
from searches import alphabeta_search
# ______________________________________________________________________________
# Players for Games
def query_player(game, state):
"Make a move by querying standard input."
# game.display(state)
return num_or_str(raw_input('Your move? '))
def random_player(game, state):
"A player that chooses a legal move at random."
return random.choice(game.legal_moves(state))
def alphabeta_player(game, state):
return alphabeta_search(state, game)
def play_game(game, *players):
"Play an n-person, move-alternating game."
state = game.initial
while True:
for player in players:
move = player(game, state)
print player, move
state = game.make_move(move, state)
if game.terminal_test(state):
print game.display(state)
return game.utility(state, 'X')
|
f92535ce08aaea0b3ded30ffaf503fab05f52ff7 | huiyuandiknow/Data-Manipulation-at-Scale_systems-and-Algorithms | /Thinking in MapReduce/inverted_index.py | 792 | 3.703125 | 4 | import MapReduce
import sys
"""
Create an inverted index- a dictionary where each word is associated with a list of the document identifiers in which that word appears.
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(list):
# key: text in doc
# value: document identifier
key = list[1] #text
value = list[0] #docid
words = key.split()
for w in words:
mr.emit_intermediate(w, value)
def reducer(key, list_of_values):
# key: text
# value: docid
# remove duplicates
newlist = list(set(list_of_values))
mr.emit((key, newlist))
# Do not modify below this line
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
|
6b01d4c552104cf6ded45f98192d888c6c976260 | harshil1903/leetcode | /Array/1389_target_array_in_given_order.py | 1,945 | 4.15625 | 4 |
# 1389. Create Target Array in the Given Order
#
# Source : https://leetcode.com/problems/create-target-array-in-the-given-order/
#
# Given two arrays of integers nums and index. Your task is to create target array under the following rules:
#
# Initially target array is empty.
# From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
# Repeat the previous step until there are no elements to read in nums and index.
# Return the target array.
#
# It is guaranteed that the insertion operations will be valid.
from typing import List
class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
result = []
for i in range(len(nums)):
result.insert(index[i], nums[i])
return result
def createTargetArray1(self, nums: List[int], index: List[int]) -> List[int]:
result = [9999] * len(nums)
for i in range(len(nums)):
ind = index[i]
val = nums[i]
if (result[ind] == 9999):
result[ind] = val
else:
for k in range(len(nums) - 1, ind, -1):
result[k] = result[k - 1]
result[ind] = val
return result
def createTargetArray2(self, nums: List[int], index: List[int]) -> List[int]:
result = [None] * len(nums)
for i in range(len(nums)):
if (result[index[i]] is None):
result[index[i]] = nums[i]
else:
for k in range(len(nums) - 1, index[i], -1):
result[k] = result[k - 1]
result[index[i]] = nums[i]
return result
if __name__ == "__main__":
s = Solution()
print(s.createTargetArray([0, 1, 2, 3, 4],[0, 1, 2, 2, 1]))
print(s.createTargetArray1([0, 1, 2, 3, 4], [0, 1, 2, 2, 1]))
print(s.createTargetArray2([0, 1, 2, 3, 4], [0, 1, 2, 2, 1])) |
276041013d231458fceca93bb8d1b5f126cd2c4d | angelahyoon/LeetCodeSolutions | /validPalindrome.py | 220 | 3.828125 | 4 | # Valid Palindrome
def isPalindrome(self, s: str) -> bool:
string = ""
for i in s:
if (i.isalnum()):
string += i.lower()
return string == string[::-1] |
aa1dbc137a647ffa0bfe54432169f825b551e7fe | logicalpermission7/projects | /Game.py | 1,810 | 3.84375 | 4 | from math import *
import random
from Player import Player
from Student import Student
# This is a "Player Object"
player1 = Player("Elvis", 5, 100, 500)
print(player1.power)
print(player1.is_elvis())
# This is a Student Object
elvis = Student("Elvis", "CSCI", 4.0, True)
print(str(elvis.is_on_honers()) + " is on honers")
# This is a 2d array or "list"
gridList = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16],
[17,18,19],
[20],
]
# This is a nested for loop
for row in gridList:
for col in row:
print(col)
# This is a Dictionary with 12 Key Value Pairs
monthConversion = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
10: "October",
11: "November",
12: "December",
}
# This will print out key 2 and its value
print(monthConversion.get(2))
# This will open a file and read from it
file = open("/Users/ironman/Desktop/shakespeare_ai-master/sonnets.txt", "r")
print(file.read())
file.close()
# This will give you a invalid entry unless you type a float, or integer number
while True:
try:
number = float(input("Please enter a number: "))
except ValueError:
print("Invalid Entry")
continue
else:
break
# This is a function that will return the square root answer to a number
def getSquareRoot(num):
num = sqrt(num)
newNumber = round(num)
return newNumber
# This will print out every individual letter
for letters in "the fox jump ove the big red barn":
print(letters)
print(getSquareRoot(67))
# this is a list
list = [1,2,3,4,5,6,77,65,45,33,1234,567]
# This will print out the biggest number in the list
print(max(list))
list.reverse()
print(list)
print(list.index(33))
|
a554aeea8d1e4a83b9896e7bbec8738c14b516d8 | guoqi228/dungeon_monster_python | /Monster.py | 4,814 | 3.65625 | 4 | class Monster():
def __init__(self, coords = [0, 0]):
self.coords = coords
def init_coords(self, rows, cols):
self.coords = [random.randint(0, cols - 1), random.randint(0, rows - 1)]
def check_nearby(self, rows, cols, eggs, door, monsters):
go_up = True
go_down = True
go_left = True
go_right = True
for monster in monsters:
if [self.coords[0] + 1, self.coords[1]] == [monster.coords[0], monster.coords[1]]:
go_down = False
elif [self.coords[0] - 1, self.coords[1]] == [monster.coords[0], monster.coords[1]]:
go_up = False
elif [self.coords[0], self.coords[1] + 1] == [monster.coords[0], monster.coords[1]]:
go_right = False
elif [self.coords[0], self.coords[1] - 1] == [monster.coords[0], monster.coords[1]]:
go_left = False
for egg in eggs:
if [self.coords[0] + 1, self.coords[1]] == [egg.coords[0], egg.coords[1]]:
go_down = False
elif [self.coords[0] - 1, self.coords[1]] == [egg.coords[0], egg.coords[1]]:
go_up = False
elif [self.coords[0], self.coords[1] + 1] == [egg.coords[0], egg.coords[1]]:
go_right = False
elif [self.coords[0], self.coords[1] - 1] == [egg.coords[0], egg.coords[1]]:
go_left = False
if [self.coords[0] + 1, self.coords[1]] == [door.coords[0], door.coords[1]]:
go_down = False
elif [self.coords[0] - 1, self.coords[1]] == [door.coords[0], door.coords[1]]:
go_up = False
elif [self.coords[0], self.coords[1] + 1] == [door.coords[0], door.coords[1]]:
go_right = False
elif [self.coords[0], self.coords[1] - 1] == [door.coords[0], door.coords[1]]:
go_left = False
# check boundary
if self.coords[0] == rows - 1:
go_down = False
elif self.coords[0] == 0:
go_up = False
elif self.coords[1] == cols - 1:
go_right = False
elif self.coords[1] == 0:
go_left = False
return [go_up, go_down, go_left, go_right]
def move_monster(self, rows, cols, player, boolean_list):
[go_up, go_down, go_left, go_right] = boolean_list
row_diff = self.coords[0] - player.coords[0]
col_diff = self.coords[1] - player.coords[1]
if row_diff > 0 and col_diff == 0 and go_up == True and self.coords[0] - 1 >= 0:
self.coords = [self.coords[0] - 1, self.coords[1]]
elif row_diff < 0 and col_diff == 0 and go_down == True and self.coords[0] + 1 <= rows - 1:
self.coords = [self.coords[0] + 1, self.coords[1]]
elif row_diff == 0 and col_diff > 0 and go_left == True and self.coords[1] - 1 >= 0:
self.coords = [self.coords[0], self.coords[1] - 1]
elif row_diff == 0 and col_diff < 0 and go_right == True and self.coords[1] + 1 <= cols - 1:
self.coords = [self.coords[0], self.coords[1] + 1]
elif abs(row_diff) <= abs(col_diff) and row_diff > 0 and go_up == True and self.coords[0] - 1 >= 0:
self.coords = [self.coords[0] - 1, self.coords[1]]
elif abs(row_diff) <= abs(col_diff) and row_diff < 0 and go_down == True and self.coords[0] + 1 <= rows - 1:
self.coords = [self.coords[0] + 1, self.coords[1]]
elif abs(row_diff) >= abs(col_diff) and col_diff > 0 and go_left == True and self.coords[1] - 1 >= 0:
self.coords = [self.coords[0], self.coords[1] - 1]
elif abs(row_diff) >= abs(col_diff) and col_diff < 0 and go_right == True and self.coords[1] + 1 <= cols - 1:
self.coords = [self.coords[0], self.coords[1] + 1]
elif go_up == True and rows - 1 > self.coords[0] > (rows - 1)//2:
self.coords = [self.coords[0] + 1, self.coords[1]]
elif go_down == True and 0 < self.coords[0] < (rows -1) // 2:
self.coords = [self.coords[0] - 1, self.coords[1]]
elif go_left == True and cols - 1 > self.coords[1] > (cols - 1)//2:
self.coords = [self.coords[0], self.coords[1] - 1]
elif go_right == True and 0 < self.coords[1] < (cols - 1)//2:
self.coords = [self.coords[0], self.coords[1] + 1]
elif go_up == True and self.coords[0] - 1 >= 0:
self.coords = [self.coords[0] - 1, self.coords[1]]
elif go_down == True and self.coords[0] + 1 <= rows - 1:
self.coords = [self.coords[0] + 1, self.coords[1]]
elif go_left == True and self.coords[1] - 1 >= 0:
self.coords = [self.coords[0], self.coords[1] - 1]
elif go_right == True and self.coords[1] + 1 <= cols - 1:
self.coords = [self.coords[0], self.coords[1] + 1]
|
e352ac26bcc8e3ed7b79750bf056070061d79cbd | ryanlonergan/100_days_of_projects | /day_34_gui_trivia_game/quiz_brain.py | 1,311 | 3.625 | 4 | import html
class QuizBrain:
def __init__(self, q_list):
self.question_number = 0
self.score = 0
self.question_list = q_list
self.current_question = None
def still_has_questions(self):
"""
Checks if there are still questions left to be asked
:return: True or False
"""
return self.question_number < len(self.question_list)
def next_question(self):
"""
Changes the current_question, increments the question_number and formats the question text before returning it
:return: f-string for the next question
"""
self.current_question = self.question_list[self.question_number]
self.question_number += 1
q_text = html.unescape(self.current_question.text)
return f"Q.{self.question_number}: {q_text}"
def check_answer(self, user_answer: str):
"""
Checks if the user gave the correct answer and increases their score if they did
:param user_answer: The input the user gave for the question
:return: True or False
"""
correct_answer = self.current_question.answer
if user_answer.lower() == correct_answer.lower():
self.score += 1
return True
else:
return False
|
aaab2fdf0f5450502d98516c24092c0a8d581971 | pierre-crucifix/real-spanish | /tweepyManager.py | 4,117 | 3.734375 | 4 | """
Script #1
Retrieve all the latest tweets of the chosen usernames (see screen_name_list)
Need to create a file called twitter_credentials.py in the same folder. This file will store the keys to log in to the twitter app
"""
import tweepy
import pandas as pd
import simplejson as json
import datetime
import twitter_credentials #Python file which contains only my twitter credentials as global variables
def get_posts(username):
"""
Function retrieving as much tweets as possible of a specific user
:param username: The name after the @ in Twitter
:return: a list of string, where a cell correspond to a tweet
"""
# Authenticate to Twitter
auth = tweepy.OAuthHandler(twitter_credentials.CONSUMER_KEY, twitter_credentials.CONSUMER_SECRET)
auth.set_access_token(twitter_credentials.ACCESS_TOKEN, twitter_credentials.ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
try:
api.verify_credentials()
print("Authentication OK")
except:
print("Error during authentication")
alltweets=[]
new_tweets = api.user_timeline(screen_name = username,count=200,tweet_mode='extended')
status = new_tweets[0]
json_str = json.dumps(status._json)
#convert to string
json_str = json.dumps(status._json)
#deserialise string into python object
parsed = json.loads(json_str)
print(json.dumps(parsed, indent=4, sort_keys=True))
# save most recent tweets
alltweets.extend(new_tweets)
# save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
# keep grabbing tweets until there are no tweets left to grab
while len(new_tweets) > 0:
print(f"getting tweets before {oldest}")
# all subsiquent requests use the max_id param to prevent duplicates
new_tweets = api.user_timeline(screen_name=username, count=200, max_id=oldest,tweet_mode='extended')
# save most recent tweets
alltweets.extend(new_tweets)
# update the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
print(f"...{len(alltweets)} tweets downloaded so far")
outtweets=[]
for item in alltweets:
mined = {
'tweet_id': item.id,
'name': item.user.name,
'screen_name': item.user.screen_name,
'retweet_count': item.retweet_count,
'lang' : item.lang,
'text': item.full_text,
'mined_at': datetime.datetime.now(),
'created_at': item.created_at,
'favourite_count': item.favorite_count,
'hashtags': item.entities['hashtags'],
'status_count': item.user.statuses_count,
'location': item.place,
'source_device': item.source
}
try:
mined['retweet_text'] = item.retweeted_status.full_text # In case the tweet is a RT, there is a need to
# retrieve the retweet_text field which contains the full comment (up to 280 char) accompanying the retweet
except:
mined['retweet_text'] = ''
outtweets.extend([mined])
return outtweets
#We can now call the above function in order to retrive tweets of several users
screen_name_list=["el_pais","elmundoes","abc_es","LaVanguardia","ExpansionMx"]#4 most popular Spanish newspapers, and one newspaper specialised in economics/business
#Init dataframe with first user
screen_name_list_start=screen_name_list[0]
df=pd.DataFrame(get_posts(screen_name_list_start))
#Fill dataframe with all next users
try:
screen_name_list_end=screen_name_list[1:]
for current_username in screen_name_list_end:
current_df = pd.DataFrame(get_posts(current_username))
# df.append(current_df,ignore_index=True)#does not work=> use concat
df=pd.concat([df, current_df])
except:
print("error in username listing")
#Save (csv for ease of reuse, excel for human-readibility)
df.to_csv(r".\1.Tweets\AllTweets.csv")
df.to_excel(r".\1.Tweets\AllTweets.xlsx") |
e428c29741bc3206f8ac8964f131925275a26a27 | RaskovskyDavid/pong_arcade_game | /paddle.py | 683 | 3.859375 | 4 | from turtle import Turtle
class Paddle(Turtle):
def __init__(self, coordinates):
super().__init__()
self.color("white")
self.penup()
self.shape("square")
self.shapesize(stretch_wid=5, stretch_len=1)
self.goto(coordinates)
def go_up(self):
new_y = self.ycor() + 20
self.goto(self.xcor(), new_y)
def go_down(self):
new_y = self.ycor() - 20
self.goto(self.xcor(), new_y)
'''paddle = Turtle()
paddle.shape("square")
# stretch_len amd stretch_wid values are going to multiply by 20
paddle.shapesize(stretch_wid=5, stretch_len=1)
paddle.color("white")
paddle.penup()
paddle.goto(350, 0)'''
|
59d949581e56eb8bdfa53862612dd5bcaae8091c | kenwoov/PlayLeetCode | /Algorithms/Easy/448. Find All Numbers Disappeared in an Array/answer.py | 407 | 3.734375 | 4 | from typing import List
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
result = []
s = set(nums)
for i in range(len(nums)):
if i + 1 not in s:
result.append(i + 1)
return result
if __name__ == "__main__":
s = Solution()
result = s.findDisappearedNumbers([4, 3, 2, 7, 8, 2, 3, 1])
print(result)
|
7f435cafd0325b74583c4f732051a30d2f412f02 | dieu-pham/pythonbasic | /ngoinhamouoc.py | 516 | 3.796875 | 4 | # import turtle
#
# star = turtle.Turtle()
#
# for i in range(3):
# star.forward(50)
# star.right(144)
#
# turtle.done()
import turtle
#đặt kích thước viền cho hình tròn là 5
turtle.pensize (5)
#đặt màu sắc cho viền hình tròn là màu xanh
turtle.pencolor ("blue")
#for outer bigger circle
#đặt màu nền cho hình tròn là màu đỏ
turtle.fillcolor ("red")
turtle.begin_fill()
#đặt bán kính của hình tròn là 150
turtle.circle (150)
turtle.end_fill()
turtle.done |
2b28afffc750d08920341c8e9aa877e60810b815 | food-always-food/casino-night | /sqlite-database.py | 778 | 3.53125 | 4 | import sqlite3
import pandas as pd
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("CREATE TABLE stocks (date text, symbol text, third text)")
cur.execute("INSERT INTO stocks VALUES ('test','DTFY','more shit')")
cur.execute("INSERT INTO stocks VALUES ('tes2t','DTFY','another i guess')")
conn.commit()
cur.close()
conn.row_factory = dict_factory
cur = conn.cursor()
cur.execute("SELECT * FROM stocks")
# print(cur.description)
result = cur.fetchall()
print(result)
for row in result:
print(row)
df = pd.read_sql_query("Select * From stocks", conn)
conn.close()
# print(df)
# for x in df.iterrows():
# print(x)
|
34fd65d0c946d2fc843455f28f8b000bc5b137eb | chipperrip/IN1900 | /veke 6/f2c_shortcut_plot.py | 720 | 3.875 | 4 | """
Exercise 5.12: Plot exact and inexact Fahrenheit-Celsius conversion formulas
A simple rule to quickly compute the Celsius temperature from the Fahrenheit degrees
is to subtract 30 and then divide by 2: C = (F-30)/2. Compare this curve
against the exact curve C =(F-32)*5/9 in a plot. Let F vary between -20 and 120.
"""
import numpy as np
import matplotlib.pyplot as plt
F = np.linspace(-20,121)
C_exact = ((F-32)*5)/9
C_approx = (F-30)/2
plt.title('Celsius as a function of Fahrenheit')
plt.plot(F, C_exact, label='C_exact = (F-32)*5/9')
plt.plot(F, C_approx,'r+', label='C_approx = (F-30)/2')
plt.xlabel('F')
plt.ylabel('C')
plt.legend()
plt.show()
"""
Programmet teiknar to grafar som ser korrekte ut.
"""
|
88b8ef4bc7d6cf84fedbdf7604efb69f88015bd3 | Feng-Xu/TechNotes | /python/geektime/exercise/9_1.py | 1,101 | 3.921875 | 4 | # 1.创建一个函数,用于接收用户输入的数字,并计算用户输入数字的和
def add():
nums = input("请输入两个数次,用','分隔:")
print(type(nums))
# 当一些元素不用时,用_表示是更好的写法,可以让读代码的人知道这个元素是不要的
# 多个元素不用时,则使用*_
num1, *_, num2 = list(nums)
print(type(num1))
print(int(num1) + int(num2))
#add()
# 2. 创建一个函数,传入n个整数,返回其中最大的数和最小的数
# def find_num(list):
# print('max:%d' % max(list))
# print('min:%d' % min(list))
#
# list = [6, 2, 3, 4, 5]
# find_num(list)
def find_num(*args):
print('max:%d' % max(list(args)))
print('min:%d' % min(list(args)))
find_num(1,2,3,4,6,3,0)
# 3. 创建一个函数,传入一个参数n,返回n的阶乘
def fact(num):
if num == 0 or num == 1:
return 1
else:
return num * fact(num - 1)
print(fact(7))
from functools import reduce
num = 7
# 7! = 1 * 2 * 3 * 4 * 5 * 6 * 7
print(reduce(lambda x, y: x * y, range(1, num + 1))) |
4c662d843927545d38b2e33449a798af9bb4e315 | allenhsu6/python_learn | /100example/12.py | 491 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5
"""
from math import sqrt
def isprime(n):
while n > 1:
k = int(sqrt(n))
i = 2
while i <= k:
if n % i == 0:
return 0
i += 1
else:
return 1
i = 2
a = int(input())
while isprime(a) == 0:
while a % i == 0:
print(i)
a = a / i
i += 1
if a != 1:
print(a)
|
6516d4659f2a0e580f28c1fc57a288a7cd6190e6 | dml-prog/OOP | /Eception.py | 404 | 3.59375 | 4 | a = 5
b = 2
try:
f= open("C:/Users/Nikhesh/desktop/niks.txt",'r+')
k = (input("Enter what ever u want "))
f.write(k)
print("Division is ",a/b)
except ValueError as n:
print("Invalid input")
except ZeroDivisionError as e:
print("Divide by zero is not poosibe")
except Exception as e:
print("Something went wrong ")
finally:
print("bye")
f.close() |
f18d7113814578050defe4078b83984d0e0bbcc6 | cuzai/pythonStudy | /crawling/collats.py | 507 | 4.28125 | 4 | def collatz(number) :
if(number % 2 == 0) :
return int(number / 2)
else :
return int(number * 3 + 1)
while True :
number = input("Input number")
try :
number = int(number)
except ValueError :
if number == 'exit' :
exit()
print("'{}'{}".format(number, "is not a number"))
continue
break
while True :
number = collatz(number)
print(number)
if number ==1 :
break
print("finished") |
16ac3a1431faa19a11478156ab135324098c5f09 | sarathchandra0007/python_practice | /python_practice/permutations.py | 247 | 3.671875 | 4 | import itertools
def permutation(s):
return list(itertools.permutations(s))
def permu(s):
out=[]
if len(s)==1:
output=[s]
else:
for index,i in enumerate(s):
permu('abc')
print (permutation('abc'))
|
168706532b5e650a14d3e9acf0d6a6e0876c04ff | Henryy-rs/Subway_RIdership_COVID-19 | /source.py | 11,366 | 3.609375 | 4 | import pandas as pd
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
class Data:
def __init__(self, date_strat, date_end):
self.date_start = date_strat
self.date_end = date_end
self.df = pd.DataFrame()
def initialize_df(self):
pass
def print_df(self, day_of_week = None):
if day_of_week == None:
print(self.df)
else:
print(self.df[self.df['day_of_week'] == day_of_week])
def get_df(self):
return self.df
class Subway_Data(Data):
def initialize_df(self):
year_start = int(self.date_start[0:4]) #입력받은 데이터를 년, 월로 쪼갠다. (csv파일을 불러오기 위해)
month_start = int(self.date_start[4:6])
year_end = int(self.date_end[0:4])
month_end = int(self.date_end[4:6])
months = 12*(year_end-year_start)-month_start+month_end+1 #요청 기간을 달 수로 계산
df = pd.DataFrame() # 빈 df생성
for i in range(months):
if month_start+i > 12: # 1년이 지나면
year_start += 1 # 연도 + 1
month_start -= 12 #달 - 12
if(str(year_start)+str(month_start+i).zfill(2)<='202004'):
df_ = pd.read_csv('CARD_SUBWAY_MONTH_'+str(year_start)+str(month_start+i).zfill(2)+'.csv', encoding='CP949',
names=['date', 'line', 'station_id', 'station_name', 'num_on', 'num_off', 'date_rgs'] ) #파일 읽어오고 저장
df_ = df_.drop(0)
df_ = df_.drop('station_id', axis=1)
elif(str(year_start)+str(month_start+i).zfill(2)<='202005'): #5월 데이터는 역 id를 제공하지 않음
df_ = pd.read_csv('CARD_SUBWAY_MONTH_'+str(year_start)+str(month_start+i).zfill(2)+'.csv', encoding='CP949',
names=['date', 'line', 'station_name', 'num_on', 'num_off', 'date_rgs'] )
df_ = df_.drop(0)
if i == 0: #선택된 날짜까지만 저장
df_ = df_[df_['date'] >= self.date_start]
if i == months-1:
df_ = df_[df_['date'] <= self.date_end]
df = pd.concat([df, df_], ignore_index=True) #달로 분리된 df 합침
df['num_pass'] = df['line']# num_pass column생성
for i in range(len(df)):
df['num_pass'].loc[i] = int(float(df['num_on'].loc[i])) + int(float(df['num_off'].loc[i]))
#float로 바꾸고 int로 바꿔야함
#승하차객 합쳐서 이용객으로 취급
df['date'] = pd.to_datetime(df['date'], errors='coerce') #datetime 객체로 바꿔주고
df['day_of_week'] = df['date'].dt.day_name()# 요일 계산하여 column추가
#필요없는 데이터 제거
df = df.drop('num_on', axis=1)
df = df.drop('num_off', axis=1)
df = df.drop('date_rgs', axis=1)
self.df = df
def get_subway_daily_df(self): #역당 일일 평균 이용객을 구하여 df만드는 함수
df = self.df
result_df = pd.DataFrame()
converted_date_start = dt.datetime.strptime(self.date_start, '%Y%m%d').date() #string날짜를 datetime객체로 바꿔줌
converted_date_end = dt.datetime.strptime(self.date_end, '%Y%m%d').date()
days = (converted_date_end-converted_date_start).days
for i in range(days+1):
date = converted_date_start + dt.timedelta(days=i)
converted_date = date.strftime('%Y%m%d')
#print(converted_date)
df_ = df[df['date'] == converted_date]
df__ = pd.DataFrame(data={'date': [date], 'num_pass': [df_['num_pass'].mean()], 'day_of_week' : [date.weekday()]}) #date.weekday()
#num_pass 는 모든 역의 일일 평균 이용객 수임
result_df = pd.concat([result_df, df__], ignore_index=True)
#if i == 1:
# print(df_)
# print(df_['num_pass'].mean())
return result_df
def get_num_pass_mean(self, day_of_week = None):
if day_of_week == None:
return self.df['num_pass'].mean()
else:
return self.df[self.df['day_of_week'] == day_of_week]['num_pass'].mean()
class Corona_Data(Data):
def initialize_df(self):
date_start = self.date_start[0:4] + '-' + self.date_start[4:6] + '-' + self.date_start[6:8]
date_end = self.date_end[0:4] + '-' + self.date_end[4:6] + '-' + self.date_end[6:8]
df = pd.read_csv('wuhan_daily_diff.csv', encoding='CP949', names=['date', 'inspected', 'negative',
'confirmed', 'recoverd', 'deaths'])
df = df.drop(0)
df = df[df['date'] >= date_start]
df = df[df['date'] <= date_end]
df['date'] = pd.to_datetime(df['date'], errors='coerce') #datetime type으로 바꿈
df['day_of_week'] = df['date'].dt.day_name()
df['confirmed'] = df['confirmed'].astype(float)
df = df.reset_index(drop=True)
self.df = df
#지하철, 코로나 데이터를 하나의 dataframe으로 만들어주는 함수
def concatenate(date_start, date_end, factor=0, drop_holiday=False):
test_subway = Subway_Data(date_start, date_end)
test_corona = Corona_Data(date_start, date_end)
test_subway.initialize_df()
test_corona.initialize_df()
test_df = pd.concat([test_subway.get_subway_daily_df().set_index('date'), test_corona.get_df().set_index('date')], axis = 1)
test_df = test_df.loc[:,~test_df.columns.duplicated()]
test_df = test_df.drop('inspected', axis=1)
test_df = test_df.drop('negative', axis=1)
test_df.index = pd.to_datetime(test_df.index)
if factor != 0 :
#가중치 구하기
test_weekday = Subway_Data('20170101', '20171231') #과거지하철 데이터 생성
test_weekday.initialize_df()
weekday_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
num_pass_mean_list = [] #요일별 이용객 수가 저장될 리스트
weight_list = [] #요일별 가중치가 저장될 리스트
for weekday in weekday_list:
num_pass_mean_list.append(test_weekday.get_num_pass_mean(day_of_week=weekday)) #Subway_Data의 메소드를 사용하여 요일별 평균을 구함
mean = sum(num_pass_mean_list)/len(num_pass_mean_list) #요일별 평균 이용객 수의 평균을 구한다.
for num_pass_mean in num_pass_mean_list:
weight_list.append((mean/num_pass_mean)**factor) #weight = 요일별 이용객 수 평균의 평균/요일별 평균
#가중치 곱해주기
i = 0
for weight in weight_list:
test_df.loc[test_df['day_of_week'] == i, 'num_pass'] = test_df.loc[test_df['day_of_week'] == i, 'num_pass'] * weight
i += 1
if drop_holiday == True :
#주말 이용객 수를 0으로 만듦
len_df = len(test_df)
for i in range(len_df):
if test_df.iloc[i, 1] == 5 : #index의 요일(week_of_day)이 토요일일 때
if 0 < i < len_df-2 :
test_df.iloc[i, 0] = 0 #test_df.iloc[i-1,0] + (1/3)*(test_df.iloc[i+2,0] - test_df.iloc[i-1,0])
#금요일과 월요일의 이용객 수 차를 1:2로 내분하는 지점 + 금요일 이용객 수
elif i == 0 :
test_df.iloc[i, 0] = test_df.iloc[i+2, 0]
elif i >= len_df -2 :
test_df.iloc[i, 0] = test_df.iloc[i-1, 0]
elif test_df.iloc[i, 1] == 6 :
if 1 < i < len_df -1 :
test_df.iloc[i, 0] = 0 #test_df.iloc[i+1,0] - (1/3)*(test_df.iloc[i+1,0] - test_df.iloc[i-2,0]) # 2:1로 내분하는 지점
elif i <= 1 :
test_df.iloc[i, 0] = test_df.iloc[i+1, 0]
elif i >= len_df -1 :
test_df.iloc[i, 0] = test_df.iloc[i-2, 0]
#4.30 부처님오신날
#5.1 근로자의날
#5.2 토요일 5.3 일요일
#5.4 연휴
#5.5 어린이날
#이 구간만 추출하면 에러 발생할 수 있음
if date_end == '20200430' > date_start:
test_df.loc['2020-04-30', 'num_pass'] = test_df.loc['2020-04-29', 'num_pass']
elif date_end > '20200504' and '20200430' > date_start :
test_df.loc['2020-04-30', 'num_pass'] = test_df.loc['2020-04-29', 'num_pass'] + (1/7)*( test_df.loc['2020-05-06', 'num_pass']- test_df.loc['2020-04-29', 'num_pass'])
test_df.loc['2020-05-01', 'num_pass'] = test_df.loc['2020-04-29', 'num_pass'] + (2/7)*( test_df.loc['2020-05-06', 'num_pass']- test_df.loc['2020-04-29', 'num_pass'])
test_df.loc['2020-05-04', 'num_pass'] = test_df.loc['2020-04-29', 'num_pass'] + (5/7)*( test_df.loc['2020-05-06', 'num_pass']- test_df.loc['2020-04-29', 'num_pass'])
test_df.loc['2020-05-05', 'num_pass'] = test_df.loc['2020-04-29', 'num_pass'] + (6/7)*( test_df.loc['2020-05-06', 'num_pass']- test_df.loc['2020-04-29', 'num_pass'])
#4.15 총선
if date_end == '20200415' > date_start :
test_df.loc['2020-04-15', 'num_pass'] = test_df.loc['2020-04-14', 'num_pass']
elif date_end > '20200415' > date_start :
test_df.loc['2020-04-15', 'num_pass'] = 0.5*(test_df.loc['2020-04-14', 'num_pass'] + test_df.loc['2020-04-16', 'num_pass'])
for i in range(len_df):
if test_df.iloc[i, 1] == 5 : #index의 요일(week_of_day)이 토요일일 때
if 0 < i < len_df-2 :
test_df.iloc[i, 0] = test_df.iloc[i-1,0] + (1/3)*(test_df.iloc[i+2,0] - test_df.iloc[i-1,0])
#금요일과 월요일의 이용객 수 차를 1:2로 내분하는 지점 + 금요일 이용객 수
elif i == 0 :
test_df.iloc[i, 0] = test_df.iloc[i+2, 0]
elif i >= len_df -2 :
test_df.iloc[i, 0] = test_df.iloc[i-1, 0]
elif test_df.iloc[i, 1] == 6 :
if 1 < i < len_df -1 :
test_df.iloc[i, 0] = test_df.iloc[i+1,0] - (1/3)*(test_df.iloc[i+1,0] - test_df.iloc[i-2,0]) # 2:1로 내분하는 지점
elif i <= 1 :
test_df.iloc[i, 0] = test_df.iloc[i+1, 0]
elif i >= len_df -1 :
test_df.iloc[i, 0] = test_df.iloc[i-2, 0]
test_df = test_df.drop('day_of_week', axis=1)
return test_df
"""
소스 출처 : https://frhyme.github.io/machine-learning/regression_evaluation_score/
"""
from sklearn.metrics import explained_variance_score, mean_squared_error, mean_absolute_error, r2_score
def PrintRegScore(y_true, y_pred):
print('explained_variance_score: {}'.format(explained_variance_score(y_true, y_pred)))
print('mean_squared_errors: {}'.format(mean_squared_error(y_true, y_pred)))
print('r2_score: {}'.format(r2_score(y_true, y_pred)))
"""
소스 출처 https://frhyme.github.io/machine-learning/regression_evaluation_score/
"""
def main():
return 0
if __name__ == "__main__":
main()
|
bc6b064f163310628ed172b4fca7d8cfb9196205 | Electrostatus/Analytic | /analytic_funcs.py | 3,599 | 3.578125 | 4 | # Copyright (c) 2017 - 2023, Philip Herd
# This file is distributed under the BSD 2-Clause License
from cmath import sqrt
__doc__ = """
A collection of general purpose analytic formulas
for polynomials of degree 0 through 4
Polynomials with degrees higher than four do not have analytic solutions
"""
def root_0(a):
"""returns the roots for a constant equation
a = 0, polynomial of degree 0"""
return 0
def root_1(a, b):
"""returns the roots for a linear equation
ax + b = 0, polynomial of degree 1"""
return -b / a
def root_2(a, b, c):
"""returns the roots for a quadratic equation
ax^2 + bx + c = 0, polynomial of degree 2"""
p1 = sqrt(b * b - 4. * a * c)
p2 = -2. * a
x1 = (b - p1) / p2
x2 = (b + p1) / p2
return x1, x2
def root_3(a, b, c, d):
"""returns the roots for a cubic equation
ax^3 + bx^2 + cx + d = 0, polynomial of degree 3"""
abc = a * b * c
bbb = b * b * b
aad = a * a * d
dd = (18. * abc * d - 4. * bbb * d
+ b * b * c * c - 4. * a * c * c * c
- 27. * aad * d)
d0 = b * b - 3. * a * c
# second and third cubic unity roots (first is just 1)
cu2 = -0.5 + 0.86602540378443864676j
cu3 = -0.5 - 0.86602540378443864676j
if not dd and not d0: # all real roots
x1 = x2 = x3 = -b / (3. * a)
elif not dd and d0: # double root, simple root
x1 = x2 = ((9. * a * d - b * c) / (2. * d0))
x3 = (4. * abc - 9. * aad - bbb) / (a * d0)
else:
d1 = 2. * bbb - 9. * abc
d1 = d1 + 27. * aad
if not d0: cin = d1 + 0j # inner terms cancel
else: cin = (d1 - sqrt(-27.0 * a * a * dd)) / 2.
cc = cin ** (1. / 3.)
p = (-1. / (3. * a))
x1 = p * (b + cc + d0 / cc)
x2 = p * (b + cu2 * cc + d0 / (cu2 * cc))
x3 = p * (b + cu3 * cc + d0 / (cu3 * cc))
return x1, x2, x3
def root_4(a, b, c, d, e):
"""returns the roots for a quartic equation
ax^4 + bx^3 + cx^2 + dx + e = 0, polynomial of degree 4"""
aa, bb, cc, dd = b / a, c / a, d / a, e / a
a2, b2 = aa * aa, bb * bb
bq = (- (2. * b2 * bb) + 9. * aa * bb * cc
- 27. * (cc * cc + a2 * dd)
+ 72. * bb * dd)
c1 = (b2 - 3. * aa * cc + 12. * dd)
cu2 = -0.5 + 0.86602540378443864676j
p1 = sqrt(bq * bq - (4. * c1 * c1 * c1))
v = (bq - p1) / -2.
if not v: v = (bq + p1) / -2. # choose non zero quad root
u = a2 / 4. - (2. * bb) / 3.
if not v: uu = u # both quad roots zero, uu simplifies to u
else:
v3 = (v ** (1. / 3.)) * cu2
uu = u + (1. / 3.) * (v3 + c1 / v3)
p1 = - aa / 4.
if not uu: # degenerate, quadruple root
x1 = x2 = x3 = x4 = p1
else:
p2 = 3. * a2 - 8. * bb - 4. * uu
p3 = -(a2 * aa) + 4. * aa * bb - 8. * cc
usq = sqrt(uu)
usq2 = usq / 2.
u4 = uu / 4.
blkp = .25 * sqrt(p2 + p3 / usq)
blkm = .25 * sqrt(p2 + p3 / -usq)
x1 = p1 + usq2 + blkp
x2 = p1 - usq2 + blkm
x3 = p1 + usq2 - blkp
x4 = p1 - usq2 - blkm
return x1, x2, x3, x4
def cons(a):
"constant formula, returns root_0(a)"
return root_0(a)
def lin(a, b):
"linear formula, returns root_1(a, b)"
return root_1(a, b)
def quad(a, b, c):
"quadratic forumula, returns root_2(a, b, c)"
return root_2(a, b, c)
def cubic(a, b, c, d):
"cubic forumula, returns root_3(a, b, c, d)"
return root_3(a, b, c, d)
def quartic(a, b, c, d, e):
"quartic formula, returns root_4(a, b, c, d, e)"
return root_4(a, b, c, d, e)
|
71f0780cb08cc149a4d3d0fff97529c50b8e2735 | ton4phy/hello-world | /Python/47. Logic.py | 155 | 3.78125 | 4 | # Exercise
# Write an is_mister function that accepts a string and checks if it is the word 'Mister'
def is_mister(string):
return string == 'Mister'
|
d26337bdbdba2653c53a1116230bcee55075ef64 | kcexn/coded-distributed-computing | /coded_distributed_computing.py | 1,984 | 3.8125 | 4 | ''' coded_distributed_computing
This module contains functions related to a study of the coded distributed computing model.
'''
import numpy as np
def encode_matrix(A: np.matrix, G: np.matrix) -> np.matrix:
''' encode_matrix
Parameters:
---
A: np.matrix, input matrix to code.
G: np.matrix, generator matrix to encode A with.
---
Returns:
---
A*G: np.matrix, output encoded matrix.
---
Description:
---
Following van Lint's text "Introduction to Coding Theory",
I am constructing linear block codes using a generator matrix G
and an input matrix A.
Actually typically the codes would be constructed using a
generator matrix G and an input vector k which would create an
output message, a vector, m.
Following from my conversation with Jingge last week though.
I'm convinced that encoding a matrix to preserve the
matrix vector multiplication Ax is exactly the same as encoding
multiple messages across time simultaneously. i.e. If I were to
accumulate n messages (column vectors) of size k and concatenated them
I would end up with a matrix of size k x n (rows and columns). Encoding
it with the generator matrix G would give me a matrix of size m x n. Where
each column in the matrix A*G can be considered one message to be delivered
over time. The matrix vector multiplication Ax is simply the rows of multiple
messages concatenated together multiplied with the vector x.
This is not a super great analogue, because obviously matrices in a matrix vector
multiplication are shared with everyone all at once not one column at a time.
But I think it's a useful way to reason about the coding properties of
the matrix A*G. And I believe opens up the possibilities of
matrix encodings to ALL codes that can be represented as linear block codes
(which I believe are simply, ALL linear codes).
'''
return np.matmul(A,G)
|
9fd2ab9d408757a5a91e6f09a733fdd989598993 | zsmountain/lintcode | /python/helper.py | 10,130 | 3.96875 | 4 | ################################### List ###################################
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
def printList(head):
while head:
print(head.val, '->', end=' ')
head = head.next
print('None')
class LinkedList():
def __init__(self, l):
if not l:
self.head = None
return
head = ListNode(l[0])
pre = head
for i in range(1, len(l)):
cur = ListNode(l[i])
pre.next = cur
pre = cur
self.head = head
def print(self):
printList(self.head)
################################### Trie ###################################
class TrieNode():
def __init__(self):
self.children = {}
self.word = ''
class Trie():
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.word = word
def find(self, word):
node = self.root
for ch in word:
node = node.children.get(ch)
if node is None:
return False
return len(node.word) > 0
################################### Graph ###################################
'''
How we serialize an undirected graph:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by #.
First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
Second node is labeled as 1. Connect node 1 to node 2.
Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
'''
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
class DirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
def createGraph(graph_str):
if not graph_str:
return {}
nodes = {}
nodes_str = graph_str.split('#')
for node_str in nodes_str:
values = node_str.split(',')
node = DirectedGraphNode(values[0])
nodes[values[0]] = node
for node_str in nodes_str:
values = node_str.split(',')
for i in range(1, len(values)):
nodes[values[0]].neighbors.append(nodes[values[i]])
return [nodes[node] for node in nodes]
def printGraph(graph):
for node in graph:
print(node.label, [n.label for n in node.neighbors])
################################### Tree ###################################
from copy import deepcopy as deepcopy
import sys
class ParentTreeNode:
def __init__(self, val):
self.val = val
self.parent, self.left, self.right = None, None, None
class Queue(object):
def __init__(self, items=None):
if items is None:
self.a = []
else:
self.a = items
def enqueue(self, b):
self.a.insert(0, b)
def dequeue(self):
return self.a.pop()
def isEmpty(self):
return self.a == []
def size(self):
return len(self.a)
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def visit(self):
sys.stdout.write(self.val)
def getNumNodes(self):
total = 0
if self.left:
total += self.left.getNumNodes()
if self.right:
total += self.right.getNumNodes()
return total + 1
@classmethod
def createTree(cls, depth):
tree = TreeNode('X')
cls.createTreeHelper(tree, depth, 1)
return tree
@classmethod
def createTreeHelper(cls, node, depth, cur):
if cur == depth:
return
node.left = TreeNode('X')
node.right = TreeNode('XX')
cls.createTreeHelper(node.left, depth, cur + 1)
cls.createTreeHelper(node.right, depth, cur + 1)
def getHeight(self):
return TreeNode.getHeightHelper(self)
@staticmethod
def getHeightHelper(node):
if not node:
return 0
else:
return max(TreeNode.getHeightHelper(node.left), TreeNode.getHeightHelper(node.right)) + 1
def fillTree(self, height):
TreeNode.fillTreeHelper(self, height)
def fillTreeHelper(node, height):
if height <= 1:
return
if node:
if not node.left:
node.left = TreeNode(' ')
if not node.right:
node.right = TreeNode(' ')
TreeNode.fillTreeHelper(node.left, height - 1)
TreeNode.fillTreeHelper(node.right, height - 1)
def prettyPrint(self):
"""
"""
# get height of tree
total_layers = self.getHeight()
tree = deepcopy(self)
tree.fillTree(total_layers)
# start a queue for BFS
queue = Queue()
# add root to queue
queue.enqueue(tree) # self = root
# index for 'generation' or 'layer' of tree
gen = 1
# BFS main
while not queue.isEmpty():
# copy queue
#
copy = Queue()
while not queue.isEmpty():
copy.enqueue(queue.dequeue())
#
# end copy queue
first_item_in_layer = True
edges_string = ""
extra_spaces_next_node = False
# modified BFS, layer by layer (gen by gen)
while not copy.isEmpty():
node = copy.dequeue()
# -----------------------------
# init spacing
spaces_front = pow(2, total_layers - gen + 1) - 2
spaces_mid = pow(2, total_layers - gen + 2) - 2
dash_count = pow(2, total_layers - gen) - 2
if dash_count < 0:
dash_count = 0
spaces_mid = spaces_mid - (dash_count*2)
spaces_front = spaces_front - dash_count
init_padding = 2
spaces_front += init_padding
if first_item_in_layer:
edges_string += " " * init_padding
# ----------------------------->
# -----------------------------
# construct edges layer
edge_sym = "/" if node.left and node.left.val is not " " else " "
if first_item_in_layer:
edges_string += " " * (pow(2, total_layers - gen) - 1) + edge_sym
else:
edges_string += " " * (pow(2, total_layers - gen + 1) + 1) + edge_sym
edge_sym = "\\" if node.right and node.right.val is not " " else " "
edges_string += " " * (pow(2, total_layers - gen + 1) - 3) + edge_sym
# ----------------------------->
# -----------------------------
# conditions for dashes
if node.left and node.left.val == " ":
dash_left = " "
else:
dash_left = "_"
if node.right and node.right.val == " ":
dash_right = " "
else:
dash_right = "_"
# ----------------------------->
# -----------------------------
# handle condition for extra spaces when node lengths don't match or are even:
if extra_spaces_next_node:
extra_spaces = 1
extra_spaces_next_node = False
else:
extra_spaces = 0
# ----------------------------->
# -----------------------------
# account for longer val
val_length = len(str(node.val))
if val_length > 1:
if val_length % 2 == 1: # odd
if dash_count > 0:
dash_count -= ((val_length - 1)//2)
else:
spaces_mid -= (val_length - 1)//2
spaces_front -= (val_length - 1)//2
if val_length is not 1:
extra_spaces_next_node = True
else: # even
if dash_count > 0:
dash_count -= ((val_length)//2) - 1
extra_spaces_next_node = True
# dash_count += 1
else:
spaces_mid -= (val_length - 1)
spaces_front -= (val_length - 1)
# ----------------------------->
# -----------------------------
# print node with/without dashes
if first_item_in_layer:
print((" " * spaces_front) + (dash_left * dash_count) + \
str(node.val) + (dash_right * dash_count), end = '')
first_item_in_layer = False
else:
print((" " * (spaces_mid-extra_spaces)) + (dash_left *
dash_count) + str(node.val) + (dash_right * dash_count), end = '')
# ----------------------------->
if node.left:
queue.enqueue(node.left)
if node.right:
queue.enqueue(node.right)
# print the fun squiggly lines
if not queue.isEmpty():
print("\n" + edges_string)
# increase layer index
gen += 1
print()
def createTree(vals):
if not vals:
return None
node_list = []
root = TreeNode(vals[0])
node_list.append(root)
index = 0
is_left = True
for i in range(1, len(vals)):
val = vals[i]
if val != '#':
node = TreeNode(val)
if is_left:
node_list[index].left = node
else:
node_list[index].right = node
node_list.append(node)
if not is_left:
index += 1
is_left = not is_left
return root
def getSampleBstTree():
return createTree([8, 3, 10, 1, 6, '#', 14, '#', '#', 4, 7, 13])
if __name__ == '__main__':
# prep the tree...
#
# layer 1
root = TreeNode('A')
# layer 2
root.left = TreeNode('B')
root.right = TreeNode('C')
# layer 3
root.left.left = TreeNode('D')
root.left.right = TreeNode('E')
root.left.right.right = TreeNode.createTree(2)
root.right.left = TreeNode('F')
root.right.right = TreeNode('G')
# layer 3
root.left.left.left = TreeNode('H')
root.left.left.right = TreeNode('I')
root.left.right.left = TreeNode('J')
# root.left.right.right = TreeNode('K')
# root.right.left.left = TreeNode('L')
# root.right.left.right = TreeNode('M')
root.right.right.left = TreeNode('N')
root.right.right.right = TreeNode('O')
root.prettyPrint()
|
b12f1662741b40261c5f29a95fe891542b758bd0 | pacificpatel165/MyPythonLearning | /Python_Cookbook/CookBook_7.6_Defining_Anonymous_Or_Inline_Functions.py | 717 | 4.03125 | 4 | """
Problem
You need to supply a short callback function for use with an operation such as sort(),
but you don’t want to write a separate one-line function using the def statement. Instead,
you’d like a shortcut that allows you to specify the function “in line.”
"""
# Solution
# Simple functions that do nothing more than evaluate an expression can be replaced by
# a lambda expression. For example:
add = lambda x, y: x + y
print(add(2, 3))
print(add('hello', 'world'))
# Typically, lambda is used in the context of some other operation, such as sorting or a
# data reduction:
names = ['David Beazley', 'Brian Jones',
'Raymond Hettinger', 'Ned Batchelder']
print(sorted(names, key=lambda name: name.split()[-1].lower()))
|
3af077fa491d3f590dd12dd1ad13eba7085fcee7 | hayleycd/project-polyglot | /pythonlang/problem_2_python.py | 640 | 3.921875 | 4 | # Even Fibonacci numbers
# Problem 2
# Each new term in the Fibonacci sequence is generated by
# adding the previous two terms. By starting with 1 and 2,
# the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose
# values do not exceed four million, find the sum of the
# even-valued terms.
def even_fibbo_sum(limit):
first = 1
second = 2
next = first + second
fibbo_sum = second
while next <= limit:
if next%2 == 0:
fibbo_sum += next
first = second
second = next
next = first + second
return fibbo_sum
print(even_fibbo_sum(4000000))
|
ef57746d123533fe33bbe1719995e11418be7c41 | jpablolima/machine_learning | /python/listas_tuplas.py | 319 | 3.703125 | 4 | meses = ('janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro',
' novembro', 'dezembro')
print(meses)
type(meses)
alunos = ('Pablo','Luan', 'Ana', 'Raquel')
print(alunos)
type(alunos)
len(meses)
len(alunos)
meses[1]
alunos[3]
alunos[1] = 'João Pablo'
alunos.append('Julia')
|
100897a70ad1ede903638eeea6e1ebe8b4fc197d | CiaranGruber/CP1404practicals | /prac_07/extension_grading.py | 1,359 | 3.59375 | 4 | from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
class GradeChecker(App):
def build(self):
"""
Build the Kivy GUI
:return:
"""
Window.size = (800, 300)
self.title = 'Grade Checker'
self.root = Builder.load_file('extension_grading.kv')
return self.root
def clear_all(self):
"""
Clear all text
:return:
"""
self.root.ids.output_label.text = ''
self.root.ids.input_grade.text = ''
def calculate_grade(self):
"""
Handle the pressing the greet button
:return:
"""
try:
if int(self.root.ids.input_grade.text) >= 85:
grade = 'High Distinction'
elif int(self.root.ids.input_grade.text) >= 75:
grade = 'Distinction'
elif int(self.root.ids.input_grade.text) >= 65:
grade = 'Credit'
elif int(self.root.ids.input_grade.text) >= 50:
grade = 'Pass'
else:
grade = 'Fail'
print('Your grade is', grade)
self.root.ids.output_label.text = 'Grade: ' + grade
except ValueError:
print('Invalid Grade')
self.root.ids.output_label.text = 'Invalid Grade'
GradeChecker().run()
|
09c88b40d0824b36c955f992c0d89826a376f36c | yxcui/Machine-Learning | /SimpleLinear Regression.py | 812 | 3.921875 | 4 | # -*- coding:utf-8 -*-
import numpy as np
def fitSLR(x, y): # x,y分别为自变量和因变量的样本值
n = len(x)
x_mean = np.mean(x)
y_mean = np.mean(y)
numerator = 0 # 分子
dinominator = 0 # 分母
for i in range(0,n):
numerator += (x[i] - x_mean)*(y[i] - y_mean)
dinominator += (x[i] - x_mean)**2
b1 = numerator/float(dinominator)
b0 = y_mean - b1*float(x_mean)
print "b0: %f, b1: %f" %(b0,b1)
return b0,b1
def predict(x,b0,b1):
return b0 + b1*x
if __name__ == "__main__":
x = [1,3,2,1,3]
y = [14,24,18,17,27]
b0,b1 = fitSLR(x,y)
print "intercept: %f, slope:%f" %(b0,b1)
x_test = 6
y_test = predict(x_test,b0,b1)
print "The linear regression equation is y = %f + %f x" %(b0, b1)
print "y_test:", y_test
|
d6a5ee036ef9bd70e6495b3849638f89ed7ad91d | ajhyndman/python-guessing-game | /guessing_game.py | 836 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Guessing Game from teamtreehouse.com's Python Basics course.
# @author: Andrew Hyndman
import random
answer = random.randint(1, 10)
print("I have picked a number between 1 and 10. Try to guess it!")
guesses_remaining = 5
guess = 0
while guesses_remaining > 0:
print("You have {} guesses remaining".format(guesses_remaining))
guess = int(input("::: "))
guesses_remaining -= 1
if guess == answer:
print("Congratulations! You guessed my number [{}] in {} guesses!".format(answer, (5 - guesses_remaining)))
break
elif guess > answer:
print("Nope. My number is less than that.")
else:
print("Nope. My number is greater than that.")
if 0 == guesses_remaining:
print("I win! Muahahaha!")
|
98b90d8e768edb4bfcf518d260525aac19d80a87 | YutaLin/Python100 | /Day6/string.py | 850 | 4.15625 | 4 | def main():
string1 = 'hello, world!'
print(len(string1)) # 13
print(string1.capitalize()) # Hello, world!
print(string1.upper()) # HELLO, WORLD!
print(string1.find('or')) # 8
print(string1.find('shit')) # -1
print(string1.startswith('He')) # False
print(string1.startswith('hel')) # True
print(string1.endswith('!')) # True
print(string1.center(50, '*'))
print(string1.rjust(50, ' '))
string2 = 'abc123456'
print(string2[2]) # c
print(string2[2:5]) # c12
print(string2[2:]) # c123456
print(string2[2::2]) # c246
print(string2[::2]) # ac246
print(string2[::-1]) # 654321cba
print(string2[-3:-1]) #45
print(string2.isdigit()) # False
print(string2.isalpha()) # False
print(string2.isalnum()) # True
string3 = ' xsw@gmail.com '
print(string3)
print(string3.strip())
if __name__ == "__main__":
main()
|
7c3e5fdedc844e4ad185d4d4c994b5d9b5e11625 | debadri16/Python-Basics | /oop/oop1.py | 983 | 3.84375 | 4 | import random
class Bank:
balance=0
def __init__(self):
print('hey homie!welcome')
self.account_id=random.randint(1000,10000)
print('niggah ur id is',self.account_id)
def menu(self):
user_input=int(input('''how can we help u
1.display
2.withdraw
3.deposit
4.exit '''))
if user_input==1:
self.display()
elif user_input==2:
self.withdraw()
elif user_input==3:
self.deposit()
else:
exit()
def display(self):
print('your balnce is',self.balance)
self.menu()
def withdraw(self):
amount=int(input('enter amount to withdraw '))
self.balance=self.balance-amount
self.display()
self.menu()
def deposit(self):
amount = int(input('enter amount to deposit '))
self.balance=self.balance+amount
self.display()
self.menu()
sbi=Bank()
sbi.menu()
|
660b6be3b6081acaa535cc94be750a19bf8f08dc | hamburgcodingschool/L2CX-November | /lesson 1J/p3-concatenation.py | 169 | 3.953125 | 4 | # Concatenation
name = "Helder"
age = 37
print("Hello my name is " + name + " and I am " + str(age) + " years old.")
# Hello ny name is Helder and I am 37 years old.
|
40116939ff4e5a284a3d0d09bad006a7ec5489f6 | helgaKalicz/statistics | /reports.py | 3,453 | 3.734375 | 4 | # Making list of the games
def making_list_of_games(file_name):
with open(file_name, "r") as f:
i = len(f.readlines())
with open(file_name, "r") as f:
games = []
for j in range(i):
line = list(f.readline().split("\t"))
line[len(line)-1] = (line[len(line)-1])[:-1]
games.append(line)
return games
# Making sorted without using built-in functions
def making_sort_of_list(list_name):
for k in range(len(list_name)):
for l in range(len(list_name)-1):
m = 0
while m < min([len(list_name[l]), len(list_name[l + 1])]):
if list_name[l][m].lower() > list_name[l + 1][m].lower():
changing = list_name[l + 1]
list_name[l + 1] = list_name[l]
list_name[l] = changing
m = min([len(list_name[l]), len(list_name[l + 1])])
elif list_name[l][m].lower() < list_name[l + 1][m].lower():
m = min([len(list_name[l]), len(list_name[l + 1])])
else:
if m == min([len(list_name[l]), len(list_name[l + 1])])-1:
if len(list_name[l]) < len(list_name[l + 1]):
m += 1
else:
changing = list_name[l + 1]
list_name[l + 1] = list_name[l]
list_name[l] = changing
m += 1
else:
m += 1
return(list_name)
# First question
def count_games(file_name):
with open(file_name, "r") as f:
return len(f.readlines())
# Swcond question
def decide(file_name, year):
games = making_list_of_games(file_name)
return False if str(year) not in list(games[k][2] for k in range(len(games))) else True
# Third question
def get_latest(file_name):
games = making_list_of_games(file_name)
for k in range(len(games)):
if (str(max([int(games[l][2]) for l in range(len(games))]))) in games[k][2]:
return games[k][0]
# Fourth question
def count_by_genre(file_name, genre):
games = making_list_of_games(file_name)
return list(games[k][3] for k in range(len(games))).count(genre)
# Fifth question
def get_line_number_by_title(file_name, title):
games = making_list_of_games(file_name)
try:
in_list_check = 0
for k in range(len(games)):
if title in games[k][0]:
in_list_check += 1
return k + 1
if in_list_check == 0:
raise Exception
except:
return ValueError
# Sixth question
def sort_abc(file_name):
games = making_list_of_games(file_name)
return making_sort_of_list(list(games[k][0] for k in range(len(games))))
# Seventh question
def get_genres(file_name):
games = making_list_of_games(file_name)
return making_sort_of_list(list(set(list(games[k][3] for k in range(len(games))))))
# Eight question
def when_was_top_sold_fps(file_name):
games = making_list_of_games(file_name)
try:
topFPS = max([float(games[k][1]) if 'First-person shooter' in games[k][3] else 0 for k in range(len(games))])
if topFPS == 0:
raise Exception
for k in range(len(games)):
if topFPS == float(games[k][1]):
return int(games[k][2])
except:
return ValueError
|
65b4b2bff8e84479c47b6222c8d8fdbc755b413a | MikelSotomonte/mask-turret | /SpeachToText Example.py | 444 | 3.515625 | 4 | import speech_recognition as sr
r = sr.Recognizer()
''' Euskera --> "eu-ES" ---- English --> "en-US" ---- Castellano --> "es-ES" '''
print("Speak you CrackHead")
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
data = r.record(source, duration=3)
print("Analizando")
try:
text = r.recognize_google(data, language="eu-ES")
print(text)
except:
print("No se ha detectado nada") |
dad9273b740cd380e3794ee666b063f286c09cf9 | anishshanmug/python-homework | /Block 2 Work/3-11.py | 214 | 4.03125 | 4 | num = int(input("Please Enter any Number: "))
rev = 0
while(num > 0):
mod = num %10
rev = (rev *10) + mod
num = num //10
print("Reverse of entered number is = %d" %rev)
|
c713da4a3304a6c833ac7a6ba52a3d28a16e2b99 | Da1anna/Data-Structed-and-Algorithm_python | /leetcode/其它题型/字符串/common/回文子串.py | 2,107 | 3.625 | 4 | # -*- coding:utf-8 -*-
# @Time: 2020/6/23 16:27
# @Author: Lj
# @File: 回文子串.py
'''
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
示例 1:
输入: "abc"
输出: 3
解释: 三个回文子串: "a", "b", "c".
示例 2:
输入: "aaa"
输出: 6
说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindromic-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
'''
参考答案思路:中心拓展
1.可以知道一共有2*N-1个回文串的中心:字符或两个字符之间
2.对每个中心同时向左向右拓展,判断其是否是回文串
'''
class Solution:
#暴力法:列举出所有字符串组合,对每个组合判断其是否是回文串
#时间复杂度——O(1/4 n3)超时
def countSubstrings(self, s: str) -> int:
def is_huiwen(str) -> bool:
i, j = 0, len(str)-1
while i < j:
if str[i] == str[j]:
i += 1
j -= 1
else:
return False
return True
count = 0
for i in range(len(s)):
j = i+1
while j <= len(s):
if is_huiwen(s[i:j]):
count +=1
j += 1
return count
#参考答案:中心拓展法
def countSubstrings_1(self, s: str) -> int:
N = len(s)
cnt = 0
#在计算中心点的左右两边位置需要细心推敲
for center in range(2*N-1):
left = center // 2
right = left + center % 2
while left >=0 and right < N and s[left] == s[right]:
cnt += 1
left -= 1
right += 1
return cnt
#测试
s = 'aba'
res = Solution().countSubstrings_1(s)
print(res) |
52971ea05a64cd026263d092dbe3e6bd443d3a1d | nevesjf/python | /Lista3/exercicio1.py | 301 | 4.0625 | 4 | #EXERCICIO 1
nota = int(input("Insira uma nota entre 0 e 10: "))
a = 0
while a == 0:
if nota >= 0 and nota <= 10:
print("Ok!")
a = 1
else:
a = 0
print("Valor invalido! Digite novamente...")
nota = int(input("Insira uma nota entre 0 e 10: "))
|
051ebc540457a2150522fde4297ef68649f1f05b | spertus/shakespeare_conspiracy | /author_compare.py | 7,147 | 3.546875 | 4 | #Script to run a naive Bayes to learn two bodies of work, then compare two books to determine which is more likely written by which author.
#Reference texts must be put in "Samples" directory with format "author_text.txt"
import re
import string
import operator
from prettytable import PrettyTable
from sh import find
import math
#Format: "author1, author2, ..."
#possible options right now "joyce","conrad","austen", "wilde","shakespeare"
authors = ["austen","joyce","conrad"]
#input book files
book_files = ["heartofdarkness.txt","ulysses.txt","prideandprejudice.txt"]
#IMPORTANT: text files to learn should be in the format: "author1_book.txt"
#Functions to get text files into tokenized, enumerated format
def remove_punctuation(s):
"see http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python"
table = string.maketrans("","")
return s.translate(table, string.punctuation)
def tokenize(text):
text = remove_punctuation(text)
text = text.lower()
return re.split("\W+", text)
def count_words(words):
wc = {}
for word in words:
wc[word] = wc.get(word, 0.0) + 1.0
return wc
#Initiate data structures.
#vocab holds word totals across writers.
#priors is simply how many books were written by a given author over total books
vocab = {}
word_counts = {}
priors = {}
for i in authors:
word_counts[i] = {}
priors[i] = 0.0
docs = []
#find("Samples") prints a list with entries like: "Samples/austen_emma.txt" from which we want only "austen"
#If sample texts are not in "Samples" directory, need to change arg to find().
#Would also need to change indices to work.split() in author_work to grab only the author.
for work in find("Samples"):
work = work.strip()
author_work = work.split("_")[0][8:len(work.split("_")[0])]
#Reject anything that's not a text file or not by one of our authors
if work.endswith(".txt") == False or author_work not in authors:
continue
#Categorize by author
else:
for i in authors:
if i in work:
category = i
docs.append((category, work))
#Record how many books by each author for priors
priors[category] += 1
#Open actual work, get word counts, and store in word_counts dict under each author.
text = open(work, "r").read()
words = tokenize(text)
counts = count_words(words)
for word, count in counts.items():
if word not in vocab:
vocab[word] = 0.0
if word not in word_counts[category]:
word_counts[category][word] = 0.0
vocab[word] += count
word_counts[category][word] += count
#Initialize structure for books to be estimated and read in word counts.
counts_combined = {}
for i in book_files:
book = open(i, "r").read()
counts_combined[i] = count_words(tokenize(book))
#determine actual priors from counts and initialize log_probs which will hold probabilities for each author.
prior_authors = {}
log_probs = {}
for writer in authors:
prior_authors[writer] = priors[writer] / sum(priors.values())
log_probs[writer] = 0.0
print prior_authors
#Initalize scores which will store "posteriors" for each author and book.
scores = {}
for i in book_files:
scores[i] = {}
#Cycle through each book
for i in counts_combined.keys():
#Cycle through each word in the book and its count
for w, cnt in counts_combined[i].items():
if len(w) <= 3 or w not in vocab:
#vocab[w] = 0.0
#word_counts[category][word] = 0.0
#vocab[w] += count
#word_counts[category][word] += count
continue
#Marginal probability of that word across all authors
p_word = vocab[w] / sum(vocab.values())
p_w_given_author = {}
#cycle through each author
for writer in authors:
#Probability of that word given the author = how many times that author uses the word over total uses by all authors
p_w_given_author[writer] = word_counts[writer].get(w, 0.0) / sum(word_counts[writer].values())
#assume independence and as long as prob is greater than 0, multiply total uses by probability over marginal.
if p_w_given_author[writer] > 0:
log_probs[writer] += math.log(cnt * p_w_given_author[writer] / p_word)
#account for prior by adding to likelihood/marginal (log space)
scores[i][writer] = (log_probs[writer] + math.log(prior_authors[writer]))
#reset log_probs for new book
log_probs = dict.fromkeys(log_probs, 0)
#Print out results.
for i in scores:
for j in authors:
print "Log Score:", i, "by", j, ":", scores[i][j]
print "Best estimate:", max(scores[i].iteritems(), key = operator.itemgetter(1))[0]
#Authors Test:
#Log Score: ulysses.txt by austen : 9642.80702934
#Log Score: ulysses.txt by conrad : 14932.2173448
#Log Score: ulysses.txt by joyce : 17500.5657755
#Log Score: ulysses.txt by shakespeare : 10033.0624186
#Best estimate: joyce
#Log Score: prideandprejudice.txt by austen : 7153.27425347
#Log Score: prideandprejudice.txt by conrad : 5666.03909939
#Log Score: prideandprejudice.txt by joyce : 5565.07551535
#Log Score: prideandprejudice.txt by shakespeare : 4445.20736575
#Best estimate: austen
#Log Score: hamlet.txt by austen : 1485.07494488
#Log Score: hamlet.txt by conrad : 2390.74121565
#Log Score: hamlet.txt by joyce : 2521.26483009
#Log Score: hamlet.txt by shakespeare : 4279.33267111
#Best estimate: shakespeare
#Log Score: heartofdarkness.txt by austen : 2025.94770753
#Log Score: heartofdarkness.txt by conrad : 5129.62954923
#Log Score: heartofdarkness.txt by joyce : 3609.35070408
#Log Score: heartofdarkness.txt by shakespeare : 2721.69724393
#Best estimate: conrad
#Shakespeare Conspiracy Test:
#Log Score: macbeth.txt by bacon : 900.979009441
#Log Score: macbeth.txt by marlowe : 2109.01760165
#Log Score: macbeth.txt by jonson : 1328.89977797
#Best estimate: marlowe
#Log Score: juliuscaesar.txt by bacon : 1235.75172668
#Log Score: juliuscaesar.txt by marlowe : 1917.26873699
#Log Score: juliuscaesar.txt by jonson : 1793.3410116
#Best estimate: marlowe
#Log Score: hamlet.txt by bacon : 1758.60057006
#Log Score: hamlet.txt by marlowe : 2568.39370564
#Log Score: hamlet.txt by jonson : 2564.34610823
#Best estimate: marlowe
#Log Score: kinglear.txt by bacon : 1476.00847081
#Log Score: kinglear.txt by marlowe : 2459.11011593
#Log Score: kinglear.txt by jonson : 2447.74485476
#Best estimate: marlowe
#Log Score: romeoandjuliet.txt by bacon : 1339.0301033
#Log Score: romeoandjuliet.txt by marlowe : 2676.93833073
#Log Score: romeoandjuliet.txt by jonson : 2373.05048049
#Best estimate: marlowe
#Log Score: othello.txt by bacon : 1133.18352159
#Log Score: othello.txt by marlowe : 2379.71496655
#Log Score: othello.txt by jonson : 1731.50711955
#Best estimate: marlowe
#Log Score: shakescompleteworks.txt by bacon : 18703.8356354
#Log Score: shakescompleteworks.txt by marlowe : 21570.1923297
#Log Score: shakescompleteworks.txt by jonson : 23070.4888151
#Best estimate: jonson
|
3a9d6b18cf61ce6da4b7f5514da8021a48c279d9 | ishaan001/SPY-CHAT | /spychat/add_friend.py | 2,054 | 4.15625 | 4 | from default_spy_details import Spy,friends
import re
def add_friend():
new_friend=Spy(" "," ",0,0.0)
while(True):
new_friend.name= raw_input("enter your friend name :")
#user regex which will ask user to add name with first letter capital only
pattern_nf = '^[A-Z]{1}[a-z\s]+$'
if (re.match(pattern_nf, new_friend.name) != None):
print ("your name is :" + new_friend.name)
break
else:
print "name cannot be numeric and Should start with capital letter"
while (True):
#will ask user to add friends salutation
new_friend.salutation = raw_input("enter salutation of your fiend what should we call him6 Mr/Ms. :")
if (new_friend.salutation == "Mr" or new_friend.salutation == "Ms"):
f_name=new_friend.salutation+"."+new_friend.name
print "hello you friend name is %s"%(f_name)
break
else:
print "salutation not provided correctly"
while (True):
# will ask user to add friends age
new_friend.age = raw_input("enter age :")
pattern_nf_a = '^[0-9]{1,3}$'
if (re.match(pattern_nf_a, new_friend.age) != None):
print "your age is " + str(new_friend.age)
new_friend.age = int(new_friend.age)
break
else:
print "age cannot be 0 or alphabet"
while (True):
# will ask user to add friends rating and that too should be less the 5.0 and should be floating point value only
try:
new_friend.rating = float(raw_input("enter friend rating :"))
if (new_friend.rating <= 5.0):
print "your friend rating is " + str(new_friend.rating)
break
else:
print "rating cannot be greater than 5"
except Exception:
print "invalid rating it can't be string"
new_friend.is_online=True
friends.append(new_friend)
print "Friend ADDED"
return len(friends)
|
8fe696ea8eddb5d2dee991e777da2277b6456ffd | 668/projecteuler | /q19/q19.py | 1,317 | 4.125 | 4 | dayslist = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday'
]
def is_leap(year):
if year%4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def no_of_days(month, year):
number_of_days = 0
if month == 1:
m_limit = 12
y_limit = year-1
else:
m_limit = month - 1
y_limit = year
for y in range(1900, y_limit+1):
for m in range(1, 13):
if y == y_limit and m > m_limit:
break
if m == 2:
if is_leap(y):
number_of_days += 29
else:
number_of_days += 28
elif m in (4, 6, 9, 11):
number_of_days += 30
else:
number_of_days += 31
return number_of_days
def get_first_day(month, year, dayslist):
number_of_days = no_of_days(month, year)
eff_num = number_of_days % 7
return dayslist[eff_num]
count = 0
for year in range(1901, 2001):
for month in range(1, 13):
if get_first_day(month, year, dayslist) == dayslist[6]:
count += 1
print count
|
9abe58710a32623d1026176b9c149439da9308b0 | SyreenBn/Python-Programming-Essentials-for-the-Health-Sciences | /Projects/Project two/HINF5502_GUIs.py | 1,933 | 4.21875 | 4 | # HINF 5502: Program snippets: GUIs
#
# Here are some short(ish) program snippets on Graphic User Interfaces (GUIs).
# For best results, be sure to run each of them in their own
# window as a program, rather than typing them in one line at a
# time in IDLE's interactive window.
#
# A very simple GUI program, with just a Quit button.
from Tkinter import *
root = Tk()
button = Button(root, text="Goodbye",
command=root.destroy)
button.pack()
mainloop()
# An example of named parameters. Note that there are many
# options for styling the text label.
from Tkinter import *
root = Tk()
label = Label(root, text="Hello", background="white",
foreground="red", font="Times 20",
relief="groove", borderwidth=3)
label.pack()
mainloop()
# A slightly larger example, creating an interface which has
# two buttons. One increments a counter in the same window, and
# the other button quits the program.
from Tkinter import *
root = Tk()
count_label = Label(root, text="0")
count_label.pack()
count_value = 0
def increment_count():
global count_value, count_label
count_value += 1
count_label.configure(text=str(count_value))
incr_button = Button(root, text="Increment", command=increment_count)
incr_button.pack()
quit_button = Button(root, text="Quit", command=root.destroy)
quit_button.pack()
mainloop()
# A different version of the above, using the IntVar mutable
# type, making the code a little more straightforward.
from Tkinter import *
root = Tk()
count_value = IntVar()
count_value.set(0)
count_label = Label(root, textvariable=count_value)
count_label.pack()
def increment_count():
count_value.set(count_value.get() + 1)
incr_button = Button(root, text="Increment", command=increment_count)
incr_button.pack()
quit_button = Button(root, text="Quit", command=root.destroy)
quit_button.pack()
mainloop()
|
d7a760a5775da3053b7fdf55d5541972d646e8fc | mgalvank/CodingChallenges | /Gigster/Question3.py | 1,390 | 3.90625 | 4 | import Queue
def solution(a,b,floors,max_capacity,max_weight):
q = Queue.Queue()
weight = 0
people = 0
no_of_trips = []
trip = []
no_of_stops = 0
#Populate the queue
for i in range(0,len(a)):
q.put((i,a[i],b[i]))
#Assuming that the weight of one person will always be lower than the max weight that the elevator can carry
#Loop through the queue
while not q.empty():
#Peek at the head
temp = q.queue[0]
weight += temp[1]
people += 1
#Check if the capacity and weight condition passes
if weight <= max_weight and people <= max_capacity:
temp = q.get()
floor = temp[2]
trip.append(floor)
else:
if q.queue[0][1] > max_capacity:
print "Weight too muhc. Please use stairs"
q.get()
no_of_trips.append(trip)
weight = 0
people = 0
trip = []
no_of_trips.append(trip)
no_of_trips_update = [x for x in no_of_trips if x != []]
for i in no_of_trips:
no_of_stops += len(list(set(i)))
no_of_stops += len(no_of_trips)
print no_of_trips_update
return no_of_stops
# a = [40,40,100,80,20]
# b = [3,3,2,2,3]
# print "No of stops", solution(a,b,3,5,200)
a = [260,80,40]
b = [2,3,3]
print "No of stops", solution(a,b,5,2,200) |
f946ba581d1b18048bfa2f48b899f0020f649e31 | andrewwgao/R3-SoftwareTraining2-AndrewGao | /main.py | 4,558 | 3.84375 | 4 | # import modules
import pygame
import numpy
import random
done = False # boolean variable for checking when maze is fully generated
# colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
n = random.randint(5,50) # random maze size
w = 800 # width
h = 800 # height
sr = w/n # size of 1 cell (square)
screen = pygame.display.set_mode((w, h)) # set window size to 800x800
clock = pygame.time.Clock() # fps for pygame
# maze class
class maze:
'''
declaring variables
'''
def __init__(self, x, y):
self.x = x # x coordinate
self.y = y # y coordinate
self.adj = [] # the 4 cells adjacent to the current cell
self.visited = False # variable to track if cell was visited for algorithm
self.walls = [True, True, True, True] # variable to see if there is a wall (1 of the 4 sides of a cell)
'''
drawing the walls
'''
def draw(self, color):
if self.walls[0]: # draw the top wall
pygame.draw.line(screen, color, [self.x*sr, self.y*sr], [self.x*sr+sr, self.y*sr])
if self.walls[1]: # draw the right wall
pygame.draw.line(screen, color, [self.x*sr+sr, self.y*sr], [self.x*sr+sr, self.y*sr + sr])
if self.walls[2]: # draw the bottom wall
pygame.draw.line(screen, color, [self.x*sr+sr, self.y*sr+sr], [self.x*sr, self.y*sr+sr])
if self.walls[3]: # draw the left wall
pygame.draw.line(screen, color, [self.x*sr, self.y*sr+sr], [self.x*sr, self.y*sr])
'''
adding the adjacent cells to the adj array if they have not been visited
'''
def add_adj(self):
if self.x > 0:
self.adj.append(grid[self.x - 1][self.y])
if self.y > 0:
self.adj.append(grid[self.x][self.y - 1])
if self.x < n - 1:
self.adj.append(grid[self.x + 1][self.y])
if self.y < n - 1:
self.adj.append(grid[self.x][self.y + 1])
'''
remove one of the sides of the current cell to create a "path"
'''
def remove_walls(a, b):
if a.y == b.y and a.x > b.x: # remove left wall
grid[b.x][b.y].walls[1] = False
grid[a.x][a.y].walls[3] = False
if a.y == b.y and a.x < b.x: # remove right wall
grid[a.x][a.y].walls[1] = False
grid[b.x][b.y].walls[3] = False
if a.x == b.x and a.y < b.y: # remove top wall
grid[b.x][b.y].walls[0] = False
grid[a.x][a.y].walls[2] = False
if a.x == b.x and a.y > b.y: # remove bottom wall
grid[a.x][a.y].walls[0] = False
grid[b.x][b.y].walls[2] = False
grid = [[maze(i, j) for j in range(n)] for i in range(n)] # array for grid
for i in range(n): # adjacent cell array
for j in range(n):
grid[i][j].add_adj()
current = grid[0][0] # start at top left corner of window
visited = [current] # the current cell is visited
completed = False # boolean variable to check when maze is done generating
while not done:
clock.tick(60) # run at 60 fps
screen.fill(BLACK) # background color
if not completed: # keep looping until maze is generated
grid[current.x][current.y].visited = True # current cell is visited
next_cell = False # next cell
temp = 10 # repeat loop
while not next_cell and not completed: # randomly choose an adjacent cell to go next
r = random.randint(0, len(current.adj)-1)
Tempcurrent = current.adj[r]
if not Tempcurrent.visited: # if the chosen cell has not been visited yet
visited.append(current)
current = Tempcurrent
next_cell = True
if temp == 0: # if there is still unvisited cells, keep looping
temp = 10
if len(visited) == 0: # all cell visited, end the loop
completed = True
break
else:
current = visited.pop() # adds current cell to visited array
temp = temp - 1
if not completed: # maze not completed, keep removing walls
remove_walls(current, visited[len(visited)-1])
for i in range(n): # draw grid
for j in range(n):
grid[i][j].draw(WHITE)
current.visited = True
pygame.display.flip() # update display
for event in pygame.event.get(): # checks for exiting the window
if event.type == pygame.QUIT:
done = True
quit()
|
4e89006b4a0efe53303da54019e87083a9c10684 | newton-li/GIS6345 | /Exercise12.1.py | 937 | 4.21875 | 4 | english_text = 'the report was due the next day but she still chose to procrastinate'
french_text = 'le rapport devait être remis le lendemain mais elle a quand même choisi de tergiverser'
italian_text = 'il rapporto doveva essere consegnato il giorno successivo ma lei scelse comunque di procrastinare'
def most_frequent(text):
text = text.replace(" ", "")
dictionary = dict()
count = 0
result = []
for letter in text:
dictionary[letter] = dictionary.get(letter, 0) + 1
for letter, count in dictionary.items():
result += [(count, letter)]
result.sort(reverse=True)
for count, letter in result:
print(letter, count)
print('English Letter Frequency:')
most_frequent(english_text)
print(" ")
print('French Letter Frequency:')
most_frequent(french_text)
print(" ")
print('Italian Letter Frequency:')
most_frequent(italian_text)
|
af202ca9d69f0288e4bb3c5e71f56b273eef48a9 | emdre/first-steps | /starting out with python/ch12t2 recursive multipication.py | 102 | 3.71875 | 4 | def multiply(x, y):
if x == 1:
return y
else:
return y + multiply(x - 1, y)
|
8f47de3208833543e640537cd04d8d34420ac5c3 | AnthonyBonfils3/Simplon_Brief_faur_in_rows | /Projet/connect4/player.py | 5,096 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 02 10:25:37 2021
@author: bonfils
"""
from abc import ABC, abstractmethod
import numpy as np
import tensorflow as tf
Qlearning_model_path = './Qlearning/models/'
class Player(ABC): ## la classe doit être abstraite pour pouvoir utiliser
## une méthode abstraite (donc classe hérite de ABC)
def __init__(self, board, name:str='player 1', couleur="Red"):
"""
-------------
DESCRIPTION :
-------------
INPUT : self :
IOUTPUT :
-------------
"""
self.board = board
self.name = name
self.couleur = couleur
if self.couleur=="Red":
self.value = 1
elif self.couleur=="Yellow":
self.value = -1
@abstractmethod ## méthode abstraite doit être redéfinie dans les class filles
def play(self):
"""
-------------
DESCRIPTION : Choose a column to put a pawn
-------------
"""
pass
class Human(Player):
def __init__(self, board, name='Ia1', couleur="Red"):
"""
-------------
DESCRIPTION :
-------------
INPUT : self :
IOUTPUT :
-------------
"""
Player.__init__(self, board, name=name, couleur=couleur)
print('---> Human initialized <---')
def play(self):
"""
-------------
DESCRIPTION :
-------------
INPUT : self :
IOUTPUT :
-------------
"""
column = int(input(f"entrez la position d'une colonne (integer between 1 and {self.board.n_columns}: "))-1
return column
class Ia(Player):
def __init__(self, board, name='Ia1', couleur="Red", strategy='random', mode='1'):
"""
-------------
DESCRIPTION :
-------------
INPUT : self :
IOUTPUT :
-------------
"""
Player.__init__(self, board, name=name, couleur=couleur)
self.strategy = strategy ## type d'IA -> random q_learning
self.mode = mode
if self.strategy=='Q_learning':
if self.mode==1:
filepath = Qlearning_model_path + 'model_test.h5' # 'P4_model_train_rand_2000_step.h5'
elif self.mode==2:
filepath = Qlearning_model_path + 'model_qlearning195.h5' # 'model_qlearning100.h5'
elif self.mode==3:
filepath = Qlearning_model_path + 'model_qlearning500.h5' ## 'model_qlearning1.h5'
elif self.mode==4:
filepath = Qlearning_model_path + 'model_CNNqlearning40.h5'
else:
print(f"Error : strategy {self.strategy} with mode {self.mode} is not available yet.")
self.model = tf.keras.models.load_model(filepath, custom_objects=None, compile=True, options=None)
if (self.strategy=='random'):
print('---> Random IA initialized <---')
elif (self.strategy=='Q_learning'):
print('---> Q_learning IA initialized <---')
def play(self):
"""
-------------
DESCRIPTION :
-------------
INPUT : self :
IOUTPUT :
-------------
"""
if (self.strategy=='random'):
column = np.random.randint(0, self.board.n_columns)
elif (self.strategy=='heuristics'):
print(f"Error : strategy {self.strategy} is not available yet.")
elif (self.strategy=='Q_learning'):
if (self.mode==1):
current_state_flat = self.board.grid.reshape(1,-1)
column = np.argmax(self.model.predict(current_state_flat)[0])
print("Qlearning model choice of column", column)
elif (self.mode==2):
current_state_flat = self.board.grid.reshape(1,-1)
column = np.argmax(self.model.predict(current_state_flat)[0])
print("Qlearning model choice of column", column)
elif (self.mode==3):
current_state_flat = self.board.grid.reshape(1,-1)
column = np.argmax(self.model.predict(current_state_flat)[0])
print("Qlearning model choice of column", column)
elif (self.mode==4):
current_state_reshape = np.reshape(self.board.grid, (1, self.board.n_rows, self.board.n_columns, 1))
column = np.argmax(self.model.predict(current_state_reshape)[0])
print("Qlearning model choice of column", column)
else:
print(f"Error : strategy {self.strategy} with mode {self.mode} is not available yet.")
else:
print(f"Error : strategy {self.strategy} is not available yet.")
return column |
72c7a34605037a349a33054fe0e7653f7573e0b3 | devinupreti/coding-problems | /nonAdjacentSum.py | 829 | 4.0625 | 4 | # PROBLEM : Given a list of integers, write a function that returns the
# largest sum of non-adjacent numbers. Numbers can be 0 or negative.
# For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5.
# [5, 1, 1, 5] should return 10, since we pick 5 and 5.
# Can you do this in O(N) time and constant space?
# Time : O(n) | Space : O(1)
def nonAdjacentSum(array):
if len(array) < 3:
return max(array)
maxSecondLast = array[0]
maxLast = array[1]
for index in range(2,len(array)):
maxYet = max(maxLast,maxSecondLast + array[index])
maxSecondLast = max(maxLast,maxSecondLast)
maxLast = maxYet
return maxYet
arr = [2, 4, 6, 2, 5]
assert nonAdjacentSum(arr) == 13, "Test 1 Failed"
arr2 = [5, 1, 1, 5]
assert nonAdjacentSum(arr2) == 10, "Test 2 Failed"
|
a3d9c04c1257e83a450760fb9d4db8dcd5010f2a | pbwis/training | /HackerRank/HR_ch03/HR_ch03.py | 224 | 3.71875 | 4 | if __name__ == '__main__':
n = int(input())
each_number = []
while n > 0:
n = n - 1
each_number.append(n)
each_number.sort(reverse=False)
for num in each_number:
print(num ** 2) |
f98fe5390d6eadacac768d929588f155d0fe926a | fabriciofmsilva/labs | /python/basic/dictionary.py | 197 | 3.53125 | 4 | dictionary = {'code': 1, 'age': 28, 'cpf': 12312312312}
print dictionary['code']
print dictionary['age']
print dictionary['cpf']
print len(dictionary)
for i in dictionary:
print dictionary[i]
|
1fe55081e35f70c6af15a7a2a8ecb05724a9dde0 | SouzaCadu/guppe | /Secao_05_Lista_Ex_41e/ex_05.py | 223 | 3.90625 | 4 | """
Receba um número inteiro e verifique se é par ou impar
"""
v1 = int(input("Insira um número inteiro para saber se é par ou ímpar:"))
if v1 % 2 == 0:
print(f"{v1} é par.")
else:
print(f"{v1} é ímpar.")
|
33bc8c7e1766e1b7aa1892d8b4ff04e057ea8bd1 | jgraykeyin/robotalker | /talkforme.py | 2,924 | 3.734375 | 4 | # Robotalker 0.1 by Justin Gray
# Program for making your computer speak to your smart device.
# Built around the pyttsx3 module: https://pypi.org/project/pyttsx3/
# Currently supported devices: Google Home & Amazon Echo
import pyttsx3
# Initialize the Text-to-speech module
engine = pyttsx3.init()
# Select the voice
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
# Number code for devices
# 1: GOOGLE HOME
# 2: AMAZON ECHO
smart_device = 1
# Main menu of commands
def mainMenu():
command_list = ["Commands:",
"[1] - Play Music",
"[2] - Set Alarm",
"[3] - Check Weather",
"[4] - Check Time",
"[5] - Watch TV or Movie",
"[6] - User Command",
"[0] - Quit"]
return command_list
# Each supported device will need to have a menu button here
def selectDevice():
while True:
user_device = input("[G]oogle Home or [A]mazon Echo: ")
if user_device.upper() == "G":
smart_device = 1
break
elif user_device.upper() == "A":
smart_device = 2
break
return(smart_device)
# Trigger the Text-To-Speech command
def speakCommand(command,device):
if device == 1:
engine.say("OK Google,"+command)
elif device == 2:
engine.say("Hey Alexa,"+command)
engine.runAndWait()
# Initial prompt to select which device the user has
print("Robotalker 0.1")
print("Please select your Smart Device: ")
device = selectDevice()
while True:
# Display the main command menu
main_menu = mainMenu()
for item in main_menu:
print(item)
while True:
try:
user_command = int(input("> "))
except:
print("Please input a number")
else:
break
if user_command == 0:
# Quit the program
break
elif user_command == 1:
# Play Music
speakCommand("play music",device)
elif user_command == 2:
# Set an alarm
print("Example> 'Tomorrow at 6 am'")
user_alarm = input("Set alarm for: ")
user_alarm = "set alarm for " + user_alarm
speakCommand(user_alarm,device)
elif user_command == 3:
# Check the weather
speakCommand("what's the weather today?",device)
elif user_command == 4:
# Check the time
speakCommand("what time is it?", device)
elif user_command == 5:
# Play a show or movie
print = "What would you like to watch?"
user_watch = input("> ")
user_watch = "play " + user_watch
speakCommand(user_watch,device)
elif user_command == 6:
# Custom command entered by the user
print("What would you like to say to your device?")
user_command = input("> ")
speakCommand(user_command,device)
print("Thanks for using Robotalker!") |
0a74c1a7159acb30bd11bbf47409cb8a9565dea1 | yanghongkai/yhkleetcode | /pointer/reverse_string_344.py | 523 | 3.765625 | 4 | # 344 反转字符串 https://leetcode-cn.com/problems/reverse-string/
from typing import List
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
# left right
left = 0
right = len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
return s
s = ["h", "e", "l", "l", "o"]
print(Solution().reverseString(s))
|
50de813bfaaa6b50adf0c6419c45b8b624009e62 | solesensei/PythonCourses | /HSE Python Coursera/week 4/07-sum-no-sum.py | 286 | 3.6875 | 4 | import math
def ssum(a, b):
s = 0
if a == 0:
return b
if a < 0:
s += ssum(a+1, b) - 1
else:
s += ssum(a-1, b) + 1
return s
def main():
a = int(input())
b = int(input())
print(ssum(a, b))
if __name__ == "__main__":
main()
|
56c3109b3c8c811a23b4c9e996542316c2bed949 | thanhENC/TDLT | /Tutorial #5/random_password_generator.py | 888 | 4 | 4 | import string
import random
def password_generator(length=8):
LETTERS = string.ascii_letters
DIGITS = string.digits
PUNCTUATION = string.punctuation
printable = f'{LETTERS}{DIGITS}{PUNCTUATION}'
printable = list(printable)
random.shuffle(printable)
password = random.choices(printable, k=length)
password = ''.join(password)
return password
def get_password_length():
length = 0
while True:
try:
length = int(input('How long do you want your password: '))
if length <= 0:
raise Exception
else:
return length
except:
print('Input is invalid. Please input again!')
def main():
password_length = get_password_length()
random_password = password_generator(password_length)
print(random_password)
if __name__ == '__main__':
main() |
9c1e583773f0171fcdb9f0bdd741cc9f2af7f0c6 | wdjlover/Office-Administration | /app/auth/forms.py | 1,932 | 3.515625 | 4 | from flask_wtf import FlaskForm
from wtforms import PasswordField,StringField,SubmitField,ValidationError
from wtforms.validators import DataRequired,Email,EqualTo
from ..models import Employee
#create the RegistrationForm class
#it inherits the FlaskForm
class RegistrationForm(FlaskForm):
#this is the form for users to create new accounts
#the form fields below
email=StringField('Email', validators=[DataRequired(),Email()])#each form contains validators to check the input
username=StringField('Username',validators=[DataRequired()])
first_name=StringField('First Name',validators=[DataRequired()])
last_name=StringField('Last Name',validators=[DataRequired()])
password=PasswordField('Password', validators=[DataRequired(), EqualTo('confirm_password')])#ensure email is equal to confirm password field
confirm_password=PasswordField('Confirm Password')
#submit field will rep a button that users will be able to click to register
submit=SubmitField('Register')
#methods to validate email and username
#they query data from the database
#they ensure that email and username are not in the database
def validate_email(self,field):
#THIS VALIDATES THE EMAIL
if Employee.query.filter_by(email=field.data).first():
#RAISE VALUE ERROR IF EMAIL ALREADY EXISTS
raise ValidationError('EMAIL ALREADY IN USE')
def validate_username(self,field):
#THIS CHECKS IF THE USERNAME EXISTS IN THE DATABASE
if Employee.query.filter_by(username=field.data).first():
#RAISE VALIDATION ERROR IF IT EXISTS
raise ValidationError("Username already exists")
class LoginForm(FlaskForm):
#form for users to log-in
email=StringField('Email', validators=[DataRequired(),Email()])
password=PasswordField('Password',validators=[DataRequired()])
submit=SubmitField('Login')
|
225b15b7b0103434f70b0f7f78188561f8cb5399 | duanyadian/PycharmProjects | /iteration factor.py | 467 | 3.609375 | 4 | for num in range(10,20): # 迭代10~20之间的数值
for i in range(2,num): # 根据因子迭代
if num%i == 0: # 确定第一个因子
j = num/i # 计算第二个因子
print("%d 是一个合数" %num)
break # 跳出当前循环
else: # 循环else部分
print("%d 是一个质数" %num)
|
c62717082a369b9d69a524caa3c9e57114d76eca | Zejima/Python_Tutorials | /General-Programing-Tutorial-WIth-Python/Tutorial-3.py | 881 | 4.21875 | 4 | # Ask the user to user 2 values and store them in variables num1 and num2
num1, num2= input('Enter 2 numbers:').split() #.split assigns tow variables
# Convert the strings into regular numbers
num1=int(num1)
num2=int(num2)
# Add the values entered and store in sum
sum = num1 + num2
# Subtract values and store in difference
difference = num1 - num2 # Difference is different than "difference"
# Multiply the values and store in the product
product = num1 * num2
# Divide the values and store in the quotient
quotient = num1 / num2
# Use the modulus to find the remainder
remainder = num1 % num2
#Print the results
print("{} + {} = {})".format(num1, num2, sum))
print("{} - {} = {})".format(num1, num2, difference))
print("{} * {} = {})".format(num1, num2, product))
print("{} / {} = {})".format(num1, num2, quotient))
print("{} % {} = {})".format(num1, num2, remainder))
|
492d563539a2f3e1f732bfbb8e982cd65f355584 | LEXBROS/Stepik_PyCharm | /list_example_2.1.py | 133 | 3.546875 | 4 | n = int(input())
example = [val for val in range(1, n + 1)]
result = [example[:i] for i in range(1, n + 1)]
print(*result, sep='\n')
|
45e521c689c83141447df22d25b5506b962dd02e | BipronathSaha99/dailyPractiseCode | /try_3.py | 819 | 4.34375 | 4 | #---------------------------Removing elements-------------------------#
#---we use pop(removes the last member)
#---------remove(removes the given number)--------------------------#
my_list=["earth","mars","aris","makemake","jupiter"]
#--------------------Q_1-----------------------------#
#---------------remove all the elements---------------#
#---------------------'To remove specific elements---------------------------#
my_list.remove("earth")
print(my_list)
#----------------------To clear at a time we use clear()-------------------------#
my_list=["earth","mars","aris","makemake","jupiter"]
my_list.clear()
print(my_list)
#-------------------------To remove only last elements----------------------------#
my_list=["earth","mars","aris","makemake","jupiter"]
my_list.pop(4)
print(my_list) |
1c53a0b48f06c2fcc33705d30efce602a7cbceba | susoooo/IFCT06092019C3 | /GozerElGozeriano/python/20200313/for5.py | 417 | 3.84375 | 4 | #5-Escriba un programa que pregunte cuántos números se van a introducir, pida esos números, y diga al final cuántos han sido pares y cuántos impares.
print("¿Cuantos números se van a introducir?")
n1=int(input())
pares=0
impares=0
print("Pues venga: ")
for n in range(0,n1):
print("Número: ")
num=int(input())
if(num%2==0):
pares+=1
else:
impares+=1
print("Pares ", pares)
print("Impares ", impares)
|
1c5fa692a1dd6667083577e9daa55f092eb75cd9 | arya-pv/pythonjuly2021 | /oop/polymorphism/overloading_1.py | 535 | 3.890625 | 4 | class Person:
def set(self,name,age):
self.name=name
self.age=age
print(self.name,self.age)
class Employee(Person):
def set(self,salary,jobrole):
self.salary=salary
self.jobrole=jobrole
print(self.salary,self.jobrole)
obj=Employee()
obj.set("ANU",23,3000,"HR")
class Operators:
def num(self,num1):
self.num1=num1
print(self.num1)
def num(self,num2,num3):
self.num2=num2
self.num3=num3
print(num2+num3)
obj=Operators()
obj.num(3)
|
f8be967696b5d8874038ff5033ab9a54ef034025 | bennettt5851/cti110 | /P3LAB2A_Bennett.py | 476 | 4.34375 | 4 | # This program uses turtle program (for) to draw a basic square and triangle
# 3/14/21
# CTI-110-0B01
# Tyler Bennett
import turtle
win = turtle.Screen()
t = turtle.Turtle()
t.pensize(5)
t.pencolor("red")
t.shape("turtle")
for i in (1,2,3,4):
t.forward(100)
t.left(90)
t.right(100)
for i in (1,2,3):
t.forward(100)
t.left(120)
win.mainloop()
# Set turtle program
# Input command to create a square
# Input command to create a triangle
# End program
|
c407a7edb24f7364fd7b4dcfd84562a36a803bb5 | kkrugler/codecademy-validator | /bitney_adventure/game_complete_default.py | 723 | 3.828125 | 4 | def game_complete():
# Level - 3
global g_visited_room_names
global g_score
# TODO decide when to congratulate user and return True. This would
# be the case for when they've visited every room. So you can either
# compare their score against the sum of scores from every room, or
# if the g_visited_room_names list length is == the number of rooms.
return False
# This is a list of all of names of all the rooms that the player has visited.
# It starts off with just the current room that they're in.
g_visited_room_names = ['hallway', 'computer lab']
# This is the player's current score. They get points for visiting a room
# (but only the first time!)
g_score = 10
game_complete()
|
d072ab11c1838e325f54c05e85033ca2c8939ba9 | q10242/pythone-practice | /ch7/ch7-2.py | 261 | 4.03125 | 4 | x = 10
number1 = list(range(x));
print number1;
y = 16
number2 = list(range(x,y))
print number2
z = 2
number3 = list(range(x,y,z))
print number3
t = 0
for numbers in number3:
t= t+numbers
else: #結束之後執行的區塊
print "over!"
print t
|
5a814ad4abbd8822de6a69cb64decc060210b84c | Jochizan/courses-python | /programs-python/manager_files.py | 1,005 | 3.625 | 4 | from io import open
archivo_texto=open("archivo.txt", "r+") # lectura y escritura
# archivo_texto.write("\n Siempre es una buena ocasión para estudiar Python")
# archivo_texto.close()
# lineas_texto = archivo_texto.readlines()
# archivo_texto.close()
# print(lineas_texto)
# texto = archivo_texto.readlines()
# archivo_texto.close()
# print(texto)
# frase = "Estupendo día para estudiar python\nel viernes\nsiempre es una buena ocasión para estudiar Python"
# archivo_texto.write(frase)
# archivo_texto.close()
# archivo_texto.seek(11)
# archivo_texto.seek(len(archivo_texto.readline()))
# print(archivo_texto.read())
# archivo_texto.write("Comienzo del texto")
# print(archivo_texto.readlines())
lista_texto=archivo_texto.readlines();
lista_texto[1]=" Esta linea ha sido incluida del esxterior \n"
archivo_texto.seek(0)
archivo_texto.writelines(lista_texto)
archivo_texto.close()
# with io.open("file_dir", "modo"):
# print(archivo_texto.read())
print(archivo_texto.closed) |
7a5bf6c35433284d53d51547c3053039c6d77968 | ash/amazing_python3 | /299-negative-index.py | 241 | 4.1875 | 4 | # Negative indices when accessing
# list elements
data = [
'alpha', 'beta', 'gamma',
'delta', 'epsilon'
]
# Accessing the first item:
print(data[0])
# Accessing the last item:
print(data[-1])
# The second to last
print(data[-2])
|
50ff8ce7a08f67f17afb1cb573763cc48fc630de | merodriguezblanco/CS6601 | /assignment_1/player_submission.py | 6,769 | 3.5625 | 4 | #!/usr/bin/env python
from operator import itemgetter
# This file is your main submission that will be graded against. Only copy-paste
# code on the relevant classes included here from the IPython notebook. Do not
# add any classes or functions to this file that are not part of the classes
# that we want.
# Submission Class 1
class OpenMoveEvalFn():
"""Evaluation function that outputs a
score equal to how many moves are open
for AI player on the board minus
the moves open for opponent player."""
def score(self, game, maximizing_player_turn=True):
# get unique moves using set then get the number of moves left
p1_num_moves = len(set(sum(game.get_legal_moves().values(), [])))
p2_num_moves = len(set(sum(game.get_opponent_moves().values(), [])))
if maximizing_player_turn:
return p1_num_moves - p2_num_moves
else:
return p2_num_moves - p1_num_moves
# Submission Class 2
class CustomEvalFn():
"""Custom evaluation function that acts
however you think it should. This is not
required but highly encouraged if you
want to build the best AI possible."""
def score(self, game, maximizing_player_turn=True):
# get unique moves using set then get the number of moves left
p1_num_moves = len(set(sum(game.get_legal_moves().values(), [])))
p2_num_moves = len(set(sum(game.get_opponent_moves().values(), [])))
if maximizing_player_turn:
return p1_num_moves - (3 * p2_num_moves)
else:
return p2_num_moves - (3 * p1_num_moves)
class CustomPlayer():
# TODO: finish this class!
"""Player that chooses a move using
your evaluation function and
a depth-limited minimax algorithm
with alpha-beta pruning.
You must finish and test this player
to make sure it properly uses minimax
and alpha-beta to return a good move
in less than 5 seconds."""
def __init__(self, search_depth=3, eval_fn=CustomEvalFn(), algo='alphabeta'):
# if you find yourself with a superior eval function, update the
# default value of `eval_fn` to `CustomEvalFn()`
self.eval_fn = eval_fn
self.search_depth = search_depth
self.algo = algo
self.time_limit = 2000
def move(self, game, legal_moves, time_left):
if self.algo == 'minimax':
best_move, best_queen, utility = self.minimax(game, time_left, depth=self.search_depth, maximizing_player=True)
elif self.algo == 'alphabeta':
best_move, best_queen, utility = self.alphabeta(game, time_left, depth=self.search_depth, maximizing_player=True)
else:
# iterative deepening and alpha beta pruning
move_dict = {}
# use array because minimax/alpha-beta pruning select the left most path
move_array = []
depth = 2
while time_left() > self.time_limit:
move, queen, utility = self.alphabeta(game, time_left, depth=depth, maximizing_player=True)
key = (move, queen)
if key in move_dict:
move_dict[key] += 1
else:
move_dict[key] = 1
move_array.append(key)
if move_dict[key] >= 4:
break
depth += 1
best_move = None
best_queen = None
select_count = 0
# move thru the array selecting the one with the highest count and the left most position
for key in move_array:
count = move_dict[key]
if select_count < count:
select_count = count
best_move, best_queen = key
return best_move, best_queen
def utility(self, game):
"""TODO: Update this function to calculate the utility of a game state"""
return self.eval_fn.score(game)
def minimax(self, game, time_left, depth=float("inf"), maximizing_player=True):
best_move = None
best_queen = None
moves = [(queen, move) for queen, legal_moves in game.get_legal_moves().iteritems() for move in legal_moves]
value_list = []
if depth == 1 or len(moves) == 0:
return best_move, best_queen, self.utility(game)
for queen, move in moves:
forecasted_game = game.forecast_move(move, queen)
_, _, val = self.minimax(forecasted_game, time_left, depth=(depth - 1), maximizing_player=(not maximizing_player))
value_list.append(val)
if maximizing_player:
index, best_val = max(enumerate(value_list), key=itemgetter(1))
else:
index, best_val = min(enumerate(value_list), key=itemgetter(1))
best_queen, best_move = moves[index]
return best_move, best_queen, best_val
def alphabeta(self, game, time_left, depth=float("inf"), alpha=float("-inf"), beta=float("inf"), maximizing_player=True):
best_move = (-1, -1)
best_queen = -1
move_dict = game.get_legal_moves()
moves = set(sum(move_dict.values(), []))
if depth == 1 or len(moves) == 0 or time_left() < self.time_limit:
return best_move, best_queen, self.utility(game)
if maximizing_player:
val = float('-inf')
for queen in move_dict:
for move in move_dict[queen]:
forecasted_game = game.forecast_move(move, queen)
_, _, next_val = self.alphabeta(forecasted_game, time_left, depth=(depth - 1),
alpha=alpha, beta=beta, maximizing_player=(not maximizing_player))
val = max(val, next_val)
if alpha < val:
alpha = val
best_move = move
best_queen = queen
if beta <= alpha:
break
return best_move, best_queen, val
else:
val = float('inf')
for queen in move_dict:
for move in move_dict[queen]:
forecasted_game = game.forecast_move(move, queen)
_, _, next_val = self.alphabeta(forecasted_game, time_left, depth=(depth - 1),
alpha=alpha, beta=beta, maximizing_player=(not maximizing_player))
val = min(val, next_val)
if beta > val:
beta = val
best_move = move
best_queen = queen
if beta <= alpha:
break
return best_move, best_queen, val
|
3f1246385d651ac33bcb31b8e7229b160aa569c4 | i0Ek3/PythonCrashCourse | /code/part1/20_while-2.py | 331 | 3.734375 | 4 | #!/usr/bin/env python
# coding=utf-8
# Let customer to select when to quit!
prompt = "\nWelcome to my world,please help youself enjoy!"
prompt += "\nJust fun!\n"
msg = ""
while msg != 'quit':
# msg = input(prompt) #python3
msg = raw_input(prompt) #python2
if msg != 'quit': #avoid to print 'quit'
print(msg)
|
85f40bd1070f3c7c171c270eafa4855f4bb01ff4 | p3t3r67x0/vigenere_cipher | /vigenere.py | 3,615 | 3.578125 | 4 | #!/usr/bin/env python
import re
import sys
import argparse
from argparse import RawTextHelpFormatter
def encrypt(text, key):
universe = [c for c in (chr(i) for i in range(32, 127))]
universe_length = len(universe)
plain_text = text.read().strip()
key_length = len(key)
cipher_text = []
key_text = key
for i, l in enumerate(plain_text):
if l not in universe:
cipher_text.append(l)
else:
text_index = universe.index(l)
k = key_text[i % key_length]
key_index = universe.index(k)
code = universe[(text_index + key_index) % universe_length]
cipher_text.append(code)
for i in re.finditer('\n', plain_text):
cipher_text[i.start()] = '\n'
return ''.join(cipher_text)
def decrypt(text, key):
universe = [c for c in (chr(i) for i in range(32, 127))]
universe_length = len(universe)
plain_text = text.read().strip()
key_length = len(key)
cipher_text = []
key_text = key
for i, l in enumerate(plain_text):
if l not in universe:
cipher_text.append(l)
else:
text_index = universe.index(l)
k = key_text[i % key_length]
key_index = universe.index(k)
code = universe[(text_index - key_index) % universe_length]
cipher_text.append(code)
for i in re.finditer('\n', plain_text):
cipher_text[i.start()] = '\n'
return ''.join(cipher_text)
def main():
parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter,
description='Encrypt or decrypt a vigenere cipher text',
epilog='''
And that's how you'd run this prgramm. You have multiple choices running this programm,
wether you like to read from STDIN or from FILE and wether you like to write to STDOUT
or to FILE. Here I will show you a few examples, how to proper use this programm. When
you want to decrypt a cipher text you can run the following example:
This will decrypt and write the cipher text to STDOUT and read the plain text from STDIN.
echo '<intext>' | ./vigenere.py -d -k <key> -o - -i -
This will encrypt and write the cipher text to STDOUT and read the plain text from FILE.
./vigenere.py -e -k <key> -o - -i <infile>
This will decrypt and write the cipher text to FILE and read the plain text from FILE.
./vigenere.py -d -k <key> -o <outfile> -i <infile>
''')
parser.add_argument('-d, --decrypt', dest='decrypt', action='store_true',
help='set flag to decrypt given cipher text')
parser.add_argument('-e, --encrypt', dest='encrypt', action='store_true',
help='set flag to encrypt given plain text')
parser.add_argument('-k, --key', required=True, dest='key',
help='set key as argument, this is required')
parser.add_argument('-i, --in', metavar='INPUT', nargs='?', dest='input', type=argparse.FileType('r'),
default=sys.stdin, help='string from stdin or from file')
parser.add_argument('-o, --out', metavar='OUTPUT', nargs='?', dest='output', type=argparse.FileType('w'),
default=sys.stdout, help='result defaults to stdout or specify a file')
args = parser.parse_args()
if args.encrypt:
value = encrypt(args.input, args.key)
args.output.write(value)
elif args.decrypt:
value = decrypt(args.input, args.key)
args.output.write(value)
if __name__ == '__main__':
main()
|
7776b986b5893143c746d42e99974ffda823e91e | InfiniteWing/Solves | /zerojudge.tw/d329.py | 223 | 3.734375 | 4 | def Reverse(n):
c=0
while(n>0):
c=c*10
c+=n%10
n=int((n-n%10)/10)
return c
n=int(input())
for i in range (n):
s=input()
data=s.split()
a1=int(data[0])
a2=int(data[1])
print(Reverse(Reverse(a1)+Reverse(a2))) |
7bdf76de21aabf775c6e98b3af285294306c76ee | horacepan/ProjectEuler | /primes.py | 1,492 | 3.90625 | 4 | import math
# return all primes up to n
def populatePrimes( n ):
primes = [2,3,5]
if n < 2:
return
else:
index = 1
while (6*index + 1) <= n:
upperBoundA = int(math.sqrt(6*index+1)) + 1
upperBoundB = int(math.sqrt(6*index+1)) + 1
isPrimeA = True
isPrimeB = True
for prime in primes:
if prime > upperBoundA:
break
if (6*index+1) % prime == 0:
isPrimeA = False
break
for prime in primes:
if prime > upperBoundB:
break
if (6*index+5) % prime == 0:
isPrimeB = False
break
if isPrimeA:
primes.append(6*index+1)
if isPrimeB:
primes.append(6*index+5)
index += 1
return primes
# max = how high to populate, primes = list of all primes up to max
def primeFactorize( max, primes ):
pFactorizations = {}
for n in range(2, max + 1):
if n in primes:
pFactorizations[ n ] = { n: 1}
for i in range(2, int(math.sqrt(n) + 1)):
#print i, n
#print pFactorizations
if n%i == 0:
factorization = pFactorizations[ n/i ].copy() # might not be correct?
if i in factorization:
factorization[ i ] = factorization[ i ] + 1
else:
factorization[ i ] = 1
pFactorizations[ n ] = factorization
break
#pFactorization = prime factorization dict, div = dict to populate
def getDivisors( pFactorization ):
div = {}
for k, v in pFactorization.iteritems():
product = 1
for a, b in v.iteritems():
num = a**(b+1) - 1
den = a-1
product *= num/den
div[ k ] = product - k
|
06333996667b175122aa94f564044c7893726b8a | StudyForCoding/BEAKJOON | /05_Practice1/Step06/gamjapark.py | 720 | 3.890625 | 4 | n = int(input())
for i in range(n):
if n % 2 == 0: #짝수
for j in range(n - 1):
if j % 2 == 0:
print("*", end="")
else:
print(" ", end="")
print()
for j in range(n):
if j % 2 == 0:
print(" ", end="")
else:
print("*", end="")
print()
else: #홀수
for j in range(n):
if j % 2 == 0:
print("*", end="")
else:
print(" ", end="")
print()
for j in range(n - 1):
if j % 2 == 0:
print(" ", end="")
else:
print("*", end="")
print() |
e8543815a822dcc21b4c502dd1c46e2482929af0 | seriousbee/UCL-Classifier | /src/simple_classifier/Classifier.py | 1,177 | 4.0625 | 4 | # represents a classifier system - it has a list of clusters, is able to create the clusters, and allocate an unknown
# sentence to one of the clusters
__all__ = ["Classifier"]
class Classifier:
def __init__(self, clusters):
self.__clusters = clusters
def classify(self, sentence):
max_value = 0
max_cluster = ""
for cluster in self.__clusters:
value = cluster.rate_new_sentence(sentence)
if value > max_value:
max_value = value
max_cluster = cluster.name
return max_cluster
# test data is a list of tuples - sentence and the correct outcome
def test(self, test_data):
total = 0.0
correct = 0
for test_case in test_data:
total += 1
result = self.classify(test_case[0])
if result == test_case[1]:
print("Passed: " + test_case[0] + " correctly identified as " + test_case[1])
correct += 1
else:
print("Failed: " + test_case[0] + " identified as " + result + ", instead of " + test_case[1])
print("Success rate: " + str(correct/total)) |
f0912b7a2d7b133988cef0ebf1c61e44d7cef943 | erauner12/python-scripting | /Linux/Python_Crash_Course/chapter_code/chapter_04_working_lists/reference/squares.py | 435 | 4.4375 | 4 |
# ** means to the power of
# so this function will multiply every number between one and ten by the power of 2 and assign that value to every the next item in the list
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
# using list comprehension, we can insert the values of the expression "value**2" directly into the list squares
squares2 = [value**2 for value in range(1, 11)]
print(squares2)
|
82d71ff20fab238d636455f1811b3a5386f3216e | arabindamahato/personal_python_program | /programming_class_akshaysir/palindrome.py | 521 | 4.125 | 4 |
'''Very easy method'''
''' By checking reverse number and main number if the number is same then it is palindrome'''
print('To reverse the given no')
n=(input('Enter your no : '))
m=int(n)
o=n[::-1]
p=int(o)
if m==p:
print(' palindrome')
else:
print(' not a Palindrome')
'''Another method'''
# n=12321
# m=n
# rev=0
# while n!=0:
# ld=n%10
# n=n//10
# rev=rev*10+ld
#
# if m==rev:
# print(' palindrome')
# else:
# print(' not a Palindrome')
'''Another method'''
|
30960dccfab807b8c067fe51da2f9a384d526fc6 | eamaccready/STP_Exercises | /python_scripts/interit_square.py | 393 | 4 | 4 | # Inheritance way.
class Rectangle():
def __init__(self, l, w):
self.length =l
self.width = w
def calculate_perimeter(self):
return 2 * (self.length + self.width)
class Square(Rectangle):
def calculate_perimeter(self):
return 4* self.length
r1 = Rectangle(3,6)
s1 = Square(4,4,)
print(r1.calculate_perimeter())
print(s1.calculate_perimeter())
|
e73500ca12e64dd1fb28043b804239c15cc25327 | MayWorldPeace/QTP | /Python基础课件/代码/第七天的代码/hm_sum.py | 711 | 3.515625 | 4 | # 如果一个模块中使用了__all__
# 只用在__all__的列表中的字符串才可以在其他模块中使用
# 条件 其他模块必须是通过from 模块名 import * 方式导入的模块
__all__ = ["name"]
# 全局变量
name = "加法运算"
# 函数
def add2num(a, b):
return a + b
# 类
class Person(object):
def eat(self):
print("人会吃饭")
# git 或者是 svn -> 远程仓库
# 在自己定义一个模块中 进行自测 (程序员做的事情)
# 定义一个函数 -> 自测函数
def main():
print(name)
ret = add2num(10, 20)
print(ret)
p = Person()
p.eat()
# __name__ = __main__
# print(__name__)
if __name__ == '__main__':
main() |
a1d75a44545c3953aa3facd0deaf80a0321f8ef7 | mazuralexey93/python_faculty | /05102020/hw4.py | 1,344 | 4.4375 | 4 | """
Программа принимает действительное положительное число x и целое отрицательное число y.
Необходимо выполнить возведение числа x в степень y.
Задание необходимо реализовать в виде функции my_func(x, y).
При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
Подсказка: попробуйте решить задачу двумя способами.
Первый — возведение в степень с помощью оператора **.+
Второй — более сложная реализация без оператора **, предусматривающая использование цикла.+
"""
def my_func():
"""returns the result of raising to a negative power"""
global x , y
x = float(input('enter float: '))
y = int(input('enter negative integer: '))
return x**y
def my_func_2():
global x, y
result = 1
x = float(input('enter float: '))
y = int(input('enter negative integer: '))
for i in range(abs(y)):
result *= x
return 1 / result
print(my_func())
print(my_func_2())
|
6608e2579cbe6bba83fcdfa8a737d76c62cae374 | rupam-87/data-structure--recursion | /basepow.py | 164 | 3.6875 | 4 | def power(n,e):
if e==1:
return n
else:
p=n*power(n,e-1)
return p
n=int(input())
e=int(input())
k=power(n,e)
print(k)
|
d2af1c60034d9e4c0c77dbcd1ef2ed24fbe22488 | vaishnavi-rajagopal/Python_Code | /Exercise/matrixinverse.py | 493 | 3.90625 | 4 | ###Q3 -2 Grading Tag
matrix_inp = input("Please enter four numbers seperated by spaces : ")
matrix_list=matrix_inp.split()
if(len(matrix_list)==4):
a=float(matrix_list[0])
b=float(matrix_list[1])
c=float(matrix_list[2])
d=float(matrix_list[3])
matrix_tup=((a,b),(c,d))
print("Matrix:"+ str(matrix_tup))
x=(1/((a*d)-(b*c)))
a1=d*x
b1=-b*x
c1=-c*x
d1=a*x
inverse_tup=((a1,b1),(c1,d1))
print("Inverse:"+str(inverse_tup))
else:
print("Please enter 4 numbers seperated by spaces") |
991ef3aa7d9f6f306c25835ee5e597622e8e26cd | joaovlev/estudos-python | /Desafios/Mundo 3/desafio082.py | 595 | 3.75 | 4 | lista = []
lista_pares = []
lista_impares = []
while True:
numero = int(input('Digite um valor: '))
lista.append(numero)
if numero % 2 == 0:
lista_pares.append(numero)
else:
lista_impares.append(numero)
confirmacao = input('Deseja continuar ? ').upper()
if confirmacao in ['SIM', 'S']:
continue
if confirmacao in ['NÃO', 'NAO', 'N']:
print(f'Lista com os valores: {lista}')
print(f'Lista com os valores pares digitados: {lista_pares}')
print(f'Lista com os valores ímpares digitados: {lista_impares}')
break
|
11d2676e4b82e12b9c6a96ea79d8c9007c1bbe69 | gschen/sctu-ds-2020 | /1906101015-胡金注/homework1/1.py | 197 | 3.53125 | 4 | x = int(input())
wrong_nums = [1,10,20,30,40,50]
def JC(x):
if x == 0:
return 1
else:
return x*JC(x-1)
if x in wrong_nums:
print('wrong num')
else:
print(JC(x))
|
c4042b95934bb1585298d8c1180ebe3d64825d2f | odin2350/PCC | /Chapter 4.py | 5,162 | 4.125 | 4 | magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title())
magicians = ['alice', 'lavid', 'carolina']
for magician in magicians:
print((magician.title()) + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
magicians = ['alice', 'lavid', 'carolina']
for magician in magicians:
print((magician.title()) + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
print("Thank you, everyone. That was a great magic show!")
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
print("Thank you everyone, that was a great magic show!")
# Try it yourself
# 4-1 Pizza
pizzas = ['meat lover', 'mushroom', 'buffalo chicken']
for pizza in pizzas:
print("My favorite pizza is " + pizza.title() + " pizza!!!")
print("I love pizza so so much!!!")
# 4-2 Animals
animals = ['mouse', 'dog', 'cat']
for animal in sorted(animals):
print(animal)
animals = ['mouse', 'dog', 'cat']
for animal in sorted(animals):
print(animal.title() + ' would make a great pet.')
print('All this animals that I lived with lol')
for value in range(1,5):
print(value)
numbers = list(range(1,6))
print(numbers)
even_numbers = list(range(2,11,2))
print(even_numbers)
squares = []
for value in range(1,13):
squares.append(value**2)
print(squares)
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits)
max(digits)
z=sum(digits)
print(min(digits))
print('Summery: ' + str(z))
squares = [value**2 for value in range(1,11)]
print(squares)
z = [value/2 for value in range(2,17,2)]
print(z)
print('\n')
# Try it yourself
# 4-3 Counting to Twenty:
numbers = [number for number in range(1,21)]
print(numbers)
print('\n')
# 4-4 One million(100)
numbers = [number for number in range(1,101)]
print(numbers)
print('\n')
# 4-5. Summing a Million(100)
numbers = [number for number in range(1,101)]
print(numbers)
print('Minimum ' + str(min(numbers)))
print('Maximum ' + str(max(numbers)))
print('Summary ' + str(sum(numbers)))
print('\n')
# 4-6. Odd Numbers
for number in range(1,21,2):
print(number)
numbers = [number for number in range(1,21,2)]
print(numbers)
print('\n')
# 4-7. Threes
for tree in range(3,30):
print(tree*3)
trees = [tree*3 for tree in range(3,30)]
print(trees)
print('\n')
# 4-8 Cubes
for cube in range(1,11):
print(cube**3)
print('\n')
cubes = [cube**3 for cube in range(1,11)]
print(cubes)
# Working with Part of a List
print('\n')
print('\n')
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print('\n')
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])
# slicing specific players from the list of players
players = ['charles', 'martina', 'michael', 'florence', 'eli']
for player in players[0:3]:
print(player)
# slicing specific players from the list of players into a new list of new_players
new_players = [player for player in players[:3]]
print(new_players)
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
print('\n')
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
# Try it yourself
# 4-10 Slices
numbers = [number for number in range(1,21,2)]
print(numbers)
print("The first 3 items in the list are " + str(numbers[:3]))
middle = max(numbers)/min(numbers)
print("item from the middle of the range is " + str(middle))
print("Some from the middle " + str(numbers[4:-3]))
print("The last 3 items in the list are " + str(numbers[-3:]))
# 4-11. My Pizzas, Your Pizzas
pizzas = ['meat lover', 'mushroom', 'buffalo chicken']
friends_pizzas = pizzas[:]
pizzas.append('cheesy')
friends_pizzas.append("herring")
print("\nMy favorite pizzas are: ")
for pizza in pizzas:
print(str(pizza) + " pizza.")
print("\nMy friend’s favorite pizzas are: ")
for pizza in friends_pizzas:
print("\t" + str(pizza) + " pizza.\n")
# Tuples
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
print('\n')
print('\n')
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
print('\n')
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
print('\n')
# Try it yourself
# 4-13 Buffet
buffet = ('rice', 'pasta', 'mashed potatoes', 'grilled chicken', 'mushrooms')
for food in sorted(buffet, reverse = True):
print(food)
print('\n')
print(sorted(buffet))
print('\n')
buffet= ('avocado', 'french fries', 'rice', 'pasta', 'mashed potatoes', 'grilled chicken', 'mushrooms')
for food in sorted(buffet):
print(food)
print('\n')
|
d3991b71a8db90d43cc6dba3185948ace4760634 | HemantDeshmukh96/Message-Encruption-Toolkit-Ceaser-Cipher- | /Ceaser Cipher.py | 565 | 3.96875 | 4 | def main( ):
valid=True
while valid:
key=int(input("Enter the key between(1-25) :"))
if key>25:
valid=True
else:
valid=False
return key
def encrupt(key):
inp=input("Enter the Messege to be Encrupted :")
string=inp.upper()
for ch in string:
ch1=ord(ch)
if ch1==32:print(" ",end="")
else:
base=ch1+key
if base>90:
base=base-26
encrup=chr(base)
print(encrup,end="")
x=main( )
encrupt(x) |
0698e5040002d77eba6fcce2e17cc48caec923fc | IonatanSala/Python | /built_in_functions/bin.py | 136 | 3.640625 | 4 | # bin(x)
# this converts an integer number to a binary string.
my_binary_string = bin(100)
print(my_binary_string) # prints: 0b1100100 |
ec83c3c96acdcc049a2a25c6e1cbc51754568b8b | aquib-sh/classic-cs-problems | /iter_fib.py | 335 | 4.0625 | 4 | # Solves fibonacci iteratively
def fib(n: int) -> int:
if n == 0 : return n
last: int = 0 # last num
next: int = 1 # next num
for _ in range(1, n):
temp = last
last = next
next = temp + next
return next
if __name__ == "__main__":
n = int(input("Enter a number: "))
print(fib(n))
|
855892c5da60c094207f7850af7dd137bf11d252 | IrenaVent/pong | /game.py | 5,145 | 3.515625 | 4 | import pygame as pg
from random import randrange
SIZE = (800,600) # we decided no parmetric screen
class Movil(): #la clase padre, IMPORTANTE de ellas heredan el resto
def __init__(self, x, y, w, h, color=(255,255,255)):
self.x = x
self.y = y
self.w = w
self.h = h
self.color = color
@property
def izquierda(self):
return self.x
@izquierda.setter
def izquierda(self,valor):
self.x = valor
@property
def derecha(self):
return self.x + self.w
@derecha.setter
def derecha (self, valor):
self.x = valor - self.w
@property
def arriba(self):
return self.y
@arriba.setter
def arriba(self, valor):
self.y = valor
@property
def abajo(self):
return self.y + self.h
@abajo.setter
def abajo(self, valor):
self.y = valor - self.h
def actualizate(self):
pass
def procesa_eventos(self, lista_eventos=[]):
pass
def dibujate(self, lienzo):
pg.draw.rect(lienzo, self.color, pg.Rect(self.x, self.y, self.w, self.h))
class Raqueta(Movil):
def __init__(self, x, y, color=(255,255,255)):
Movil.__init__(self, x, y, 20, 120, color) #esto es lo mismo que ...otra manera de escribirlo
self.tecla_arriba = pg.K_UP # tecla_arriba será K_UP por defecto
self.tecla_abajo = pg.K_DOWN # tecla_abajo será K_DOWN por defecto
def procesa_eventos(self, lista_eventos=[]):
if pg.key.get_pressed()[self.tecla_arriba]:
self.y -= 5
if self.arriba <= 0:
self.arriba = 0
if pg.key.get_pressed()[self.tecla_abajo]:
self.y += 5
if self.abajo >= SIZE[1]:
self.abajo = SIZE[1]
class Bola(Movil):
def __init__(self, x, y, color=(255,255,255)):
super().__init__(x, y, 20, 20, color) #esto es lo mismo que ... otra manera de escribirlo
self.swDerecha = True
self.swArriba = True
# self.incremento_x = 5
# self.incremento_y = 5
def actualizate(self):
# movement X (left - right)
if self.swDerecha:
self.x += 5
else:
self.x -= 5
if self.derecha >= SIZE [0]: # if self.x + self.w >= SIZE [1]
self.swDerecha = False
if self.izquierda <= 0:
self.swDerecha = True
# movemnent Y (up - down)
if self.swArriba:
self.y -= 5
else:
self.y += 5
if self.abajo >= SIZE [1]: # if self.y + self.h >= SIZE [1]
self.swArriba = True
if self.arriba <= 0:
self.swArriba = False
# solución MON
# self.x += self.incremento_x
# self.y += self.incremento_y
# if self.x + self.w > SIZE [0] or self.x < 0:
# self.incremento_x *= -1
# if self.y + self.h > SIZE [1] or self.y < 0:
# self.incremento_y *= -1
def comprobar_choque(self, algo):
return self.derecha >= algo.izquierda and self.izquierda <= algo.derecha and \
self.abajo >= algo.arriba and self.arriba <= algo.abajo
class Game(): # el bucle principal lo convertimos en una clase
def __init__(self):
self.pantalla = pg.display.set_mode((SIZE))
self.reloj = pg.time.Clock()
self.todos = []
self.player1 = Raqueta (10, (SIZE[1]-120) //2)
self.player1.tecla_arriba = pg.K_w #sólo para player1, player dos utiliza K_UP/DOWN - y es en la calse donde se le asigna el valor K_UP
self.player1.tecla_abajo = pg.K_s #sólo para player1, player dos utiliza K_UP/DOWN - y es en la calse donde se le asigna el valor K_DOWN
self.player2 = Raqueta (SIZE[0]-30, (SIZE[1]-120) //2)
self.todos.append(self.player1)
self.todos.append(self.player2)
self.bola = Bola(SIZE[0] // 2 - 10, SIZE[1] // 2 - 10, (255, 255, 0))
self.todos.append(self.bola)
def bucleppal(self):
game_over = False
pg.init()
while not game_over:
self.reloj.tick(60)
eventos = pg.event.get()
for evento in eventos:
if evento.type == pg.QUIT:
game_over = True
for movil in self.todos:
movil.procesa_eventos()
if self.bola.comprobar_choque(self.player1) or self.bola.comprobar_choque(self.player2):
self.bola.swDerecha = not self.bola.swDerecha
for movil in self.todos:
movil.actualizate()
self.pantalla.fill((0, 0, 0))
for movil in self.todos:
movil.dibujate(self.pantalla)
pg.display.flip()
pg.quit()
if __name__ == "__main__": # para que no lo ejecute el programa si lo llamamos desde otro archivo
juego = Game() #instanciar la clase
juego.bucleppal() #llamar al método de la calse Game de la instancia juego
|
6a449cbb00c0fadedda2a9be80df8eb0324a56ac | AlyMetwaly/python-scripts | /miscellaous/recur_fibo.py | 238 | 4.125 | 4 | num = int(input())
def fibonacci(n):
if n<=1:
return n
else:
return (fibonacci(n-1) + fibonacci(n-2))
if num <= 0:
print("Plese enter a positive integer")
else:
for i in range(num):
print(fibonacci(i))
|
2267b84aa2844b68f333e9795ee0bdc487762fdb | ranzhongsi/dacangku | /jieyue2.py | 234 | 3.609375 | 4 | """
阶跃信号
"""
import numpy as np
import matplotlib.pyplot as plt
#定义阶跃信号
def unit(t):
r=np.where(t>0.0,1.0,0.0)
return r
t=np.linspace(-1.0,3.0,1000)
plt.ylim(-1.0,3.0)
plt.plot(t,unit(t))
plt.show() |
6888804b0964f62d7b0d8aa48584e57f3ffce6af | Shaileshsachan/ds_algo | /array.py | 610 | 3.90625 | 4 | numbers = [10, 20, 30, 40, 50]
print(numbers[0])
numbers[1] = 'shailesh'
print(numbers)
for _ in numbers:
print(_)
max = numbers[0]
for num in numbers:
if num > max:
max = num
print(max)
from array import *
print(dir(array))
array1 = array('i', [10, 20, 30, 40, 50])
for i in array1:
print(i)
print(array1[0])
print(array1[2])
array1.insert(8, 60)
array1.insert(-1, 70)
print(array1)
for i in array1:
print(i)
array1 = array('i', [10, 20, 30, 40, 50])
array1.remove(40)
for i in array1:
print(i)
print(array1.index(50))
array1[3] = 100
for i in array1:
print(i)
|
92233569bb3136afc58a5e8f4f213702eea2fab2 | Jorgepastorr/m03 | /python/entregas/19-5-17/calendario-de-año.py | 1,570 | 3.953125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import calendar
def mi_rango(inicio,final,incremento):
if inicio <= final :
while inicio <= final :
yield inicio
inicio = inicio + incremento
else:
while inicio >= final :
yield inicio
inicio = inicio - incremento
#############3
anyo=input("Indica el año: ")
mes =1
cont = 1
meses={1:"Enero",2:"Febrero",3:"Marzo",4:"Abril",5:"Mayo",6:"Junio",7:"Julio",8:"Agosto",9:"Septiembre",10:"Octubre",11:"Noviembre",12:"Diciembre"}
for vuelta in mi_rango(1,12,1):
# da la totalidad de días que tiene ese mes en ese año
fin_dias_mes=calendar.monthrange(anyo, mes)[1]
#~ da el día de la semana que empieza el mes de lunes a domingo en 1 - 7
inicio_dia_semana=(calendar.weekday(anyo,mes,1))+1
print meses[mes]
for fila in mi_rango(1,7,1):
for columna in mi_rango(1,7,1):
if (fila == 1 ):
if columna == 1 :
print "L ",
if columna == 2 :
print "M ",
if columna == 3 :
print "X ",
if columna == 4 :
print "J ",
if columna == 5 :
print "V ",
if columna == 6 :
print "S ",
if columna == 7 :
print "D ",
elif ( fila == 2 ):
if (inicio_dia_semana <= columna ):
print cont,"",
cont=cont+1
else:
print " ",
elif ( cont <= fin_dias_mes ):
####### solo para que quede bonito.
if cont < 10 :
print cont,"",
cont=cont+1
#################
else:
print cont,
cont=cont+1
else:
print " ",
print " "
print ""
mes=mes+1
cont=1
#####################
|
9107adea45514d778f40708a4f0e4983cc49424e | DenKarlos/ITC_Bootcamp_classes_2 | /classes_2_5-7slide.py | 3,284 | 3.65625 | 4 | # 3)Car
# Создайте класс Car. Пропишите в конструкторе параметры make, model, year,
# odometer, fuel. Пусть у показателя odometer будет первоначальное значение 0,
# а у fuel 70. Добавьте метод drive, который будет принимать расстояние в км. В
# самом начале проверьте, хватит ли вам бензина из расчета того, что машина
# расходует 10 л / 100 км (1л - 10 км) . Если его хватит на введенное расстояние,
# то пусть этот метод добавляет эти километры к значению одометра, но не
# напрямую, а с помощью приватного метода __add_distance. Помимо этого
# пусть метод drive также отнимет потраченное количество бензина с помощью
# приватного метода __subtract_fuel, затем пусть распечатает на экран “Let’s
# drive!”. Если же бензина не хватит, то распечатайте “Need more fuel, please, fill
# more!”
class Car:
# , make, model, year, odometer, fuel
def __init__(self):
self.make = ''
self.model = ''
self.year = ''
self.odometer = 0
self.fuel = 70
def __add_distance(self, distance):
self.odometer += distance
def __subtract_fuel(self, distance):
self.fuel -= distance / 10
def drive(self, distance):
if self.fuel * 10 >= distance:
print("Let’s drive!")
self.__add_distance(distance)
self.__subtract_fuel(distance)
else:
print("Need more fuel, please, fill more!")
BMW = Car()
BMW.drive(1000)
BMW.drive(696)
BMW.drive(10)
# 4)ContactList
# Создайте класс ContactList, который должен наследоваться от
# встроенного класса list. В нем должен быть реализован метод
# search_by_name, который должен принимать имя, и возвращать список
# всех совпадений. Замените all_contacts = [ ] на all_contacts =
# ContactList(). Создайте несколько контактов, используйте метод
# search_by_name.
class ContactList(list):
def search_by_name(self, name):
result = []
for i in self:
if i == name:
result.append(i)
return result
all_contacts = ContactList()
all_contacts += ['Vasya', 'Petya', 'Erbol', 'Nurdoolot', 'Apolinarij']
all_contacts.append('Vasya')
print(all_contacts)
print(all_contacts.search_by_name('Vasya'))
# 5)AK-47
# Soldier Ryan has an AK47
# Soldiers can fire ("tigi-tigitishh").
# Guns can fire bullets.
# Guns can fill bullets - increase the number of bullets(reloads)
# Create class Act_of_Shooting, which will inheritates from class Soldier, class Guns.
# Where soldier will fire from a gun and reload, and fire one more time.
class AK47:
def fire(self):
print('tigi-tigitishh')
|
c7f71314f3be062c920b07e9cbc529f25e665968 | christinang89/baboon | /1-5.py | 567 | 3.578125 | 4 | import string
input = "aabccccaaa"
def compress(st):
if len(st) <= 1:
return st
first = 0
last = first+1
result = ""
for i in xrange(len(st)):
if last >= len(st):
result += st[first]
result += str(last-first)
elif st[last] != st[first]:
result += st[first]
result += str(last-first)
first = last
last += 1
else:
last += 1
if len(result) >= len(st):
return st
else:
return result
print compress(input)
|
2816ee1a44c3e84af73955e455f08db5a2a24517 | TheBitShepherd/pygame | /example_programs/snoflakes1.py | 2,378 | 3.6875 | 4 | import pygame
import random
# COLORS
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0 , 255)
COLORS = [RED, GREEN, BLUE]
def randColor():
return COLORS[random.randrange(len(COLORS))]
# SCREEN
WIDTH = 600
HEIGHT = 600
class Snowflake:
def __init__(self, x, y, size):
self.x = x
self.y = y
self.size = size
def __iter__(self):
return self
def move(self):
self.y += self.size
if(self.y > HEIGHT):
self.y = -10
self.x = random.randrange(0, WIDTH)
def render(self, screen):
pygame.draw.circle(screen, WHITE, [self.x, self.y], self.size)
def main():
pygame.init()
# SCREEN SIZE
size = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Snowflakes! ZOMG!")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
NUM_FLAKES = 500;
snowflakes = []
for i in range(NUM_FLAKES):
x = random.randrange(0, WIDTH)
y = random.randrange(0, HEIGHT)
MIN_FLAKE_SIZE = 1
MAX_FLAKE_SIZE = 5
size = random.randrange(MIN_FLAKE_SIZE, MAX_FLAKE_SIZE)
flake = Snowflake(x, y, size)
snowflakes.append(flake)
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic should go here
# --- Screen-clearing code goes here
# Here, we clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# If you want a background image, replace this clear with blit'ing the
# background image.
screen.fill(BLACK)
for flake in snowflakes:
flake.render(screen)
flake.move()
# --- Drawing code should go here
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
# Close the window and quit.
pygame.quit()
if __name__ == "__main__":
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.