blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
4eccc46ac6a27ed06c52a9f96d689e424b2fc5d8 | aandr26/Learning_Python | /Coursera/Week4/Week4b/Project/project_template.py | 6,920 | 4 | 4 | # Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT = True
SCORE_SIZE = 50
ball_pos = [WIDTH / 2, HEIGHT / 2]
ball_vel = [1, 1]
paddle1_pos = 150
paddle2_pos = 150
paddle1_vel = 0
paddle2_vel = 0
score1 = 0
score2 = 0
# initialize ball_pos and ball_vel for new bal in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
''' This function starts the initial movement of the ball in the game,
by randomly assigning a velocity to the ball '''
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH / 2, HEIGHT / 2]
ball_vel = [1,1]
if direction == RIGHT:
ball_vel= [random.randrange(120, 240)/60, random.randrange(-180, -60)/60]
if direction == LEFT:
ball_vel = [random.randrange(-240, -120)/60, random.randrange(60, 180)/60]
# define event handlers
def new_game():
''' Starts a new game, and resets everything '''
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers
global score1, score2 # these are ints
score1 = 0
score2 = 0
spawn_ball(LEFT)
# draw the game
def draw(canvas):
''' This function draws all the required simplegui canvas objects,
and contians the logic for reflecting the ball of the walls and paddles and scoring. '''
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel
# draw mid line and gutters
canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
# left gutter line
canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
# right gutter line
canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# update ball
if (
(ball_pos[0] <= (WIDTH - PAD_WIDTH) - BALL_RADIUS) or
(ball_pos[0] >= (PAD_WIDTH + BALL_RADIUS)) or
(ball_pos[1] <= BALL_RADIUS) or
(ball_pos[1] >= HEIGHT - BALL_RADIUS)
):
ball_pos[1] += ball_vel[1]
ball_pos[0] += ball_vel[0]
# collide and reflect off of left hand side of canvas
if (ball_pos[0] <= (PAD_WIDTH + BALL_RADIUS)):
if (ball_pos[1] >= (paddle1_pos - HALF_PAD_HEIGHT)) and (ball_pos[1] <= (paddle1_pos + HALF_PAD_HEIGHT)):
area1a = paddle1_pos - HALF_PAD_HEIGHT
area2a = paddle1_pos + HALF_PAD_HEIGHT
print("I hit the left paddle " + str(ball_pos[1]))
print(str(area1a) + " " + str(area2a))
print("")
ball_vel[0] = - ball_vel[0]
ball_vel[1] += .10
ball_vel[0] += .10
else:
area1a = paddle1_pos - HALF_PAD_HEIGHT
area2a = paddle1_pos + HALF_PAD_HEIGHT
print("I hit the left side " + str(ball_pos[1]))
print("I missed")
print(str(area1a) + " " + str(area2a))
print("")
score2 += 1
spawn_ball(RIGHT)
# collide and reflect off of right hand side of canvas
if (ball_pos[0] >= (WIDTH - PAD_WIDTH) - BALL_RADIUS):
if (ball_pos[1] >= (paddle2_pos - HALF_PAD_HEIGHT)) and (ball_pos[1] <= (paddle2_pos + HALF_PAD_HEIGHT)):
area1b = paddle2_pos - HALF_PAD_HEIGHT
area2b = paddle2_pos + HALF_PAD_HEIGHT
print("I hit the right paddle " + str(ball_pos[1]))
print(str(area1b) + " " + str(area2b))
print("")
ball_vel[0] = - ball_vel[0]
ball_vel[1] += .10
ball_vel[0] += .10
else:
area1b = paddle2_pos - HALF_PAD_HEIGHT
area2b = paddle2_pos + HALF_PAD_HEIGHT
print("I hit the right side " + str(ball_pos[1]))
print("I missed")
print(str(area1b) + " " + str(area2b))
print("")
score1 += 1
spawn_ball(LEFT)
# collide and reflect off of top of canvas
if ball_pos[1] <= BALL_RADIUS:
ball_vel[1] = - ball_vel[1]
# collide and reflect off of bottom of canvas
elif ball_pos[1] >= HEIGHT - BALL_RADIUS:
ball_vel[1] = - ball_vel[1]
# draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
# update paddle's vertical position, keep paddle on the screen
paddle1_pos += paddle1_vel
paddle2_pos += paddle2_vel
# keep paddle 1 - left paddle - on screen
if paddle1_pos <= 1:
paddle1_pos = 0
if paddle1_pos >= (400 - PAD_HEIGHT):
paddle1_pos = (400 - PAD_HEIGHT)
# keep paddle 2 - right paddle - on screen
if paddle2_pos <= 1:
paddle2_pos = 0
if paddle2_pos >= (400 - PAD_HEIGHT):
paddle2_pos = (400 - PAD_HEIGHT)
# draw paddles
# paddle 1 - left paddle
canvas.draw_polygon([(PAD_WIDTH - PAD_WIDTH/2, paddle1_pos),(PAD_WIDTH/2, PAD_HEIGHT + paddle1_pos)], 8, "White")
# paddle 2 - right paddle
canvas.draw_polygon([(WIDTH - PAD_WIDTH + PAD_WIDTH/2, paddle2_pos),(WIDTH - PAD_WIDTH + PAD_WIDTH/2, PAD_HEIGHT + paddle2_pos)], 8, "White")
# determine whether paddle and ball collide
# draw scores
canvas.draw_text(str(score1), [WIDTH/2 - SCORE_SIZE, HEIGHT/8], SCORE_SIZE, "White")
canvas.draw_text(str(score2), [WIDTH/2 + SCORE_SIZE/2, HEIGHT/8], SCORE_SIZE, "White")
# control the game: movement
def keydown(key):
''' This function captures the pressing of the keys 'w','s','up', and 'down' on the keyboard
and moves paddles based on the key pressed '''
global paddle1_vel, paddle2_vel
# paddle 1 - left paddle
if key == simplegui.KEY_MAP["w"]:
paddle1_vel -= 6
if key == simplegui.KEY_MAP["s"]:
paddle1_vel += 6
# paddle 2 - right paddle
if key == simplegui.KEY_MAP["up"]:
paddle2_vel -= 6
if key == simplegui.KEY_MAP["down"]:
paddle2_vel += 6
# control the game: stop movement
def keyup(key):
''' This function captures the releasing of the keys 'w','s','up', and 'down' on the keyboard
and stops the movement of the paddles based on the key released '''
global paddle1_vel, paddle2_vel
if key == simplegui.KEY_MAP["up"]:
paddle2_vel = 0
if key == simplegui.KEY_MAP["down"]:
paddle2_vel = 0
if key == simplegui.KEY_MAP["w"]:
paddle1_vel = 0
if key == simplegui.KEY_MAP["s"]:
paddle1_vel = 0
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
restart = frame.add_button("Restart Game", new_game, 75)
# start frame
new_game()
frame.start()
|
f63968e54881348076c5bb054c0ef006a570406d | w940853815/my_leetcode | /medium/209.长度最小的子数组.py | 1,622 | 3.578125 | 4 | #
# @lc app=leetcode.cn id=209 lang=python3
#
# [209] 长度最小的子数组
#
# https://leetcode-cn.com/problems/minimum-size-subarray-sum/description/
#
# algorithms
# Medium (44.78%)
# Likes: 536
# Dislikes: 0
# Total Accepted: 109.7K
# Total Submissions: 244.7K
# Testcase Example: '7\n[2,3,1,2,4,3]'
#
# 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的 连续
# 子数组,并返回其长度。如果不存在符合条件的子数组,返回 0。
#
#
#
# 示例:
#
# 输入:s = 7, nums = [2,3,1,2,4,3]
# 输出:2
# 解释:子数组 [4,3] 是该条件下的长度最小的子数组。
#
#
#
#
# 进阶:
#
#
# 如果你已经完成了 O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。
#
#
#
from typing import List
# @lc code=start
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
l, r = 0, 0
res = len(nums)
flag = False
if not nums:
return 0
while r < len(nums):
r += 1
while(sum(nums[l:r]) >= s):
# print(nums[l:r], sum(nums[l:r]), s)
# print(min(len(nums[l:r]), res), len(nums[l:r]), res)
res = min(len(nums[l:r]), res)
l += 1
flag = True
return res if flag else 0
# @lc code=end
if __name__ == '__main__':
s = Solution()
# res = s.minSubArrayLen(7, [2, 3, 1, 2, 4, 3])
# 15 [5,1,3,5,10,7,4,9,2,8]
res = s.minSubArrayLen(15, [5, 1, 3, 5, 10, 7, 4, 9, 2, 8])
print(res)
|
8a7c1571bff9747480b3abec8dc58177e9f0cc33 | dl-00-e8/Python_for_Coding_Test | /10-2.py | 786 | 3.71875 | 4 | def findParent(parent, x):
if parent[x] != x:
parent[x] = findParent(parent, parent[x])
return parent[x]
def unionParent(parent, a, b):
a = findParent(parent, a)
b = findParent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
n, m = map(int, input().split())
parent = [0] * (n + 1)
graph = []
result = []
for i in range(1, n + 1):
parent[i] = i
# a = 출발 / b = 도착 / c = 비용
for i in range(m):
a, b, c = map(int, input().split())
graph.append((a, b, c))
graph = sorted(graph, key = lambda x : x[2])
for node in graph:
a, b, c = node
if findParent(parent, a) != findParent(parent, b):
unionParent(parent, a, b)
result.append(c)
result.sort(reverse = True)
print(sum(result[1:])) |
9585d1e145c500321059f9ae5554a939de71abe2 | marcusshepp/hackerrank | /python/openkattis/erase.py | 316 | 3.546875 | 4 | num, str_one, str_two = int(raw_input()), raw_input(), raw_input()
def switch(s):
x = str()
for i in range(len(s)):
if s[i] == "0": x+="1"
else: x+="0"
return x
x = str_one
for i in range(num):
x = switch(x)
if x == str_two: print "Deletion succeeded"
else: print "Deletion failed" |
bd1488f7ee61d4c2dc41983c0582ab8b5b95ae1f | MurylloEx/Data-Structures-and-Algorithms | /Week_3/merge_sort.py | 648 | 3.59375 | 4 | import math
def merge_sort(srcList, sl_idx, sr_idx):
if sr_idx > sl_idx:
middle = (sl_idx + sr_idx) // 2
merge_sort(srcList, sl_idx, middle)
merge_sort(srcList, middle + 1, sr_idx)
merge(srcList, sl_idx, middle, sr_idx)
def merge(srcList, l_idx, middle, r_idx):
r_len = (middle - l_idx) + 1
l_len = (r_idx - middle)
left = [None] * (l_len + 1)
right = [None] * (r_len + 1)
for idx in range(l_len):
left[idx] = srcList[l_idx + 1]
for idx in range(r_len):
right[idx] = srcList[middle + idx + 1]
left[-1] = math.inf
right[-1] = math.inf
i = 0
j = 0
|
1232a0159d9e68c85db5cc130622b3e2c3a0ad67 | rwelsh98/isat252 | /PC_chp FIles/PC_chp8/pizza.py | 911 | 3.71875 | 4 | """
Your module description
"""
#Passing an arbitrary number of arguments
def make_pizza(*toppings):
"""Print the list of toppings that have been requested."""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers', 'extra cheese')
#improve
def make_pizza(*toppings):
"""Summarize the pizza we are about to make."""
print("\nMaking a pizza wiht the following toppings:")
for topping in toppings:
print(f"-{topping}")
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
#mixing positional and arbitraty arguments
def make_pizza(size,*toppings):
"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"-{topping}")
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese') |
3f0037139ad867fd30abfd2502ad7291e8ea9282 | chuckinator0/Projects | /scripts/symmetricTree.py | 1,035 | 4.40625 | 4 | '''
Given a binary tree t, determine whether it is symmetric around its center, i.e. each side mirrors the other.
'''
#
# Definition for binary tree:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def mirror(s,t):
# let's look at situations when at least one node is None
if not (s and t):
# Two empty trees are mirrors of each other
if not s and not t:
return True
# if one is None and the other exits, then the trees are not symmetric
else:
return False
# Let's look at when both nodes exist. In order for the trees to be symmetric,
# the root values must be equal, and
elif s.value == t.value:
# the left subtree of s must be a mirror of the right subtree of t, and visa versa
return mirror(s.left,t.right) and mirror(s.right,t.left)
else:
return False
def isTreeSymmetric(t):
if not t:
return True
return mirror(t.left,t.right) |
e93131c72f9fc4e5b704169d804c67fd0891abe7 | swatirathore15/python | /cropimage.py | 351 | 3.65625 | 4 | from PIL import Image
left = int(input("Pixels From Left : "))
top = int(input("Pixels From Top : "))
right = int(input("Pixels From Right : "))
bottom = int(input("Pixels From Bottom : "))
img_path = str(input("enter Image path : "))
image1 = Image.open(img_path)
crop_image = image1.crop((left, top, right, bottom))
crop_image.show() |
c8f5c64ec4a167ea93b2ec088205c428e194faa8 | 5l1v3r1/python_hacking_code | /random_dice.py | 255 | 3.875 | 4 | import random
print("This is a rolling dice simulator")
min_dice = 1
max_dice = 6
while True:
print(random.randint(min_dice,max_dice))
nExt = input("Roll again? ")
if nExt.startswith("y"):
continue
else:
break
|
a89057edd56b008f0e289477f3522af494996f22 | namratarane20/python | /algorithm/primenumber.py | 510 | 4.25 | 4 | #this program is used to find prime number within the given range of numbers from user
from util import utility
try:
start = int(input("enter from where you want to find prime number :"))
stop = int(input("enter till where you want to find prime number :"))
if start > -1 and stop < 1002: # condition
utility.prime(start, stop) # calls the method
else:
print("enter number between 0-1000")
except ValueError:
print("ENTER THE NUMBERS")
|
e3aa009a79f3d5ee18a6fce162c824e88cf90bc5 | pfengdev/pysnake | /DefaultMap.py | 344 | 3.640625 | 4 | from Map import Map
from Wall import Wall
class DefaultMap(Map):
def initWalls(self):
wall = Wall(0, 0, 1, 20)
self.addWall(wall)
wall = Wall(760, 0, 1, 20)
self.addWall(wall)
wall = Wall(0, 0, 20, 1)
self.addWall(wall)
wall = Wall(0, 760, 20, 1)
self.addWall(wall)
def __init__(self):
super(DefaultMap, self).__init__() |
46ab0371ef00ec8b075c8bf3378e80605aa995eb | vipsinha/Python | /Udacity/1_DataStructures.py | 7,707 | 4.46875 | 4 | '''
A good understanding of data structures is integral for programming and data analysis.
As a data analyst, you will be working with data and code all the time, so a solid understanding
of what data types and data structures are available and when to use each one will help you write more efficient code.
Remember, you can get more practice on sites like HackerRank.
In this lesson, we covered four important data structures in Python:
Data Structure Ordered Mutable Constructor Example
List Yes Yes [ ] or list() [5.7, 4, 'yes', 5.7]
Tuple Yes No ( ) or tuple() (5.7, 4, 'yes', 5.7)
Set No Yes {}* or set() {5.7, 4, 'yes'}
Dictionary No No** { } or dict() {'Jun': 75, 'Jul': 89}
* You can use curly braces to define a set like this: {1, 2, 3}. However, if you leave the curly
braces empty like this: {} Python will instead create an empty dictionary. So to create an empty set, use set().
** A dictionary itself is mutable, but each of its individual keys must be immutable.
'''
'''
List mutable ordered sortable to add -- .append []
Tupple im-mutable ordered sortable to add -- .append ()
Set mutable unordered un-sortable to add -- .add {}
Dictionary mutable unordered un-sortable to add -- .update {}
'''
'''
Quiz: List Indexing
Use list indexing to determine how many days are in a particular month based
on the integer variable month, and store that value in the integer variable num_days.
For example, if month is 8, num_days should be set to 31, since the eighth month, August, has 31 days.
Remember to account for zero-based indexing!
'''
month = 8
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
# use list indexing to determine the number of days in month
num_days=days_in_month[month-1]
print(num_days)
'''
#####Lists - mutable and ordered
'''
'''
Quiz: Slicing Lists
Select the three most recent dates from this list using list slicing notation. Hint: negative indexes work in slices!
'''
eclipse_dates = ['June 21, 2001', 'December 4, 2002', 'November 23, 2003',
'March 29, 2006', 'August 1, 2008', 'July 22, 2009',
'July 11, 2010', 'November 13, 2012', 'March 20, 2015',
'March 9, 2016']
# TODO: Modify this line so it prints the last three elements of the list
print(eclipse_dates[-3:])
'''
What would the output of the following code be? (Treat the comma in the multiple choice answers as newlines.)
'''
names = ["Carol", "Albert", "Ben", "Donna"]
print(" & ".join(sorted(names)))
'''
Length of list
'''
arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(arr[0])
print(arr[2:6])
print(arr[:3])
print(arr[4:])
'''
#####Tuples - im-mutable and ordered
'''
tuple_a = 1, 2
tuple_b = (1, 2)
print(tuple_a == tuple_b)
print(tuple_a[1])
'''
#####Sets - mutable and unordered
'''
fruit = {"apple", "banana", "orange", "grapefruit"} # define a set
print("watermelon" in fruit) # check for element
fruit.add("watermelon") # add an element
print(fruit)
print(fruit.pop()) # remove a random element
print(fruit)
'''
#####Dictionary - Like sets with values
key:value
Key must be im-mutable
'''
'''
Quiz: Define a Dictionary
Define a dictionary named population that contains this data:
Keys Values
Shanghai 17.8
Istanbul 13.3
Karachi 13.0
Mumbai 12.5
'''
# Define a Dictionary, population,
# that provides information
# on the world's largest cities.
# The key is the name of a city
# (a string), and the associated
# value is its population in
# millions of people.
# Key | Value
# Shanghai | 17.8
# Istanbul | 13.3
# Karachi | 13.0
# Mumbai | 12.5
population = {'Shanghai':17.8,
'Istanbul':13.3,
'Karachi':13.0,
'Mumbai':12.5}
print(population['Mumbai'])
'''
Quiz: Adding Values to Nested Dictionaries
Try your hand at working with nested dictionaries. Add another entry, 'is_noble_gas,'
to each dictionary in the elements dictionary. After inserting the new entries you should
be able to perform these lookups:
'''
elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'},
'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
print(elements)
# todo: Add an 'is_noble_gas' entry to the hydrogen and helium dictionaries
# hint: helium is a noble gas, hydrogen isn't
elements['hydrogen']['is_noble_gas'] = False
elements['helium']['is_noble_gas'] = True
print(elements['hydrogen']['is_noble_gas'])
print(elements['helium']['is_noble_gas'])
print(elements)
'''
Quiz: Count Unique Words
Your task for this quiz is to find the number of unique words in the text.
In the code editor below, complete these three steps to get your answer.
Split verse into a list of words. Hint: You can use a string method you learned in the previous lesson.
Convert the list into a data structure that would keep only the unique elements from the list.
Print the length of the container.
'''
verse = "if you can keep your head when all about you are losing theirs and blaming it on you if you can trust yourself when all men doubt you but make allowance for their doubting too if you can wait and not be tired by waiting or being lied about don’t deal in lies or being hated don’t give way to hating and yet don’t look too good nor talk too wise"
print(verse, '\n')
# split verse into list of words
verse_list = verse.split()
print(verse_list, '\n')
# convert list to a data structure that stores unique elements
verse_set = set(verse_list)
print(verse_set, '\n')
# print the number of unique words
num_unique = len(verse_set)
print(num_unique, '\n')
'''
Quiz: Verse Dictionary
In the code editor below, you'll find a dictionary containing the unique words of verse stored as keys
and the number of times they appear in verse stored as values. Use this dictionary to answer the following
questions. Submit these answers in the quiz below the code editor.
Try to answer these using code, rather than inspecting the dictionary manually!
How many unique words are in verse_dict?
Is the key "breathe" in verse_dict?
What is the first element in the list created when verse_dict is sorted by keys?
Hint: Use the appropriate dictionary method to get a list of its keys, and then sort that list.
Use this list of keys to answer the next two questions as well.
Which key (word) has the highest value in verse_dict?
'''
verse_dict = {'if': 3, 'you': 6, 'can': 3, 'keep': 1, 'your': 1, 'head': 1, 'when': 2, 'all': 2, 'about': 2, 'are': 1, 'losing': 1, 'theirs': 1, 'and': 3, 'blaming': 1, 'it': 1, 'on': 1, 'trust': 1, 'yourself': 1, 'men': 1, 'doubt': 1, 'but': 1, 'make': 1, 'allowance': 1, 'for': 1, 'their': 1, 'doubting': 1, 'too': 3, 'wait': 1, 'not': 1, 'be': 1, 'tired': 1, 'by': 1, 'waiting': 1, 'or': 2, 'being': 2, 'lied': 1, 'don\'t': 3, 'deal': 1, 'in': 1, 'lies': 1, 'hated': 1, 'give': 1, 'way': 1, 'to': 1, 'hating': 1, 'yet': 1, 'look': 1, 'good': 1, 'nor': 1, 'talk': 1, 'wise': 1}
print(verse_dict, '\n')
# find number of unique keys in the dictionary
num_keys = len(set(verse_dict))
print(num_keys)
# find whether 'breathe' is a key in the dictionary
contains_breathe = 'breathe' in verse_dict
print(contains_breathe)
# create and sort a list of the dictionary's keys
sorted_keys = sorted(verse_dict.keys())
# get the first element in the sorted list of keys
print(sorted_keys[0])
# find the element with the highest value in the list of keys
print(max(sorted_keys)) |
6e51244b0c6b80e60354da5f53cb79e273e5882c | reiterative/aoc2019 | /password.py | 886 | 3.59375 | 4 | minval = 137683
maxval = 596253
def test_ascend(number):
s = str(number)
for i in range(1, len(s)):
if int(s[i]) < int(s[i-1]):
return False
# /if
# /for
return True
# /def
def test_repeat(number):
s = str(number)
dup = 0
match = False
for i in range(1, len(s)):
if int(s[i]) == int(s[i-1]):
if dup == 0:
match = True
dup = int(s[i])
elif dup == int(s[i]):
match = False
else:
return True
# /if
# /if
# /if
# /for
return match
# /def
password = []
for x in range(minval, maxval):
if test_ascend(x) and test_repeat(x):
print "Password = {}".format(str(x))
password.append(x)
# /if
# /for
print "{} password candidates found".format(len(password))
|
d8dcb88f3060ceb43340acf641b98bc6e0eb0c2f | carojasq/python_projects | /Decorators/simple_decorator.py | 349 | 4.5 | 4 | #A decorator is just a callable that takes a function as an argument and returns a replacement function.
def outer(func):
def inner():
f = func()
return f+1
return inner
def func1():
return 1
decorated = outer(func1) # Decorated is a decorated version of func1
func1 = outer(func1) #Func1 reassigned
print (decorated())
print (func1())
|
799a4597f5ea2fbedc3954ce072d73cd5984b99f | a62mds/exercism | /python/atbash-cipher/atbash_cipher.py | 506 | 3.515625 | 4 | #!/usr/bin/env python
from string import ascii_lowercase as abcs
ekey = dict(zip(abcs, reversed(abcs)))
dkey = {v : k for k, v in ekey.iteritems()}
def decode(encstr):
subst = lambda c: dkey[c] if c.isalpha() else c
return ''.join(map(subst, ''.join(encstr.split())))
def encode(rawstr):
subst = lambda c: ekey[c] if c.isalpha() else c
encstr = ''.join(map(subst, ''.join(c.lower() for c in rawstr if c.isalnum())))
return ' '.join(encstr[i:i+5] for i in xrange(0, len(encstr), 5))
|
1b1c962ba53de50a21e629bf889cb1dadf762a63 | codeAligned/codingChallenges | /CodeFights/arcade/python/groupDating.py | 298 | 3.6875 | 4 | def groupDating(male, female):
return [[male[idx] for idx in range(len(male)) if male[idx] != female[idx]], [female[idx] for idx in range(len(male)) if male[idx] != female[idx]]]
""" TESTS """
male = [5, 28, 14, 99, 17]
female = [5, 14, 28, 99, 16]
res = groupDating(male, female)
print(res)
|
80b4479b4ab53d4058f8596f2be2f7f3da5e24da | as950118/Algorithm | /python/DP/1914.py | 1,034 | 3.90625 | 4 | import sys
def my_pop(n, cur, stack):
if cur >= 0:
return stack[cur], cur-1, stack[:cur]
else:
return 0, cur, stack
def hanoi(n, f, b, t):
stack = []
flag = 1
cur = -1
while flag:
while n>1:
print("adad")
stack.append(t)
stack.append(b)
stack.append(f)
stack.append(n)
n -= 1
stack.append(t)
t = b
b,cur,stack = my_pop(b,cur,stack)
if stack:
n,cur,stack = my_pop(n,cur,stack)
f,cur,stack = my_pop(f,cur,stack)
b,cur,stack = my_pop(b,cur,stack)
t,cur,stack = my_pop(t,cur,stack)
n -= 1
stack.append(f)
f = b
b,cur,stack = my_pop(b,cur,stack)
else:
flag = 0
def Hanoi(n,f,b,t):
if n==1:
return 0
else:
Hanoi(n-1,f,b,t)
Hanoi(n-1,b,f,t)
n = int(input())
print(hanoi(n,0,1,2))
|
7de5616da67f29909fbe8e9a397c9a44109ff477 | allanfs1/Java-c-c-python | /python/Qt/has.py | 748 | 3.71875 | 4 | #-*-coding:utf8;-*-
#qpy:3
#qpy:console
print("This is console module")
m=5
cont=0
livre ='L'
lista = [None for i in range(m)]
def hashing(x):
return x % m
def main():
global cont
while True:
if lista is not None:
numero = int(input("Insira um numero:"))
cont+=1
if cont < m:
pos=hashing(numero)
lista[pos] = numero
print("Contador:",cont)
else:
print("Hashi Cheia")
break
def imprima():
print("lista hashing:{0} e Tamanho:{1}".format(lista,len(lista)))
def moatra_hashi():
if lista is not None:
for i in range(m):
if i < m:
print(lista[i])
else:
print("N Elementos Maximo")
main()
#imprima()
moatra_hashi()
|
e340a497e6ceda441743b00ff7fa565226602559 | putraprstyo/python-OOP | /latihan-encapulasi/main.py | 1,465 | 3.59375 | 4 | class Hero:
# private variable
__jumlah = 0
def __init__(self, name, health, attPower, armor):
self.__name = name
self.__healthStandar = health
self.__attPowerStandar = attPower
self.__armorStandar = armor
self.__level = 1
self.__exp = 0
self.__healthMax = self.__healthStandar * self.__level
self.__attPower = self.__attPowerStandar * self.__level
self.__armor = self.__armorStandar * self.__level
self.__health = self.__healthStandar
Hero.__jumlah += 1
@property
def info(self):
return "{} level {}: \n\thealth : {}/{} \n\tattack : {} \n\tarmor : {}".format(self.__name,self.__level, self.__health, self.__healthMax, self.__attPower, self.__armor)
@property
def gainExp(self):
pass
@gainExp.setter
def gainExp(self,addExp):
self.__exp += addExp
if (self.__exp >= 100):
print(self. __name, 'level up')
self.__level += 1
self.__exp -= 100
self.__healthMax = self.__healthStandar * self.__level
self.__attPower = self.__attPowerStandar * self.__level
self.__armor = self.__armorStandar * self.__level
def attack(self, musuh):
self.gainExp = 50
miya = Hero("Miya", 100, 5, 10)
layla = Hero("Layla", 100, 5, 10)
print(miya.info)
miya.attack(layla)
miya.attack(layla)
miya.attack(layla)
print(miya.info) |
aed3b69baea1773df909aa6df2b3b87cbe238a5a | rpoliselit/python-for-dummies | /exercises/068.py | 848 | 3.953125 | 4 | """
Create a program that reads the
age, and gender of several people.
To each registered person the program
should ask if the user wants to continue.
In the end show:
[1] Number of people over 21
[2] Number of registered men
[3] Number of women under 21
"""
print(f"""
{'='*30}
{'REGISTER':^30}
{'='*30}""")
major = underage = men = 0
while True:
age = int(input('Age: '))
sex = ' '
while sex not in 'MF':
sex = str(input('Sex [m/f]: ')).strip().upper()[0]
if age >= 21:
major += 1
elif sex == 'F':
underage += 1
if sex == 'M':
men += 1
answer = ' '
while answer not in 'YN':
answer = str(input('Continue? [y/n] ')).strip().upper()[0]
if answer == 'N':
break
print(f"""
Number of legal age: {major}
men: {men}
underage women: {underage}""")
|
43fc37b83ce83822b9de60bf6f207890b7849438 | jeff-hwang/Algorithm | /LeetCode/172. Factorial Trailing Zeroes.py | 785 | 3.765625 | 4 | class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
'''
fact = self.factorial(n)
ln = len(str(fact))
lst = list(str(fact))
rst = 0
for i in range(ln-1, -1, -1):
if lst[i] == '0':
rst += 1
else :
break
return rst
'''
cnt = 0
while n >= 5:
n //= 5
cnt += n
return cnt
def factorial(self, n):
if n==0:
return 1
else:
return n * self.factorial(n-1)
'''
if __name__ == "__main__":
n = 3
sl = Solution().trailingZeroes(n)
print(sl)
''' |
d2ad0c8292ccf5fe146aef29e5cdc08150f5d26e | Domnus/Learning-Code | /Udemy Exercises/Function Practice Exercises/LEVEL 1 PROBLEMS/Master_Yoda.py | 260 | 3.84375 | 4 | # MASTER YODA: Given a sentence, return a sentence with the words reversed
def master_yoda(words):
mylist = []
new_word = ''
mylist.append(words.split(' '))
for i in range(len(mylist). -1):
new_word.join
master_yoda('I am home') |
40509e6625c05b09fdce2bc6f511084f7400c369 | subnr01/Programming_interviews | /programming-challanges-master/codeeval/016_number-of-ones.py | 546 | 4 | 4 | #!/usr/bin/env python
"""
Number of Ones
Challenge Description:
Write a program to determine the number of 1 bits in the internal representation of a given integer.
Input sample:
The first argument will be a text file containing an integer, one per line. e.g.
10
22
56
Output sample:
Print to stdout, the number of ones in the binary form of each number.
e.g.
2
3
3
"""
import sys
if __name__ == '__main__':
with open(sys.argv[1]) as f:
for line in f:
print(bin(int(line)).count('1'))
|
c69f8ff5529848c5c0741226afe6debfb960a229 | facesvision/Monty-Hall | /monty_hall.py | 1,013 | 3.734375 | 4 |
import random
class MontyHall:
def __init__(self):
self.doors = [1, 2, 3, 4]
self.winner_door = random.choice(self.doors)
def turn1(self, chosen_door):
if chosen_door == self.winner_door:
other_doors = [door for door in self.doors if door != chosen_door]
return random.choice(other_doors)
else:
other_doors = [door for door in self.doors if door != chosen_door and door != self.winner_door]
return random.choice(other_doors)
def turn2(self, chosen_door):
return 1 if chosen_door == self.winner_door else 0
if __name__ == '__main__':
NUM_EXPTS = 100000
player_not_change = PlayerNotChange()
player_change = PlayerChange()
for expt in range(NUM_EXPTS):
game = MontyHall()
player_not_change.play(game)
player_change.play(game)
print(f'Player not change: {player_not_change.score / NUM_EXPTS}')
print(f'Player change: {player_change.score / NUM_EXPTS}')
|
bdb9d5872001d8309f7eb2a176d7726f8a3daedc | Shourya-Tyagi/Algorithms_basic | /insertionsort.py | 612 | 4.125 | 4 | #def insertion_sort(list_a):
# for i in range(1,len(list_a)) :
# value_to_sort = list_a[i]
#
# while list_a[i-1] > value_to_sort and i > 0 :
# list_a[i-1] ,list_a[i] = list_a[i] , list_a[i-1]
# i = i-1
# return list_a
def insertion_sort(list_a):
indexing_length = range(1, len(list_a))
for i in indexing_length:
value_to_sort = list_a[i]
while list_a[i-1] > value_to_sort and i > 0:
list_a[i], list_a[i-1] = list_a[i-1], list_a[i]
i = i -1
list_a = [1,4,2,3,67,9]
insertion_sort(list_a)
print(list_a)
|
45ea597788636b9cde1909789c45fcc171ced32c | corinnemedeiros/plaintext | /CodingChallenge_multidigits_alt_3functions.py | 540 | 3.75 | 4 | encoded_string = "12oocvz09jqquiH11yywxsanmvbpI13yer6twweop14s 21gebwvsrxeqdwygrtuhijwT11hhllknbvxzdH00E01iR10kkjsagetrdE"
# empty lists to store found characters
DECODED_WORD = []
DECODED_WORD_MULTIDIGIT = []
# converts the encoded string into a list of individual characters
CHARACTER_LIST = list(encoded_string)
LENGTH = len(encoded_string)
def main(encoded_string):
i = 0
if CHARACTER_LIST[i].isdigit() == True:
plaintext(encoded_string)
if CHARACTER_LIST[i + 1].isdigit() == True:
plaintext_multidigit(encoded_string) |
0d3d94d9b38f2e1a4671cfd9a8b8345468d4b6d1 | larrythwu/python-tensorflow-exercises | /KNN/knn.py | 1,562 | 3.609375 | 4 | import sklearn
from sklearn.utils import shuffle
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
import numpy as np
from sklearn import linear_model, preprocessing
# preprocessing -> convert test in data file to numerical values
data = pd.read_csv("car.data")
print(data.head())
le = preprocessing.LabelEncoder()
#######Panda -> Numerical List
#fit transform automatically assign a numerical value to the text attributes
#in this case we also fit transformed numerical data such as doors, which essensially just transform array to list
#list: array -> list
buying = le.fit_transform(list(data["buying"]))
maint = le.fit_transform(list(data["maint"]))
door = le.fit_transform(list(data["door"]))
persons = le.fit_transform(list(data["persons"]))
lug_boot = le.fit_transform(list(data["lug_boot"]))
safety = le.fit_transform(list(data["safety"]))
cls = le.fit_transform(list(data["class"]))
predict = "class"
x = list(zip(buying, maint, door, persons, lug_boot, safety))
y = list(cls)
x_train,x_test,y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.1)
#Takes in the amount of neighbors
model = KNeighborsClassifier(4);
model.fit(x_train, y_train)
acc = model.score(x_test, y_test)
print(acc)
predictions = model.predict(x_test)
names = ["unacc", "acc", "good", "vgood"]
for x in range(len(x_test)):
print("Predicted: ", predictions[x], "Actual: ", y_test[x] )
print("Predicted: ", names[predictions[x]], "Actual: ", names[y_test[x]])
n=model.kneighbors([x_test[x]], 2, True)
print(n, "\n")
|
da2a565e9ebc5bb0ddb8b6ab781f92d0df81c350 | ibrahimGuilherme/Exercicio_Guilherme | /exercicio14.py | 120 | 3.765625 | 4 | import math
numr = float(input('Digite um número real: '))
print(f'Número {numr} - Parte inteira {math.trunc(numr)}')
|
86260963fe2db4356d853c534eace3ba421e995d | bulat92/OZON-Skils | /j.py | 1,248 | 3.5625 | 4 | import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
def open_file():
filepath = askopenfilename(
filetypes=[("Текстовые файлы", "*.txt"), ("Все файлы", "*.*")])
if not filepath:
return
txt_edit.delete("1.0", tk.END)
with open(filepath, "r") as input_file:
text = input_file.read()
txt_edit.insert(tk.END, text)
window.title(f"Текстовый редактор - {filepath}")
def save_file():
filepath = asksaveasfilename(defaultextension="txt",
filetypes=[("Текстовые файлы", "*.txt"), ("Все файлы", "*.*")],
)
if not filepath:
return
with open(filepath, "w") as output_file:
text = txt_edit.get("1.0", tk.END)
output_file.write(text)
window.title(f"Текстовый редактор - {filepath}")
window = tk.Tk()
txt_edit = tk.Text()
txt_edit.pack()
fr_buttons = tk.Frame()
fr_buttons.pack(fill=tk.X)
btn_submit = tk.Button(master=fr_buttons, text="Загрузить", command=open_file)
btn_submit.pack(side=tk.LEFT)
btn_clear = tk.Button(master=fr_buttons, text="Сохранить", command=save_file)
btn_clear.pack(side=tk.RIGHT)
window.mainloop() |
1fe971f3a5b0a3757b88782509f61845ee9e4141 | skosantosh/python | /s01_method_inheritance.py | 693 | 3.953125 | 4 | class Rectagle():
def __init__(self):
print("Rectagle Created")
def whoAmI(self):
print("Rectagle")
def draw(self):
print('Drawing')
# This class inheritance from Rectagle class
# this doesn't vahe mothod whoIam, draw it stell inheritance from rectagle
# if we un comment Rectagle.__init__(selt) it also inheritance this too.
class square(Rectagle):
def __init__(self):
# Rectagle.__init__(self)
print("Square Created")
# add neww method
def color(self):
print('Red')
# Orverride method from Rectagle Class
def draw(self):
print("Drawing done.")
mySqu = square()
mySqu.whoAmI()
mySqu.draw()
mySqu.color()
|
dd191147d9ab0ba965a249bed5e4b12e76adfd05 | superY-25/algorithm-learning | /src/algorithm/202003/lengthOfLIS.py | 380 | 3.796875 | 4 | """
给定一个无序的整数数组,找到其中最长上升子序列的长度。
示例:
输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-increasing-subsequence
"""
class Solution:
def lengthOfLIS(self, nums: list) -> int:
|
7056d4b35c1873a098eaee6fa93ab6f5a2af11ad | MrBanh/textFileToSpreadsheet | /textFileToSpreadsheet.py | 1,686 | 3.6875 | 4 | #! python3
# textFileToSpreadsheet.py - Reads in the contents of several text files from desktop, and insert the contents
# into a spreadsheet; one line of text per row, one text file per column
import os
import openpyxl
from openpyxl.utils import get_column_letter
import sys
desktop = os.path.join(os.environ['USERPROFILE'], 'Desktop\\')
# Converts the text file to spreadsheet
def textFileToSpreadsheet(listOfTextfiles):
os.chdir(desktop)
# Validates if files exist
for textFile in listOfTextfiles:
if not os.path.isfile(textFile) or not textFile.endswith('.txt'):
print('One or more file list does not exist or is invalid')
print('Please try again')
exit()
wb = openpyxl.Workbook()
sheet = wb.active
for i in range(len(listOfTextfiles)):
# Open each .txt file
txtFile = open(listOfTextfiles[i])
# Read the first line of the .txt file
line = txtFile.readline()
# Row counter. keeps track of each line in the .txt file
cnt = 1
# While there's more lines to read
while line:
# Assign the line from .txt file to the row
sheet[get_column_letter(i + 1) + str(cnt)] = line
# Read in next line
line = txtFile.readline()
# Increment for next row and line
cnt += 1
# Close the .txt file
txtFile.close()
# Saves the resulting spreadsheet on desktop
wb.save('textFileToSpreadsheet.xlsx')
# Get text files via command line
if len(sys.argv) > 1:
textFileToSpreadsheet(sys.argv[1:])
else:
print('Please enter the name of the text file') |
c96990247bb544ffad1f171fca1fcb2cb1b34fc0 | wing1king/python_xuexi | /阶段1-Python核心编程/04-数据序列/03-元组/hm_02_定义元组.py | 304 | 3.765625 | 4 | # 1.多个数据元组
# t1 = (10, 20, 30)
# print(t1)
# print(type(t1))
# 2.单个数据元组
# t2 = (10,)
# print(type(t2))
# 3.如果单个数据的元组不加逗号
# t3 = (10)
# print(type(t3)) # int
# t4 = ('aaa')
# print(type(t4)) # str
#
# t5 = ('aaa',)
# print(type(t5)) # tuple
|
540810795ec427964bad133afebdec927796f59f | yuryanliang/httpclient | /segment/http_client_practice.py | 4,381 | 4 | 4 | """
The goal is to write reusable client code that can be used to access an HTTP API that returns currency exchange rates in JSON format.
Note that the exchange rates at a specified date are immutable: the same request would always return the same response.
This API is live on the internet and can be accessed using a GET request to a URL formatted like
https://interview.segment.build/api/rates/<date>?base=<base>&symbols=<symbol>
where <base> is a currency code (e.g. USD for US dollars, EUR for Euro, and GBP for British Pound),
<symbol> is a comma-delimited list of the currency codes we want to compare against the base and <date> is the date.
An example request using the curl command:
$ curl -s 'https://interview.segment.build/api/rates/2017-01-02?base=USD&symbols=EUR,GBP'
{
"Base": "USD",
"Date": "2017-01-02",
"Rates": {
"EUR": 0.95557,
"GBP": 0.81357
}
}
"""
import sys
import requests
class exchange_client:
def __init__(self, date, base, symbols):
self.date = date
self.base = base
self.symbols = symbols
def get_data(self):
url = "https://interview.segment.build/api/rates/{}?base={}&symbols={}".format(self.date, self.base,
",".join(symbols))
response = requests.get(url=url)
data = response.json()
size = sys.getsizeof(data)
# 248 * 365*10*100/1024/1024 = 86 Mb
return data
# @classmethod
# def get_cache
class ExchangeRateClient:
def __init__(self):
self.cache = {}
# cache
# size =sys.getsizeof(data)
# 248 * 365*10*100/1024/1024 = 86 Mb
# no need to LRU or LFU
def get_rate(self, date, base, symbols):
result = {}
new_symbols=[]
for symbol in symbols:
ind = date + "+" + base + "-" + symbol
if ind in self.cache:
result[ind] = self.cache[ind]
else:
new_symbols.append(symbol)
# 1. see if request already in cache
# ind = date + "+" + base + ":" + "-".join(symbols)
# if ind in self.cache:
# return self.cache[ind]
# else:
if new_symbols:
# 2. api
url = "https://interview.segment.build/api/rates/{}?base={}&symbols={}".format(date, base,
",".join(new_symbols))
try:
response = requests.get(url=url, timeout=10)
response.raise_for_status()
except requests.exceptions.ConnectionError as e:
# DNS failure, refused connection
print(e.args[0].reason.args[0])
sys.exit(1)
except requests.exceptions.Timeout as e:
print("Time out:", e)
sys.exit(1)
# Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.HTTPError as e:
# there is a non-200 error
# currency error. date error
print("Status code is non-200:", e.response.text)
sys.exit(1)
# if want to do retry:
# from requests.adapters import HTTPAdapter
#
# s = requests.Session()
# s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=5))
# 3. update cache
data = response.json()
for symbol, rate in data["Rates"].items():
ind = date + "+" + base + "-" + symbol
result[ind]=rate
self.cache[ind] = rate
return result
""" base + symbol
for symbol, rate in data["Rates"].items():
ind = base + "-" + symbol
if ind not in self.cache:
self.cache[ind] = {date: rate}
else:
if date not in self.cache[ind]:
self.cache[ind].update({date: rate})
"""
if __name__ == "__main__":
date_1 = "2007-01-02"
base = "USD"
symbols = ["EUR"]
client = ExchangeRateClient()
rate = client.get_rate(date_1, base, symbols)
date_2 = "2007-01-02"
symbols = ["EUR", "GBP"]
rate_2 = client.get_rate(date_2, base, symbols)
print(rate_2)
|
485d5c80a3d29ddaa7f4e187b7b9909f441b9b2f | ramjiik1992/201909-hp-python | /scripts-threading-socket/threading-2.py | 696 | 3.859375 | 4 | import threading as t
import time
class Counter(t.Thread):
_count=0
def __init__(self,max,name=None):
t.Thread.__init__(self)
self.max=max
self.name= name if(name !=None) else 'Thread#'+Counter._count
Counter._count+=1
def run(self):
print('{} started'.format(self.name))
while self.max>=0:
print('{} counted {}'.format(self.name,self.max))
self.max-=1
time.sleep(1)
c1=Counter(10,'Counter1')
c2=Counter(10,'Counter2')
c1.start()
c2.start()
print('waiting for thread to finish')
c1.join() #wait for this thread
c2.join() #wait for this thread
print('program ends...')
|
ff2242681c678f7e42b509941097fb43607eaa47 | ak-alam/Python_Problem_Solving | /max_of_three/main.py | 440 | 4.28125 | 4 | '''
Find the largest of the three numbers.
'''
first_num = int(input('Enter value :'))
sec_num = int(input('Enter value :'))
third_num = int(input('Enter value :'))
if first_num > sec_num and first_num > third_num:
print(f'Large Number is {first_num}')
elif sec_num > first_num and sec_num > third_num:
print(f'Large Number is {sec_num}')
elif third_num > sec_num and third_num > first_num:
print(f'Large Number is {third_num}')
|
17194706c33250717bb8415fe9bf95870e18b12d | Dansmith-rgb/dinosaur_game | /dinosaur_game/background.py | 804 | 3.53125 | 4 | import pygame
class Background(object, pygame.sprite.Sprite):
def __init__(self,x, y):
pass
"""
def collide(self, bird, win):
returns if a point is colliding with the pipe
:param bird: Bird object
:return: Bool
bird_mask = bird.get_mask()
top_mask = pygame.mask.from_surface(self.PIPE_TOP)
bottom_mask = pygame.mask.from_surface(self.PIPE_BOTTOM)
top_offset = (self.x - bird.x, self.top - round(bird.y))
bottom_offset = (self.x - bird.x, self.bottom - round(bird.y))
b_point = bird_mask.overlap(bottom_mask, bottom_offset)
t_point = bird_mask.overlap(top_mask,top_offset)
if b_point or t_point:
return True
return False
""" |
81711c7aa4f4bd4568092dba570ef1ef862a472f | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/brnann016/question2.py | 772 | 3.984375 | 4 | #Vending machine program
#Annika Brundyn
#16/04/2014
cost = eval(input("Enter the cost (in cents):\n"))
deposit1= eval(input("Deposit a coin or note (in cents):\n"))
total_deposit=deposit1
while total_deposit<cost:
deposit=eval(input("Deposit a coin or note (in cents):\n"))
total_deposit+=deposit
if total_deposit>=cost:
change=total_deposit-cost
dollar = change//100
quarter = (change%100)//25
tencents = ((change%100)%25)//10
fivecents = (((change%100)%25)%10)//5
onecents = ((((change%100)%25)%10)%5)
print("Your change is:")
if dollar>0:
print(dollar,"x $1")
if quarter>0:
print(quarter,"x 25c")
if tencents>0:
print(tencents,"x 10c")
if fivecents>0:
print(fivecents,"x 5c")
if onecents>0:
print(onecents,"x 1c")
|
e8eb61ee07ad9b9c14f24828dc19f23fc98ac87e | vmukund100/practice | /Intro_computation_Guttag/temp2_chpt5_6.py | 14,346 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
Author - Vineetha Mukundan
To uncomment, press ctrl+1
This is a temporary script file.
Contains exercise codes from Chapter 5 & 6 of
'Introduction to Computation and programming by Python' by John Guttag'
Third Edition
"""
# t1 = (1, 'two', 3)
# t2 = (t1, 3.25)
# print(t2)
# print(t1+t2)
# print((t1+t2))
# print((t1+t2)[3])
# print((t1+t2)[2:5])
# def intersect(t1, t2):
# '''Assumes t1 & t2 are tuples
# returns a tuple containing elements that are in both t1 & t2'''
# #i=0
# #while i<len(t1):
# result = () #defines tuple
# for e in t1:
# if e in t2:
# result = result+ (e,)
# #i = i+1
# return result
# print(intersect((1,'a',2), ('b', 2, 'a')))
# def find_extreme_divisors(n1,n2):
# ''' Assumes that n1 and n2 are +ve ints
# returns a tuple containing the smallest common divisor >1 and
# the largest common divisor of n1 & n2. If no common divisor,
# other than 1, returns (None, None)'''
# min_val, max_val = None, None
# for i in range(2, min(n1,n2) +1):
# if n1%i == 0 and n2%i ==0:
# if min_val == None:
# min_val = i
# max_val = i
# return min_val, max_val
# min_divisor, max_divisor = find_extreme_divisors(100, 200)
# print(min_divisor, max_divisor)
'''Fingerling 5-1:sum in tuple'''
# tuple_1 = (1,2,3,4,5,6)
# mean_1 = sum(tuple_1)/len(tuple_1)
# print(mean_1)
# l1= [1,2,3]
# print(l1[-1])
# print(l1[2])
# l2 = l1[-1::-1]
# print(l2)
# for i in range(len(l1)):
# print (l1[i]*l2[i])
# l1 = [[]]*2
# l2 = [[], []]
# for i in range(len(l1)):
# print('step',i)
# l1[i]. append(i)
# print('L1',l1)
# l2[i].append(i)
# print('L2',l2)
# print('L1=', l1, 'but ', 'l2=',l2)
'''fingerling 5-2: code to print'''
# L = [1,2,3]
# L.append(L)
# print(L[3:])
# print(L[-1])
# print(L is L[-1])
# def append_val(val, List_1 = []):
# List_1.append(val)
# print(List_1)
# append_val(3)
# append_val(4)
# append_val(5)
# L1=[1,2,3]
# L2 = [4,5,6]
# L3 = L1+L2
# print('L3 =', L3)
# L1.extend(L2)
# print('L1 =', L1)
# L1.append(L2)
# print('L1=', L1)
# def remove_dups(l1,l2):
# '''Assumes that l1 & l2 are lists.
# Removes any element from l1 that also occurs in l2
# key - Note that the list L1 is mutated within the loop'''
# for e1 in l1:
# if e1 in l2:
# l1.remove(e1)
# l1 = [1,2,3,4]
# l2 = [1,2,5,6]
# remove_dups(l1,l2)
# print('L1 =',l1)
''' Use slicing or copy to clone the list - SHALLOW COPY'''
# import copy
# L=[2]
# L1=[L]
# #L2=L1[:]
# L2= copy.deepcopy(L1)
# #Gives an error undefined name 'copy'
# L.append(3)
# print(f'L1 ={L1}, L2 ={L2}')
'''Prime number by list comprehension'''
# [x for x in range(2, 100) if all(x % y != 0 for y in range(2,x))]
# def gen_primes():
# primes = []
# for x in range(2, 100):
# is_prime= True
# for y in range(3,x):
# if x%y == 0:
# is_prime = False
# if is_prime:
# primes.append(x)
# print(primes)
# return primes
# gen_primes()
'''List comprehension
[expr for elem in iterable if test]'''
'''def f(expr, ol_list, test = lambda x:True):
new_list = []
for e in iterable:
if test(e):
new_list.append(expr(e))
return new_list'''
# xyz1 = [e**2 for e in range(10) if e%2==0]
# print(xyz1)
# xyz2= [x**2 for x in [2,'a', 3, 4.0] if type(x) == float]
# print(xyz2)
#conveninet way to generate a list
# xyz3= [[] for _ in range(10)]
# print(xyz3)
# #multiple for statement within a list comprehension
# print( [(x,y) for x in range(6) if x%2 ==0 for y in range(6) if y%3==0])
# #Nesting a list comprehension within a list comprehension
# print([[(x,y) for x in range(6) if x%2 ==0] for y in range(6) if y%3 == 0])
'''Fingerling 5-3 Non primes between 2, 100 by list comprehension
+ nested list '''
#[x for x in range(2, 100) if all(x % y == 0 for y in range(x,2))]
# def gen_nonprimes():
# nonprimes = []
# for x in range(2, 100):
# is_nonprime= False
# for y in range(2,x):
# if x%y == 0:
# is_nonprime = True
# if is_nonprime:
# nonprimes.append(x)
# print(nonprimes)
# return nonprimes
# gen_nonprimes()
'''WRONG LIST COMPREHENSION'''
#xyz4 = [y for y in range(2,100) if all(y%z!=0 for z in range(y,2))]
# print(xyz4)
'''Figure 5-5 Higher order operations on lists'''
# def apply_to_each(L,f):
# '''Assumes L is a list, f is a function
# Mutates L by replacing each element, e, of L by f(e)'''
# for i in range(len(L)):
# L[i] = f(L[i])
# L= [1,-2, 3.33]
# print('Apply abs to each element of L')
# apply_to_each(L, abs)
# print(L)
# print('Apply int to each element of L')
# apply_to_each(L, int)
# print(L)
# print('Apply squaring to each element of L')
# apply_to_each(L, lambda x:x**2)
# print(L)
'''Map function usually used with for loop'''
# print(list(map(str, range(10))))
# print([str(e) for e in range(10)])
# for i in map(lambda x:x**2, [2,6,4]):
# print(i)
# L1 = [1,28,36]
# L2 = [2,57,9]
# for i in map(min, L1, L2):
# print(i)
'''Fingerling 5-4 '''
# def f(L1,L2):
# '''L1,L2 lists of same length of numbers
# return the sum raising each elemtn in L1
# to the power of the element at the same index in L2
# for example, f([1,2], [2,3]) returns 9
# Hint - use lambda in the body of implementation'''
# suma = 0
# for i in map(lambda x,y:x**y, L1, L2):
# #for i in map(x**y, L1, L2):
# suma = suma +i
# #print(i)
# return suma
# answer1 = f([1,2],[2,3])
# print(answer1)
# month_numbers = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May'}
# print('The third month is '+month_numbers[3])
# dist = month_numbers ['Apr'] -month_numbers['Jan']
# print('Apr and Jan are', dist,'months part')
'''Figure 5-9'''
# EtoF = {'bread':'pain', 'wine':'vin', 'with':'avec', 'I':'Je', 'eat':'mange', 'drink':'bois', 'John':'Jean', 'friends':'amis', 'and':'et', 'of':'du', 'red':'rouge'}
# FtoE = {'pain':'bread', 'vin':'wine', 'avec':'with', 'Je':'I', 'mange':'eat', 'bois':'drink', 'Jean':'John', 'amis':'friends', 'et':'and','du':'of', 'rouge':'red'}
# dicts = {'English to French':EtoF, 'French to English':FtoE}
# def translate_word(word, dictionary):
# if word in dictionary:
# return dictionary[word]
# elif word!='':
# return '"'+word+'"'
# return word
# def translate(phrase, dicts, direction):
# UC_letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# lc_letters = 'abcdefghijklmnopqrstuvwxyz'
# punctuation = '.,;:?'
# letters = UC_letters + lc_letters
# dictionary = dicts[direction]
# translation = ''
# word = ''
# for c in phrase:
# if c in letters:
# word = word+c
# elif word != '':
# if c in punctuation:
# c = c+''
# translation = (translation + translate_word(word, dictionary) +c)
# word = ''
# return f'{translation} {translate_word(word, dictionary)}'
# print(translate('I drink good red wine and eat bread.', dicts, 'English to French'))
# print(translate('Je bois du vin rouge.', dicts, 'French to English'))
'''Implement all codes shown in section 5.7 on Dictionaries'''
# month_numbers = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May'}
# print(month_numbers)
# print('The third month is '+ month_numbers[3])
# dist = month_numbers['Apr'] - month_numbers['Jan']
# print('Apr and Jan are', dist, 'months apart')
capitals = {'France':'Paris', 'Italy':'Rome', 'Japan':'Kyoto'}
# for key in capitals:
# print('The capital of ', key, 'is', capitals[key])
# cities=[]
# for val in capitals.values():
# cities.append(val)
# print(cities, 'is a list of capital cities')
# cap_values =capitals.values()
# print(cap_values)
# capitals['Japan'] = 'Tokyo'
# print(cap_values)
# for key,val in capitals.items():
# print(val,'is the capital of', key)
'''Fingerling 5-5'''
'''Slightly changed the exercise by making a dict of all alphabets'''
# def get_min(d):
# """d a dict mapping letters to int
# returns the value in d with the key that occurs first
# in the alphabet. E.g., if d = {x = 11, b = 12}, get_min
# returns 12."""
# foo = 'abcdefghijklmnopqrstuvwxyz'
# {letter: num for (num, letter) in enumerate(foo)}
'''Dictionary comprehension
{key: value for id1, id2 in iterable if test}'''
# number_to_word = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 10:'ten'}
# word_to_number = {w: d for d, w in number_to_word.items()}
# word_to_number = {w: d for d, w in number_to_word.items() if d< 10}
# plain_text = "no is no"
# book = "Once upon a time, in a house in a land far away"
# gen_code_keys =(lambda book, plain_text: ({c:str(book.find(c)) for c in plain_text}))
# print(gen_code_keys(book, plain_text))
# book2 = "In the village of La Mancha, the name of which I have no desire to call to mind, therelived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack and a greyhound for coursing"
# print(gen_code_keys(book2, plain_text))
# encoder = (lambda code_keys, plain_text:
# ''.join(['*' + code_keys[c] for c in plain_text]) [1:])
# encrypt = (lambda book, plain_text:
# encoder(gen_code_keys(book, plain_text), plain_text))
# print(encrypt(book2, plain_text))
'''Fingerling 5-6: NOT YET DONE
Remedy the problem descried in th previous paragraph.
Hint: a simple way to do this is to create a new book by appending
something to the original book'''
'''Fingerling 5-7:NOT YET DONE
Using encoder and encrypt as models, implement decoder nd decrypt. Use them to decrpt the message
22*13*33*137*59*11*23*11*1*57*6*13*1*2*6*57*2*6*1*22*13*33*1
37*59*11*23*11*1*57*6*173*7*11'''
# '''CHAPTER 6'''
# '''Figure 6-1 Two ways for factorial - iterative & recursive'''
#base case
# def fact_iter(n):
# '''Assumes n an int>0
# returns n!'''
# result =1
# for i in range(1, n+1):
# #result = result*i
# result*=i
# #print(result)
# return result
# print(fact_iter(10))
# #recursive/inductive case
# def fact_rec(n):
# '''Assumes n an int>0
# returns n!'''
# if n==1:
# return n
# else:
# return n*fact_rec(n-1)
# print(fact_rec(10))
'''Fingerling 6-1: Harmonic sum of an Integer'''
# def harmsum_iter(n):
# result=0
# for i in range(1, n+1):
# result= result +(1/i)
# return result
# print(harmsum_iter(2))
# def harmsum_rec(n):
# '''Assume n an int>0
# returns 1+1/2+1/3...+1/n'''
# result = 0
# if n==1:
# result = 1
# if n>1:
# while n>0:
# result = result+ (1/n)
# n=n-1
# return result
# # return 1+1/(harmsum_rec(n-1))
# def harmsum_rec(n):
# if n==1:
# return n
# else:
# return (1/n)+harmsum_rec(n-1)
# print(harmsum_rec(5))
#'''Figure 6-3'''
# def fib(n):
# '''Assumes n int>=0
# returns fibonacci of n'''
# if n == 0 or n == 1:
# return 1
# else:
# # print((n-2), 'and', (n-1))
# return fib(n-1)+fib(n-2)
# def test_fib(n):
# for i in range(n+1):
# print('fib of ', i, '=', fib(i))
# print(fib(5))
# test_fib(5)
# '''Figure 6-4'''
# '''Recursion in non-numbers - Uses divide & conquer principle'''
# def is_palindrome(s):
# '''Assumes s is str
# return True if letters in s form a palindrome; False otherwise.
# Non-letters and capitalization are ignored'''
# def to_chars(s):
# #not required if input letters are in lower case
# s = s.lower()
# letters = ''
# for c in s:
# if c in 'abcdefghijklmnopqrstuvwxyz':
# letters = letters + c
# print(letters)
# return letters
# def is_pal(s):
# if len(s) <= 1:
# return True
# else:
# print(s[1:-1])
# return s[0] == s[-1] and is_pal(s[1:-1])
# return is_pal(to_chars(s))
#print(is_palindrome('MalayaLam'))
# def is_pal(s):
# if len(s) <= 1:
# return True
# else:
# print(s[1:-1])
# return s[0] == s[-1] and is_pal(s[1:-1])
# print(is_pal('malayalam'))
# '''Figure 6-5'''
# '''Code to visulaize palindrome testing'''
# def is_palindrome(s):
# '''Assumes s is str
# return True if letters in s form a palindrome; False otherwise.
# Non-letters and capitalization are ignored'''
# def to_chars(s):
# s = s.lower()
# letters = ''
# for c in s:
# if c in 'abcdefghijklmnopqrstuvwxyz':
# letters = letters + c
# return letters
# def is_pal(s):
# print(' is_pal called with',s)
# if len(s) <= 1:
# print('About to return True from the base case')
# return True
# else:
# answer = s[0] == s[-1] and is_pal(s[1:-1])
# print(' About to return', answer, 'for', s)
# return answer
# return is_pal(to_chars(s))
#print(is_palindrome('Malayalam'))
# print('Try dogGod')
# print(is_palindrome('dogGod'))
# print('Try doGood')
# print(is_palindrome('doGood'))
# '''Figure 6-6 Using global variables'''
# def fib(x):
# '''Assumes n int>=0
# returns fibonacci of x'''
# global num_fib_calls
# num_fib_calls +=1
# if x == 0 or x == 1:
# return 1
# else:
# #print((n-2), 'and', (n-1))
# return fib(x-1)+fib(x-2)
# def test_fib(n):
# for i in range(n+1):
# global num_fib_calls
# num_fib_calls = 0
# print('fib of ', i, '=', fib(i))
# print('fib called', num_fib_calls, 'times.')
|
b1740a4f4c332a4d4a4e997e134222a585af0743 | Mahrokh-Eb/LA-college-Python | /sameForLoop.py | 215 | 3.90625 | 4 | # getting same result,
# writting for loop in two ways:
firstName = 'MAhrokh'
for i in firstName:
print(i)
print('----------------')
lastName = 'Ebrahimi'
for i in range(len(lastName)):
print(lastName[i]) |
d1f64a86ad12f9d117a099438cd5b09556679b0e | banjarajanardan/algorithmicToolboxUniversityOfSanDiego | /week3_greedy_algorithms/7_maximum_salary/largest_number.py | 339 | 3.703125 | 4 | #Uses python3
import sys
def largest_number(a,n):
for i in range(n):
for j in range(n-1):
if((a[j]+a[j+1])<(a[j+1]+a[j])):
a[j+1], a[j] = a[j], a[j+1]
return "".join(a)
if __name__ == '__main__':
n = int(input())
a = input()
a = a.split()
print(largest_number(a,n))
|
c5ed75caa0046dcf06284870e05a12e1e1370017 | niallmul97/Poker-Minigame | /poker-mini-game.py | 5,520 | 3.59375 | 4 | import random
class Card:
def __init__(self, value, suit):
self.value = value
self.suit = suit
#def faceCardSwitchCase(self, i):
#faceCards = {11: 'J', 12: 'Q', 13: 'K', 14: 'A'}
#return faceCards.get(i, str(i))
def show(self):
if self.value == 11 or self.value == '11':
print('J of {}'.format(self.suit))
elif self.value == 12:
print('Q of {}'.format(self.suit))
elif self.value == 13:
print('K of {}'.format(self.suit))
elif self.value == 14:
print('A of {}'.format(self.suit))
else:
print('{} of {}'.format(self.value, self.suit))
class Deck:
def __init__(self):
self.cards = []
self.hand = []
self.build()
def build(self):
for s in ['Spades', 'Hearts', 'Diamonds', 'Clubs']:
for v in range(2,14):
self.cards.append(Card(v,s))
def show(self):
for c in self.cards:
c.show()
for c in self.hand:
c.show()
def shuffle(self):
random.shuffle(self.cards)
def drawCard(self):
return self.cards.pop()
class Player:
def __init__(self, name):
self.name = name
self.score = 0
self.finalHand = ''
self.hand = []
def draw(self, deck):
for i in range(0,5):
self.hand.append(deck.drawCard())
return self
def showHand(self):
print(self.name +"'s hand:")
for card in self.hand:
card.show()
def faceCardSwitchCase(self, i):
faceCards = {11: 'J', 12: 'Q', 13: 'K', 14: 'A'}
return faceCards.get(i, str(i))
def scoreHand(self):
handDict = {}
suitDict = {}
score = 0
twoPairMod = 0
fourOakMod = 1
handList = [False] * 9
finalHand = ''
sortedHandByValue = sorted(self.hand, key=lambda card: card.value)
sortedHandBySuit = sorted(self.hand, key=lambda card: card.suit)
#adding all cards in hand to a dict in which the value is the key, aids in checking for pairs/three of a kind/four of a kind
for i in sortedHandByValue:
key = i.value
if key in handDict:
handDict[key] +=1
else:
handDict[key] = 1
#adding all cards in hand to a dict in which the vsuit is the key, aids in checking for a flush
for i in sortedHandBySuit:
key = i.suit
if key in suitDict:
suitDict[key] += 1
else:
suitDict[key] = 1
#finding of pairs
for key in handDict.keys():
#pair
if len(handDict) == 4 and handDict.get(key) == 2:
strPair = "Pair of {}'s".format(self.faceCardSwitchCase(int(key)))
finalHand = finalHand + strPair
handList[1] = True
#3oak and Two Pair
if len(handDict) == 3:
for key in handDict.keys():
if handDict.get(key) == 2:
twoPairMod +=2
elif handDict.get(key) == 3:
twoPairMod +=1
#Two Pair
if twoPairMod % 2 == 0:
strPair = "Two pair"
finalHand = finalHand + strPair
handList[2] = True
#3oak
else:
strTrips = "Triple {}'s".format(self.faceCardSwitchCase(int(key)))
finalHand = finalHand + strTrips
handList[3] = True
#4oak/Full House
if len(handDict) == 2:
for key in handDict.keys():
if handDict.get(key) == 4:
fourOakMod +=1
#4oak
if fourOakMod & 2 == 0:
strQuads = "Quad of {}'s".format(self.faceCardSwitchCase(int(key)))
finalHand = finalHand + strQuads
handList[7] = True
#Full House
else:
strFH = 'Full House'
finalHand = finalHand + strFH
handList[6] = True
#straight
if len(handDict) == 5 and list(handDict.keys())[4] - list(handDict.keys())[0] == 4:
print('Straight')
handList[4] = True
#Straight for Ace low
if list(handDict.keys()) == [2, 3, 4, 5, 14]:
print('Straight')
handList[4] = True
#flush
if len(suitDict) == 1:
print(' Flush')
handList[5] = True
#Straight flush
if handList[4] == True and handList[5] == True:
print('Straight Flush')
handList[8] = True
#Royal Flush
if list(handDict.keys()) == [10, 11, 12, 13, 14] and len(suitDict) == 1:
strRoyal = 'Royal Flush'
finalHand = finalHand + strRoyal
handList[9] = True
#Hand Score
for i in reversed(handList):
if i == True:
score = handList.index(i)
break
print(finalHand)
print(score)
deck = Deck()
deck.shuffle()
p1 = Player('Player1')
p1.draw(deck)
p1.showHand()
print('')
p1.scoreHand()
print('')
p2 = Player('Player2')
p2.draw(deck)
p2.showHand()
print('')
p2.scoreHand()
print('')
#if p2.score == p1.score:
# print("Draw!")
#elif p2.score > p1.score:
# print("Player2 Wins!")
#else:
# print("Player1 Wins!")
#card = deck.drawCard()
#card.show()
#deck.show()
|
04511079d26730994d932713b86343af0868834d | mustang25/CS-325-Project-1 | /algo4_linear.py | 754 | 3.796875 | 4 | #!/usr/bin/env python3
"""Linear algorithm based on the psuedocode from https://atekihcan.github.io/CLRS/E04.01-05/"""
def linear(array):
"""Linear algorithm to determine the maximum subarray in an array.
The algorithm will return a subarray and the maximum sum that was found.
Arguments:
array -- An array that contains at least one element.
"""
low = 0
high = 0
max_sum = array[low]
temp_sum = 0
temp_low = 0
for i, value in enumerate(array):
temp_sum = max(value, temp_sum + value)
if temp_sum == value:
temp_low = i
if temp_sum > max_sum:
max_sum = temp_sum
high = i
low = temp_low
return array[low:high+1], max_sum
|
93682ef567ed20d5ff6fb0996833873b7e44be9f | asen-krasimirov/Python-Advanced-Course | /9. Error Handling/9.1 Lab/test.py | 162 | 3.515625 | 4 |
try:
string = input()
repeated_times = int(input())
print(string*repeated_times)
except ValueError:
print("Variable times must be an integer")
|
d62b77c6a9d32a388711fc7f7d65c0597e068452 | Ryctorius/Curso-de-Python | /PycharmProjects/CursoExercicios/ex028.py | 300 | 4 | 4 | import emoji
import random
n = random.randint(0, 5)
a = int(input('Digite um numero inteiro de 0 a 5: '))
if n == a:
print('Parabéns! Você venceu!!!')
else:
print('Que pena, você errou! O número sorteado foi {}.'.format(n))
print(emoji.emojize('Obrigado por jogar conosco :sunglasses:'))
|
e92bd2f8cbeb13a289934a135994e7bafe42fe4d | Nikunj-Gupta/Python | /practice/Level3/swap.py | 285 | 3.875 | 4 | a=[]
length = input("Enter length of the list: ")
i = 1
while(i<=length):
n = input("Enter a number: ")
a.append(n)
i = i + 1
pos1 = input("Enter position 1: ")
pos2 = input("Enter position 2: ")
swap = a[pos1]
a[pos1] = a[pos2]
a[pos2] = swap
print "New List : " + str(a)
|
31ff4bdddd9ea3a29967ee42b37f87eee8ab0290 | adwylie/simple-hangman | /game.py | 2,517 | 3.671875 | 4 | class Hangman:
MAXIMUM_TRIES = 5
PHRASES = ['3dhubs', 'marvin', 'print', 'filament', 'order', 'layer']
def __init__(self, phrase, guesses=None, tries=None):
# Allow an existing game to be continued if given all arguments.
# TODO: Validate arguments?
self.phrase = phrase
self.guesses = guesses or {' '}
self.tries = tries or 0
def guess(self, letter):
"""Allow a user to make a guess, uppercase/lowercase doesn't matter."""
self.guesses.add(letter.lower())
if letter.lower() not in self.phrase.lower():
self.tries += 1
def is_game_over(self):
return self.tries >= Hangman.MAXIMUM_TRIES \
or set(self.phrase.lower()).issubset(self.guesses)
def is_game_won(self):
return set(self.phrase.lower()).issubset(self.guesses) \
and self.tries < Hangman.MAXIMUM_TRIES
def is_guess_valid(self, guess):
# The input guess must be a single character, alphanumeric,
# and must not have already been guessed.
if guess and isinstance(guess, str) \
and len(guess) == 1 \
and guess.isalnum() \
and guess.lower() not in self.guesses:
return True
return False
def get_display_phrase(self):
"""Return the phrase with unknown letters covered."""
return ''.join(
['_' if x.lower() not in self.guesses else x for x in self.phrase])
def get_guesses(self):
"""Convenience function for GUI (show user which letters are available)."""
# Return a copy of the guesses so it can't be modified.
return self.guesses - {' '}
def get_tries(self):
"""Convenience function for GUI (drawing the hanged man)."""
return self.tries
if __name__ == '__main__':
import random
def get_input():
return input("Enter your guess: ").strip()
game = Hangman(random.choice(Hangman.PHRASES))
while not game.is_game_over():
print(' '.join(game.get_display_phrase()))
# Allow the user to make a guess.
text = get_input()
while not game.is_guess_valid(text):
print("Invalid guess entered, please try again.")
text = get_input()
game.guess(text)
if game.is_game_over():
if game.is_game_won():
print("Congratulations, you win!")
else:
print("Sorry, you lost!")
exit()
|
5c0c1e43ee15a3a0d37828905ed8b66c1dd1594e | spurgn14/thantology | /Password Checker.py | 1,370 | 4.0625 | 4 | #Author: Jonathan Anthony Hernandez
#Password Checker Program
#Description: Easy Password Checker using list, if-else, and for loop
Lower_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Upper_letters= ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+','_']
systemrequirement = int(input("How long should the password will be?"));
userpassword = str(input("Type your password "));
lower_letter_password = 0;
upper_letter_password = 0;
number_password=0;
symbols_password=0;
if len(userpassword) >= systemrequirement:
for values in userpassword:
if values in Lower_letters:
lower_letter_password+=1;
elif values in Upper_letters:
upper_letter_password+=1;
elif values in numbers:
number_password+=1;
elif values in symbols:
symbols_password+=1;
print (f"Your password has {upper_letter_password} upper case letters, {lower_letter_password} lower letters, {number_password} numbers, {symbols_password} symbols")
else:
print ("You password is not sufficient for our system")
|
ede0013a66c4ef42597769dbc8142e946a69d1ea | MegatronChen/MCLearnGUI | /BuildInModule_Learn/GUI/2018.05.14Strat_GUI.py | 1,179 | 3.546875 | 4 | __author__ = 'lenovo'
print('\n')
# 《python编程》GUI章节学习
# Chapter7
# # Example7.1
# from tkinter import Label
# widget = Label(None,text='Hello GUI world!')
# widget.pack()
# widget.mainloop()
# # Example7.6
# from tkinter import *
# Label(text='hello GUI world!').pack(expand=YES,fill=BOTH)
# mainloop()
# # Example7.8
# from tkinter import *
# root = Tk()
# widget = Label(root)
# widget.config(text='hello GUI world!')
# widget.pack(side=TOP,expand=YES,fill=BOTH)
# root.title('gui1g.py')
# root.mainloop()
# # Example7.10
# import sys
# from tkinter import *
# widget = Button(None,text='Hello Widget World',command=sys.exit)
# widget.pack()
# widget.mainloop()
# # Example7.11
# from tkinter import *
# root = Tk()
# Button(root,text='press',command=root.quit).pack(side=LEFT,expand=YES)
# root.mainloop()
# # Example7.17
# from tkinter import *
#
# def greeting():
# print('Hello stdout world!...')
#
# win = Frame()
# win.pack()
# Label(win,text='Hello container world').pack(side=TOP)
# Button(win,text='Hello',command=greeting).pack(side=LEFT)
# Button(win,text='Quit',command=win.quit).pack(side=RIGHT)
#
# win.mainloop()
# 2018.05.15
|
2cde1073d9e106525a4746802a396415370c6632 | RIAW2013/Intro-to-Python | /palindrome.py | 500 | 3.703125 | 4 | palList= []
def palindrome(x, y):
while y > 99:
palin = x * y
palin_for = str(palin)
palin_bac = str(palin)[::-1]
if palin_for == palin_bac:
palList.append(palin)
if x < 100:
x = 999
y -= 1
else:
x -= 1
print(palin_for, palin_bac, x, y)
print(max(palList))
palindrome(999, 999) |
cce091aa62914b3e55f1f977e5b538a1cd7107fe | sdeepanshu368/Python-Mini-Projects | /pr6 JumbledNames.py | 440 | 4.09375 | 4 | import random
n = int(input("Enter the numbers of friends : "))
firstName = []
lastName = []
for i in range(n):
fname = input(f"Enter the first name of friend {i+1} : ")
lname = input(f"Enter the last name of friend {i+1} : ")
firstName.append(fname)
lastName.append(lname)
random.shuffle(firstName)
random.shuffle(lastName)
print("Here Are Jumbled Names")
for items in zip(firstName,lastName):
print(" ".join(items))
|
2451bc034f033787c672009605c616125270f5ee | cyrillelamal/pogrom | /sem4/task2/primo.py | 947 | 4.28125 | 4 | # Разработать прототип программы «Калькулятор», позволяющую
# выполнять базовые арифметические действия и функцию обертку,
# сохраняющую название выполняемой операции, аргументы и результат в
# файл
FILE = "./log.txt"
def logger(func):
def calc_with_log(*args, **kwargs):
res = func(*args, **kwargs)
with open(FILE, "at") as f:
operator, a, b = args
f.write(f"{a} {operator} {b} = {res}\n")
return calc_with_log
def calc(operator, a, b) -> float:
if operator == '+':
return a + b
elif operator == '-':
return a - b
elif operator == '*':
return a * b
elif operator == '/':
return a / b
else:
raise Exception
func = logger(calc)
func('+', 3, 5)
func('*', 2119, 21)
|
8d806192b0d9e7c4e9af1329defdcaf1362bac97 | PacktPublishing/Getting-Started-with-Python | /Chapter10/hash.py | 242 | 3.640625 | 4 | def hash(data):
counter = 1
sum = 0
for d in data:
sum += counter * ord(d)
return sum % 256
items = ['foo', 'bar', 'bim', 'baz', 'quux', 'duux', 'gnn']
for item in items:
print("{}: {}".format(item, hash(item)))
|
c45e6e8119be02380ee93ee99b5549ed7d974a2a | NawaskhanFathimaMafeeza/code1 | /Circle1.py | 140 | 3.65625 | 4 | class Circle:
def __init__(self,r):
self.radius=r
def __int__(self):
return 3.14 * (self.radius ** 2)
C1=Circle(8)
|
26538ae43d48a8e2fda3ba44cf72081f9fb7cb6f | yurygnutov/hexlet | /solutions/fibonacci.py | 250 | 3.765625 | 4 | __author__ = 'yury'
# Return the N'th item in the Fibonacci sequence. Hint: The first item in the sequence is 0.
# Example:
# 13 == solution(7)
def solution(num):
if num < 2:
return num
return solution(num - 1) + solution(num - 2)
|
ce59d267a57fa4a947177dc6d76e7c61b62dbdaa | nahaza/pythonTraining | /ua/univer/HW06/ch10ProgTrain05/__main__.py | 728 | 4.375 | 4 | # 5. RetailItem Class
# Write a class named RetailItem that holds data about an item in a retail store. The class
# should store the following data in attributes: item description, units in inventory, and price.
# Once you have written the class, write a program that creates three RetailItem objects
# and stores the following data in them:
# Description Units in Inventory Price
# Item #1 Jacket 12 59.95
# Item #2 Designer Jeans 40 34.95
# Item #3 Shirt 20 24.95
import retailitem
def main():
items = []
item1 = retailitem.RetailItem('Jacket', 12, 59.95)
item2 = retailitem.RetailItem('Designer Jeans', 40, 34.95)
item3 = retailitem.RetailItem('Shirt', 20, 24.95)
items = [item1, item2, item3]
main()
|
17ad695b6269c43f88487f3be5d4d4da03f5f270 | Gabeali93/Gabe | /Ali_Networking1.py | 935 | 4.46875 | 4 | #1.) ###Prompt for 'url'###> 2.)read JSON data from the 'url' USING URLLIB 3.) parse and extract the comment #counts JSON data 4.)compute the sum of the numbers in the file and enter below
#using python3 in terminal
import urllib.request
import json
url = input("Enter name of website: ") #create variable 'url' through user input
#url = "http://py4e-data.dr-chuck.net/comments_42.json"
response = urllib.request.urlopen(urllib.request.Request(url)).read().decode('utf-8') #response variable '=' 'url' variable opened and decoded
data = json.loads(response) #'data' '=' json.loads which takes a file object, reads the data and uses the string to create an object
counts = list() #creates list counts
comments = data['comments'] #comments variable '=' looks for comments in 'data'
for comment in comments:
counts.append(comment['count']) #appends 'count' to 'counts' list
print(sum(counts)) #prints sum of 'counts' list
|
06014a5f79fed9d0404e076bf39129224d1e1efc | Kedaj/Cmp108 | /.gitignore/Mj16.py | 652 | 3.8125 | 4 | import turtle
win = turtle.Screen()
tic = turtle.Turtle()
tic.speed(10)
win.setworldcoordinates(-0.5,-0.5,3.5,3.5)
for i in range (0,10):
tic.penup()
tic.goto(0,i)
tic.pendown()
tic.forward(9)
tic.left(90)
for i in range (0,10):
tic.penup()
tic.goto(0,i)
tic.pendown()
tic.forward(9)
import turtle
win = turtle.Screen()
tic = turtle.Turtle()
tic.speed(10)
win.setworldcoordinates(-0.5,-0.5,3.5,3.5)
for i in range (0,10):
tic.penup()
tic.goto(0,i)
tic.pendown()
tic.forward(9)
tic.left(90)
for i in range (0,10):
tic.penup()
tic.goto(i,0)
tic.pendown()
tic.forward(9)
tic.penup
|
4ac0cc8ac3a42bd745aaf482c75e66419a402b88 | sanjeevbhatia3/Python-Programming | /statements.py | 276 | 4.125 | 4 | is_raining = False
if is_raining:
print("Take Umbrella")
else:
print("It is not raining")
dinner = 'cheese pizza'
if dinner == 'veggie pizza':
print('I will have it')
elif dinner == 'chicken pizza':
print('I may have it')
else:
print('I am not hungry')
|
4ea49bee81aca5a227dda469c0b7af91d0489df5 | Hazurl/adventofcode | /2022/advent_of_code/day17/__init__.py | 6,879 | 3.90625 | 4 | from typing import Iterable, Optional, TypeVar
def main() -> None:
with open("./advent_of_code/day17/input.txt") as f:
raw_input = f.read()
print(f"Part 1: {part1(raw_input)}")
print(f"Part 2: {part2(raw_input)}")
class Grid:
def __init__(self):
self.rows = []
def _add_row(self):
self.rows.append([False] * 7)
def get(self, x: int, y: int) -> bool:
if x < 0 or x >= 7:
return True
elif y < 0:
return True
elif y >= len(self.rows):
return False
else:
return self.rows[y][x]
def set(self, x: int, y: int):
while len(self.rows) <= y:
self._add_row()
assert 0 <= x < 7
assert not self.rows[y][x]
self.rows[y][x] = True
def get_origin(self) -> tuple[int, int]:
return (2, len(self.rows) + 3)
def print_it(self, blocks: Optional[Iterable[tuple[int, int]]] = None):
blocks_positions = set(blocks) if blocks is not None else set()
for y in range(len(self.rows) + 3, -1, -1):
row = self.rows[y] if y < len(self.rows) else [False] * 7
print("#", end="")
for x, cell in enumerate(row):
c = "#" if cell else "."
if (x, y) in blocks_positions:
c = "@"
print(c, end="")
print("#")
print("#" * 9)
def compute_hash(self) -> tuple[int, ...]:
# For each column, find the index of the block at the top
# The index is relative to the top-most row
return tuple(
next((index_relative_to_top for index_relative_to_top, row in enumerate(self.rows[::-1]) if row[col]), -1) for col in range(7)
)
class Shape:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def down(self):
self.y -= 1
def left(self):
self.x -= 1
def right(self):
self.x += 1
def up(self):
self.y += 1
def get_relative_blocks(self) -> list[tuple[int, int]]:
raise NotImplementedError
def blocks(self) -> Iterable[tuple[int, int]]:
return [(dx + self.x, dy + self.y) for dx, dy in self.get_relative_blocks()]
def is_colliding(self, grid: Grid) -> bool:
for x, y in self.blocks():
if grid.get(x, y):
return True
return False
def place(self, grid: Grid):
for x, y in self.blocks():
grid.set(x, y)
class HorizontalShape(Shape):
def get_relative_blocks(self) -> list[tuple[int, int]]:
return [
(0, 0),
(1, 0),
(2, 0),
(3, 0),
]
class PlusShape(Shape):
def get_relative_blocks(self) -> list[tuple[int, int]]:
return [
(1, 1),
(1, 0),
(1, 2),
(0, 1),
(2, 1),
]
class JShape(Shape):
def get_relative_blocks(self) -> list[tuple[int, int]]:
return [
(0, 0),
(1, 0),
(2, 0),
(2, 1),
(2, 2),
]
class VerticalShape(Shape):
def get_relative_blocks(self) -> list[tuple[int, int]]:
return [
(0, 0),
(0, 1),
(0, 2),
(0, 3),
]
class CubeShape(Shape):
def get_relative_blocks(self) -> list[tuple[int, int]]:
return [
(0, 0),
(1, 0),
(0, 1),
(1, 1),
]
shapes_order = [
HorizontalShape,
PlusShape,
JShape,
VerticalShape,
CubeShape,
]
T = TypeVar("T")
def repeated(iterable: Iterable[T]) -> Iterable[T]:
while True:
for i in iterable:
yield i
def part1(raw_input: str) -> int:
jets = raw_input.strip()
def play_shape(shape: Shape, jets: Iterable[str]):
for j in jets:
if j == ">":
shape.right()
else:
assert j == "<"
shape.left()
if shape.is_colliding(grid):
# Revert
if j == "<":
shape.right()
else:
shape.left()
shape.down()
if shape.is_colliding(grid):
# Revert
shape.up()
shape.place(grid)
return
grid = Grid()
infinite_jets = repeated(jets)
for i, shape_constructor in enumerate(repeated(shapes_order)):
if i == 2022:
break
shape = shape_constructor(*grid.get_origin())
play_shape(shape, infinite_jets)
return len(grid.rows)
def part2(raw_input: str) -> int:
# Doesn't work...
jets = raw_input.strip()
def play_shape(shape: Shape, index_jets: int):
while True:
j = jets[index_jets % len(jets)]
index_jets += 1
if j == ">":
shape.right()
else:
assert j == "<"
shape.left()
if shape.is_colliding(grid):
# Revert
if j == "<":
shape.right()
else:
shape.left()
shape.down()
if shape.is_colliding(grid):
# Revert
shape.up()
shape.place(grid)
return
grid = Grid()
input_hashes: dict[tuple[int, ...], tuple[int, int]] = dict()
max_i = 1000000000000
for i, shape_constructor in enumerate(repeated(shapes_order)):
index_jets = i % len(jets)
index_shape = i % len(shapes_order)
if index_jets == 0 and index_shape == 0:
grid_hash = grid.compute_hash()
print(f"Hash: {grid_hash}")
if -1 not in grid_hash and grid_hash in input_hashes:
hi, hl = input_hashes[grid_hash]
gl = len(grid.rows)
dl = len(grid.rows) - hl
di = i - hi
mi = max_i - i
print(f"Found loop: {i}={gl}, {hi}={hl}, ~{di}={dl}, {mi}")
print(f"Expected next loop: {i+di}={gl+dl}")
steps = mi // di
print(f"Steps: {steps}")
gl += steps * dl
i += steps * di
print(f"Got {i}={gl}")
# TODO: Do the remaining steps
# In the test case i == max_i, but I get the wrong result, this
# means, the grid_hash is not unique enough
# and the solution is not correct
return gl
else:
input_hashes[grid_hash] = (i, len(grid.rows))
shape = shape_constructor(*grid.get_origin())
play_shape(shape, index_jets)
return len(grid.rows)
if __name__ == "__main__":
main()
|
c6be6235bc81bc0dd648cfc94c84f3b7846e2ea9 | Dturati/Lagrange | /lagrange.py | 2,423 | 3.90625 | 4 | #Python 3
#David Turati
#Metodo de imterpolacao da forma de lagrange
# _*_ coding:latin 1 _*_
from math import sqrt
from functools import reduce
class Lagrange(object):
dominio=[]
imagem = []
resultado_numerador = []
resultado_denominador = []
temp = []
#construtor
def __init__(self,tm):
print("Inicio")
self.__tamanho = tm
for i in range(tm):
self.resultado_denominador.append(0)
self.resultado_numerador.append(str(" "))
#metodos getters
def get__Tamanho(self):
return self.__tamanho
#metodos setters
def set__Tamanho(self,tm):
sefl.__tamanho = tm
#preenche vetor com os valores do dominio
def preeche_dominio(self):
for i in range(self.__tamanho):
print("Digite um valor para x:")
self.dominio.append(int(input()))
print(" ")
#preenche vetor com os valores da imagem
def preeche_imagem(self):
for i in range(self.__tamanho):
print("Digite um valor pra fx:")
self.imagem.append(int(input()))
print(" ")
#calcula valores do denominador
def calcula(self):
for i in range(self.tamanho):
self.resultado_numerador[i]=(str(self.imagem[i])+"*")
for j in range(self.tamanho):
if (j != i):
#realiza subtracoes dos elentos do denominador
self.temp.append(self.subtracao(self.dominio[i],self.dominio[j]))
self.resultado_numerador[i]+=str(('x',-self.dominio[j]))
#realiza multiplicacao dos elementos do denominador
self.resultado_denominador[i] = reduce( (lambda x,y : x*y),self.temp)
#remove elementos da lista
tm = len(self.temp)-1
while(tm >= 0):
del self.temp[tm]
tm = tm-1
print(" ")
#realiza subtracao no denominador
def subtracao(self,x,y):
return x-y
#imprime dominio e imagem
def imprime_dominio_imagem(self):
dm = lambda i : i
print("Dominio X")
print(dm(self.dominio))
print("Imagem F(x)")
img = lambda j : j
print(img(self.imagem))
#imprime resultado
def imprime_resultado(self):
print("As equações são:")
for i,j in enumerate(self.resultado_numerador):
print(j,"Divido por",self.resultado_denominador[i])
print(" ")
#property
tamanho = property(fget = get__Tamanho , fset = set__Tamanho)
class Calcula(Lagrange):
def fim(self):
print("Fim")
print("digite o tamando do dominio e da imagem")
c = Calcula(int(input())) #cria objeto
#chamada de funcoes
c.preeche_dominio()
c.preeche_imagem()
c.imprime_dominio_imagem()
c.calcula()
c.imprime_resultado()
c.fim() |
06ea2de924d733888fe13f8e0609f35db03ac7aa | w1r2p1/crypto-pair-search-engine | /crypto_pair_search_engine.py | 2,528 | 4.3125 | 4 | import cryptowatch as cw
# Asks user to input a trading pair they would like to search
# Think about whether they will enter the entire name or the 3-letter ticker
# Will eventually need this to be a dropdown list with search
pair1_currency1 = input('Enter the abbreviation for the 1st currency of the 1st trading pair to search: ')
pair1_currency2 = input('Enter the abbreviation for the 2nd currency of the 1st trading pair to search: ')
# Pairs in the CryptoWatch API can either be btceth or ethbtc, this code creates both combos to search
pair1_name1 = pair1_currency1 + pair1_currency2
pair1_name2 = pair1_currency2 + pair1_currency1
pair_matrix = []
pair_matrix.append([pair1_name1, pair1_name2])
# Asks user if they want to search a 2nd pair and 3rd pair
second_pair_answer = None
second_pair_answer = input("Would you like to search for another trading pair? Enter y/n: ")
if second_pair_answer == "y":
pair2_currency1 = input(
'Enter the abbreviation for the 1st currency of the 2nd trading pair to search: ')
pair2_currency2 = input(
'Enter the abbreviation for the 2nd currency of the 2nd trading pair to search: ')
pair2_name1 = pair2_currency1 + pair2_currency2
pair2_name2 = pair2_currency2 + pair2_currency1
pair_matrix.append([pair2_name1, pair2_name2])
third_pair_answer = None
third_pair_answer = input("Would you like to search for another trading pair? Enter y/n: ")
if third_pair_answer == "y":
pair3_currency1 = input(
'Enter the abbreviation for the 1st currency of the 3rd trading pair to search: ')
pair3_currency2 = input(
'Enter the abbreviation for the 2nd currency of the 3rd trading pair to search: ')
pair3_name1 = pair3_currency1 + pair3_currency2
pair3_name2 = pair3_currency2 + pair3_currency1
pair_matrix.append([pair3_name1, pair3_name2])
print(pair_matrix)
# Searches all pairs in pair_matrix for markets
all_markets = cw.markets.list()
market_exchange_count = 0
for pair_combo in pair_matrix:
for pair in pair_combo:
for market in all_markets.markets:
if market.pair == pair:
print("{} has a {} market".format(market.exchange, pair))
market_exchange_count = market_exchange_count + 1
if market_exchange_count == 0:
print("There doesn't seem to be a market for these currencies. Wanna try another pair?")
else:
print("There are {} exchanges that have this market".format(market_exchange_count))
|
21e29fa1afe44ffcd4bb274b8882335d671d267b | bodii/test-code | /python/python-cookbook-test-code/7 section/12.py | 4,080 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Topic: 第七章:函数
Desc: 使用 def 语句定义函数是所有程序的基础。本章的目标是讲解一些更加高级和不
常见的函数定义与使用模式。涉及到的内容包括默认参数、任意数量参数、强制关键
字参数、注解和闭包。另外,一些高级的控制流和利用回调函数传递数据的技术在这
里也会讲解到。
Title; 访问闭包中定义的变量
Issue:你想要扩展函数中的某个闭包,允许它能访问和修改函数的内部变量。
Answer: 通常来讲,闭包的内部变量对于外界来讲是完全隐藏的。但是,你可以通过编写访
问函数并将其作为函数属性绑定到闭包上来实现这个目的。
"""
def sample():
n = 0
def func():
print('n=', n)
def get_n():
return n
def set_n(value):
nonlocal n
n = value
func.get_n = get_n
func.set_n = set_n
return func
f = sample()
f()
# n= 0
f.set_n(10)
f()
# n= 10
print(f.get_n())
# 10
"""
为了说明清楚它如何工作的,有两点需要解释一下。首先,nonlocal 声明可以让
我们编写函数来修改内部变量的值。其次,函数属性允许我们用一种很简单的方式将
访问方法绑定到闭包函数上,这个跟实例方法很像 (尽管并没有定义任何类)。
还可以进一步的扩展,让闭包模拟类的实例。你要做的仅仅是复制上面的内部函数
到一个字典实例中并返回它即可。
"""
import sys
class ClosureInstance:
def __init__(self, locals=None):
if locals is None:
locals = sys._getframe(1).f_locals
self.__dict__.update(
(key, value) for key, value in locals.items()
if callable(value)
)
def __len__(self):
return self.__dict__['__len__']()
def Stack():
items = []
def push(item):
items.append(item)
def pop():
return items.pop()
def __len__():
return len(items)
return ClosureInstance()
"""
下面是一个交互式会话来演示它是如何工作的
"""
s = Stack()
print(s)
# <__main__.ClosureInstance object at 0x000002D6FAB534A8>
print(s.push(10))
# None
print(s.push(20))
# None
print(s.push('hello'))
print(len(s))
# 3
print(s.pop())
# hello
print(s.pop())
# 20
print(s.pop())
# 10
class Stack2:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.itmes.pop()
def __len__(self):
return len(self.itmes)
"""
如果这样做,你会得到类似如下的结果
"""
from timeit import timeit
s = Stack()
print(timeit('s.push(1);s.pop()', 'from __main__ import s'))
s = Stack2()
print(timeit('s.push(1);s.pop()', 'from __main__ import s'))
"""
结果显示,闭包的方案运行起来要快大概 8%,大部分原因是因为对实例变量的简
化访问,闭包更快是因为不会涉及到额外的 self 变量。
Raymond Hettinger 对于这个问题设计出了更加难以理解的改进方案。不过,你得
考虑下是否真的需要在你代码中这样做,而且它只是真实类的一个奇怪的替换而已,
例如,类的主要特性如继承、属性、描述器或类方法都是不能用的。并且你要做一些其
他的工作才能让一些特殊方法生效 (比如上面 ClosureInstance 中重写过的 len ()
实现。)
最后,你可能还会让其他阅读你代码的人感到疑惑,为什么它看起来不像一个普通
的类定义呢?(当然,他们也想知道为什么它运行起来会更快)。尽管如此,这对于怎样
访问闭包的内部变量也不失为一个有趣的例子。
总体上讲,在配置的时候给闭包添加方法会有更多的实用功能,比如你需要重置内
部状态、刷新缓冲区、清除缓存或其他的反馈机制的时候。
""" |
5ad92eb7c97e913b947092519fa6b3faccbfdf3f | Minakshi-Verma/Intro-Python-II | /src/item.py | 663 | 3.921875 | 4 | class Item:
def __init__(self, name, description):
self.name = name
self.description = description
#create instances of class Item
item_1 = Item('key', 'You can open the treasure box!')
item_2 = Item("sword", "You can kill the monsters!")
item_3 = Item("flashlight", "You can see in the dark")
item_4 = Item("backpack", "You might need this to carry your newly found treasure!")
item_5 = Item("lightsaber", "You got special powers!")
item_6 = Item("hat", "You got a swag, keep it safe!")
item_7 = Item("nail", "You can hang your swag here!")
item_8 = Item("hammer", "You will need this to put your nail on the wall!")
# print(item_1.name) |
c67628e5ed8ab483de84d6f3b58a3df8df7c9ca0 | eronekogin/leetcode | /2020/longest_increasing_path_in_a_matrix.py | 1,488 | 4.0625 | 4 | """
https://leetcode.com/problems/longest-increasing-path-in-a-matrix/
"""
from typing import List
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
if not matrix or not matrix[0]: # Empty matrix.
return 0
R, C = len(matrix), len(matrix[0])
memo = [[0] * C for _ in range(R)]
def walk(currRow: int, currCol: int) -> int:
"""
Start from the cell specified by (currRow, currCol) and
try to walk to its four directions and return the length
of the longest path it could get.
"""
if not memo[currRow][currCol]: # Current cell is not calculated.
nextMaxLen = 0
for nextRow, nextCol in [
(currRow, currCol - 1), (currRow, currCol + 1),
(currRow - 1, currCol), (currRow + 1, currCol)]:
if -1 < nextRow < R and -1 < nextCol < C and \
matrix[nextRow][nextCol] > matrix[currRow][currCol]:
nextMaxLen = max(nextMaxLen, walk(nextRow, nextCol))
memo[currRow][currCol] = 1 + nextMaxLen
return memo[currRow][currCol]
rslt = 0
for r in range(R):
for c in range(C):
rslt = max(rslt, walk(r, c))
return rslt
matrix = [
[3, 4, 5],
[3, 2, 6],
[2, 2, 1]
]
print(Solution().longestIncreasingPath(matrix))
|
0c1543ef06f262abfc38b6ba403db391fa64f4f6 | tpracser/PracserTamas-GF-cuccok | /week-03/day-3/06a.py | 404 | 4.34375 | 4 | # create a function that takes a list and returns a new list that is reversed
list = [2, 6, 8, 4, 10, 7]
def newList(lista):
new_list = []
print("The original list:", lista)
for i in range(len(lista)):
lastPosition = len(lista)-1
new_list.append(lista[lastPosition])
lista.remove(lista[lastPosition])
print("This is the reversed list:", new_list)
newList(list)
|
9b422733fd6b4342546b16d7b8344fdbc9d97fc8 | chr1sM/Programacao | /Ficha 4 (Entregar)/Ex 2.py | 687 | 3.890625 | 4 | #1 euro = 1.2323 dolar
dolar = 1.2323
#1 dolar = 0.81148 euro
euro = 0.81148
print('Conversao de Euro(€) para Dolar($) ou Dolar($) para Euro(€)')
print('Introduza o valor e o caracter. ')
valor = float(input('Introduza o valor: '))
caracter = input('Escolha o caracter que queira E ou D: ')
def conversao(valor, caracter , dolar , euro):
if caracter == "d" or caracter == "D":
totald = valor * euro
print('Conversao de dolares para euros {0:.2f} €'.format(totald))
elif caracter == "e" or caracter == 'E':
totale = valor * dolar
print('Conversao de euros para Dolares {0:.2f} $'.format(totale))
conversao(valor, caracter , dolar , euro)
|
b5c442809a7a218bdff857ae6f63c9a8224605ad | praveen5658/cspp1 | /cspp1_practise/cspp1-assignments/m6/p3/digit_product.py | 660 | 3.859375 | 4 | '''
Author :Praveen
Date : 04-08-2018
'''
def main():
'''
THis function prints the product of digits in the given number
'''
int_input = int(input())
if int_input == 0:
print(int_input)
else:
fl_ag = 0
if int_input < 0:
fl_ag = 1
int_input = abs(int_input)
rem_inder = 0
pro_duct = 1
while int_input != 0:
rem_inder = int_input % 10
pro_duct = pro_duct * rem_inder
int_input = int_input // 10
if fl_ag == 1:
print(0 - pro_duct)
else:
print(pro_duct)
if __name__ == "__main__":
main()
|
0938686867e8f3011b30682a1a68b92afba4320e | poparrish/AutoDock | /Rotation_Matrix/calc_pose.py | 789 | 3.5 | 4 | import math
def calculate_translation(y_theta, z_dist, approach_dist):
"""
Returns the translation vector needed to reach the "approach point" (rad, dist)
:param y_theta: rotation of platform (rad)
:param z_dist: distance to platform (cm)
:param approach_dist: desired distance in front of platform (cm)
:return:
"""
# find dist to approach point using law of cosines
dist = math.sqrt(approach_dist**2 + z_dist**2 - 2 * approach_dist * z_dist * math.cos(y_theta))
rel_angle = math.asin(approach_dist * math.sin(y_theta) / dist)
angle = -y_theta - rel_angle
# handle case when we're in front of the approach point
if z_dist < approach_dist:
angle = -angle + math.copysign(math.pi, angle)
return math.degrees(angle), dist
|
44d076f38a1a4acc1b338abf50b9d02d8e461907 | mariamhayrapetyan/Sudoku_AI_Diff_Search_Algorithms | /CSP.py | 6,577 | 3.578125 | 4 | import itertools
rows = "123456789"
cols = "ABCDEFGHI"
class Sudoku:
def __init__(self, grid):
self.variables = list()
self.variables = self.generate_variables()
self.domains = dict()
self.domains = self.generate_domains(grid)
global_constraints = self.generate_global_constraints()
self.binary_constraints = list()
self.binary_constraints = self.generate_binary_constraints(global_constraints)
self.neighbors = dict()
self.neighbors = self.generate_neighbor_variables()
self.eliminated = dict()
self.eliminated = {v: list() if grid[i] == '0' else [int(grid[i])] for i, v in enumerate(self.variables)}
def generate_variables(self):
variables = []
for col in cols:
for row in rows:
new_variable = col + row
variables.append(new_variable)
return variables
def generate_domains(self, grid):
grid_list = list(grid)
domains = dict()
for i, variable in enumerate(self.variables):
if grid_list[i] == "0":
domains[variable] = list(range(1, 10))
else:
domains[variable] = [int(grid_list[i])]
return domains
def generate_global_constraints(self):
row_constraints = []
column_constraints = []
subgrid_constraints = []
#rows constraints
for row in rows:
row_constraints.append([col + row for col in cols])
#columns constraints
for col in cols:
column_constraints.append([col + row for row in rows])
#subgrid constraints
rows_subgrid = (cols[i:i + 3] for i in range(0, len(rows), 3))
rows_subgrid = list(rows_subgrid)
cols_subgrid = (rows[i:i + 3] for i in range(0, len(cols), 3))
cols_subgrid = list(cols_subgrid)
for row in rows_subgrid:
for col in cols_subgrid:
current_subgrid_constraints = []
for i in row:
for j in col:
current_subgrid_constraints.append(i + j)
subgrid_constraints.append(current_subgrid_constraints)
return row_constraints + column_constraints + subgrid_constraints
def generate_binary_constraints(self, global_constraints):
generated_binary_constraints = list()
for constraint_set in global_constraints:
binary_constraints = list()
for i in itertools.permutations(constraint_set, 2):
binary_constraints.append(i)
for constraint in binary_constraints:
constraint_list = list(constraint)
if (constraint_list not in generated_binary_constraints):
generated_binary_constraints.append([constraint[0], constraint[1]])
return generated_binary_constraints
def generate_neighbor_variables(self):
neighbor_variables = dict()
for var in self.variables:
neighbor_variables[var] = list()
for constraint in self.binary_constraints:
if var == constraint[0]:
neighbor_variables[var].append(constraint[1])
return neighbor_variables
def isFinished(self):
for variables, domains in self.domains.items():
if len(domains) > 1:
return False
return True
def __str__(self):
output = ""
count = 1
round = 0
for variable in self.variables:
value = str(self.domains[variable])
if type(self.domains[variable]) == list:
if len(self.domains[variable]) > 1:
value = "0"
else:
value = str(self.domains[variable][0])
output += " " + value + " "
if count % 3 == 0:
output += "|"
if count >= 9:
count = 0
round += 1
output = output[:-1]
output += "\n"
tazaban = round * 9
if tazaban % 27 == 0 and tazaban != 81:
output += "=============================\n"
count += 1
return output
def not_equal(xi, xj):
result = xi != xj
return result
def number_of_conflicts(csp, var, value):
count = 0
for neighbor in csp.neighbors[var]:
if len(csp.domains[neighbor]) > 1 and value in csp.domains[neighbor]:
count += 1
return count
def is_consistent(csp, assignment, var, value):
is_consistent = True
for current_var, current_value in assignment.items():
if current_value == value and current_var in csp.neighbors[var]:
is_consistent = False
return is_consistent
def assign(var, value, assignment):
assignment[var] = value
def assign_with_forward_check(csp, var, value, assignment):
assignment[var] = value
if csp.domains:
forward_check(csp, var, value, assignment)
def unassign(var, assignment):
if var in assignment:
del assignment[var]
def unassign_with_forward_check(csp, var, assignment):
if var in assignment:
for (variable, value) in csp.eliminated[var]:
csp.domains[variable].append(value)
csp.eliminated[var] = []
del assignment[var]
def forward_check(csp, var, value, assignment):
for neighbor in csp.neighbors[var]:
if neighbor not in assignment:
if value in csp.domains[neighbor]:
csp.domains[neighbor].remove(value)
csp.eliminated[var].append((neighbor, value))
# def print_grid1(grid):
# output = ""
# count = 1
# round = 0
#
# for cell in grid:
#
# value = cell
# output += " " + value + " "
#
# if count % 3 == 0:
# output += "|"
# if count >= 9:
# count = 0
# round += 1
# output = output[:-1]
# output += "\n"
# tazaban = round * 9
# if tazaban % 27 == 0 and tazaban != 81:
# output += "=============================\n"
# count += 1
# return output
|
621e565e4f87ed43f7161fed09e40872fe051398 | sanketc029/python_assi2 | /Assi_2/assignment2_5.py | 283 | 4.03125 | 4 |
def prime(no):
cnt=1
for i in range(2,no):
if no%i==0:
cnt=0
break
if cnt == 1:
print("Number is prime")
else:
print("Number is not prime")
print("Enter the number")
no=int(input())
prime(no)
|
ee3125537d60fccede81f704729fb3889d0f17de | sainathurankar/Python-programs | /InsertionSort.py | 310 | 4.125 | 4 | def InsertionSort(arr):
l=len(arr)
for i in range(1,l):
key=arr[i]
j=i-1
while j>=0 and arr[j]>key:
arr[j+1]=arr[j]
j=j-1
arr[j+1]=key
arr=list(map(int,input("Enter array: ").split()))
InsertionSort(arr)
print("Sorted Array:",*arr)
|
56f84ee9f7bc86723e50cc8a3fb949a3a6637795 | jdwestwood/algorithms_pt2 | /HWwk3_prob1_knapsack.py | 1,963 | 3.703125 | 4 | # Algorithms Pt2 HW 3 problem 1 9/19/2013
#
# File format is:
# [knapsack_size][number_of_items], followed by [value1][weight1] ... , one item per line
# Maximum value of items in knapsack, subject to total weight <= knapsack size
#
# see slides-dp-algo2-dp-knapsack.pdf's from lecture notes
# 9/26/13: ran program on the problem dataset and obtain 2493893 for the maximum value.
from sys import exit # allows me to exit the program early using exit(0)
import time # allows me to time the execution of various parts of code
class item:
value = 0
weight = 0
dataFile = open('example10.txt', 'r')
#dataFile = open('HWwk3_prob1_knapsack_example.txt', 'r')
#dataFile = open('HWwk3_prob1_knapsack.txt', 'r')
header = dataFile.readline().split()
knapSize = int(header[0])
nItem = int(header[1])
print knapSize, nItem
# create the knapsack value array A[iItem][jWeight]
A = [[0 for jWeight in range(knapSize+1)] for iItem in range(nItem+1)] # will use the 0 indices in the algorithm
itemList = []
itemList.append(item()) # add empty item to occupy the 0-index position
for line in dataFile: # read items into array of item objects
itemData = line.split()
curItem = item()
curItem.value = float(itemData[0])
curItem.weight = int(itemData[1])
itemList.append(curItem)
# use knapsack algorithm without optimizing the array storage strategy.
for iItem in range(1,nItem+1): # 1 to nItem-1
for jWeight in range(knapSize+1): # 0 to knapSize
noItem_i = A[iItem-1][jWeight]
if jWeight - itemList[iItem].weight >= 0:
withItem_i = A[iItem-1][jWeight - itemList[iItem].weight] + itemList[iItem].value
else:
withItem_i = 0
A[iItem][jWeight] = max(noItem_i, withItem_i)
print "The maximum value for items in the knapsack is:", A[nItem][knapSize]
|
5570b28b00245d5c3a3cbefa2882b218dcde94ee | oneshan/Leetcode | /accepted/013.roman-to-integer.py | 982 | 3.828125 | 4 | #
# [13] Roman to Integer
#
# https://leetcode.com/problems/roman-to-integer
#
# Easy (45.22%)
# Total Accepted:
# Total Submissions:
# Testcase Example: '"DCXXI"'
#
# Given a roman numeral, convert it to an integer.
#
# Input is guaranteed to be within the range from 1 to 3999.
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
num, i, currV = 0, 1, roman[s[0]]
while i < len(s):
nextV = roman[s[i]]
if nextV > currV:
num -= currV
else:
num += currV
i += 1
currV = nextV
num += currV
return num
if __name__ == "__main__":
sol = Solution()
print(sol.romanToInt('MCMLIV'))
print(sol.romanToInt('MMXIV'))
|
d3dcb43a7fa8e193bc5364d6f016e6a7ca188465 | fascarii/Projetos-Python | /Curso em vídeo - Python/Exercícios/cev_ex026.py | 909 | 4.125 | 4 | # contando número de aparições de uma letra sem acento
# não consegui fazer sozinho
texto = str(input('Digite seu texto:\n')).strip().lower()
#conta quantas vezes a letra aparece
contagem_a = texto.count('a')
#localiza a posição a partir do começo da frase, depois pelo fim
prim_a = (texto.find('a')+1)
ult_a = (texto.rfind('a')+1)
# mensagens são impressas conforme os resultados acima
# se a letra aparece uma vez
if contagem_a == 1:
print("No texto digitado a letra 'a' aparece {} vez.".format(contagem_a))
# se a letra não aparece
elif contagem_a == 0:
print('A letra "a" não aparece no texto digitado.')
#se a letra aparece mais de uma vez
else:
contagem_a > 1
print("No texto digitado a letra 'a' aparece {} vezes.".format(contagem_a))
# informa as posições das letras
print("A primeira vez na posição {}.".format(prim_a))
print("A última vez na posição {}.".format(ult_a)) |
6292f47843616d7c476fa4898c81772620a4b161 | 9Echo/gc-goods-allocation | /app/test/test_json.py | 897 | 3.515625 | 4 | import json
class Customer:
def __init__(self, name, grade, age, home, office):
self.name = name
self.grade = grade
self.age = age
self.address = Address(home, office)
def __repr__(self):
return repr((self.name, self.grade, self.age, self.address.home,
self.address.office))
class Address:
def __init__(self, home, office):
self.home = home
self.office = office
def __repr__(self):
return repr((self.name, self.grade, self.age))
if __name__ == "__main__":
customers = [
Customer('john', 'A', 15, '111', 'aaa办公室'),
Customer('jane', 'B', 12, '222', 'bbb办公室'),
Customer('dave', 'B', 10, '333', 'ccc办公室')]
json_str = json.dumps(
customers[0].address.__dict__, sort_keys=True,
ensure_ascii=False, indent=4)
print(json_str)
|
d79fc10d6e4f2741d94c0a847b2fa4d8b939ff28 | eireneapostol/codeadvent | /day7/code2.py | 5,663 | 3.8125 | 4 | '''
--- Part Two ---
The programs explain the situation: they can't get down. Rather, they could get down, if they weren't expending all of their energy trying to keep the tower balanced. Apparently, one program has the wrong weight, and until it's fixed, they're stuck here.
For any program holding a disc, each program standing on that disc forms a sub-tower. Each of those sub-towers are supposed to be the same weight, or the disc itself isn't balanced. The weight of a tower is the sum of the weights of the programs in that tower.
In the example above, this means that for ugml's disc to be balanced, gyxo, ebii, and jptl must all have the same weight, and they do: 61.
However, for tknk to be balanced, each of the programs standing on its disc and all programs above it must each match. This means that the following sums must all be the same:
ugml + (gyxo + ebii + jptl) = 68 + (61 + 61 + 61) = 251
padx + (pbga + havc + qoyq) = 45 + (66 + 66 + 66) = 243
fwft + (ktlj + cntj + xhth) = 72 + (57 + 57 + 57) = 243
As you can see, tknk's disc is unbalanced: ugml's stack is heavier than the other two. Even though the nodes above ugml are balanced, ugml itself is too heavy: it needs to be 8 units lighter for its stack to weigh 243 and keep the towers balanced. If this change were made, its weight would be 60.
Given that exactly one program is the wrong weight, what would its weight need to be to balance the entire tower?
'''
import json
import re
f = open("./inputs/day7","r")
towers = []
# reading input in a list of towers
for line in f:
tower = {}
line = line.split()
tower["aa_name"] = line[0]
match = re.search('[0-9]+',line[1]) # extract the weight from the parenthesis
weight = (str(match.group()))
tower["aa_weight"] = int(weight)
if len(line) > 2:
tower["children"] = []
for i in range(3, len(line)):
child_name = line[i].split(',')[0] # remove the coma from the name
tower["children"].append(child_name)
towers.append(tower)
# arranging the towers in a tree
def create_tree(tree,root):
#print(tree)
#print(json.dumps(towers, indent=4, sort_keys=True))
for tower in towers:
if tower["aa_name"] == root:
#print(root)
tree["aa_name"] = root
tree["aa_weight"] = tower["aa_weight"]
towers.remove(tower)
tree["aa_children_weight"] = 0
if "children" in tower:
#print(root)
tree["children"] = []
for tower_child in tower["children"]:
child = {}
#child["name"] = tower_children
child_name = tower_child
#print(tower_children)
child = create_tree(child,child_name)
tree["children"].append(child)
return tree
def search_tree(tree):
#print(tree["aa_name"])
if "children" in tree:
for i in tree["children"]:
#print(i["aa_name"])
tree["aa_children_weight"] += search_tree(i)
#print(tree["aa_children_weight"])
return int(tree["aa_children_weight"]) + tree["aa_weight"]
#print(tree["weight"])
else:
return int(tree["aa_weight"])
def check_tree(tree):
if "children" in tree:
subtower_weight_list = []
for i in tree["children"]:
check_tree(i)
subtower_weight_list.append((i["aa_weight"] + i["aa_children_weight"]))
#subtower_weight_list = list(set(subtower_weight_list))
subtower_weight_list = sorted(subtower_weight_list)
bb = "false"
#print(subtower_weight_list)
if subtower_weight_list[len(subtower_weight_list) - 1] != subtower_weight_list[len(subtower_weight_list) - 2]:
unbalanced = subtower_weight_list[len(subtower_weight_list) - 1]
balanced = subtower_weight_list[len(subtower_weight_list) - 2]
bb = "true"
elif subtower_weight_list[0] != subtower_weight_list[1]:
unbalanced = subtower_weight_list[0]
balanced = subtower_weight_list[1]
bb = "true"
if (bb == "true"):
for i in tree["children"]:
if (i["aa_weight"] + i["aa_children_weight"]) == unbalanced:
ww = i["aa_weight"]
#print(ww)
#print(i["aa_name"])
#print(balanced)
#print(unbalanced)
if balanced > unbalanced:
print(ww + abs(balanced-unbalanced))
return ww + abs(balanced-unbalanced)
else:
print(ww - abs(balanced-unbalanced))
return ww - abs(balanced-unbalanced)
def check_tree2(tree):
if "children" in tree:
subtower_weight_list = []
for i in tree["children"]:
subtower_weight_list.append(i["aa_children_weight"] + i["aa_weight"])
print(i["aa_name"])
#subtower_weight_list = sorted(subtower_weight_list)
print(subtower_weight_list)
#print(tree["weight"])
#return int(tree["weight"])
#root = "tknk" # obtained from running the test example from Part1
root = "mwzaxaj" #obtained from running input code from Part1
#root = "xegshds"
tree = {}
tree = create_tree(tree,root)
#children_balanced = "yes"
search_tree(tree)
check_tree(tree) # the first printed number is the highes unbalanced tower
print(json.dumps(towers, indent=4, sort_keys=True))
print(json.dumps(tree, indent=4, sort_keys=True)) |
124ca339577cf68b84fd5e4dbf666f4dd3e2b568 | chudierp/stacksandqueues | /stacks/stack.py | 341 | 3.78125 | 4 | class Stack:
def __init__(self):
#CREATE AN EMPTY stack
#put the front at index 0
#back at index n - 1
self.my_stack = []
def enstack(self, item):
self.my_stack.append(item)
def destack(self, item):
self.my_stack.pop(0)
def peek(self, item):
return self.my_stack[0] |
bfd721addfc2915b3a08754547cc9f8ac7163eb5 | rakeshvar/Lekhaka | /telugu/splitglyph.py | 536 | 3.8125 | 4 | import re
pattern = re.compile(r'([క-హ]|్[క-హ]|[ా-్])')
def akshara_to_glyphs(akshara):
if akshara[-1] in "ృౄౢౣ":
return akshara_to_glyphs(akshara[:-1]) + [akshara[-1]]
elif len(akshara) <= 2:
return [akshara]
elif akshara[1] == "్":
parts = pattern.findall(akshara)
if len(akshara) % 2 == 0:
return [parts[0]+parts[-1]] + parts[1:-1]
else:
return parts
else:
raise ValueError("Did not understand akshara: ", akshara) |
8142c2460a3c997838fad6b2959135420be9b602 | JefterV/Cursoemvideo.py | /Exercícios/ex075.py | 612 | 3.90625 | 4 | num = (int(input('Numeor inteiro: ')),
int(input('Numeor inteiro: ')),
int(input('Numeor inteiro: ')),
int(input('Numeor inteiro: ')))
print(f'O numeros digitados foram: {num}')
print(f'O numero 9, foi digitado {num.count(9)} vezes')
if 3 in num:
print(f'O valor 3, apareceu na posição {num.index(3)+1}')
else:
print('O numero 3 não foi digitado.')
#print(f'Foram digitados os numeros: ', end='')
n = 0
for p in num:
if p % 2 == 0:
n += 1
print(f'\nForam digitados {n} pares. Eles são: ',end='')
for p in num:
if p % 2 == 0:
print(f'{p}...', end=' ')
|
db0617dadb2166b737ba83b2de4504e6f73530ff | soultalker/gaoyuecn | /Python123/format.py | 251 | 4.125 | 4 | age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name,age))
print('{:.3f}'.format(float(age)/3))
print('{name} wrote {book}'.format(name='Swaroop',book='A Byte of Python'),end='/')
print('{:_^11}'.format('hello')) |
af45ba17d4be17b325ebfa292b88b8c84b6e027a | roshangardi/Leetcode | /70. Climbing Stairs.py | 2,085 | 4.28125 | 4 | # I didn't understand why this solution of fibonacci method works.
# Update: I finally understood when I traced the recursion tree diagram from bottom up
from typing import List
"""
The problem seems to be a dynamic programming one. Hint: the tag also suggests that!
Here are the steps to get the solution incrementally.
Base cases: if n <= 0, then the number of ways should be zero. if n == 1, then there is only way to climb the stair.
if n == 2, then there are two ways to climb the stairs. One solution is one step by another; the other one is two
steps at one time.
The key intuition to solve the problem is that given a number of stairs n, if we know the number ways to get to the
points [n-1] and [n-2] respectively, denoted as n1 and n2 , then the total ways to get to the point [n] is n1 + n2.
Because from the [n-1] point, we can take one single step to reach [n]. And from the [n-2] point, we could take two
steps to get there.
The solutions calculated by the above approach are complete and non-redundant. The two solution sets (n1 and n2)
cover all the possible cases on how the final step is taken. And there would be NO overlapping among the final
solutions constructed from these two solution sets, because they differ in the final step.
Now given the above intuition, one can construct an array where each node stores the solution for each number n. Or
if we look at it closer, it is clear that this is basically a fibonacci number, with the starting numbers as 1 and 2,
instead of 1 and 1.
Check Similar problems:
https://leetcode.com/problems/decode-ways
https://leetcode.com/problems/unique-paths/
https://leetcode.com/problems/fibonacci-number/
"""
class Solution:
def climbStairs(self, n):
# Base Cases
if n <= 0: return 0
if n == 1: return 1
if n == 2: return 2
first = 1
second = 2
third = 0
for i in range(2, n):
third = first + second
first = second
second = third
return third
sol = Solution()
print(sol.climbStairs(4))
|
f30627e838410b236e552589ebca6c5afb52a553 | jesssyb/PythonYear2 | /3.4/3.4.py | 1,890 | 3.953125 | 4 | #Jessica
#Continents
def infile():
op = open("Continent.txt",'r')
l = []
for x in op:
l.append(x.rstrip())
op.close()
l2 = []
for x in range(len(l)):
split = l[x].split(',')
app = l2.append(split)
for x in range(len(l2)):
l2[x][2] = eval(l2[x][2])
l2[x][3] = eval(l2[x][3])
return l2
def area():
print ("Countries organized by area in increasing order:")
l = []
for x in range(len(infile())):
l.append(infile()[x][3])
l.sort()
for x in l:
print (x,)
for z in range(len(l)):
if x == infile()[z][3]:
print (infile()[z][0])
return area3()
def area3():
print ("\nTop 3 countries with the most area:")
l = []
for x in range(len(infile())):
l.append(infile()[x][3])
l.sort()
l.reverse()
c = 0
for x in l:
print (x,)
for z in range(len(l)):
if x == infile()[z][3]:
print (infile()[z][0])
c+=1
if c == 3:
break
return pop()
def pop():
print ("\nCountries organized by increasing population:")
l = []
for x in range(len(infile())):
l.append(infile()[x][2])
l.sort()
for x in l:
print (x,)
for z in range(len(l)):
if x == infile()[z][2]:
print (infile()[z][0])
return pop3()
def pop3():
print ("\nTop 3 countries with highest population:")
l = []
for x in range(len(infile())):
l.append(infile()[x][2])
l.sort()
l.reverse()
c = 0
for x in l:
print (x,)
for z in range(len(l)):
if x == infile()[z][2]:
print (infile()[z][0])
c +=1
if c == 3:
break
area()
|
fd896458e66fceca47a79b19c9956799f4e5d26b | indurkhya/Python_PES_Training | /Ques49.py | 691 | 4.09375 | 4 | # Write a program to perform following file operations
# a) Open the file in read mode and read all its contents on to STDOUT.
# b) Open the file in write mode and enter 5 new lines of strings in to the new file.
# c) Open file in Append mode and add 5 lines of text into it.
fo = open("firstFile.txt","r")
print("Read String is : ",fo.read())
fo.close()
fo=open("firstFile2.txt","w")
fo.writelines("so we have come to the end now\ni don't think this is\nyes very true\n still to go\n this is final now")
fo.close()
fo=open("firstFile2.txt","a")
fo.writelines("finally\nso we have come to the end now\n again and again\nsorry to keep you waiting\nFINAL ONE!!!!")
fo.close() |
72c12f538fbd1b2b32e317d90e941a3c3c652770 | yuriarthurf/Python-semana-3 | /parte2 - 8.py | 284 | 3.796875 | 4 |
def funcao(j):
return j + 1
list = []
n = 0
while n != 'sair':
list.append(n)
n = input("Digite os elementos da lista. Digite 'sair' para sair: ")
list.pop(0)
def my_map(list, f):
for i in list:
print(i)
print(my_map(list, funcao(10))) |
66750243e6f40e42a16fb063deff84a763aa354a | Alejandro-C/aprendiendo.py | /4-tipos_de_datos_complejos.py | 930 | 3.875 | 4 | # TUPLAS
miTupla = (1, 'a', 3, 'e', 5, 'i', 7, 'o', 9, 'u')
print(miTupla)
# Un elemento de la tupla
print(miTupla[2])
# Una seccion de la tupla
print(miTupla[2:6])
# Otra forma de acceder a los elemtosde la tupla
print(miTupla[-1])
# LISTAS
miLista = [1, 'a', 3, 'e', 5, 'i', 7, 'o', 9, 'u']
print(miLista)
# Un elemento de la Lista
print(miLista[2])
# Una seccion de la Lista
print(miLista[2:6])
# Otra forma de acceder a los elemtosde la Lista
print(miLista[-1])
# modificar el valor de una posicion
miLista[1] = 'A'
print(miLista)
# Agregar un nuevo valor a la lista
miLista.append(0)
print(miLista)
# DICCIONARIOS
miDiccionario = {
'clave1' : 'valor1',
'clave2' : 'valor2',
'clave3' : 'valor3'
}
print(miDiccionario)
# acceder a un valor
print(miDiccionario['clave2'])
# eliminar un valor
del(miDiccionario['clave2'])
print(miDiccionario)
# modificar un valor
miDiccionario['clave1'] = 1
print(miDiccionario) |
8acf366a767976cdfd3a3fb5ea7d04eafaaf1705 | Shubham8037/Project-Euler-Challenge | /Problem 1 - Multiples of 3 and 5/Problem_1.py | 1,090 | 4.4375 | 4 | #!/bin/python3
"""
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of
these multiples is 23. Find the sum of all the multiples
of 3 or 5 below the provided parameter value number
"""
def solLogic(multipleOf, actualRange):
# Range is updated since problem says numbers below 10000
actualRange -= 1
# Number or terms is calculated
number_of_terms = actualRange//multipleOf
# Formula for Finite Arithmetic Progression
sum_of_terms = (number_of_terms)*(number_of_terms+1)/2
# Sum of series is returned by multiplying the multiple to calculate its sum
return int(sum_of_terms*(multipleOf))
def sumOfMultiples(number):
# Calculates sum of terms up to the given range
sumOf3 = solLogic(3, number)
sumOf5 = solLogic(5, number)
sumOf15 = solLogic(15, number)
# Multiple of 15 is duplicated so 1 multiple needs to be removed
final_value = sumOf3+sumOf5-sumOf15
# Finally Sum is returned
return final_value
if __name__ == '__main__':
print(sumOfMultiples(1000))
|
18c3e41d36fc4b1a9850fe1c744251bf74d54080 | YaniLozanov/Software-University | /Python/PyCharm/04.Complex Conditional Statements/06. Point on Rectangle Border.py | 2,537 | 4.34375 | 4 | # Problem:
# The fruit shop during the working days works at the following prices:
# fruit: banana apple orange grapefruit kiwi pineapple grapes
# price: 2.50 1.20 0.85 1.45 2.70 5.50 3.85
# Saturday and Sunday the shop runs at higher prices:
# fruit banana apple orange grapefruit kiwi pineapple grapes
# price 2.70 1.25 0.90 1.60 3.00 5.60 4.20
# Write a program that reads from the fruit console (banana / apple / orange / grapefruit / kiwi / pineapple /
# grapes), day of the week (Monday / Tuesday / Wednesday / Wednesday / Friday / Saturday / Sunday) and quantity
# (decimal number) and calculate the price according to the prices in the tables above.
# Print the result rounded by 2 digits after the decimal point. Invalid day of the week or invalid fruit name to print "error".
fruit = input()
day = input()
quantity = float(input())
price = 0
valid_Day = day == "Monday" or day == "Tuesday" or\
day == "Wednesday" or day == "Thursday" or\
day == "Friday"
if day == "Saturday" or day == "Sunday":
if fruit == "banana":
price = quantity * 2.70
print(price)
elif fruit == "apple":
price = quantity * 1.25
print(price)
elif fruit == "orange":
price = quantity * 0.90
print(price)
elif fruit == "grapefruit":
price = quantity * 1.60
print(price)
elif fruit == "kiwi":
price = quantity * 3.00
print(price)
elif fruit == "pineapple":
price = quantity * 5.60
print(price)
elif fruit == "grapes":
price = quantity * 4.20
print(price)
else:
print("error")
elif valid_Day:
if fruit == "banana":
price = quantity * 2.50
print(price)
elif fruit == "apple":
price = quantity * 1.20
print(price)
elif fruit == "orange":
price = quantity * 0.85
print(price)
elif fruit == "grapefruit":
price = quantity * 1.45
print(price)
elif fruit == "kiwi":
price = quantity * 2.70
print(price)
elif fruit == "pineapple":
price = quantity * 5.50
print(price)
elif fruit == "grapes":
price = quantity * 3.85
print(price)
else:
print("error")
else:
print("error")
|
4ecdd7bcaa012faeab67757349af33f333a181f3 | Westopher/pythonHelloWorld | /hello.py | 4,920 | 4.15625 | 4 |
""" print("hello world")
print("test")
print("saving?")
age = 20
name = 'West'
print(f'{name} was {age} years old when he wrote this book')
sport = "soccer"
skill = "nutmeg"
print(f"West is so nice at {sport}, he {skill}s people all the time")
"""
""" i = 5
print(i)
i = i + 1
print(i)
multiLineString = '''This is the first line.
This is the second line'''
print(multiLineString) """
""" length = 10
width = 5
area = length * width
print('Area is', area)
perimeter = 2 * (length + width)
print("Perimeter is", perimeter) """
""" number = 23
guess = int(input('Enter an integer:'))
if guess == number:
print("you guessed it")
print("no prize though")
elif guess < number:
print("Nope, your guess is a little lower than the number")
else:
print("you guess was too high")
print("done")
num = int(input("enter number"))
if num%2 == 0:
if num%3 == 0:
print ("Divisible by 3 and 2") #both
else:
print ("divisible by 2 not divisible by 3") #just the top if
else:
if num%3 == 0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3") """
""" number = 23
running = True
while running:
guess = int(input('enter integer '))
if guess == number:
print("you got the right number")
running = False #while loop stops running when it gets here and goes to last else below
elif guess < number:
print("no, the number guessed is too low")
else:
print("no the number is too high")
else:
print("the while loop is donzo") """
""" for i in range(0,50,2):
print(i)
else:
print("loop's done") """
"""
while True:
s = input("Say Something : ")
if s == "quit" or s == "Quit":
break
print("length of string is", len(s))
print("Done")
"""
"""
If is odd, print Weird
If is even and in the inclusive range of to , print Not Weird
If is even and in the inclusive range of to , print Weird
If is even and greater than , print Not Weird
"""
"""
n = int(input().strip())
if n % 2 != 0:
print("Weird")
elif n > 1 and n < 6:
print("Not Weird")
elif n % 2 == 0:
print("Not Weird")
if n > 5 and n < 21:
print("Weird")
elif n % 2 == 0 and n > 20:
print("Not Weird")
"""
""" n = int(input().strip())
#if odd, print weird
if n % 2 != 0:
print("Weird")
#if even and between 2 and 5 print not weird
if n % 2 == 0 and (n > 1 and n < 6):
print("Not Weird")
if n % 2 == 0 and (n > 5 and n < 21):
print("Weird")
#if n is even and larger than 20 print not weird
elif n % 2 == 0 and n > 20:
print("Not Weird")
"""
""" #function
def sayHello():
print('hello world of functions')
sayHello()
def printMax(a, b):
if a > b:
print(a, 'is bigger than B')
elif a == b:
print(a, 'is equal to', b)
else:
print(b,'is larger than', a)
printMax(15000, 20)
x = 50
y = 111111
printMax(x,y) """
""" x = 50
def func(x):
print('x is', x)
x = 2
print('changed local x to', x)
print(x)
func(x) """
"""print("x is still ", x)"""
""" def say(message, times=10):
print(message * times)
say("hello") """
"""def keywordArgs(a, b=5, c=10):
print('a =',a,", " 'b = ',b,", " 'c = ',c)
keywordArgs(55, c=600)
keywordArgs(54, 999, c=1776)"""
"""def total(a=5, *numbers, **phonebook):
print('a=', a)
for i in numbers:
print('i =', i*2)
for j, k in phonebook.items():
print(j,k)
total(10,1, 2, 3, 22, West=12345, Benedicte=678910, Luna=98765)"""
"""def maximum(x,y):
if x > y:
return x
elif x == y:
return "them numbers is equal"
else: return 'the greater number is', y
print(maximum(1, 656))"""
"""In the Gregorian calendar three criteria must be taken into account to identify leap years:
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year."""
"""def is_leap(year):
leap = False
if year % 4 == 0:
leap = True
if year % 100 == 0:
leap = False
if year % 400 == 0:
leap = True
return leap
year = int(input())
print(is_leap(year))"""
""" print each number in a range, separated by a comma """
""" def countTenByTwo(start, stop, step):
for i in range(start, stop, step):
print(i)
startVar = 2
stopVar = 10
stepVar = 2
print(countTenByTwo(startVar, stopVar, stepVar)) """
"""
import sys
print('the command line arguments are:')
for i in sys.argv:
print(i)
print("\n\nThe PythonPath is", sys.path, '\n')
"""
""" if __name__ == '__main__':
print("run by itself")
else:
print("imported from another module")
"""
def sayHi():
west = "westopher"
print(f"hello, this is your module speaking. My name is {west}")
__version__ = '0.1'
|
acd62fe871c3f5649cb573f8ac764f552dc7ba47 | brainhackerbrain/pythonlessons | /1.py | 172 | 3.671875 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
a=2
b="bbb"
print("Введите переменную с ")
c=input()
print ("a="+str(a))
print ("b="+str(b))
print ("c="+str(c)) |
c5a08065910567971f3a1adf7932df03148750f3 | Calebp98/project-euler | /45.py | 852 | 3.6875 | 4 | '''Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.'''
from math import sqrt
def check_pentagonal(p_n):
n = (sqrt(24 * p_n + 1) + 1) / 6
return n == int(n)
assert(check_pentagonal(5) == True)
assert(check_pentagonal(4) == False)
def check_hexagonal(h_n):
n = (1 + sqrt(1 + 8 * h_n)) / 4
return n == int(n)
assert(check_hexagonal(6) == True)
assert(check_hexagonal(5) == False)
n = 286
Tn = n * (n + 1) / 2
while not(check_pentagonal(Tn)) or not(check_hexagonal(Tn)):
n += 1
Tn = int(n * (n + 1) / 2)
print(n, Tn)
|
6d14606ae8e228ab3c6fd0319e9a999e9379c178 | MirzaTabassum/Python | /sharpen.py | 1,514 | 3.78125 | 4 | """
File: sharpen.py
Project 7.10
Defines and tests a function to sharpen an image.
"""
from images import Image
def sharpen(image, degree, threshold):
"""Builds and returns a sharpened image. Expects an image
and two integers (the degree to which the image should be sharpened and the
threshold used to detect edges) as arguments."""
def average(triple):
(r, g, b) = triple
return (r + g + b) // 3
blackPixel = (0, 0, 0)
whitePixel = (255, 255, 255)
new = image.clone()
for y in range(image.getHeight() - 1):
for x in range(1, image.getWidth()):
oldPixel = image.getPixel(x, y)
leftPixel = image.getPixel(x - 1, y)
bottomPixel = image.getPixel(x, y + 1)
oldLum = average(oldPixel)
leftLum = average(leftPixel)
bottomLum = average(bottomPixel)
if abs(oldLum - leftLum) > threshold or \
abs(oldLum - bottomLum) > threshold:
(r, g, b) = oldPixel
r = r-degree
if r<0:
r=0
g = g-degree
if g<0:
g=0
b = b-degree
if b<0:
b=0
new.setPixel(x, y, (r, g, b))
return new
pass
def main():
filename = input("Enter the image file name: ")
image = Image(filename)
sharpen(image, 20, 15)
image.draw()
if __name__ == "__main__":
main()
|
22bddaead4e16d572f589bfbcd44fa06779ddc72 | mothermary5951/videau | /dumpversion_hashmap.py | 7,612 | 4.125 | 4 | def new(num_buckets=256): # creates a new function with the potential for 256 (2 to the 7th) containers
"""Initializes a Map with the given number of buckets.""" # python uses 'map' instead of 'dictionary'
aMap = [] # variable 'aMap' starts as an empty list of lists WHICH CAN BE INDEXED BECAUSE THEY ARE ORDERED
for i in range(0, num_buckets): # for integer in range of 0 to 256, makes a bucket list to
aMap.append([]) # append new buckets to variable list 'aMap' within the function 'new' and
return aMap # returns the total list aMap increased by one bucket list.
def hash_key(aMap, key): #'hash is a builtin function. 'hash_key' requires 2 arguments: a new key and the aMap list index
"""Given a key, this will create a number and then convert it to an index for the aMap's buckets.""" # hash converts string to integer
return hash(key) % len(aMap) # returns the modulo remainder to be sure the index fits within the aMap larger string
def get_bucket(aMap, key): # 'Get' is a builtin method for finding values: this 'get' matches a key to where its bucket could be
"""Given a key, find the bucket where it would go."""
bucket_id = hash_key(aMap, key) # the bucket_id is defined by calling hash_key on a specific key in aMap list.
return aMap[bucket_id] # Adds the bucket_id to the aMap list
def get_slot(aMap, key, default=None): # Slots are subdivisions within bucket, like '1a, 1b', to avoid computer hash collisions.
"""
Returns the index, key, and value of a slot found in a bucket.
Returns -1, key, and default (None if not set) when not found.
"""
bucket = get_bucket(aMap, key) # Identifies a bucket
for i, kv in enumerate(bucket): # iterates through the 3 features 'enumerated' in a general slot in a bucket,
k, v = kv # where key, value = kv
if key == k: # if specified key is recognized, then
return i, k, v # return the 3-feature tuple that is in the bucket's slot on the aMap list,
return -1, key, default # if it's not, the function returns the default "none"
def get(aMap, key, default=None): # fetches the list aMap and its keys or non-members
"""Gets the value in a bucket for the given key, or the default."""
i, k, v = get_slot(aMap, key, default=default) # calls get_slot to identify the 3 features of each slot
return v # returns only the value in a given slot
def set(aMap, key, value): # new function called set; not the python builtin class
"""Sets the key to the value, replacing any existing value."""
bucket = get_bucket(aMap, key) # names get_bucket return 'bucket'
i, k, v = get_slot(aMap, key) # names get_slot return 'i, k, v'
if i >= 0: # for slot-integer numbers >= 0, set the key and value in place of the integer
# the key exists, replace it.
bucket[i] = (key, value) # sets one integer,one key, and one value per bucket, overwriting whatever is in there before.
else:
# the key does not, append to create it # if the key does not exist, make a new bucket and add it to aMap list
bucket.append((key, value))
def delete(aMap, key): # deletes a key from the aMap list
"""Deletes the given key from the Map."""
bucket = get_bucket(aMap, key) # restatement of 'bucket' definition on lines 22 & 38
for i in xrange(len(bucket)): # for slot-integer number inside the length of the bucket
k, v = bucket[i] # where key and value map to the integer
if key == k: # if the 'key' specified matches the k in bucket[i]
del bucket[i] # then delete the bucket
break # and then stop deleting
def dump(aMap): # print out hash/index integer (same thing in this script) & keys/values list for each bucket in the aMap list
"""Prints out what's in the Map."""
for index, bucket in enumerate(aMap): # The index of each dict pair/list in aMap list is the Same Thing as the hash assignment in THIS script.
for kv in bucket:
k, v = kv # where key, value = kv
print index, k, v
## NOTE ON 'ENUMERATE': The builtin function 'enumerate' counts items in any iterable object (MUST be an object) and assigns an index to each item, which
## can be acccessed with a two-part for-loop such as
## for index, item in enumerate(SomeListorListofListsorWhatever)
## print index, item
## or like the first for-loop in the 'dump' function above, but there the index counts the Buckets and the key & value are tuples In the buckets.
## NOTE ON 'HASH': Hash is a python builtin function that (among other things) assigns an integer to a string to establish its
## position in a Map or larger string; works sort of like an index in a tuple. It uses the modulo to divide the hash(key) assigned
## integer into the total string length to be sure that the position assigned fits within the string length. Hashing is made of deep
## computer magic algorithms developed by thousands of programmers over 30 years. BELIEVE, TRUST, and USE!!!
######## In python, printing out list members and then printing out 'i'-indices and 'b'-list members via the 'enumerate' builtin
## >>> bucket = [1, 2, 3, 4]
## >>> for b in bucket:
## ... print b
## ...
## 1
## 2
## 3
## 4
## >>> for i,b in enumerate(bucket):
## ...
## ... print i,b
## ...
## 0 1
## 1 2
## 2 3
## 3 4
## >>>
|
7cebbba31f3a32ee6c504a2ccfda058a376b67ba | AsteriskVideogameGroup/BYOB | /src/foundation/geometrictools/Position.py | 843 | 3.859375 | 4 | class Position:
########## ATTRIBUTES DEFINITION ##########
# _x : float
# _y : float
def __init__(self, x: float, y: float):
self._x = x
self._y = y
def __hash__(self):
return hash((self._x, self._y))
def __eq__(self, other):
return (self._x, self._y) == (other._x, other._y)
def __ne__(self, other):
# Not strictly necessary, but to avoid having both x==y and x!=y
# True at the same time
return not (self == other)
def setX(self, x: float):
self._x = x
def setY(self, y: float):
self._y = y
def getX(self):
return self._x
def getY(self):
return self._y
def toString(self):
"""
:return: the position as: (_x,_y)
"""
return "("+str(self._x)+","+str(self._y)+")"
|
5d5ffa14450b6724bde4a5956e6edd129326e2b7 | muokiv/The-Art-of-doing-40-challenges | /2_Miles_Per_Hour_Conversion_App.py | 269 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 15 15:02:06 2020
@author: mitta anand
"""
print("Welcome to Miles Per Hour Conversion App.")
n=float(input("Enter speed in Miles per Hour: "))
a=n*0.4474
res=round(a,2)
print("Speed in meters per second is:",res)
|
e56008a3f8d13e17098bdc74ccf21deef99e39a9 | CAgAG/Arithmetic_PY | /lanqiao/2013_java_/世纪末的星期.py | 849 | 3.53125 | 4 | import datetime
"""
标题: 世纪末的星期
曾有邪教称1999年12月31日是世界末日。当然该谣言已经不攻自破。
还有人称今后的某个世纪末的12月31日,如果是星期一则会....
有趣的是,任何一个世纪末的年份的12月31日都不可能是星期一!!
于是,“谣言制造商”又修改为星期日......
1999年的12月31日是星期五,请问:未来哪一个离我们最近的一个世纪末年(即xx99年)的12月31日正好是星期天(即星期日)?
请回答该年份(只写这个4位整数,不要写12月31等多余信息)
"""
if __name__ == '__main__':
one_year = datetime.timedelta(weeks=12)
for i in range(1999, 10000, 100):
Now = datetime.date(i, 12, 31)
if Now.weekday() == 6:
print(Now.year)
|
a06b5c8ef0c896ace8cc51cfb544966455753eee | EggheadJohnson/SmallerProjects | /Python/stupidgame/stupidgame.py | 6,952 | 4 | 4 | # 2048 is a very popular game. Countless variations have been created around it. Many students
# lost class time to trying to achieve a highscore. I was curious as to whether it would be
# possible to get to 2048 randomly. It's not. This program is designed to run a Monte Carlo
# simulation of the game as many times as you want. The most I ran was 2 million. The highest
# score achieved was never more than 512.
# Paul Johnson
# Spring 2014
from random import randint, choice
def makeNewBoard():
b = []
for x in range(4): b.append([0,0,0,0])
added = 0
while added<2:
x = randint(0,3)
y = randint(0,3)
if not b[x][y]:
b[x][y] = 2
added+=1
return b
def addNew(b):
options = []
for x in range(4):
for y in range(4):
if not b[x][y]: options.append((x,y))
addHere = choice(options)
b[addHere[0]][addHere[1]] = choice([2,2,2,2,2,2,2,4])
def printBoard(b):
for line in b:
outPut = ''
for item in line:
outPut += str(item)
outPut += ' '
print outPut
print '\n'
def makeAMove(b, move):
tempB = []
moveOccurred = False
for x in range(4):
tempB.append([[],[],[],[]])
for y in range(4):
tempB[x][y] = [b[x][y],0]
if move == 'down':
for y in range(4):
for x in range(3):
c = 2-x
for z in range(c+1, 4):
if tempB[z][y] == [0,0] and z == 3 and tempB[c][y][0]:
tempB[z][y] = tempB[c][y]
tempB[c][y] = [0,0]
moveOccurred = True
elif ((tempB[z][y][0] != tempB[c][y][0] and tempB[z][y][0] != 0) or tempB[z][y][1]) == 1 and tempB[c][y][0]:
tempB[z-1][y] = tempB[c][y]
if z>c+1:
tempB[c][y] = [0,0]
moveOccurred = True
break
elif tempB[z][y][0] == tempB[c][y][0] and tempB[z][y][1] == 0 and tempB[z][y][0] and tempB[c][y][0]:
tempB[z][y][1] = 1
tempB[c][y] = [0,0]
moveOccurred = True
break
if move == 'right':
for x in range(4):
for y in range(3):
c = 2-y
for z in range(c+1, 4):
if tempB[x][z] == [0,0] and z == 3 and tempB[x][c][0]:
tempB[x][z] = tempB[x][c]
tempB[x][c] = [0,0]
moveOccurred = True
elif ((tempB[x][z][0] != tempB[x][c][0] and tempB[x][z][0] != 0) or tempB[x][z][1]) == 1 and tempB[x][c][0]:
tempB[x][z-1] = tempB[x][c]
if z>c+1:
tempB[x][c] = [0,0]
moveOccurred = True
break
elif tempB[x][z][0] == tempB[x][c][0] and tempB[x][z][1] == 0 and tempB[x][z][0] and tempB[x][c][0]:
tempB[x][z][1] = 1
tempB[x][c] = [0,0]
moveOccurred = True
break
if move == 'up':
for y in range(4):
for c in range(1,4):
for z in range(1,c+1):
if tempB[c-z][y] == [0,0] and c-z == 0 and tempB[c][y][0]:
tempB[c-z][y] = tempB[c][y]
tempB[c][y] = [0,0]
moveOccurred = True
elif ((tempB[c-z][y][0] != tempB[c][y][0] and tempB[c-z][y][0] != 0) or tempB[c-z][y][1]) == 1 and tempB[c][y][0]:
myTemp = tempB[c][y]
tempB[c][y] = [0,0]
tempB[c-z+1][y] = myTemp
break
elif tempB[c-z][y][0] == tempB[c][y][0] and tempB[c-z][y][1] == 0 and tempB[c-z][y][0] and tempB[c][y][0]:
tempB[c-z][y][1] = 1
tempB[c][y] = [0,0]
moveOccurred = True
break
if move == 'left':
for x in range(4):
for c in range(1,4):
for z in range(1,c+1):
if tempB[x][c-z] == [0,0] and c-z == 0 and tempB[x][c][0]:
tempB[x][c-z] = tempB[x][c]
tempB[x][c] = [0,0]
moveOccurred = True
elif ((tempB[x][c-z][0] != tempB[x][c][0] and tempB[x][c-z][0] != 0) or tempB[x][c-z][1]== 1) and tempB[x][c][0]:
myTemp = tempB[x][c]
tempB[x][c] = [0,0]
tempB[x][c-z+1] = myTemp
break
elif tempB[x][c-z][0] == tempB[x][c][0] and tempB[x][c-z][1] == 0 and tempB[x][c-z][0] and tempB[x][c][0]:
tempB[x][c-z][1] = 1
tempB[x][c] = [0,0]
moveOccurred = True
break
for x in range(4):
for y in range(4):
if tempB[x][y][1] == 1: b[x][y] = 2*tempB[x][y][0]
else: b[x][y] = tempB[x][y][0]
if moveOccurred: addNew(b)
def keepGoing(b,maxout=False):
for x in range(3):
for y in range(3):
if b[x][y] >= 2048 and maxout: return False
if b[x][y] == 0: return True
if b[x+1][y] == 0 or b[x+1][y] == b[x][y]: return True
if b[x][y+1] == 0 or b[x][y+1] == b[x][y]: return True
for x in range(1,4):
for y in range(1,4):
if b[x][y] == 0: return True
if b[x-1][y] == 0 or b[x-1][y] == b[x][y]: return True
if b[x][y-1] == 0 or b[x][y-1] == b[x][y]: return True
return False
def runGame(printMe=False, maxout=False):
b = makeNewBoard()
while keepGoing(b, maxout=maxout):
makeAMove(b, choice(['up','down','right','left']))
if printMe: printBoard(b)
max = 0
if printMe:
printBoard(b)
for x in b:
for y in x:
if y > max: max = y
return max
def playMany(runs=5, printMe=False, maxout=False):
res = {}
tenper = runs/10
if not tenper: tenper = 1
for x in range(runs):
m = runGame(printMe=printMe, maxout=maxout)
if m in res.keys(): res[m]+=1
else: res[m] = 1
if not (x+1)%tenper:
print x+1, "runs completed"
printRes(res)
return res
def printRes(r):
a = r.keys()
a.sort()
tot = 0
for x in a:
tot += r[x]
line = ' '
for x in a:
line = ' '
line += str(x)
line += ' :: '
line += str(100.*r[x]/tot)
line += '%'
print line
r = playMany(5000, printMe=False, maxout=True)
print "results:"
printRes(r)
|
2785e4f30e27211e413b7ae887876e374d67100f | Tong-Ou/MC-and-Jet-Tutorial | /practice2.py | 1,025 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 30 20:02:12 2018
@author: Tong Ou
"""
import numpy as np
import numpy.random as random
import matplotlib.pyplot as plt
n_points=1000
def gauss(x,mu,sigma):
t=1/np.sqrt(2*np.pi*sigma**2)*np.exp(-(x-mu)**2/(2*sigma**2))
return t
#Generate random numbers of Gauss distribution
def gen(xmin,xmax,sigma,mu):
a=[]
L=xmax-xmin
i=0
while i in range(n_points):
t=random.random()
x=xmin+L*t
y=random.random()
s=gauss(x,mu,sigma)/gauss(mu,mu,sigma)
if y<=s:
a.append(x)
i+=1
return a
a=gen(0,10,2,5)
n_bins=50
#drawing the random numbers to a histogram
plt.hist(a,bins=n_bins,normed=1)
plt.xlabel("X",fontsize=15)
plt.ylabel("PDF(X)",fontsize=15)
plt.title("bins=50",fontsize=15)
#drawing the Gauss function for reference
x=np.linspace(0,10,n_bins)
y=gauss(x,5,2)
plt.plot(x,y,'r',label="Gauss distribution")
plt.legend()
plt.show()
|
848cd55a7e132cc05310fef0e64620c7c9ccc6d1 | florencevandendorpe/Informatica5 | /06 - condities/Risk.py | 674 | 3.734375 | 4 | #invoer
a = float(input('het aantal ogen van aanvaller 1: '))
b = float(input('het aantal ogen van aanvaller 2: '))
c = float(input('het aantal ogen van aanvaller 3: '))
d = float(input('het aantal ogen van verdediger 1: '))
e = float(input('het aantal ogen van verdediger 2: '))
#sorteren
f = max(a, b, c)
g = max(d, e)
h = a + b + c - f - min(a, b, c)
i = d + e - g
#berekening van het aantal verloren legers
if f > g and h > i:
print('aanvaller verliest 0 legers, verdediger verliest 2 legers')
elif f <= g and h <= i:
print('aanvaller verliest 2 legers, verdediger verliest 0 legers')
else:
print('aanvaller verliest 1 leger, verdediger verliest 1 leger')
|
d8c352576730947a91b69909177985cc0afb9dee | devaljansari/consultadd | /3.py | 655 | 3.5625 | 4 | import datetime
currentDT = datetime.datetime.now()
print (str(currentDT))
print ("Current Year is: %d" % currentDT.year)
print ("Current Month is: %d" % currentDT.month)
print ("Current Day is: %d" % currentDT.day)
print ("Current Hour is: %d" % currentDT.hour)
print ("Current Minute is: %d" % currentDT.minute)
print ("Current Second is: %d" % currentDT.second)
print ("Current Microsecond is: %d" % currentDT.microsecond)
print (currentDT.strftime("%Y-%m-%d %H:%M:%S"))
print (currentDT.strftime("%Y/%m/%d"))
print (currentDT.strftime("%H:%M:%S"))
print (currentDT.strftime("%I:%M:%S %p"))
print (currentDT.strftime("%A, %b %d, %Y")) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.