blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
94b81dee2eaa9eab1f52be61aa92b9085e95cad9 | shrvn-k/Project-Euler---Python | /Problem 29.py | 150 | 3.53125 | 4 | lst=[]
print "start"
for a in range(2,101):
for b in range(2,101):
if a**b not in lst:
lst.append(a**b)
print len(lst)
|
df852d503bcb4a7569c4490b56c6c51e0cc7043e | lwalker42/set-simulation | /logic.py | 3,335 | 3.59375 | 4 | from random import shuffle
deck = []
board = []
features = 4
values = 3
def play_game(strategy, f = 4, t = 3):
global features, values
features = f
values = t
init_deck()
sets_taken = 0
sets = []
while True:
set = strategy()
'''
print(len(deck))
print("board:", board)
print("set:", set)
'''
if (set == -1):
if(deal_cards(values) == -1):
break
continue
sets_taken += 1
sets += [[ board[set[0]], board[set[1]], board[set[2]] ]]
if (len(board) - len(set) < features * values):
replace_set(set)
else:
take_set(set)
#add info as necesary
#[number of sets taken]
return [sets_taken, sets, board]
#return [int(values**(features - 1) - len(board)/values)]
#TODO: make cleaner using modular arithmetic with range(values**features)
def init_deck():
global deck, board
deck = [[i] for i in range(values)]
board = []
for i in range(features - 1):
temp = []
for c in deck:
for j in range(values):
temp += [(c + [j])]
deck = temp
shuffle(deck)
for i in range(features*values): deal_card()
def deal_cards(n, pos = len(board)):
i = 0
for i in range(n):
if (deal_card(pos) == -1): break
if (i == 0): return -1
else: return i+1
def deal_card(pos = len(board)):
if (len(deck) <= 0): return -1
board.insert(pos, deck.pop())
return 0
#set is a tuple of card indices
def take_set(set):
for i in set:
board.pop(i)
#set is a tuple of card indices
def replace_set(set):
for i in set:
board.pop(i)
deal_card(i)
#Currently works for 3 values per feature
def find_sets(b = []):
if (len(b) == 0): b = board
sets = []
for i in range(len(b)):
for j in range(i):
for k in range(j):
c1 = b[i]
c2 = b[j]
c3 = b[k]
s = [(c1[f] + c2[f] + c3[f]) % values
for f in range(features)]
if (sum(s) == 0): sets += [[i, j, k]]
return sets
#Currently works for 3 values per feature
def find_ultra():
sets = []
for i in range(len(board)):
for j in range(i):
for k in range(j):
for l in range(k):
c1 = board[i]
c2 = board[j]
c3 = board[k]
c4 = board[l]
#Python % makes the resulting sign nonnegative
s12 = [(c1[f] + c2[f] - c3[f] - c4[f]) % values
for f in range(features)]
if (sum(s12) == 0): sets += [[i, j, k, l]]
s13 = [(c1[f] + c3[f] - c2[f] - c4[f]) % values
for f in range(features)]
if (sum(s13) == 0): sets += [[i, j, k, l]]
s14 = [(c1[f] + c4[f] - c2[f] - c3[f]) % values
for f in range(features)]
if (sum(s14) == 0): sets += [[i, j, k, l]]
return sets
#exec(open('logic.py').read())
|
03d8d87fcb01752a8f23a9cfaf63a2e53c6f6647 | j3N0/mooc_python | /practice/cypherV2.py | 276 | 3.8125 | 4 |
str = input()
low = ord('a')
up = ord('A')
for i in str:
if i.isalpha():
if i.islower():
print(chr(low+(ord(i)-low+3)%26), end='')
else:
print(chr(up+(ord(i)-up+3)%26), end='')
else:
print(i, end='')
print('')
|
61e4761edd241dd46339d15023fdb8309aff0d70 | zhousir1234/zhourui | /python应用/PY05.py | 564 | 3.53125 | 4 | import pandas as pd
df1=pd.DataFrame({'A':['A1','A2','A3','A4'],
'B':['B1','B2','B3','B4'],
'C': ['C1', 'C2', 'C3', 'C4'],
'D': ['D1', 'D2', 'D3', 'D4']},index=[1,2,3,4])
print(df1)
df2=pd.DataFrame({'B':['B2','B4','B6','B8'],
'D': ['D2', 'D4', 'D6', 'D8'],
'F': ['F2', 'F4', 'F6', 'F8']},index=[2,4,6,8])
print(df2)
print(pd.concat([df1,df2],axis=1,join='inner'))
print(pd.concat([df1,df2],axis=1,join='outer'))
print(pd.concat([df1,df2],axis=0,join='inner'))
|
70e13e6cba59f1c7a2b6b322be9725bb11ec68f2 | gschen/sctu-ds-2020 | /1906101052-曾倩/day0428/test03.py | 528 | 3.828125 | 4 | def isSymmetric(self, root: TreeNode) -> bool:#如果树为空
if not root:
return True
def tyq(root):
#如果左节点的值不等于右节点的值,返回False
if root. left. value !=root . right . value:
return False
#只有左节点或者只有右节点,而另一边没有,返回False
if not root.left or root. right:
return False
if not root.left and not root.right:
return True
return tyq(root.left) and tyq(root. right)
return tyq(root. left , root.right) |
c6fee7908a159f6e3fce4149da3cb5ab1a290c8c | rhidra/tc-cours | /3tc/elp/python/lambda_td3.py | 781 | 3.90625 | 4 | # Expression Lambda
def f(n):
def g(x):
return x + n
return g # Fonctionne car g est un objet
f4 = f(4)
f4(5) # Appelle la fonction g
# OU alors :
def f(n):
return lambda x: x + n # Définition d'une fonction sans nom
f6 = f(6)
f6(10) # Affiche 16
# Autre exemple
phrase = "Mary had a little lamb"
words = phrase.split()
sorted(words) # Mots triés en tenant compte de la casse
# On cherche à ne pas tenir compte de la casse
sorted(words, key=lambda w: w.lower()) # Key est évalué à chaque itération
# Lambda permet de ne pas avoir à définir une fonction avec un nom à chaque fois
# Trier un dico en fonction des valeurs et pas des clés (comportement par défaut)
d = { "raz":1982, "toi":1997, "guido":1956 }
sorted(d.items(), key=lambda t: t[1])
|
1c787cea83c0d25603f4d27caba92f1045099b46 | aitoehigie/Project | /pythone.py | 259 | 4.03125 | 4 | #!/usr/bin/env python
from math import e
precision = int(input("How many digits of precision:"))
while precision > 50:
print ("Precision is too large")
precision = int(input("How many digits of precision:"))
else:
print (f"{e:.{precision}f")
|
bf63a6766a0ad4e7931a330c0ac7ebe30f48a157 | Parkyes90/algo | /leetcode/701~800/703. Kth Largest Element in a Stream.py | 1,099 | 4 | 4 | from typing import List
class KthLargest:
"""https://leetcode.com/problems/kth-largest-element-in-a-stream/"""
def __init__(self, k: int, nums: List[int]):
self.nums = sorted(nums, reverse=True)[:k]
self.k = k
def binary_search(self, target: int):
left = 0
right = len(self.nums) - 1
while left <= right:
mid = (left + right) // 2
if self.nums[mid] < target:
right = mid - 1
elif self.nums[mid] > target:
left = mid + 1
else:
return mid
return left
def add(self, val: int) -> int:
index = self.binary_search(val)
self.nums.insert(index, val)
self.nums = self.nums[: self.k]
return self.nums[self.k - 1]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
if __name__ == "__main__":
obj = KthLargest(3, [4, 5, 8, 2])
print(obj.add(3))
print(obj.add(5))
print(obj.add(10))
print(obj.add(9))
print(obj.add(4))
|
62d9fe3796c4c7f29366ab5bcc2d20b5dce015ed | wusanpi825117918/study | /Day06/p_04高阶函数-reduce.py | 579 | 3.71875 | 4 | '''
高阶函数-reduce
'''
# 注意:reduce 不能直接使用,需要导入一个模块 functools
# reduce 作用是根据传入的参数一对参数二中的数据进行累计
import functools
# my_list = ['h','e','l','l','o']
my_list = list('hello')
result = functools.reduce(lambda s1,s2: s1 + s2, my_list)
# result = functools.reduce(lambda s1,s2: s1.upper() + s2.upper(), my_list)
print(result)
# 练习 :使用 reduce 求阶乘
my_list = [i for i in range(1,6)]
result = functools.reduce(lambda n1,n2: n1 * n2, my_list)
print(result)
|
37c336617304af57e3fb4394be47f5b3bd32844e | Zhuo-xz/python-selfuse | /demo22.py | 489 | 3.578125 | 4 | ##正则表达式:定义一个规则,检查是否匹配
import re
a = r'mr_\w'
b = 'MR_SHOP mr_shop'
c = re.match(a,b,re.I)
print(c)
print(c.start())
print(c.end())
print(c.group()) #若结果不存在则会出现错误
print("")
import re
d = r'(13[4-9]\d{8})|(15[01289]\d{8})$'
e = "13634222222"
f = re.match(d,e) #若无则为None re.i 不区分字母大小写
g = re.search(d,e) #若无则为None re.A 让\w不匹配汉字
h = re.findall(d,e)
print(f)
print(g)
print(h)
|
7eed1297ee4e5fb22534fd74d88d6b570c4bf05c | AaronL1011/TheVirtualD20 | /Virtual_D20.py | 2,666 | 3.59375 | 4 | import random
import time
print("Welcome to the virutal D20!")
print("Wizards, Shamans and Warriors alike, what shall the RNG gods generate for you today?")
print("Tip: You can add a number to the front of your user_roll for multiple roles! (eg. 3d6)")
def check_valid(n): #Check if user input is valid, if not, throw TypeError.
check_list = ['4', '6', '8', '10', '00', '12', '20'] # List of valid inputs
scrapValue, roll_check = user_roll.split('d') #scrapValue variable used to placehold any input before 'd'
if roll_check not in check_list:
str.x = 69
def roll_dice(n): # Function to roll dice.
if user_roll[0] != 'd': # If first character of input is not d, user is rolling multiple die.
numberOfDie, die = user_roll.split('d')
if (int(die) == 0): # Special case for D00 Roles, only available rolls are percentiles from 00 - 90
return [(random.randint(0, 9) * 10) for n in range(int(numberOfDie))]
elif int(die) == 10: # Special case where die starts at 0 and ends at 9
return [random.randint(0, 9) for n in range(int(numberOfDie))]
else: # Normal dice rolls 1 - dice number
return [random.randint(1, int(die)) for n in range(int(numberOfDie))]
else: # Single dice roll
scrapValue, die = user_roll.split('d') #scrapValue variable used to placehold unwanted value from split.
if (int(die) == 0): # Special case for D00 Roles, only available rolls are percentiles from 00 - 90
return [random.randint(0, 9) * 10]
elif int(die) == 10: # Special case where die starts at 0 and ends at 9
return [random.randint(0, 9)]
else:
return [random.randint(1, int(die))]
while True:
print(' D4 | D6 | D8 | D10 | D00 | D12 | D20 or Q to quit') # Awkward way to format print, justification wasn't working.
user_roll = input()
user_roll = user_roll.lower()
if user_roll == 'q': # Escape while loop when user decides to quit
break
else:
try:
modifier = input('Modifier? Pos/neg number or leave blank\n')
if modifier == '': #Check if input for modifier is empty, if so, assign to 0 for sum later.
modifier = 0
modifier = int(modifier)
check_valid(user_roll)
print('May your die roll true...')
time.sleep(2)
user_roll = roll_dice(user_roll)
print(user_roll)
if modifier != 0: # If user entered modifier, add to final output.
user_roll.append(modifier)
user_roll = sum(user_roll)
print('Your rolls and modifier equal: ', user_roll)
except (ValueError, TypeError): # Catch any incorrect input from user.
print("I don't understand that roll.\n")
print("Thanks for using The Virtual D20, stay strong Adventurer!")
print("Created by Aaron Lewis. Github.com/AaronL1011")
|
857225e0b42a816bb21e7bc0a728a08a1bb2730e | Forrest-HuYang/Python-Exercise | /GraphicsEngine/shapess_tony.py | 3,098 | 3.53125 | 4 | import easygui
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
def getArea(self):
area = self.height * self.width
return (area)
def getCircum(self):
circum = (self.height + self.width) * 2
return circum
class Triangle:
def __init__(self, sideA, sideB , sideC):
self.sideA = sideA
self.sideB = sideB
self.sideC = sideC
def getArea(self):
p = (self.sideA + self.sideB +self.sideC)/2
area = (p * (p - self.sideA) * (p - self.sideB) * (p - self.sideC))**(1/2)
return (area)
def getCircum(self):
circum = self.sideA + self.sideB +self.sideC
return circum
class Triangular_prism:
def __init__(self , myTriangle , height):
self.bottom = myTriangle
self.height = height
def getVolume(self):
volume = self.bottom.getArea() * self.height
return volume
class Circle:
def __init__(self, radius):
self.radius = radius
def getArea(self):
area = self.radius * (3.14)**2
return (area)
def getCircum(self):
circum = self.radius * 2 * 3.14
return circum
#########################################
choice = easygui.enterbox( "If you want a Triangle, please type 1; Rectangle, type 2; Circle, type 3.")
if choice == "1":
sideA_tri = float(easygui.enterbox("Enter first side of triangle"))
sideB_tri = float(easygui.enterbox("Enter second side of triangle"))
sideC_tri = float(easygui.enterbox("Enter third side of triangle"))
height_tri = float(easygui.enterbox("Enter height of triangular prism (type zero if you don't want a three dimensional object)"))
if (sideA_tri + sideB_tri <= sideC_tri) or (sideA_tri + sideC_tri <= sideB_tri) or (sideC_tri + sideB_tri <= sideA_tri):
easygui.msgbox ("Such a triangle doesn't exist")
else:
myTriangle = Triangle(sideA_tri , sideB_tri , sideC_tri)
area_display = str(myTriangle.getArea())
circum_display = str(myTriangle.getCircum())
if height_tri != 0:
myTriangularPrism = Triangular_prism(myTriangle , height_tri)
volume_display = str(myTriangularPrism.getVolume())
easygui.msgbox("the volume of the 3D object is " + volume_display)
if choice == "2":
length_rect = float(easygui.enterbox("Enter length of rectangle"))
width_rect = float(easygui.enterbox("Enter width of rectangle"))
myRect = Rectangle(length_rect, width_rect)
area_display = str(myRect.getArea())
circum_display = str(myRect.getCircum())
if choice == "3":
radius_circle = float(easygui.enterbox("Enter radius of circle"))
myCircle = Circle(radius_circle)
area_display = str(myCircle.getArea())
circum_display = str(myCircle.getCircum())
easygui.msgbox("The area of that 2D shape is " + area_display + "\n" + "\n" + "The circumference of that 2D shape is " + circum_display)
####################################### |
8bf08e5c607e95faef36fca9e24b41aa6a503bdc | camargodev/advent-of-code | /d6c1.py | 2,074 | 3.671875 | 4 | def manhattan_dist(p, q):
distx = abs(p[0] - q[0])
disty = abs(p[1] - q[1])
return distx + disty
points = []
maxx = 0
maxy = 0
with open("input", "r") as f:
data = f.readlines()
counter = 0
for line in data:
x, y = line.split(',')
x, y = int(x), int(y)
points.append((counter, (x, y)))
counter += 1
for point in points:
x, y = point[1]
maxx = max(x, maxx)
maxy = max(y, maxy)
M = [[None for x in range(maxy+2)] for y in range(maxx+2)]
for point in points:
x, y = point[1]
M[y][x] = point[0]
for i in range(maxy+1):
for j in range(maxx+1):
closest = None
closest_dist = 0
counter = 0
for point in points:
dist = manhattan_dist((j, i), point[1])
#print(i, j, dist)
if closest == None:
closest = point[0]
closest_dist = dist
elif closest_dist > dist:
closest = point[0]
closest_dist = dist
for point in points:
dist = manhattan_dist((j, i), point[1])
if dist == closest_dist:
counter += 1
if counter > 1:
closest = None
M[i][j] = closest
for i in range(maxy+1):
line = ''
for j in range(maxx+1):
line += ' '
line += '.' if M[i][j] == None else str(M[i][j])
print(line)
infinite_points = []
for point in points:
for i in range(maxy+1):
if point[0] in infinite_points:
break
if M[i][0] == point[0] and point[0] is not None:
infinite_points.append(point[0])
if M[i][maxx] == point[0] and point[0] is not None:
infinite_points.append(point[0])
for i in range(maxx+1):
if point[0] in infinite_points:
break
if M[0][i] == point[0] and point[0] is not None:
infinite_points.append(point[0])
if M[maxy][i] == point[0] and point[0] is not None:
infinite_points.append(point[0])
finite_points = []
for point in points:
if point[0] not in infinite_points:
finite_points.append(point[0])
max_finite_area = 0
for point in finite_points:
counter = 0
for i in range(maxy+1):
for j in range(maxx+1):
if M[i][j] == point:
counter += 1
max_finite_area = max(max_finite_area, counter)
print(infinite_points)
print(finite_points)
print(max_finite_area)
|
547062b248cdb32c29344bcf9049489c997a4416 | lucaschen321/project-euler-solutions | /python/p018.py | 1,305 | 3.59375 | 4 | # Solution to Project Euler Problem 18
# by Lucas Chen
#
# Answer: 1074
#
triangle_str = """ 75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 """
# Preprocess string input so that each row is stored in an array
triangle = triangle_str.split('\n')
for i in range(len(triangle)):
triangle[i] = list(map(int, triangle[i].strip().split()))
# Use dynamic programming to compute max path. Loop through each row,
# tabulating the maximum path to each index in some auxiliary array, max_path
max_path = [triangle[0][0]]
for i in range(1, len(triangle)):
max_row = list(map(max, zip(max_path + [0], [0] + max_path)))
max_path = list(map(sum, zip(max_row, triangle[i])))
if __name__ == "__main__":
print(max(max_path))
|
4ab91a54beb879e9bd4a170dcf0077af157bece1 | danieka/grupdat | /11/hash.py | 1,444 | 3.53125 | 4 | class Hashtabell:
# En enkel hashtabell med linjär probning
def __init__(self, size):
#När man skapar tabellen ska man ange önskad storlek
self.size = size
self.table = [None] * size #Skapar en tom lista med size antal None-element.
def put(self, key, value):
#Stoppar in ett (key, value) par i tabellen
h = hash(key) #Vi använder pythons inbyggda hashfunktion för att få en position
#Den positionen tar vi sedan modulo tabellens storlek för att garantera att positionen är inom tabellens utrymme
while self.table[h%self.size] != None: #Vi loopar tills dess att vi hittar en ledig plats
h += 1 #Eftersom vi använder linjär probning stegar vi fram en position i taget
self.table[h%self.size] = (key, value) #Vi stoppar in både key och value i tabellen. Key behöver vi vid get-operationen
def get(self, key):
#Hämtar ut värdet kopplat till key
h = hash(key)
while self.table[h%self.size][0] != key: #Nu loopar vi tills dess att vi hittar rätt (key, value) par
h += 1
return self.table[h%self.size][1] #Returnera value
tabell = Hashtabell(1500000) #Tabeller bör vara 50% större än antalet poster
with open("personer.txt") as f:
for line in f.readlines():
pnr = line.split(";")[0]
name = line.split(";")[1].strip() #Strip tar bort nyradstecken som vi annars får med.
tabell.put(pnr, name)
while True:
pnr = input("Skriv in ett personnummer: ")
print(tabell.get(pnr)) |
6f14600e831e0833bac9ebf1b4bc4a121ebe3244 | jlyang1990/LeetCode | /124. Binary Tree Maximum Path Sum.py | 839 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
result = [float("-inf")]
self.maxPathSumHelper(root, result)
return result[0]
def maxPathSumHelper(self, root, result):
if not root:
return 0
leftSum = self.maxPathSumHelper(root.left, result)
rightSum = self.maxPathSumHelper(root.right, result)
maxSinglePath = max(root.val, root.val+leftSum, root.val+rightSum)
maxPath = max(maxSinglePath, root.val+leftSum+rightSum)
result[0] = max(result[0], maxPath)
return maxSinglePath |
05400195295dbcc8032c7b41039a22a475598563 | banskt/heritability | /scripts/gtex_cis_snps/gtex_normalization.py | 2,531 | 3.5 | 4 | #!/usr/bin/env python
import numpy as np
import pandas as pd
import scipy.stats as stats
def normalize_quantiles(M, inplace=False):
"""
Note: replicates behavior of R function normalize.quantiles from library("preprocessCore")
Reference:
[1] Bolstad et al., Bioinformatics 19(2), pp. 185-193, 2003
Adapted from https://github.com/andrewdyates/quantile_normalize
"""
if not inplace:
M = M.copy()
Q = M.argsort(axis=0)
m,n = M.shape
# compute quantile vector
quantiles = np.zeros(m)
for i in range(n):
quantiles += M[Q[:,i],i]
quantiles = quantiles / n
for i in range(n):
# Get equivalence classes; unique values == 0
dupes = np.zeros(m, dtype=np.int)
for j in range(m-1):
if M[Q[j,i],i]==M[Q[j+1,i],i]:
dupes[j+1] = dupes[j]+1
# Replace column with quantile ranks
M[Q[:,i],i] = quantiles
# Average together equivalence classes
j = m-1
while j >= 0:
if dupes[j] == 0:
j -= 1
else:
idxs = Q[j-dupes[j]:j+1,i]
M[idxs,i] = np.median(M[idxs,i])
j -= 1 + dupes[j]
assert j == -1
if not inplace:
return M
def inverse_quantile_normalization(M):
"""
After quantile normalization of samples, standardize expression of each gene
"""
R = stats.mstats.rankdata(M,axis=1) # ties are averaged
Q = stats.norm.ppf(R/(M.shape[1]+1))
return Q
def normalize_expression(expression_df, counts_df, expression_threshold=0.1, count_threshold=5, min_samples=10):
"""
Genes are thresholded based on the following expression rules:
>=min_samples with >expression_threshold expression values
>=min_samples with >count_threshold read counts
"""
donor_ids = ['-'.join(i.split('-')[:2]) for i in expression_df.columns]
# expression thresholds
mask = ((np.sum(expression_df>expression_threshold,axis=1)>=min_samples) & (np.sum(counts_df>count_threshold,axis=1)>=min_samples)).values
# apply normalization
M = normalize_quantiles(expression_df.loc[mask].values, inplace=False)
R = inverse_quantile_normalization(M)
quant_std_df = pd.DataFrame(data=R, columns=donor_ids, index=expression_df.loc[mask].index)
quant_df = pd.DataFrame(data=M, columns=donor_ids, index=expression_df.loc[mask].index)
return quant_std_df, quant_df
|
65ccf858308ae9bf38573f49cd4d441a9a02fac0 | GuilhermeOS/JovemProgramadorSENAC | /pythonAula/listas_de_exercicios/lista01/exe04.py | 369 | 3.71875 | 4 | '''
O restaurante a quilo Bem-Bão cobra R$12,00 por cada quilo de refeição. Escreva
um algoritmo que leia o peso do prato montado (em quilos) e imprima o valor a
pagar. Assuma que a balança já desconte o peso do prato.
'''
pesoPrato = float(input("Informe o peso do prato: "))
print(f"O valor total a ser pago é de R${pesoPrato * 12:.2f}!") |
b3213dca570aad6f521b608d91ce8e4f70a61054 | whencespence/python | /unit-2/loops.py | 809 | 4.125 | 4 | # name = 'Christina'
# for index in range(0, 10):
# print(name);
# print the odd numbers from 1 - 10
# for index in range(0, 10):
# if index % 2 == 1:
# print(index)
# print the even numbers from 1 - 10
# for index in range(0, 10):
# if index % 2 == 0:
# print(index)
# print the sum of the even numbers
# total = 0
# for index in range (1, 11):
# if index % 2 == 0:
# # total = total + index
# total += index
# print(total)
# Loop over your full name and print only vowels
# name = 'Christina Spencer'
# for letter in name:
# if letter == 'a' or letter == 'e' or letter == 'i' or letter == 'o' or letter == 'u':
# print(letter)
my_numbers = [3, 5, 17, 11, 21, 53, 10, 27, 45, 80]
smallest = my_numbers[0]
for number in my_numbers:
if number < smallest:
smallest = number
print(smallest) |
b17912fc7a8ff13022b0961e9e4909b557c47f98 | fafa1/google-flights | /Gerando graficos e objetos no Python/estrair.py | 809 | 3.796875 | 4 |
'''
USANDO SQLITE3
Funcionou pois fiz a alteracao da data de Y-m-d para Y/m/d;
ele extrai informacao do banco de dado 'tutorialBD2.db' e gera um grafico
o arquivo estrair.py e teste.py, tem que estar no mesmo local
'''
#-*- coding: utf-8 -*-
import sqlite3
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
connection = sqlite3.connect('tutorialBD2.db')
c=connection.cursor()
sql= 'SELECT * FROM dados' # guardo em sql o banco
x=[]
y=[]
conversor=mdates.strpdate2num('%Y/%m/%d %H:%M:%S')
def leitura(leitura):
for row in c.execute(sql):
x.append(conversor(row[3]))
y.append(row[4])
leitura('python e incrivel')
fig=plt.figure()
ax1=fig.add_subplot(1,1,1, axisbg= 'white')
plt.plot_date(x,y, fmt='r-',label='values')
plt.legend(['values'])
plt.grid(True)
plt.show()
|
0a5dd2a81444a87aa46c8cc2ec454f55033fab6c | ElenaCerezoSwing/visualizing-real-world-data-project | /Methods/dicts_and_freqs.py | 548 | 3.609375 | 4 | def get_frequencies(df, col):
dictionary = {}
sorted_df_col = sorted(df[col])
unique_items = set(df[col])
for item in unique_items:
dictionary[item] = sorted_df_col.count(item)
return dictionary
def get_frequencies_from_string_data(df, col):
dictionary = {}
my_list = list(df[col])
unique_items = set(df[col])
for item in unique_items:
dictionary[item] = my_list.count(item)
return dictionary
def get_list_indexes(our_list):
return [our_list.index(item) for item in our_list] |
97fe2b254bb0d7258d20f42bd8b68e0c146b1134 | AteCastillo/holbertonschool-low_level_programming | /0x17-doubly_linked_lists/execute.py | 111 | 3.578125 | 4 | def check(mul):
res = str(mul)
if res == res[::-1]:
return True
else:
return False
|
d10c0112a086c4cfd0e005d5ae79d810bf0281b3 | ehdcks111/Womanclassex | /methodclass.py | 518 | 3.796875 | 4 |
class Woman:
def __init__(self, name, weight, height, iq):
self.name = name
self.weight = weight
self.height = height
self.iq = iq
def eat(self):
self.weight = int(self.weight) + 2
def study(self):
self.iq = int(self.iq) + 5
def sleep(self):
self.height = float(self.height)+0.3
def print_info(self):
print("----------------")
print("name:", self.name, "weight:", self.weight, "height:", self.height, "iq:", self.iq)
|
5a13587bb2938e22267d7e8bae8dbcd890084ff0 | OblivionGhoul/PythonIntro | /project5.py | 1,266 | 3.703125 | 4 | # 5.18
number = eval(input("Enter a positive integer: "))
print("The factors for", number, "is", end = " ")
factor = 2
while factor <= number:
if number % factor == 0:
number = number / factor
print(factor, end = ",")
else:
factor += 1
# 5.26
sum = 0
for i in range(1, 97 + 1, 2):
sum += i / (i + 2)
print("Sum is", sum)
# 5.2
import random
import time
correct = 0
count = 0
NUMBER_OF_QUESTIONS = 10
startTime = time.time()
while count < NUMBER_OF_QUESTIONS:
n1 = random.randint(1, 15)
n2 = random.randint(1, 15)
ans = eval(input("What is " + str(n1) + " + " + str(n2) + " = "))
if ans == (n1 + n2):
print("You are correct!")
correct += 1
else:
print("Your answer is wrong.\n", n1, "+", n2, "=", (n1 + n2))
count += 1
endTime = time.time()
testTime = int(endTime - startTime)
print("Correct count is", correct, "out of", NUMBER_OF_QUESTIONS, "\nTest time is", testTime, "seconds")
# 5.28
temp = 1
e = 1
for i in range(1, 100000 + 1):
temp = temp / i
e += temp
if (i == 10000 or i == 20000 or i == 30000 or i == 40000 or i == 50000 or
i == 60000 or i == 70000 or i == 80000 or i == 90000 or i == 100000):
print("The e is", e, "for i =", i) |
998b0fe7ef6b5bcee154c5cf77eafaebeeaf0bc1 | weijiasun2013/Algorithms | /linkedlist/merge_alternate_position/merge_alternate_position.py | 2,142 | 3.90625 | 4 |
'''
merge alternate position
'''
class Node(object):
def __init__(self,value):
self.val = value
self.next = None
def show(head):
h = head
rslt = ''
while h:
rslt += str(h.val) + ' -> '
h = h.next
rslt += 'null'
print(rslt)
def merge_alnernate_position(head1,head2):
p1= head1
while p1 and head2:
_next2 = head2.next
_next1 = p1.next
p1.next = head2
head2.next = _next1
p1 = _next1
head2 = _next2
return head1, head2
def test1():
print('test1------------------')
n1 = None
n11 = Node(1)
n12 = Node(2)
n11.next = n12
show(n1)
show(n11)
r1,r2 = merge_alnernate_position(n1,n11)
show(r1)
show(r2)
def test2():
print('test2------------------')
n11 = None
n1 = Node(1)
n2 = Node(2)
n1.next = n2
show(n1)
show(n11)
r1,r2 = merge_alnernate_position(n1,n11)
show(r1)
show(r2)
def test3():
print('test3------------------')
n1 = Node(1)
n2 = Node(2)
n1.next = n2
n11 = Node(11)
n12 = Node(12)
n11.next = n12
show(n1)
show(n11)
r1,r2 = merge_alnernate_position(n1,n11)
show(r1)
show(r2)
def test4():
print('test4------------------')
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n1.next = n2
n2.next = n3
n3.next = n4
n11 = Node(11)
n12 = Node(12)
n11.next = n12
show(n1)
show(n11)
r1,r2 = merge_alnernate_position(n1,n11)
show(r1)
show(r2)
def test5():
print('test5------------------')
n1 = Node(1)
n2 = Node(2)
n1.next = n2
n11 = Node(11)
n12 = Node(12)
n13 = Node(13)
n14 = Node(14)
n11.next = n12
n12.next = n13
n13.next = n14
show(n1)
show(n11)
r1,r2 = merge_alnernate_position(n1,n11)
show(r1)
show(r2)
def main():#
test1()
test2()
test3()
test4()
test5()
if __name__ == '__main__':
main() |
ec30fdcff8bc5038db3d1ae60cbd3c236836d166 | glatif1/Practice-Programs-in-Python | /MiniPrograms/phonebook.py | 371 | 3.921875 | 4 | def showmenu():
def main():
contacts = {}
continueYorN = "Y"
while continueYorN =="Y":
userchoice = showMenu()
if userchoice ==1:
name= input("Enter the name:")
phonenum = input("Enter the phone number: ")
contacts[name]=phonenum
elif userchoice ==2:
print(contacts)
else:
print("Invalid Input")
continueYorN = input("Continue(Y/N)?") |
aef86858a5ad1d263796d69eaddeef03a41b19a1 | sdotpeng/Python_Jan_Plan | /Jan_15/scope.py | 556 | 3.671875 | 4 | # Scope
# Local scope: the variables and functions only may be accessed
# or have local scope inside their respective current symbol table
def convertFtoC(temp):
convertedTemp = (5 / 9) * (temp - 32)
return convertedTemp
tempInF = 32
print(convertFtoC(tempInF))
tempInF = 212
print(convertFtoC(tempInF))
# Here the variable convertedTemp has a global scope
def convertFtoC_2(temp):
global convertedTemp
convertedTemp = (5 / 9) * (temp - 32)
return convertedTemp
tempInF_2 = 212
print(convertFtoC_2(tempInF_2))
print(convertedTemp) |
6a795201962bcc22d8435a8a0d7fb7bf620b921a | yeeeux/LasVegas | /cubix.py | 3,489 | 3.71875 | 4 | import random
def getDice():
return random.randint(2,12)
def cubix(mon):
playgame=True
money=mon
from mainmenu import message_in_stars
from mainmenu import getInput
from mainmenu import getIntInput
from mainmenu import currency as valuta
while playgame:
print(f"У тебя на счету {money} {valuta}")
stavka=getIntInput(0, money, f"Сделай ставку в пределах {money} {valuta}\n"
f"Введи 0, если хочешь слиться, дешёвка!\n"
f"")
if stavka ==0:
return money
play = True
stav = stavka
oldResult = getDice()
firstgame = True
while play and stav >0 and money>0:
if stavka>money:
stavka=money
print()
print(f'\n В твоем распоряжении {stavka} {valuta}')
print(f"\n Текущая сумма чисел на костях {oldResult}")
print("\n Сумма чисел накостях будет больше, меньше или равна предыдущей?")
x=getInput("0123","1 - больше (1: 1/5) , 2 - меньше (1: 1/5), 3 - равна (1: 3), 0 - выход")
if x !="0":
firstgame = False
money-=stavka
curresult = getDice()
win=False
if (oldResult > curresult):
if x == "2":
win=True
elif(oldResult<curresult):
if (x=="1"):
win=True
if not x =="3":
if win:
print(f"На столе выпала следующая сумма костей {curresult}")
message_in_stars("\033[32m Ты выиграл!!! \033[0m")
print(f"Твой выигрыш:\033[32m {stavka//5} {valuta} \033[0m")
money+=stavka+stavka//5
stavka+=stavka//5
else:
print(f"На столе выпала следующая сумма костей {curresult}")
message_in_stars("\033[31m Ты проиграл!!! \033[0m")
print(f"Ты проиграл:\033[31m {stavka} {valuta} \033[0m")
stavka=stav
elif (x=="3"):
if (oldResult==curresult):
print(f"На столе выпала следующая сумма костей {curresult}")
message_in_stars("\033[32m Ты выиграл!!! \033[0m")
print(f"Твой выигрыш:\033[32m {stavka*2} {valuta} \033[0m")
money+=stavka*3
stavka*=3
else:
print(f"На столе выпала следующая сумма костей {curresult}")
message_in_stars("\033[31m Ты проиграл!!! \033[0m")
print(f"Ты проиграл:\033[31m {stavka} {valuta} \033[0m")
stavka = stav
oldResult=curresult
else:
if firstgame:
money -=stavka
play = False
|
5c2f21d8d229c23136a2348e3dc30f444b8c0d03 | egorova-ai19-2/programming-2021-19fpl | /binary_search_tree/node_test.py | 972 | 4.125 | 4 | """
Programming for linguists
Tests for Node class.
"""
import unittest
from binary_search_tree.binary_search_tree import Node
class NodeTestCase(unittest.TestCase):
"""
This Case of tests checks the functionality of the implementation of Node
"""
def test_node_is_created(self):
"""
Create a node with root only.
Test that node is created.
"""
node = Node(10)
self.assertEqual(10, node.root)
def test_node_is_created_with_children(self):
"""
Create a node with children.
Test that node is created.
"""
node = Node(10, 8, 12)
self.assertEqual(10, node.root)
self.assertEqual(8, node.left)
self.assertEqual(12, node.right)
def test_node_creation_raises_error(self):
"""
Create a node with incorrect root.
Test that creation of node raises error.
"""
self.assertRaises(TypeError, Node, None)
|
f94ec85221d18ace99f1e72aa29edb76bcfd581c | Pallavi2000/adobe-training | /day2/p10.py | 585 | 3.75 | 4 | #Program to count perfect squares in an array
def checkPerfectSquares(n):
rootNum = int(n ** 0.5)
if rootNum * rootNum == n:
return True
else:
return False
number_of_bills = int(input("Enter the number of bills "))
#bills_array = list(map(int, input("Enter the bill values ").split()))[:number_of_bills]
bills_array = []
count_of_bills = 0
for i in range(0,number_of_bills):
bills_array.append(int(input()))
if checkPerfectSquares(bills_array[i]):
count_of_bills += 1
print("The count of bills which are perfect squares",count_of_bills) |
222adea35d37fb8899ab46aba9599fba7f1c69f5 | 01-Jacky/PracticeProblems | /Python/code_fight/array/sodoku2.py | 1,695 | 3.546875 | 4 | def _valid_subsquare(grid, i,j):
seen = set()
for i_offset in range(3):
for j_offset in range(3):
r = i + i_offset
c = j + j_offset
if grid[r][c] == '.':
continue
elif grid[r][c] in seen:
return False
else:
seen.add(grid[r][c])
return True
def sudoku2(grid):
dim = len(grid)
# Check subsquare
for i in range(0,dim,3):
for j in range(0,dim,3):
# print("check subsquare starting {} {}".format(i,j))
if not _valid_subsquare(grid, i,j):
return False
print('subsquare valid')
# Check row
for i in range(dim):
row_seen = set()
for j in range(dim):
if grid[i][j] == '.':
continue
elif grid[i][j] in row_seen:
return False
else:
row_seen.add(grid[i][j])
print('row valid')
# Check column
for i in range(dim):
row_seen = set()
for j in range(dim):
if grid[j][i] == '.':
continue
elif grid[j][i] in row_seen:
return False
else:
row_seen.add(grid[j][i])
print('column valid')
return True
grid =\
[[".","4",".",".",".",".",".",".","."],
[".",".","4",".",".",".",".",".","."],
[".",".",".","1",".",".","7",".","."],
[".",".",".",".",".",".",".",".","."],
[".",".",".","3",".",".",".","6","."],
[".",".",".",".",".","6",".","9","."],
[".",".",".",".","1",".",".",".","."],
[".",".",".",".",".",".","2",".","."],
[".",".",".","8",".",".",".",".","."]]
print(sudoku2(grid)) |
48565b103dc13a62d624209c6b36395dc5af60fc | jaychsu/algorithm | /lintcode/154_regular_expression_matching.py | 1,780 | 3.5 | 4 | """
Main Concept:
end by '*' and has no matched
case 1-1: `P[j-2:j]` is `c*` and have no matched in `S`
=> `j-2` in `dp[i][j-2]` means ignored `c` and `*`
end by `*` and is the last matched in `*`
case 1-2: `P[j-2:j]` is `.*` and `.` always matched `S[i-1]`
case 1-3: `P[j-2:j]` is `a*` and `a` == `P[j-2]` == `S[i-1]`
=> `i-1` in `dp[i-1][j]` means to check the `?` below
'...a?a'
\|
'...xa*'
case 2: `P[j-1]` is `.` and `.` always matched `S[i-1]`
case 3: `P[j-1]` is `a` and `a` == `P[j-1]` == `S[i-1]`
=> `-1` in `dp[i-1][j-1]` means previous char
"""
class Solution:
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
if s == p == '':
return True
m, n = len(s), len(p)
MULTI = '*'
ANY = '.'
"""
`dp[i][j]` means the substr end at `s[i - 1]` was matched by
the substr end at `p[j - 1]`
"""
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
# dp[i][0] = False # i = 1 -> m + 1
# dp[0][j] -> ?, need to check
for i in range(m + 1):
for j in range(1, n + 1):
if i > 0 and p[j - 1] == s[i - 1] and dp[i - 1][j - 1]:
dp[i][j] = True
elif i > 0 and p[j - 1] == ANY and dp[i - 1][j - 1]:
dp[i][j] = True
elif j > 1 and p[j - 1] == MULTI:
if dp[i][j - 2]:
dp[i][j] = True
elif i > 0 and p[j - 2] == s[i - 1] and dp[i - 1][j]:
dp[i][j] = True
elif i > 0 and p[j - 2] == ANY and dp[i - 1][j]:
dp[i][j] = True
return dp[m][n]
|
328641c37fc74c3c9bc80e79a37f2d93a0c4c32f | bnguyensn/PythonPlayground | /dc/dc_240_e.py | 1,798 | 3.828125 | 4 | # Daily Challenge #240 [Easy]: Typoglycemia
# Key takeaways:
# List comprehension
# The string.translate() function
# The random.sample() / .shuffle() function
# The string.punctuation set
# The regex to split string while preserving punctuations
# Trimming whitespaces
from random import sample
from string import punctuation
from re import findall
inp = """According to a research team at Cambridge University, it doesn't matter in what order the letters in a word are,
the only important thing is that the first and last letter be in the right place.
The rest can be a total mess and you can still read it without a problem.
This is because the human mind does not read every letter by itself, but the word as a whole.
Such a condition is appropriately called Typoglycemia."""
def xform_typoglycemia(s):
# w_list = s.translate(str.maketrans('', '', punctuation)).split(' ')
w_list = findall(r"[\w']+|[.,!?;]", s)
w_list_xformed = []
for w in w_list:
if w not in ['.', ',', '!', '?', ';'] and len(w) > 3:
# Get characters
s_char = w[0]
m_chars = w[1:-1]
e_char = w[-1]
# Shuffle middle characters
while True:
m_chars_shuffled = ''.join(sample(list(m_chars), k=len(list(m_chars))))
if m_chars_shuffled == m_chars:
continue
else:
break
# Re-join characters & append to new collection
new_w = s_char + m_chars_shuffled + e_char
w_list_xformed.append(new_w)
else:
w_list_xformed.append(w)
return ''.join([' ' + w if w not in punctuation else w for w in w_list_xformed]).lstrip()
print(xform_typoglycemia(inp))
|
ae2d41a255aed82ecc46eb70128ac963b6ec5750 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2494/60870/271529.py | 271 | 3.765625 | 4 | str_input = input()
str_input = str_input[1:-1]
array = str_input.split(',')
array = [int(x) for x in array]
count = 0
for j in range(0, len(array) - 1):
for k in range(j + 1, len(array)):
if array[j] > 2 * array[k]:
count = count + 1
print(count) |
2457016e477bbe0ec511f387e16acd84e387bffb | mindori0105/Algorithm-Study | /9663.py | 195 | 3.65625 | 4 | #let's solve N-Queen algorithm!!
import pprint
#queen을 몇 개 로 설정할지 입력을 받는다.
N = input()
N = int(N)
col = list()
for i in range(0, N):
col.append(i)
print(col)
|
d199a6b13271e931830b0509e89209fb6e911dee | NadiyaZelman/gitproject1 | /week5/home_work_8.py | 1,411 | 3.84375 | 4 | def get_full_name(first, last):
full_name= first+' '+last
return full_name.title()
qa_tester= get_full_name('nadiya', 'zelman')
print(qa_tester)
################ 8-6 ###############################
def city_country(city, country):
print(f"{city.title()}, {country.title()}")
city_country('santiago', 'chile')
city_country('lviv', 'ukraine')
city_country('aphine', 'greese')
#################### 8-7 ###############################
def make_album(name, title):
album= {'name':name.title(), 'title':title.title()}
return album
album=make_album('kesha', 'high road')
print(album)
album=make_album('krewella', 'zer0')
print(album)
album=make_album('drake', 'scorpion')
print(album)
################# 8-9 #############################
magicians =['David Copperfield', 'David Blaine', 'Harry Houdini', 'Criss Angel']
def show_magicians():
for magician in magicians:
print(f"{magician}.")
show_magicians()
################ 8-10 #############################
magicians =['David Copperfield', 'David Blaine', 'Harry Houdini', 'Criss Angel']
def make_great():
for magician in magicians:
print(f"The Great {magician}.")
make_great()
################# 8-11 ##########################
magicians =['David Copperfield', 'David Blaine', 'Harry Houdini', 'Criss Angel']
def show_magicians():
for magician in magicians:
return magician
def make_great():
for magician in magicians:
print(f"The Great {magician}.")
make_great()
show_magicians()
|
968e75b10b349948d445702e8ddafc2352717153 | patpatfc/DrawingFunctionsProject | /drawingFunctionsOOP.py | 11,969 | 3.609375 | 4 | import sys
import pygame
import random
import string
class Screen: # Class to set up display
def __init__(self):
#color
self.white = (255, 255, 255)
# Display screen in 1000x700px and
pygame.init ()
self.screen = pygame.display.set_mode ((1000, 700))
pygame.display.set_caption ("Function") #name display as Functions
self.screen.fill (self.white) #background set to white
class Field(Screen): # Class to set up xy coordinate system
def __init__(self, Screen_Class): # Takes screen class as input
#colors
self.grey = (125, 125, 125)
self.black = (0, 0, 0)
self.screen = Screen_Class.screen # gets screen variable from Screen class
self.num_array = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
self.font = pygame.font.SysFont ("times", 21)
#calls functions
self.Write_Horizontal()
self.Write_Vertical()
self.Draw_Horizontal()
self.Draw_Vertical()
def Write_Horizontal(self):
for zero1 in self.num_array: # from -5 to 5, writes all numbers on horizontal axis
line_num = self.font.render (str (20 * zero1), 1, self.black) # sets text color and text that will be written
self.screen.blit (line_num, (305 + (70 * (zero1 + 5)), 360)) # Displays the text at given loaction
def Write_Vertical(self):
for zero1 in self.num_array: # from -5 to 5, writes all numbers on vertical axis
if zero1 != 0: # at origin there is already a 0 written from Write_Horizontal function
line_num = self.font.render (str (-20 * zero1), 1, self.black) # sets text color and text that will be written
self.screen.blit (line_num, (655, (70 * (zero1 + 5)))) # Displays the text at given loaction
def Draw_Vertical(self):
x_position = 0
for zero1 in range (10):
pygame.draw.line (self.screen, self.grey, (300, x_position), (1000, x_position), 1) # draws vertical lines on coordinate system at given position
x_position += 70
def Draw_Horizontal(self):
y_position = 300
for zero1 in range (10):
pygame.draw.line(self.screen, self.grey, (y_position, 0), (y_position, 700), 1) # draws horizontal lines on coordinate system at given position
y_position += 70
class Functions(Screen, Field):
def __init__(self, Screen_Class, Field_Class):
self.avalues = []
self.bvalues = []
self.cvalues = []
self.yvalues = [] #values according to real coordinate system
self.realyvalues = [] #values according to pygame coordinate system
self.realxvalues = [] #values according to pygame coordinate system
self.lettersss= [] #name of the functions represented by letters
self.lettersss.append(random.choice(string.letters))
self.circley = 20 #color indicators radius next to the function name on the screen
self.zero4 = 0
self.zero3 = 0
self.screen = Screen_Class.screen # gets screen variable from Screen class
self.font = Field_Class.font # gets font variable from Field class
self.black = Field_Class.black # gets black variable from Field class
#calls functions
self.Get_Number_Of_Functions()
self.Get_Function_constants()
self.Get_Points_Function()
self.Function_Names()
self.Write_Function_Name()
def Get_Number_Of_Functions(self): #gets number of functions that is wanted to be draw
vf = True
while vf:
self.numberoffunctions = int(input("Number of functions (max 6)"))
if self.numberoffunctions <= 6 and self.numberoffunctions > 0: #asks for input again if the number is higher than six or lower than 0
vf = False
print("ax^2+bx+c")
print("This program can only draw constant functions, linear functions and quadratics. ")
def Get_Function_constants(self): #gets constants for all values
for zero1 in range(self.numberoffunctions): #runs number of times as functions to be drawn
self.avalues.append(int(input("what is the value of a"+ str(zero1)+ " "))) #asks for input and adds to avalues because it is a constant of a
self.bvalues.append(int(input("what is the value of b"+ str(zero1)+ " "))) #asks for input and adds to bvalues because it is a constant of b
self.cvalues.append(int(input("what is the value of c"+ str(zero1)+ " "))) #asks for input and adds to cvalues because it is a constant of c
def Get_Points_Function(self): #finds points on xy coordinate system, each point is found for x eual to -100 to 100 and x increases by 1, there is no need to store x values because
# its values are know ( -100 to 100 )
for zero2 in range(self.numberoffunctions): #makes this process for each function
zero3 = -100 #start number of x
zero1 = 0
for zero1 in range(201):
self.yvalue = (self.avalues[zero2]) * zero3 * zero3 + self.bvalues[zero2] * zero3 + self.cvalues[zero2] #finds the y value by putting x's value in x which is zero3
# in this case and multiplys by its constants gathered from the user
self.yvalues.append(self.yvalue) #adds the value found to the list
zero3 += 1 #x increases by 1 each time
def Function_Names(self):
count = 0
zero1= 0
self.functiony = 10
vf = True
newletter = random.choice(string.letters) #generate a letter
while vf: #makes this process for each function -1 because first letter was found in init function, runs until it is known that new letter found is not same with another one
if len(self.lettersss) == self.numberoffunctions: #makes vf False because there is no need to find any more letters
vf = False
if self.lettersss[zero1] == newletter: # if new letter is same as a previously found letter then generates once again
newletter = random.choice(string.letters)
count = 0 #equal count ot 0 to start the comparing process again
zero1 = -1
if (self.lettersss[zero1]) != (newletter): # if letter is not same as the previously find letter at spesified index then adds count 1
count += 1
if count == len(self.lettersss): #if all letter previously found is compared to new letter and it is not same as any, then adds to list
self.lettersss.append(newletter)
newletter = random.choice(string.letters)
count = 0
zero1 = -1
zero1 += 1
def Write_Function_Name(self):
for zero2 in range(self.numberoffunctions): #runs number of times as functions to be drawn
zero1 = 0
self.color = (random.randint(0,255), random.randint(0,255), random.randint(0,255)) #generates a random color
#all of these if satets are written to write the function in correct syntax (by wrong syntax I mean 0x^2 + 0x +2)
if self.avalues[zero2]!= 0 and self.bvalues[zero2]!= 0 and self.cvalues[zero2]!= 0: #if function is a quadratic such as 2x^2 + 2x +2
numline = self.font.render((self.lettersss[zero2]+ "(x) = " + str(self.avalues[zero2])+ "x^2 + " + str(self.bvalues[zero2]) + "x + "+ str(self.cvalues[zero2])), 1,
self.black)
if self.avalues[zero2]== 0 and self.bvalues[zero2]!= 0 and self.cvalues[zero2]!= 0: #if function is linear such as 2x +2
numline = self.font.render((self.lettersss[zero2]+ "(x) = " + str(self.bvalues[zero2]) + "x + "+ str(self.cvalues[zero2])), 1, self.black)
if self.avalues[zero2]!= 0 and self.bvalues[zero2]== 0 and self.cvalues[zero2]!= 0: #if function is a quadratic such as 2x^2 +2
numline = self.font.render((self.lettersss[zero2]+ "(x) = " + str(self.avalues[zero2])+ "x^2 + " + str(self.cvalues[zero2])), 1, self.black)
if self.avalues[zero2]!= 0 and self.bvalues[zero2]!= 0 and self.cvalues[zero2]== 0: #if function is a quadratic such as 2x^2 + 2x
numline = self.font.render((self.lettersss[zero2]+ "(x) = " + str(self.avalues[zero2]+ "x^2 + " + str(self.bvalues[zero2]) + "x")), 1, self.black)
if self.avalues[zero2] == 0 and self.bvalues[zero2] == 0: #if function is constant such as 2
numline = self.font.render((self.lettersss[zero2] + "(x) = " + str(self.cvalues[zero2])), 1, self.black)
if self.avalues[zero2] == 0 and self.bvalues[zero2] != 0 and self.cvalues[zero2] == 0: #if function is a linear such as 2x
numline = self.font.render((self.lettersss[zero2]+ "(x) =" + str(self.bvalues[zero2]) + "x" ), 1, self.black)
if self.avalues[zero2] != 0 and self.bvalues[zero2] == 0 and self.cvalues[zero2] == 0: #if function is a quadratic such as 2x^2
numline = self.font.render((self.lettersss[zero2]+ "(x) =" + str(self.avalues[zero2]) + "x^2 "), 1, self.black)
pygame.draw.circle(self.screen, self.color, (250, self.circley),10) #draws a circle next to the function name in order to indicate functions by color
self.screen.blit(numline, (10, self.functiony)) #writes the function name found in previous if statements
self.functiony += 100 #increases y value to not draw on the same line on pygame
self.circley += 98 #increases y value to not draw on the same line on pygame
self.Draw_Function()
def Draw_Function(self): #converts previously found xy coordiante system y values to pygaem also converts x too
zero2 = 0
for zero1 in range(201): #for loop for all 201 point, 100 from left 100 from right and 0
self.realyvalues.append(350 - self.yvalues[self.zero4] * 3.5) #if yvalue is negative then muliplys the y value by 3.5, 3.5 is the distance between x =1 and x =2, if y
# value is negative it must be under x axis however on to go under x axis in pygame you must increase y value, thats why 3.5 is negative, becaue -*- is positive adds it to
# 350 and finds the point likewise if it is positive +*- is negative and on pygaem axis it will go upper, also at y = 0 it will be 350
self.realxvalues.append(650 + (zero1-100) * 3.5) #if zero1 (x)(x starts from -100 increases until 100) at x =0 (zero1 = 100) x will be 650. 650 is the x vlaue of origin in
# terms of pygame coordinate system, as x increases pygame x increases and as x decreases pygame x decreases too. thats why this function is consistant with the coordiante
# system
if zero2 > 0: #if this statement wasnt here then pgame would try to draw a line however on the first rub there would be only one x and y point so there wont be an endpoint as
# a result program would crash
pygame.draw.line(self.screen, self.color, (self.realxvalues[self.zero3-1], self.realyvalues[self.zero3-1]), (self.realxvalues[self.zero3], self.realyvalues[self.zero3]), 3)
self.zero3+= 1
zero2 += 1
self.zero4+=1
screen = Screen() #call Screen class and name it as screen
Coordinate_system = Field(screen) #give screen as input to Filed Class and name the object as Coordiante_system
func = Functions(screen, Coordinate_system) #give screen and Coordiante_system as input to Functions class and name the object as func
pygame.display.update () #displays everything drawn on screen
while True:
#this code runs to keep the screen alive and when an user wants to quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit() |
14a9f291e0b1edd6fd7159155944c1ee3f92d8e3 | VadimSquorpikkor/Python_Stepik | /2/2_5_list/2_neighbours.py | 1,571 | 3.640625 | 4 | # Напишите программу, на вход которой подаётся список чисел одной строкой.
# Программа должна для каждого элемента этого списка вывести сумму двух его соседей. Для элементов списка,
# являющихся крайними, одним из соседей считается элемент, находящий на противоположном конце этого списка.
# Например, если на вход подаётся список "1 3 5 6 10", то на выход ожидается список "13 6 9 15 7" (без кавычек).
#
# Если на вход пришло только одно число, надо вывести его же.
#
# Вывод должен содержать одну строку с числами нового списка, разделёнными пробелом.
#
# Sample Input 1:
# 1 3 5 6 10
#
# Sample Output 1:
# 13 6 9 15 7
#
# Sample Input 2:
# 10
#
# Sample Output 2:
# 10
"""res = [int(x) for x in input().split()]
stroke = ''
if len(res) == 1:
stroke = str(res[0])
else:
res.append(res[0])
res.insert(0, res[-2])
for x in range(1, len(res) - 1):
stroke += str(res[x - 1] + res[x + 1]) + ' '
print(stroke)"""
res = [int(x) for x in input().split()]
stroke = ''
if len(res) == 1:
stroke = str(res[0])
else:
for x in range(0, len(res)):
stroke += str(res[x - 1] + res[x - len(res) + 1]) + ' '
print(stroke)
|
5b7699d03e675db7edd8e8e4286a105c46b922d7 | xudaaaaan/Leetcode | /dan/Problems/Easy/Tree/617. Merge Two Binary Trees/solution.py | 1,120 | 4.03125 | 4 | import collections
class Solution:
#recursive
def mergeTrees1(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 and t2:
t1.val += t2.val
t1.left, t1.right = self.mergeTrees(t1.left, t2.left), self.mergeTrees(t1.right, t2.right)
return t1 if t1 else t2
#BFS + queue
def mergeTrees(self, t1, t2):
if not (t1 and t2):
return t1 or t2
q1, q2 = collections.deque([t1]), collections.deque([t2])
while q1 and q2:
node1, node2 = q1.popleft(), q2.popleft()
if node1 and node2:
node1.val += node2.val
if not node1.left and node2.left:
node1.left = TreeNode(0)
if not node1.right and node2.right:
node1.right = TreeNode(0)
q1.append(node1.left)
q1.append(node1.right)
q2.append(node2.left)
q2.append(node2.right)
return t1
|
1c80e7c1025af025277e465d1ab8e1b7ea1ccbef | fcooper/franklin-workshops | /beaglebone/workshop/bopit/files/solution/sol_adc.py | 856 | 3.734375 | 4 | #!/usr/bin/python
# Texas Instruments Created Library
import workshop
# External Helper Libraries
#import Adafruit ADC library with alias
import Adafruit_BBIO.ADC as ADC
#Standard Python Library
import time
# Call ADC Setup (Must be done only once)
ADC.setup() ## Solution
while True:
# Read ADC value from pin (P9_36) and set retrieved value to variable called "val"
val = ADC.read("P9_36") ## Solution
# Print value of "val" variable
print "ADC: ",val ## Solution
# Convert digital value stored in "val" variable to analog (voltage) value.
# Store the converted value back into "val" variable.
# Important note: Max analog value possible is 1.8V
val = val * 1.8 ## Solution
# Print value of "val" variable (should contain analog value from (0 - 1.8V)
print "Voltage: ",val ## Solution
time.sleep(1) |
c73749ffcbe8fb1d60bf31e030316461e6eaba70 | a-angeliev/Python-Fundamentals-SoftUni | /while/07. Min Number.py | 143 | 3.59375 | 4 | inpt = input()
min = 10000000000000
while inpt != "Stop":
num = int(inpt)
if num < min:
min = num
inpt = input()
print(min) |
b558ca5e9e086bb3c898a1cecde42e8653fe7efc | drschwabe/Card-Match_Python | /cardMatch.py | 4,648 | 3.515625 | 4 | #### Card Match alpha3 Python3 ####
from random import shuffle
from sys import exit
from time import sleep
#Establish variables:
spark = ""
beginSwitch = False
checkSelectionSwitch = False
firstCard = 0
secondCard = 0
choosingFirstCard = False
choosingSecondCard = False
cardValues = []
cardStatus = []
matches = 0
chances = 6
#Function to handle player input:
def playerHandler():
global spark
global beginSwitch
global checkSelectionSwitch
global firstCard
global secondCard
global choosingFirstCard
global choosingSecondCard
#Player input initiates execution flow so let's refer to it as the "spark":
spark = input()
if(spark == "begin" or spark =="b"):
print("Game starts\n\n")
#Hit the beginSwitch...
beginSwitch = True
#and connect to the ai function:
aiHandler()
if(choosingFirstCard == True):
#Convert the player's input from string to an integer so it can be used as an array key:
firstCard = int(spark)
checkSelectionSwitch = True
aiHandler()
if(choosingSecondCard == True):
selectedCard = firstCard
secondCard = int(spark)
print ("the second card is " + str(secondCard))
checkSelectionSwitch = True
aiHandler()
#Function to compute most logic:
def aiHandler():
global spark
global beginSwitch
global checkSelectionSwitch
global firstCard
global secondCard
global choosingFirstCard
global choosingSecondCard
global cardValues
global cardStatus
global chances
global matches
if(beginSwitch == True):
#Set card values, their status, and then shuffle them.
cardValues = ['cow','cow','cow','cow','eagle','eagle','eagle','eagle','ladybug','ladybug',
'ladybug','ladybug','gold','gold','ruby','ruby','diamond','diamond']
cardStatus = ['face down','face down','face down','face down','face down','face down',
'face down','face down','face down','face down','face down','face down',
'face down','face down','face down','face down','face down','face down']
shuffle(cardValues)
#[graphics] Display a 'table' of cards for the user:
print(cardStatus)
#[graphics] Prompt the user to make a selection...
print("\nPlease choose a card from 0 to 17")
#activate "choostingFirstCard"...
choosingFirstCard = True
#turn off beginSwitch...
beginSwitch = False
#Fire back to the player input function:
playerHandler()
if(checkSelectionSwitch == True):
if cardStatus[firstCard] == "face down" :
#If the firstCard is face down, we know this is their first selection.
#[graphics] Inform the user we will flip over the card now:
print("\nYou chose card", firstCard)
print("We will now turn over that card to see what it is...\n")
#Flip the card...
cardStatus[firstCard] = "face up"
#[graphics] Create a 1 second delay before revealing anything:
sleep(1)
#[graphics] Reveal the value of the card to the user:
print("The card value is: " + cardValues[firstCard] + "\n")
sleep(1)
print(cardStatus)
print("\nChoose another card from 0 to 17 (to match your: " + cardValues[firstCard] + ")")
choosingFirstCard = False
choosingSecondCard = True
playerHandler()
elif cardStatus[secondCard] == "face down" :
print("\nYou chose card", secondCard)
print("Lets see what it is...\n")
cardStatus[secondCard] = "face up"
sleep(1)
print("The card value is: ", cardValues[secondCard])
sleep(1)
if (cardValues[firstCard] == cardValues[secondCard]) :
print("You got a match!\a\n\n")
matches = matches + 1
#Set the status of the card to the value of the card (flipped up permanently):
cardStatus[firstCard] = cardValues[firstCard]
cardStatus[secondCard] = cardValues[secondCard]
if matches == 9 :
print(cardStatus)
print("You won the game!\a\a\a\a\a\n")
exit()
else:
print("You have this many matches: " + str(matches) + " (of 9 total required)\n")
print(cardStatus)
print("\nSee if you can match another pair. Choose a card from 0 to 17:")
choosingFirstCard = True
playerHandler()
else :
print("\nSorry, that was not a match. Try again.")
chances = chances -1
print("(You have this many chances left: " + str(chances) + ")\n")
cardStatus[firstCard] = "face down"
cardStatus[secondCard] = "face down"
if chances == 0 :
print("Game over")
sleep(1)
exit()
else:
print(cardStatus)
choosingFirstCard = True
playerHandler()
else :
print("That card is already flipped!")
sleep(1)
print("Choose another card from 0 to 17:")
playerHandler()
print("\n#### Welcome to Card Match ####\n(type 'B' to Begin)")
playerHandler() |
3df42240b6ddd5916bc1ec5e15def0f16bfa7260 | AxolotlDev/PruebasPython | /Ej6.py | 308 | 3.734375 | 4 | #Ejercicio 6
#Calcular la media de tres números pedidos por teclado.
import statistics as st
n1 = int(input("Ingrese numero 1: "))
n2 = int(input("Ingrese numero 2: "))
n3 = int(input("Ingrese numero 3: "))
media=[n1,n2,n3]
m= st.mean(media)
print(f"La media de los 3 numeros ingresados es {m}")
|
75aa8814daafb1b0297fae18fcf53ee3bdc5f0a6 | jerryxu9/Dancing-Robot | /buzzer.py | 1,556 | 3.65625 | 4 | import time
import board
import pulseio
aaaaa
class Buzzer():
def __init__(self):
self.buzz()
def buzz(self):
# Define a list of tones/music notes to play.
TONE_FREQ = [ 262, # C
262, # C
294, # D
262, # C
349, # F
330, # E
262, # C
262, # C
294, # D
262, # C
392, # G
349, # F
262,
262,
523,
392,
349,
349,
330,
294,
466,
466,
440,
349,
392,
349 ]
# Create piezo buzzer PWM output.
buzzer = pulseio.PWMOut(board.A1, variable_frequency=True)
# Start at the first note and start making sound.
buzzer.frequency = TONE_FREQ[0]
buzzer.duty_cycle = 2**15 # 32768 value is 50% duty cycle, a square wave.
# Main loop will go through each tone in order up and down.
while True:
# Play tones going from start to end of list.
for i in range(len(TONE_FREQ)):
buzzer.frequency = TONE_FREQ[i]
time.sleep(0.5) # Half second delay.
# Then play tones going from end to start of list.
for i in range(len(TONE_FREQ)-1, -1, -1):
buzzer.frequency = TONE_FREQ[i]
time.sleep(0.5)
|
86506ad499665d89fc3672a7950c4951bec21c48 | Arno98/IdeaBag2 | /Numbers/tax_calculator.py | 1,170 | 4.25 | 4 | def cost_with_tax(x, y):
formula = x * (y / 100)
total_cost = x + formula
print("Total cost: " + str(total_cost) + "$")
def tax_calculator():
tax_dict = {"California": 13.3, "Oregon": 9.9, "Washington": 0, "Nevada": 0, "Idaho": 7.4, "Montana": 6.9,
"Utah": 5, "Arizona": 4.54, "Waioming": 0, "Colorado": 4.63, "New-Mexico": 4.9, "North Dakota": 2.9,
"South Dakota": 0, "Nebraska": 6.84, "Kanzas": 4.6, "Oklahoma": 5, "Texas": 0}
start = True
while start:
try:
enter_an_account = float(input("Enter a main account: "))
enter_a_tax = str(input("Where are you from: "))
except ValueError:
print("Please, enter a corect value. Try again")
else:
for city, value in tax_dict.items():
if enter_a_tax == city:
cost_with_tax(enter_an_account, value)
exit_or_no = str(input("Do you want repeat the process ? (enter 'y' for 'yes' or 'n' for 'no':) "))
if exit_or_no == "y":
continue
elif exit_or_no == "n":
start = False
else:
print("Please, enter a corect value (name of your state). Try again")
tax_calculator()
|
61fde88bc62babfd8e3503ffc5f0803d0d7d73f3 | mikkelmilo/kattis-problems | /lessThanTwoPoints/babybits.py | 225 | 3.546875 | 4 | bites = int(input())
mumbles = [x for x in input().split()]
f = [x for (i,x) in enumerate(mumbles) if x == str(i+1) or x == "mumble"]
if len(f) == len(mumbles):
print('makes sense')
else:
print('something is fishy')
|
724679fe12000110a1bc048517a9678e3d8117ce | jerryli18/PyDev-Package | /apt_emphasize/src/Emphasize.py | 1,632 | 3.875 | 4 | '''
Created on Jan 29, 2015
@author: Jerry
'''
def repeat(word, number):
"""
return the word with the first part of it repeated
if it is a valid part to repeat. The part to be
repeated must be repeated "number" times.
If the first letter is not a vowel, and the third
letter is a vowel, then the part to repeat is the
first three letters.
If the first and third letters are not vowels, but
the second letter is, then the part to repeat is
the first two letters.
Otherwise there is nothing to repeat.
Only the first letter of the returned word may be
a capital letter, if the original word started with
a capital letter.
"""
if len(word)== 1:
return word
if isVowel(word[0]):
return word
if len(word)== 2:
if isVowel (word[1]):
return word +word.lower() * (number-1)
else:
return word
if len(word)== 3:
if isVowel(word[2]):
return word +word.lower() * (number-1)
if isVowel(word[3]):
return word + word.lower() * (number - 1)
if len(word) > 3:
if isVowel(word[2]):
return word[:3] + word[:3].lower() * (number - 1) + word[3:]
if isVowel(word[1]):
return word[:2] + word[:2].lower() * (number - 1) + word[2:]
return word
def isVowel(ch):
ch = ch.lower()
if ch == "a":
return True
if ch == "e":
return True
if ch == "i":
return True
if ch == "o":
return True
if ch == "u":
return True
return False
|
d15f39e0dcaaa4a5c7a5b0b9940ee5bc1e909e5e | 799898961/python-learn-note | /python学习笔记/第2章-画画/2.Pythondraw.py | 6,290 | 3.71875 | 4 | # Pythondraw.py
import turtle
turtle.setup(650, 350, 200, 200)
turtle.ht() # 隐藏海龟
turtle.speed() # 绘画速度
turtle.penup()
turtle.fd(-250)
turtle.pendown()
# turtle.colormode(255)
turtle.pensize(25)
turtle.pencolor("tomato")
turtle.seth(-40)
for i in range(4):
turtle.circle(40, 80)
turtle.circle(-40, 80)
turtle.circle(40, 80/2)
turtle.fd(40)
turtle.circle(16, 180)
turtle.fd(40*2/3)
turtle.done()
# turtle(海龟)库:
# Python标准库之一 入门级的图形绘制函数库
# turtle的绘图窗体
# 以屏幕左上角的坐标为(0,0) 横向为x 纵向为y
# 绘图窗体的左上角是turtle绘图窗体的绘图原点
# 绘图窗体相对于屏幕左上角有一个相对坐标(startx,starty)
# 绘图窗体本身也有着 宽度(横向,width) 和 高度(纵向,height) 两个属性
# 可用turtle中的 setup()函数 设置窗体大小及位置
# 即:turtle.setup(width, height, startx, starty)
# 其中后两个参数可选,当后两个参数不存在时则默认窗体生成在屏幕正中心
# 且setup()函数不是必须的
# turtle的空间坐标体系:
# (1)绝对坐标:绘图窗体的正中心 横向为x 纵向为y
# 一些控制函数:
# turtle.goto(x,y):对处在任意位置的海龟去到达某一位置
# (2)海龟坐标:前侧为前进方向,类似的有:后退方向、左(右)侧方向
# 一些控制函数:
# turtle.fd(d):表示向前进方向移动d个像素
# turtle.bk(d):表示向后退方向移动d个像素
# turtle.circle(r, angle):以海龟当前前进方向左侧的某一个点为圆心
# 做半径为 r 圆心角为 angle 的圆周运动
# turtle的角度坐标体系:
# (1)绝对角度:在空间角度中,x轴正半轴为 0/360 度;y轴正半轴为 90/-270 度 并以此类推
# 一些控制函数:
# turtle.seth(angle):改变海龟的行进角度(方向),且只改变方向而不行进
# 参数 angle :绝对度数
# (2)海龟角度:从海龟坐标的角度出发,对于海龟运行的方向使用 左 和 右 来提供角度
# 一些控制函数:
# turtle.left(angle)
# turtle.right(angle)
# RGB色彩体系:
# 指由红绿蓝三个通道的颜色组合来覆盖视力所能感知的所有颜色
# RGB每色的取值范围为 0-255 的整数或 0-1 的小数
# turtle的RGB色彩模式:
# 默认采用小数值,可切换为整数值
# 一些控制函数:
# turtle.colormode(mode)
# 1.0:RGB小数值模式
# 255:RGB整数值模式
# 常用RGB色彩:
# 名称 RGB整数值 RGB小数值
# 白色(white) 255,255,255 1,1,1
# 黑色(black) 0,0,0 0,0,0
# 黄色(yellow) 255,255,0 1,1,0
# 洋红(magenta) 255,0,255 1,0,1
# 青色(cyan) 0,255,255 0,1,1
# 蓝色(blue) 0,0,255 0,0,1
#
# 海贝色(seashell) 255,245,238 1, 0.96, 0.93
# 金色(gold) 255,215,0 1, 0.84, 0
# 粉红色(pink) 255,192,203 1, 0.75, 0.80
# 棕色(brown) 165,42,42 0.65, 0.16, 0.16
# 紫色(purple) 160,32,240 0.63, 0.13, 0.94
# 番茄色(tomato) 255,99,71 1, 0.39, 0.28
# 库引用和import函数:
# 1.库引用:扩充Python程序功能的方式
# 使用 import 保留字完成,采用<a>.<b>()的编码风格
# 例:
# import <库名>
# <库名>.<函数名>(<函数参数>)
#
# 2.import函数的其他用法:
# (1) form <库名> import <函数1>,<函数2>,......
# 表示从某库中引用某个或者某些函数
# (2) from <库名> import*
# <函数名>(<函数参数>)
# 表示引用库中的全部函数,使用时直接使用函数名+函数参数(可选)
# (3) import <库名> as <库别名>
# <库别名>.<函数名>(<函数参数>)
# 表示给库起一个别名,类似于C语言的 #define <库名> <库别名>
#
# 3.(1) 和 (2)的比较
# (1)不会出现函数重名问题,但有时不方便
# (2)方便但引用多种库后易造成重名
# turtle画笔控制函数
# (1) turtle.penup() 别名 turtle.pu()
# 表示抬起画笔,使其移动轨迹不显示在画布上,让海龟起飞飞飞~
# (2) turtle.pendown() 别名 turtle.pd()
# 表示落下画笔
# 使用时一般成对出现
# (3) turtle.pensize() 别名 turtle.width
# 画笔宽度,海龟腰围
# (4) turtle.pencolor(color)
# 画笔颜色
# color 为颜色字符串或 r,g,b 值
# color参数的形式:
# a. 颜色字符串:turtle.pencolor("purple")
# b. RGB的小数值:turtle.pencolor(0.63, 0.13, 0.94)
# c. RGB的元组值:turtle.pencolor( (0.63, 0.13, 0.94) )
# d. RGB的整数值:
# 在默认情况下color参数只接受字符串和小数值所以要使用
# turtle.colormode(255)转换成RGB整数值模式,在此情况下
# turtle.pencolor(160, 32, 240)
# turtle运动控制函数:
# 1.turtle.forward(d) 别名turtle.fd(d)
# 表示向前进方向移动d个像素
# 参数 d 行进距离,可以是负数,负数表示倒退行进
# 2.turtle.circle(r, extent=None)
# 根据半径 r 绘制 extent 角度的弧形
# r:默认圆心在海龟左侧 r 距离的位置,负数时为右侧半径绝对值距离
# extent:绘制角度,默认是360度整圆
# turtle方向控制函数:
# turtle.setheading(angle) 别名 turtle.seth(angle)
# 控制海龟的面对方向:绝对角度 & 海龟角度
# angle:改变海龟当前的行进方向,使其改变为某一绝对角度
# turtle.left(angle) & turtle.right(angle)
# 向左或向右转angle度
# 循环控制:
# 常用结构:
# for <变量> in range (<参数>):
# <被循环的语句>
# <变量> 表示每次循环的计数,0到<次数>-1
# 在C语言中相当于:for(i=0; i<n; i++){}
# 例:
# for i in range(5):
# print("hello:",i)
# 输出结果:
# 共5行,为:hello: 0 hello: 1 hello: 2 以此类推
#
# print的一种输出方法:在小括号()内的输出的各种信息间用逗号,隔开
# 输出之后每输出的字符串之间会带有空格
#
# range()函数:产生循环计数序列
# 1.range(n):产生0到n-1的整数序列,共n个
# 例:range(5) 0,1,2,3,4
# 2.range(m, n):产生 m 到 n-1 的整数序列
# 例:range(2, 5) 2,3,4 |
686a2d2b06d5a2dd2ed3fc7e7f0846bef8387979 | DrWala/advent-of-code-2020 | /day-09/xmas-encoding.py | 1,242 | 3.734375 | 4 | from collections import deque
def check_valid_two_sum(number_set, target):
for prev in set(number_set):
if (target - prev) in number_set:
return True
return False
def solve_one(input):
numbers = deque()
limit = 25
# set up till limit
for idx, num in enumerate(input):
if idx >= limit:
break
num = int(num)
numbers.append(num)
for num in input[limit:]:
num = int(num)
if not check_valid_two_sum(numbers, num):
return num
else:
numbers.popleft()
numbers.append(num)
def solve_two(input, target):
input = [int(num) for num in input]
total_sum, i, j, input_length = 0, 0, 1, len(input)
while i < input_length and j < input_length:
total_sum = sum(input[i:j])
if total_sum < target:
j += 1
elif total_sum > target:
i += 1
else:
return max(input[i:j]) + min(input[i:j])
file = open("input.txt", "r")
content = file.readlines()
incorrect = solve_one(content)
print(f"First value that does not follow the pattern is {incorrect}")
weakness = solve_two(content, incorrect)
print(f"Weakness is {weakness}") |
f8bbe9ad50c6f7f606b14fb5022eb62929a9cd3f | pjryan513/Bitmap-Engine | /BitmapEngine/src/binhextrans.py | 3,032 | 3.59375 | 4 | ##Binary to Hex and Hex to Binary Script
##Works on string representations of binary and hex values in .txt files, prints results to your terminal
##Ian White 2017
import os
import sys
import binascii
global byte_array
global init_byte
global hex_list
global bin_list
global convert
def main():
dir_path = os.getcwd()
try:
file_name = sys.argv[1]
convert = sys.argv[2]
name_num = sys.argv[3]
except:
print("Usage: ")
print("binhextrans.py [filename] [hex/bin] [num]")
print("where [filename] is the name of the file,")
print("[hex/bin] are to translate from hex to binary or from binary to hexadecimal, respectively")
print("and [num] is the number to he appended the the output filename, for identification purposes.")
sys.exit()
full_path = dir_path + "/" + file_name
file = open(full_path, "r");
content = file.read();
content = content.split()
content = ''.join(content)
res_file = open('converted_test'+name_num+'.dat', 'w')
if convert == 'bin':
print("Converting from binary to hexadecimal...")
len_block = len(content)
num_bytes = len_block/8
print("Number of bytes: " + str(num_bytes))
print("Raw data:")
print(content)
i = 0
j = 0
byte_array = []
init_byte = []
for bit in content:
i = i + 1
init_byte.append(bit)
if i == 8:
#print(init_byte)
byte_array.append(init_byte)
i = 0
j = j + 1
init_byte = []
#4 bits at a time, convert those four bits to hex representation.
#for i in range(0,7):
#print(byte_array)
hex_list = []
for byte in byte_array:
byte = ''.join(byte)
#print(byte)
int_rep = int(byte, 2)
hex_rep = '%02X' % int_rep
hex_list.append(hex_rep)
res_file.write(hex_rep)
#print(hex_list)
res_file.close()
hex_string = ''.join(hex_list)
hex_list = hex_string.split('x')
hex_string = ''.join(hex_list)
print("Hex output:")
print(hex_string)
#print("Creating test file bbc_tester2.dat")
elif convert == 'hex':
print("Converting from hexadecimal to binary...")
len_block = len(content)
num_bytes = len_block/2
print("Number of bytes: " + str(num_bytes))
print("Raw data:")
print(content)
i = 0
j = 0
byte_array = []
init_byte = []
for bit in content:
i = i + 1
init_byte.append(bit)
if i == 2:
#print(init_byte)
byte_array.append(init_byte)
i = 0
j = j + 1
init_byte = []
#4 bits at a time, convert those four bits to hex representation.
#for i in range(0,7):
#print(byte_array)
bin_list = []
num_of_bits = 8
for byte in byte_array:
byte = ''.join(byte)
#print(byte)
#int_rep = int(byte, 2)
#hex_rep = '%02X' % int_rep
bin_rep = bin(int(byte, 16))[2:].zfill(8)
bin_list.append(bin_rep)
res_file.write(bin_rep)
res_file.close()
bin_string = ' '.join(bin_list)
print("Binary output:")
print(bin_string)
# display some lines
if __name__ == "__main__": main() |
931da81cabc70a6ffa7498fd530fdcb7732b024e | MrHamdulay/csc3-capstone | /examples/data/Assignment_3/gdnzik001/question2.py | 455 | 4.4375 | 4 | #Zikho Godana
#25 March 2014
#program to draw an isoceles triangle of a given height using the '*' character.
height=eval(input("Enter the height of the triangle:\n"))
def tri(height):
gap=height-1
for i in range(0,height):
print(' '*gap,end='')
if i==0:
print('*'*(i+1))
else:
print('*'*(i*2+1))
gap=gap-1 # can also write this as: gap-=1
tri(height)
|
5325962969a298cc833e84df5b8b39f00fb833e4 | mitkondratyev/geekbrains | /python_old/lesson_1/task_3.py | 891 | 4 | 4 | print('Welcome to medical card')
name = input('Please input name: ')
surname = input('Please input surname: ')
age = int(input('Please input age: '))
weight = int(input('Please input weight: '))
medical_info = name + ' ' + surname + ', ' + str(age) + ' years,' + ' weight ' + str(weight)
good_condition = 'good condition'
must_take_care = 'should take yourself'
need_a_doctor = 'need a doctor!'
if weight >= 50 and weight <= 120:
if age < 30:
print(medical_info + ' - ' + good_condition)
elif age >= 40:
print(medical_info + ' - ' + good_condition) #not in task
else:
print(medical_info + ' - ' + good_condition) #not in task
else:
if age < 30:
print(medical_info + ' - ' + must_take_care) #not in task
elif age >= 40:
print(medical_info + ' - ' + need_a_doctor)
else:
print(medical_info + ' - ' + must_take_care)
|
55b528a072d511a04624cf6b906e2da27ee62e24 | WesRoach/coursera | /specialization-data-structures-algorithms/algorithmic-toolbox/week4/solutions/2_majority_element/python/majority_element.py | 701 | 3.984375 | 4 | def get_majority_element(a: list) -> int:
"""Returns 1 if list contains a majority element, otherwise: 0"""
count = dict()
for value in a:
if value not in count:
count[value] = 0
count[value] = count[value] + 1
# sorted() returns [(value, cnt), (value, cnt), (), ...]
# with the most frequenctly counted value in the first position
# [0][1] returns the count of the most frequency value
max_count = sorted(count.items(), key=lambda x: x[1], reverse=True)[0][1]
if max_count > (len(a) / 2):
return 1
return 0
if __name__ == "__main__":
_ = input()
a = list(map(int, input().split()))
print(get_majority_element(a))
|
1f0e91a43c0fc2f5941c2de3e40c4ea75e727690 | arunkumaarr/myfirstproject | /montypy.py | 127 | 3.515625 | 4 | string ='trick or treat'
x=len(string)
print(x)
list=string[len(string)-1:1:-1]
print(list)
for c in string[::-1]:
print(c) |
7859a9738c53058c35bb23d849a2a244a86d0674 | learndevops19/pythonTraining-CalsoftInc | /training_assignments/Day_01/neelima_mishra/Day01_Prg6.py | 495 | 4.09375 | 4 | '''
6. Write a Python program to find the second largest number in a list.
sample input: [-8, 1, 2, -2, 0]
sample output: 1
'''
l1 = [-8, 1, 2, -2, 0]
sec_larg = None
count = 0
while count < len(l1):
for i in range(len(l1)-1):
if sec_larg == None:
sec_larg = l1[i]
continue
elif l1[i] > l1[i+1]:
sec_larg = l1[i]
l1[i] = l1[i+1]
l1[i+1] = sec_larg
count += 1
print('second largest element in list is: ', l1[-2]) |
857296373d479233c9bbb737bcbc779ea3e35edb | GroHD/Hd_Project | /Day2/Class_DuoTai_Practice.py | 627 | 4.1875 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
多态
2017年2月27日20:08:10
hd
'''
class Animal(object):
hobie = 'meat'
def __init__(self,name):
self.name = name
def tale(self):
print("Subclass must implement.....")
class Cat(Animal):
def __init__(self,name):
super(Cat,self).__init__(name)
def tale(self):
print("My Is Cat")
class Dog(Animal):
def __init__(self,name):
super(Dog,self).__init__(name)
def tale(self):
print("My Is Dof")
#传入方法执行多态
def Tale(obj):
obj.tale()
c = Cat('Cat')
d = Dog('dog')
Tale(c)
Tale(d)
|
eb3aca38be59cf0406e1a250c3278bc76d0bb379 | pabdominguez98/ahorcado-python | /validaciones.py | 1,813 | 3.59375 | 4 |
def ingreso_valido(letra):
'''
La función toma el ingreso del usuario y se fija si es una única letra.
Autor: Pablo Dominguez
'''
resp = False
if len(letra) == 1 and letra.isalpha():
resp = True
return resp
def letra_en_cadena(letra, palabra):
'''
Comprueba si la letra está en la palabra.
Autor: Pablo Dominguez
'''
return letra in palabra
def letra_ya_ingresada_y_es_valida(datos, diccionario):
'''
La función determina si el ingreso es valido y si está en la palabra que contiene los signos de
interrogación.
Autor: Gonzalo Bacigalupo
'''
resp = datos['ingreso valido']
resp = resp and letra_en_cadena(datos['letra'], diccionario['palabra_signos'])
return resp
def seguir(datos, diccionario):
'''
Devuelve un booleano, el cual es verdadero si el usuario que actualmente está jugando,
tiene que seguir ingresando valoreso, o falso en caso de que se tenga que pasar al siguiente
jugador.
Autor: Franco Singh
'''
resp = diccionario['desaciertos'] == datos['desaciertos']
# si los desaciertos son iguales en ambos diccionarios, significa q no se equivocó en lo q va d su turno, por lo q puede seguir jugando
resp = resp and '?' in diccionario['palabra_signos']
return resp
def perdieron_todos(jugadores):
'''
Esta función determina si todos los jugadores perdieron.
Autor:...
'''
resp = True
for jugador in jugadores:
resp = resp and jugadores[jugador]['perdio']
return resp
def gano_alguien(jugadores):
'''
Esta función determina si al menos unos de los jugadores adivinó la palabra.
Autor:...
'''
resp = False
for jugador in jugadores:
resp = resp or jugadores[jugador]['gano']
return resp
|
f875a0eae3ad5760e2211dcada158ab904beb6f4 | ygh929/rosalind_alg_code | /majority.py | 540 | 3.65625 | 4 | class major_list(list):
def find_major(self,n):
element=self[0]
vote=1
for candidate in self[0:]:
vote+=[-1,1][candidate==element]
if vote==0:
element = candidate
vote=1
return [-1,element][self.count(element)>n/2]
f=open('rosalind_maj.txt')
l1=f.readline().split()
k=int(l1[0])
n=int(l1[1])
i=0
result=[0 for j in range(k)]
for line in f:
result[i]=major_list(map(int,line.split())).find_major(n)
i=i+1
print ' '.join(map(str,result))
|
3e87a872c77a2052eabb0474af30af5ea14444d3 | woofan/leetcode | /56-merge-list.py | 579 | 3.890625 | 4 | def merge(intervals):
intervals = sorted(intervals)
for i in range(len(intervals)-1):
if intervals[i+1][0] <= intervals[i][1]:
if intervals[i+1][1] <= intervals[i][1]:
intervals[i+1] = intervals[i]
intervals[i] = []
elif intervals[i+1][1] > intervals[i][1]:
intervals[i+1] = [intervals[i][0],intervals[i+1][1]]
intervals[i] = []
res = []
for i in intervals:
if i != []:
res.append(i)
return res
a=[[1,3],[2,6],[8,10],[15,18]]
print(merge(a))
|
75ff068aa0b280120431a21bffd091c483376889 | standrewscollege2018/2019-year-13-classwork-padams73 | /buttons-in-loop.py | 661 | 4.09375 | 4 | # This program creates a new button for each item in a list, sending the name to a function
from tkinter import *
# import partial so that our values change when we display the buttons in the loop
from functools import partial
root =Tk()
root.title("Buttons from a list")
def print_name(selected_name):
print("You selected", selected_name)
names = ["Alfie", "Baz", "Chuck"]
# when the value to be sent to the function will change each iteration, we use the partial() command
# put the function name and the variable inside partial()
for name in names:
button = Button(root, text=name, command=partial(print_name, name)).grid()
root.mainloop() |
e61343124fc6269d1cd82f9fe2e2d8052604c7bf | devilnotcry77/Neuron-Network | /Neuron Network .py | 770 | 3.703125 | 4 | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class Neuron:
def __init__(self, up, down):
self.up = up
self.down = down
def feedforward(self, inputs):
total = np.dot(self.up, inputs) + self.bias
return sigmoid(total)
up = np.array([0, 1])
bias = 4
n = Neuron(up, bias)
x = np.array([2, 3])
print(n.feedforward)
class Neuron2:
def __init__(self, fast, stop):
self.fast = fast
self.stop = stop
def feedforward(self, inputs):
total = np.dot(self.fast, inputs) + self.bias
return sigmoid(total)
fast = np.array([0, 1])
bias = 5
n = Neuron2(fast, bias)
x = np.array([5, 8])
print(n.feedforward)
|
bc54521845b1fb80268a030ed0072a69022080d0 | vickiecheng/cse190final | /scripts/astar2.py | 2,657 | 3.6875 | 4 | class grid():
def __init__(self, x, y, reachable):
self.x = x
self.y = y
self.g = 0
self.h = 0
self.f = 0
self.reachable = reachable
self.parent = None
class AStar():
def __init__(self, move_list, start, goal, map_size, wall, pits):
(height, width) = map_size
self.grid_height = height
self.grid_width = width
self.start = start
self.goal = goal
self.wall = wall
self.pits = pits
self.opened = []
heapq.heapify(self.opened)
self.closed = set()
self.grids = []
def init_grid(self):
for x in range(self.grid_width):
for y in range(self.grid_height):
if (x, y) in self.wall or self.pits:
reachable = False
else:
reachable = True
self.cells.append(grid(x, y, reachable))
def process(self):
# add starting cell to open heap queue
heapq.heappush(self.opened, (self.start.f, self.start))
while len(self.opened):
# pop cell from heap queue
f, grid = heapq.heappop(self.opened)
# add cell to closed list so we don't process it twice
self.closed.add(grid)
# if ending cell, display found path
if grid is self.goal:
self.display_path()
break
# get adjacent cells for cell
adj_cells = self.get_adjacent_grids(grid)
for adj_cell in adj_cells:
if adj_cell.reachable and adj_cell not in self.closed:
if (adj_cell.f, adj_cell) in self.opened:
# if adj cell in open list, check if current path is
# better than the one previously found for this adj
# cell.
if adj_cell.g > grid.g + 1:
self.update_grid(adj_cell, grid)
else:
self.update_grid(adj_cell, grid)
# add adj cell to open list
heapq.heappush(self.opened, (adj_cell.f, adj_cell))
def get_heuristic(self, grid):
return (abs(grid.x - self.end.x) + abs(grid.y - self.end.y))
def get_grid(self, x, y):
return self.grids[x * self.grid_height + y]
def get_adjacent_grids(self, grid):
grids = []
if grid.x < self.grid_width-1:
grids.append(self.get_cell(grid.x+1, grid.y))
if grid.y > 0:
grids.append(self.get_cell(grid.x, grid.y-1))
if grid.x > 0:
gridss.append(self.get_cell(grid.x-1, grid.y))
if grid.y < self.grid_height-1:
grids.append(self.get_cell(grid.x, grid.y+1))
return grids
def display_path(self):
grid = self.goal
while grid.parent is not self.start:
grid = grid.parent
print 'path: cell: %d,%d' % (grid.x, grid.y)
def update_grid(self, adj, grid):
adj.g = grid.g + 1
adj.h = self.get_heuristic(adj)
adj.parent = grid
adj.f = adj.h + adj.g
|
448c5036cdcc634648b31c350bfe217ff69d15a4 | Nega-6/pineapple | /pineapple.py | 13,814 | 3.75 | 4 | import sys
class StoryPiece:
def __init__(self, text):
self.text = text
self.choices = []
def add_choice(self, choice):
self.choices.append(choice)
def run(self):
print self.text
while True:
data = sys.stdin.readline().rstrip()
for choice in self.choices:
if data == choice.command:
return choice.destination
print "You had one job. Type the right thing. Remember lower case."
class Choice:
def __init__(self, command, destination):
self.command = command
self.destination = destination
Menu = StoryPiece("Welcome to Castle Destroyer! The Calculus AB/BC review game. All answers are multiple choice and lower case. Simply type 'a', 'b', 'c' or 'd' to provide an answer. Type 'start' to begin. When the game ends type 'return' to restart.")
R1 = StoryPiece("You awake to find yourself in a dark, moldy cell. There is a shaded hallway on the other side of your cell door and there are no windows. A guard walks by your cell and whispers some obscenities to you before continuing. As he steps away the ring containing his keys clatters to the floor just outside your door. Type 'next' to continue.")
R2 = StoryPiece("You delicately retrieve the keys from the floor outside of your cell. You quietly unlock the door and step out in to the hallway. You look all around and the only exit is currently being blocked by that rude and unsavory guard who is moving towards it slowly. You manage to sneak up to be only a few feet behind him before taking any drastic action. Type 'next' to continue.")
R3 = StoryPiece("You wrap your arm around the guards neck from behind and subdue him. You proceed to take the club that he was carrying and bonk him over the head for good measure. You search for anything else that could be of use but find nothing but a squished carrot. As you move through the door at the end of the corridor you find yourself at the top of a long spiraling set of stairs. Type 'next' to continue.")
R4 = StoryPiece("You finally make it to the bottom of the maddeningly long staircase to find a lone door at the bottom. In your excitement you jump through the door to find yourself in a crowded kitchen. In the craziness noone immediately notices you, but you have to get out quickly before someone wises up to the fact that you stink more than a horse in heat in the middle of summer. Type 'next' to continue.")
R5 = StoryPiece("You make it through the back door to the castle and end up in the small field behind the castle, flooded with mud. A step to your right causes the ground to collapse revealing a spike pit. You manage to pull back just in time in order to not fall in. You have to move quickly, there are archers in the towers watching the yard. A moments hesitation can mean the end. Type 'next' to continue.")
R6 = StoryPiece("You carefully maneuver through the open field around to the side of the castle. A few more traps were activated and narrowly missed on the way, but you manage to avoid alerting any guards. Ahead of you, to the right, on the the side of the castle is the door your looking for. The door down to the armory! Type 'next' to continue.")
R7 = StoryPiece("You enter through the door to the armory. It is so dark here that you can't see your hands in front of your face. You take a step forward and there is a surprising drop. Oh great...you're on a staircase. But you're almost to the motherload of weapons! It's too late to give up now. Type 'next' to continue.")
R8 = StoryPiece("As you enter the armory there is a door to your right, but there is quite the ruckus coming from the other side. It is best to be quiet to avoid being found. There are old discarded weapons and shields along the floor, but there is quite the collection of prisitne weapons hanging on the wall. Type 'next to continue.")
R9 = StoryPiece("You pick out a gorgeous shield with a golden eagle on it, as well as a shiny shortsword. There were many options that looked more glamorous, but the weight of this particular shortsword was absolutely perfect. The ruckus from the other room grows closer so you rush back to the staircase in order to avoid a disaster. Type 'next' to continue")
R10 = StoryPiece("You come out of the door to the armory, and just your luck there's the ugly mug of a passing soldier staring you right in the eyes. He raises his sword, screaming something that roughly resembles 'YOURE MINE NOW!'. He beigns to swing his sword directly towards your head. Type 'next' to continue.")
R11 = StoryPiece("You swiftly cut down the screaming guard and rush along the side of the castle towards the courtyard. There is no chance of remaining undiscovered now. As you enter the courtyard you see two guards directly infront of you. On the opposite side of the courtyard there is a third guard rushing towards the mechanism to lower the gate. The two guards in front of you draw their swords and begin charging in your direction. Type 'next' to continue.")
R12 = StoryPiece("You do some sweet ninja moves and swing your sword around in a full circle chopping both guards in half, they float there in slow motion before turning in to dust. Classic ninja stuff. Now you've got to keep the gate from being closed. You rush towards the guard manning the gate, raising your sword high into the air and letting out your most vigorous war cry. Type 'next' to continue.")
R13 = StoryPiece("You manage to strike down the guard before the gate completely closes. It is left hanging two or three feet off of the ground. You go to move around towards the gate and are blocked off by a platoon of guards, no less than thirty. The only open space left is behind you, your back being towards the blacksmith's. Type 'next' to continue.")
R14 = StoryPiece("You rush in to the blacksmith's and lock the door behind you. You step away and you can see the door bending as the guards outside ram in to it. You take a look around the room and there is not much to see, there are twenty or so kegs littering the floor, and a tanning rack covered in fresh cloth. To the side of the rack is the smeltery, still lit. You peek in to one of the kegs to find it full of gunpowder. The same seems to be true of the rest. The door begins to crack under the strength of the guards slamming in to it. Type 'next' to continue.")
R15 = StoryPiece("You light a piece of cloth from the tanning rack and tuck it in to one of the powder kegs. You find a ladder in the corner of the room and climb up it on to the roof. You wait until you feel the time is right, and you jump for the gate. Landing feet before it and sliding under it. Before any of the guards have time to react they are blown from this world by the awesome power of these powder kegs. The gate slams shut and you start to walk away. As the rest of the castle starts the blow up behind you. Type 'next' to continue.")
R16 = StoryPiece("You won the game. Big woop. Cool guys don't look at explosions, you did it. Bye bye now. Type 'return' to restart")
D1 = StoryPiece("You are as loud and obnoxious as possible when reaching for the keys so you manage to alert the guard who returns and picks up his keys. GAME OVER.")
D2 = StoryPiece("As you move forward to choke out the guard, you trip in to him. When you do this, he turns around and bonks you over the head with his club. You pass out and wake up chained to the wall in your cell. GAME OVER.")
D3 = StoryPiece("You being the clumbsy person that you are, you trip and tumble down the stairs. It was a pretty long fall, you broke everything on the way down. GAME OVER.")
D4 = StoryPiece("Your stench is overwhelming. A group of cooks turn to you and in a disgusted rage start beating you with pots and pans. GAME OVER.")
D5 = StoryPiece("You begin moving through the maze of traps, and things seem fine at first. In overwhelming joy for being so quick and nimble, you jump forward. As a result, you land in a spike trap. GAME OVER.")
D6 = StoryPiece("You take way too long getting where you need to go, and an archer spots you from his post. An arrow swiftly zooms through the air and goes in one ear and out the other. GAME OVER.")
D7 = StoryPiece("You feel along the wall and stumble upon a switch. You decide that flipping it can't hurt and it fills the hallway with flames. At least you could see for a second before death. GAME OVER.")
D8 = StoryPiece("You stumble and fumble through the armmor, being extremely obnoxious you alert the guards in the next room. The storm the room and start beating you, and slashing you up with their swords. GAME OVER.")
D9 = StoryPiece("You feel along the wall and stumble upon a switch. You decide that flipping it can't hurt and it fills the hallway with flames. At least you could see for a second before death. GAME OVER.")
D10 = StoryPiece("You stare at the guard in a daze. You make the decision of indecision, and you are ended in a single blow.")
D11 = StoryPiece("As you move towards the two guards to fight back, you slip and fall on to their swords. WAY TO GO, THEY DIDNT EVEN HAVE TO DO ANYTHING. GAME OVER.")
D12 = StoryPiece("You rush towards the gate and try to slide under, but you dont make it through in time and are immediately crushed. GAME OVER.")
D13 = StoryPiece("You stand around and get captured. You are returned to your cell after a stern whipping. GAME OVER.")
D14 = StoryPiece("This plan wasn't as smart as you thought, and you blow yourself up. Good job...GAME OVER.")
D15 = StoryPiece("You look at the explosion...cool guys dont look at explosions. GAME OVER.")
Q1 = StoryPiece("d/dx CU = ? A:c'u B:cu' C:c'u' D:du")
Q2 = StoryPiece("Integral of du = ? A:u+c B:du+dc C:du+c D:u")
Q3 = StoryPiece("d/dx cosx = ? A:-sinx B:sinx")
Q4 = StoryPiece("Integral from 1 to 3 of -x^2 + 4x -3dx = ? A:6/3 B: -4/3")
Q5 = StoryPiece("Summation of 1/n^p if p = 1/3 A:Converges B:Diverges C:Cannot be determined")
Q6 = StoryPiece("Integral of e^x = ? A:e^x + c B:12 C:e^x^x")
Q7 = StoryPiece("Integral of x^2 = ? A:2x+c B:1/2x^2 +c C:2+c D: 1/3x^3 +c")
Q8 = StoryPiece("Integral from 1 to 2 of x^2 = ? A:7/3 B:2/3 C:7 D:3")
Q9 = StoryPiece("d/dx x^6 + 3x^5 + 7x +3 = ? A: 601231 B:6x^5 +15x^4 C:6x^5 + 15x^4 + 7")
Q10 = StoryPiece("d/dx 3x^2 A:5x B:1231 C:6x D:42")
Q11 = StoryPiece("If d/dx represents speed, what will taking the integral yield? A:Speed B:Acceleration C:Nothing D:Position")
Q12 = StoryPiece("What is another term for anti-derivative that may include bounds? A:Integral B:Summation")
Q13 = StoryPiece("Fluffy the kitty accelerates at 6m/s. How can you determine his speed at time x=t? A:Take the derivative B:Use summation C:Take the integral and plug in t for x D:Take the integral")
Q14 = StoryPiece("On a position time graph, what represents the velocity? A: Slope of the tangent line B: Slope")
Q15 = StoryPiece("The ratio test is useful for what type of problem? A:Derivative B:Summation C:Integral")
R1.add_choice(Choice("next", Q1))
R2.add_choice(Choice("next", Q2))
R3.add_choice(Choice("next", Q3))
R4.add_choice(Choice("next", Q4))
R5.add_choice(Choice("next", Q5))
R6.add_choice(Choice("next", Q6))
R7.add_choice(Choice("next", Q7))
R8.add_choice(Choice("next", Q8))
R9.add_choice(Choice("next", Q9))
R10.add_choice(Choice("next", Q10))
R11.add_choice(Choice("next", Q11))
R12.add_choice(Choice("next", Q12))
R13.add_choice(Choice("next", Q13))
R14.add_choice(Choice("next", Q14))
R15.add_choice(Choice("next", Q15))
Q1.add_choice(Choice("a",D1))
Q1.add_choice(Choice("b",R2))
Q1.add_choice(Choice("c",D1))
Q1.add_choice(Choice("d",D1))
Q2.add_choice(Choice("a",R3))
Q2.add_choice(Choice("b",D2))
Q2.add_choice(Choice("c",D2))
Q2.add_choice(Choice("d",D2))
Q3.add_choice(Choice("a",R4))
Q3.add_choice(Choice("b",D3))
Q4.add_choice(Choice("a",D4))
Q4.add_choice(Choice("b",R5))
Q5.add_choice(Choice("a",D5))
Q5.add_choice(Choice("b",R6))
Q5.add_choice(Choice("c",D5))
Q6.add_choice(Choice("a",R7))
Q6.add_choice(Choice("b",D6))
Q6.add_choice(Choice("c",D6))
Q7.add_choice(Choice("a",D7))
Q7.add_choice(Choice("b",D7))
Q7.add_choice(Choice("c",D7))
Q7.add_choice(Choice("d",R8))
Q8.add_choice(Choice("a",R9))
Q8.add_choice(Choice("b",D8))
Q8.add_choice(Choice("c",D8))
Q8.add_choice(Choice("d",D8))
Q9.add_choice(Choice("a",D9))
Q9.add_choice(Choice("b",D9))
Q9.add_choice(Choice("c",R10))
Q10.add_choice(Choice("a",D10))
Q10.add_choice(Choice("b",D10))
Q10.add_choice(Choice("c",R11))
Q10.add_choice(Choice("d",D10))
Q11.add_choice(Choice("a",D11))
Q11.add_choice(Choice("b",D11))
Q11.add_choice(Choice("c",D11))
Q11.add_choice(Choice("d",R12))
Q12.add_choice(Choice("a",R13))
Q12.add_choice(Choice("b",D12))
Q13.add_choice(Choice("a",D13))
Q13.add_choice(Choice("b",D13))
Q13.add_choice(Choice("c",R14))
Q13.add_choice(Choice("d",D13))
Q14.add_choice(Choice("a",D14))
Q14.add_choice(Choice("b",R15))
Q15.add_choice(Choice("a",D15))
Q15.add_choice(Choice("b",R16))
Q15.add_choice(Choice("c",D15))
Menu.add_choice(Choice("start",R1))
D1.add_choice((Choice("restart"Menu))
D2.add_choice((Choice("restart"Menu))
D3.add_choice((Choice("restart"Menu))
D4.add_choice((Choice("restart"Menu))
D5.add_choice((Choice("restart"Menu))
D6.add_choice((Choice("restart"Menu))
D7.add_choice((Choice("restart"Menu))
D8.add_choice((Choice("restart"Menu))
D9.add_choice((Choice("restart"Menu))
D10.add_choice((Choice("restart"Menu))
D11.add_choice((Choice("restart"Menu))
D12.add_choice((Choice("restart"Menu))
D13.add_choice((Choice("restart"Menu))
D14.add_choice((Choice("restart"Menu))
D15.add_choice((Choice("restart"Menu))
R16.add_choice((Choice("restart"Menu))
part = Menu
while True:
part = part.run()
|
66a4ac0f10a0f5ea3e0b0e6ca52ade97db5109f9 | zachwemhoff/learn-arcade-work | /Testing/array-backed grids example.py | 2,048 | 3.734375 | 4 | import arcade
WIDTH = 20
HEIGHT = 20
MARGIN = 5
ROW_COUNT = 10
COLUMN_COUNT = 10
SCREEN_HEIGHT = HEIGHT * ROW_COUNT + MARGIN * (ROW_COUNT + 1)
SCREEN_WIDTH = WIDTH * COLUMN_COUNT + MARGIN * (COLUMN_COUNT + 1)
class MyGame(arcade.Window):
"""
Main application class.
"""
def __init__(self, width, height):
super().__init__(width, height)
arcade.set_background_color(arcade.color.BLACK)
self.grid = []
for row in range(ROW_COUNT):
self.grid.append([])
for column in range(COLUMN_COUNT):
self.grid[row].append(0)
# self.grid[2][5] = 1
self.grid[row][column]
for row in self.grid:
print(row)
# self.grid = [[0 for x in range(10)] for y in range (10)]
def on_draw(self):
"""
Render the screen.
"""
arcade.start_render()
for row in range(ROW_COUNT):
for column in range(COLUMN_COUNT):
if self.grid[row][column] == 0:
color = arcade.color.ICTERINE
else:
color = arcade.color.AMETHYST
arcade.draw_rectangle_filled((WIDTH / 2) + (column * (WIDTH + MARGIN)) + MARGIN,
HEIGHT / 2 + (row * (HEIGHT + MARGIN)) + MARGIN,
WIDTH, HEIGHT,
color)
def on_mouse_press(self, x, y, button, key_modifiers):
"""
Called when the user presses a mouse button.
"""
grid_x = x // (WIDTH + MARGIN)
grid_y = y // (HEIGHT + MARGIN)
print(f"Click coordinates: ({x}, {y}). Grid coordinates: ({row}, {column})")
if self.grid[grid_y][grid_x] == 0:
self.grid[grid_y][grid_x] = 1
else:
self.grid[grid_y][grid_x] = 0
print(grid_x, grid_y)
def main():
window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT)
arcade.run()
if __name__ == "__main__":
main()
|
cb9c832edfdf929734d7ef555df4d4d26370008d | azhou31/Python | /OOP/animal.py | 1,256 | 3.65625 | 4 | class Animal(object):
def __init__(self, name):
self.name = name
self.health = 10
# self.status = "Healthy"
# def mobility(self, status):
# if status == "walk":
# self.health -= 1
# self.status = "Good"
# if status == "run":
# self.health -= 5
# self.status = "Exhausted"
# print "Health score is: " + str(self.health)
# print "Health status is: " + str(self.status)
def walk(self):
self.health -= 1
def run(self):
self.health -= 5
# def displayHealth(self):
# print str(self.health)
class Dog(Animal):
def __init__(self, name):
super(Dog, self). __init__(name)
self.health = 150
def pet(self):
self.health += 5
class Dragon(Animal):
def __init__(self, name):
super(Dragon, self).__init__(name)
self.health = 170
def fly(self):
self.health -= 10
tiger=Animal("Bob")
tiger.walk()
tiger.walk()
tiger.walk()
tiger.run()
tiger.run()
print "Health: " + str(tiger.health)
d=Dog("Yogi")
d.walk()
d.walk()
d.walk()
d.run()
d.run()
d.pet()
print "Health: " + str(d.health)
D=Dragon("Hoover")
print D.health
print "I am a Dragon"
|
ba9a08067c92f0bfac6e716037643c1df9a79407 | alirezaghey/leetcode-solutions | /python/validate-stack-sequence.py | 400 | 3.59375 | 4 | class Solution:
# Time complexity: O(n) where n the length of pushed is
# Space complexity: O(n)
def validateStackSequences(self, pushed, popped):
j = 0
stack = []
for x in pushed:
stack.append(x)
while stack and j < len(popped) and stack[-1] == popped[j]:
stack.pop()
j += 1
return j == len(popped) |
f9893b056cc892a78f9d377c0ea7e97be4574241 | ardaunal4/My_Python_Lessons | /machine_learning/Classification/logistic_regression_classification/logistic_reg_with_sklearn.py | 1,216 | 3.59375 | 4 | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
def main():
data = pd.read_csv("C:\\Users\\ardau\\OneDrive\\Masaüstü\\machine_learning\\regression_types\\logistic_regression_classification\\data.csv")
data.drop(["id", "Unnamed: 32"], axis = 1, inplace = True) # Remove unnecessary features of data
data.diagnosis = [1 if each == "M" else 0 for each in data.diagnosis] # Change object to the integer
y = data.diagnosis.values # binary classification outputs
x_data = data.drop(["diagnosis"], axis = 1, inplace = False) # drop output to make database constructed by feature which is necessary for diagnosis
print(x_data.info())
x = ((x_data - np.min(x_data))/(np.max(x_data) - np.min(x_data))).values # normalization
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 42) # Split data into train and test part
logistic_reg = LogisticRegression()
logistic_reg.fit(x_train, y_train) # (455, 30)
print("Test accuracy = {}".format(logistic_reg.score(x_test, y_test)))
if __name__ == "__main__":
main()
|
fa7b9d2baa443f4899f3c4d0eeaf26eee7f42829 | JanhaviNandish/Python | /remnum.py | 104 | 3.8125 | 4 | s=input()
t=''
for i in s:
if (i>='a' and i<='z') or (i>='A' and i<='Z'):
t+=i
print(t) |
7f00c59f89adf7e0d9b1d923d6b65a848aa5c6a8 | Programacion-Algoritmos-18-2/ejercicios-clases2bim-002-Rennato99 | /tutoria-2-sc/manejo_archivos/paquete_modelo/mimodelo.py | 3,848 | 3.96875 | 4 | """
creación de clases
"""
class Persona(object):
# Constructor
def __init__(self, nombre, apellido, edad, codigo, nota1, nota2):
self.agregar_nombre(nombre)
self.agregar_apellido(apellido)
self.agregar_edad(edad)
self.agregar_codigo(codigo)
self.agregar_nota1(nota1)
self.agregar_nota2(nota2)
# Metodos set
def agregar_nombre(self, n):
self.nombre = n
def agregar_edad(self, n):
self.edad = int(n)
def agregar_codigo(self, n):
self.codigo = int(n)
def agregar_apellido(self, n):
self.apellido = n
def agregar_nota1(self, n):
self.nota1 = int(n)
def agregar_nota2(self, n):
self.nota2 = int(n)
# Metodos get
def obtener_nombre(self):
return self.nombre
def obtener_edad(self):
return self.edad
def obtener_codigo(self):
return self.codigo
def obtener_apellido(self):
return self.apellido
def obtener_nota1(self):
return self.nota1
def obtener_nota2(self):
return self.nota2
# Modificamos el str
def __str__(self):
return " %s - %s - %d - %d - %d - %d" % (self.obtener_nombre(), self.obtener_apellido(),\
self.obtener_edad(), self.obtener_codigo(), self.obtener_nota1(), self.obtener_nota2())
# Creando la clase OperacionesPersona
class OperacionesPersona(object):
# Constructor
def __init__(self, listado):
self.listado_personas = listado
# Modificamos el str
def __str__(self):
cadena = "\nListado de todas las personas:\n"
for n in self.listado_personas:
cadena = ("%s\tNombre: %s %s\n" %(cadena, n.obtener_nombre(), n.obtener_apellido()))
return cadena
# Metodo para obtener el promedio de las notas 1
def obtener_promedio_n1(self):
suma = 0 # Inicializamos suma
for n in self.listado_personas: # Recorremos el listado de personas
suma += n.obtener_nota1() # Actualizamos suma
promedio = suma / len(self.listado_personas) # Calculamos el promedio
return promedio # Retornamos el promedio
# Metodo para obtener el promedio de las notas 2
def obtener_promedio_n2(self):
suma = 0 # Inicializamos suma
for n in self.listado_personas: # Recorremos el listado de personas
suma += n.obtener_nota2() # Actualizamos suma
promedio = suma / len(self.listado_personas) # Calculamos el promedio
return promedio # Retornamos el promedio
# Metodo que retorne los personas con notas1 menores que 15
def obtener_listado_n1(self):
cadena = "Personas con nota 1 menores que 15:\n" # Encabezado
for n in self.listado_personas: # Recorremos el listado de personas
if (n.obtener_nota1() < 15): # Verificamos si es menor que 15
cadena = ("%s\tNombre: %s %s; Nota %d\n" %(cadena, n.obtener_nombre(), n.obtener_apellido(), n.obtener_nota1())) # Formateo de cadena
return cadena # Retornamos la cadena
# Metodo que retorne los personas con notas2 menores que 15
def obtener_listado_n2(self):
cadena = "Personas con nota 2 menores que 15:\n" # Encabezado
for n in self.listado_personas: # Recorremos el listado de personas
if (n.obtener_nota2() < 15): # Verificamos si es menor que 15
cadena = ("%s\tNombre: %s %s; Nota: %d\n" %(cadena, n.obtener_nombre(), n.obtener_apellido(), n.obtener_nota2())) # Formateo de cadena
return cadena # Retornamos la cadena
# Metodo que retorna el listado de personas cuyo nombre empieza con dos letras específicas
def obtener_listado_personas(self, primeraLetra, segundaLetra):
cadena = "Personas con las iniciales especificadas:\n" # Encabezado
for n in self.listado_personas: # Recorremos el listado de personas
if (n.obtener_nombre()[0] == primeraLetra or n.obtener_nombre()[0] == segundaLetra): # Verificamos si la primera letra del nombre empieza con las letras especificadas
cadena = ("%s\tNombre: %s %s\n" %(cadena, n.obtener_nombre(), n.obtener_apellido())) # Formateo de cadena
return cadena # Retornamos la cadena |
31c429c604a310ec5c8c7b2b5a2a92606578519e | lostlang/hackerrank-interview-preparation-kit | /countingValleys.py | 479 | 4.09375 | 4 |
def counting_valleys(steps: int, path: str) -> int:
valleys: int = 0
height: int = 0
state_path_down: str = "D"
for i in path:
if i == state_path_down:
height -= 1
else:
height += 1
if height == 0:
valleys += 1
return valleys
if __name__ == '__main__':
steps = int(input().strip())
path = input()
result = counting_valleys(steps, path)
print(result)
|
4d0ff100df96f78e91c164cc6b0f8108ad06d5c1 | Michikouwu/primerrepo3c | /operaciones_basicas (1).py | 410 | 3.875 | 4 | # Este es el ejercicio del grupo tercero c
# del dia 13 de septiembre de 2021
# esta linea coloca un mensaje en la consola
print("Este programa hace operaciones basicas")
num1 = 130
numero_2 = 345
suma = num1 + numero_2 # la resta se hace con el simbolo '-'
multip = num1 * numero_2 # la division se hace con una '/'
print("la suma es: ")
print(suma)
print("La multiplicacion da como resultado: ", multip)
|
756c6bb4be91e30880e0c895155fc0674552b4fc | akhandsingh17/assignments | /topics/Arrays/Pascal.py | 839 | 3.65625 | 4 | """
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
"""
class Solution:
def generate(self, numRows):
result = []
if not numRows:
return []
if numRows == 1:
return [[1]]
if numRows == 2:
return [[1], [1, 1]]
if numRows >= 3:
last = self.generate(numRows-1)
result.extend(last)
prev = last[-1][0]
curr = 0
temp = [prev]
for i in range(1, len(last[-1])):
curr = last[-1][i]
total = prev + curr
temp.append(total)
prev = curr
temp.append(prev)
result.append(temp)
return result
if __name__ == "__main__":
s = Solution()
print(s.generate(5))
|
e65e43f430b20dfbdcdac8bdcb67c2dcb104bd90 | mpgomez/python-things | /swap/swap.py | 875 | 4.0625 | 4 | def swap_add(a, b):
"""
version 1
Swaps a and b in place
Only works with numeric values
"""
a = a + b
b = a - b
a = a - b
return a, b
# def swap_or(a, b):
# """
# version 2
# Swaps a and b in place
# Works with different types - NOT IN PYTHON. We would have to convert to bits first
# """
# abyte = bytearray(a)
# bbyte = bytearray(b)
# abyte = bytes(x ^ y for (x, y) in zip(abyte, bbyte))
# bbyte = bytes(x ^ y for (x, y) in zip(abyte, bbyte))
# abyte = bytes(x ^ y for (x, y) in zip(abyte, bbyte))
# return a, b
def swap_or(a, b):
"""
version 2
Swaps a and b in place
Works with different types - NOT IN PYTHON. We would have to convert to bits first
"""
a = a ^ b
b = a ^ b
a = a ^ b
return a, b
return a, b
def swap(a, b):
return swap_or(a, b) |
b116b7c6f5ab7a590149e6ba2e7cd1fa3fb2aa8a | jubi020/TWoC-assignment-problems- | /swapping.py | 206 | 3.953125 | 4 | a = int(input("enter first number to be swapped"))
b = int(input("enter second number to be swapped"))
a = a + b
b = a - b
a = a - b
print("two numbers after swapping are :")
print("a:", a)
print("b:", b)
|
3f17bf2747a9d722e7ea3e0e264e85030c76e39d | gobelinus/playground | /memory_puzzle.py | 1,621 | 4 | 4 | # ============================================================ #
# Game description
# How to Play Memory Puzzle
# In the Memory Puzzle game, several icons are covered up by
# white boxes. There are two of each icon. The player can click
# on two boxes to see what icon is behind them. If the icons
# match, then those boxes remain uncovered. The player wins
# when all the boxes on the board are uncovered.
# To give the player a hint, the boxes are quickly uncovered
# once at the beginning of the game.
# ============================================================ #
import pygame
import sys
from pygame.locals import *
# lets start with 4 by 4 game
# define piece dimensions
SQUARE_SIZE = 40
GUTTER = 20
ROWS = 4
COLS = 4
#COLORs
GRAY = pygame.Color(80, 80, 80)
def main():
"""
"""
# lets start game
# init
pygame.init()
# calculate window dimensions considering left-right top-bottom gaps
window_width = COLS * SQUARE_SIZE + (COLS + 1) * GUTTER
window_height = ROWS * SQUARE_SIZE + (ROWS + 1) * GUTTER
# set up drawing surface
display_surface = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Memory Puzzle')
bgcolor = GRAY
display_surface.fill(bgcolor)
# run the game loop
while True:
# listen on events
for event in pygame.event.get():
# if quit event, close game, exit the program.. duh
if event.type == QUIT:
pygame.quit()
sys.exit()
# update display
pygame.display.update()
if __name__ == '__main__':
main()
|
6b5f85bbe20ceb43afe29b16ebaf1a4b7b9bb21f | santiagopemo/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 357 | 4.09375 | 4 | #!/usr/bin/python3
"""Read Lines Module"""
def read_lines(filename="", nb_lines=0):
"""Function that reads n lines of a text file and prints it to stdout"""
with open(filename, encoding="utf-8") as f:
lines = 1
for l in f:
print(l, end="")
if lines == nb_lines:
break
lines += 1
|
594b3ea9156cfc11f9a9846d3a5ce46fc3999964 | alem-classroom/student-algo-and-data-structures-Adilyam | /bubble-sort/bubble_sort.py | 225 | 3.984375 | 4 | def bubble_sort(lst):
for i in range(len(lst)):
for j in range(1, len(lst)):
if lst[j] < lst[j - 1]:
temp = lst[j]
lst[j] = lst[j - 1]
lst[j - 1] = temp
# sort the list via bubble sort
|
186a677b7b254ffe3396aa33443aa75e05c4119f | toshhPOP/SoftUniCourses | /Python Fundamentals/Text Processing/rage_out.py | 727 | 3.734375 | 4 | text = input().upper()
digit = ''
for i in range(len(text)):
if text[i].isdigit():
if not i+1 >= len(text)-1:
if text[i+1].isdigit():
digit += text[i] + text[i+1] + " "
else:
if text[i] not in digit:
digit += text[i] + " "
else:
digit += text[i]
digit = digit.split()
digit = [int(x) for x in digit]
result = ''
while len(digit) > 0:
for a in digit:
word = text[:text.index(str(a))]
result += word * a
text = text.replace(word, '', 1)
text = text.replace(str(a), '', 1)
digit.remove(a)
break
unique = set(result)
print(f"Unique symbols used: {len(unique)}\n{result}") |
901d782298876ab77949c6122b3c4c3c1ebb79e5 | hellokayas/Some-Programming-Samples | /BettingCode.py | 2,437 | 3.96875 | 4 | #Python 3 code, compiled in JupyterHub
import random
# the following function generates head and tail randomly with prob of a head being 0.6
def flip(p):
return 'H' if random.random() < p else 'T'
# a short experiment if we are getting right results!
N = 300
flips = [flip(0.6) for i in range(N)]
float(flips.count('H'))/N
# money is the parameter we have to choose and experiment with i.e. what fixed bet should be everytime
# ct keeps track of how many times we are getting to play the coin toss
def fixed_bet(money):
amt = 25
ct = 0
for i in range(300):
if amt <= 0: break # this is getting busted!
if amt >= 250: break # limit reached!
if flip(0.6) == "H":
print(ct)
ct += 1
amt += money # updating money
else:
print(ct)
ct += 1
amt -= money # updating money
return amt
# now we play with the parameter money to find what works best and put it in ans
# the follwoing experiment is done with all the strategies.
ans = []
for i in range(1,25):
if fixed_bet(i) > 249: ans.append(i) # replace 249 with any number in [1,250] to check if you can cross that
ans
def martingale_bet(starter):
amt = 25
ct = 0
for i in range(300):
if amt <= 0: break
if amt >= 250: break
if flip(0.6) == "H":
print(ct)
amt += starter
ct += 1
else:
print(ct)
amt -= starter
starter = 2 * starter # if we lose, we double our bet to be back on track on first win!
ct += 1
return amt
# experiment with the starting bet
ans = []
for i in range(1,25):
if martingale_bet(i) > 249: ans.append(i) # replace 249 with whatever!
ans
def proportional_bet(frac):
amt = 25
ct = 0
for i in range(300):
if amt <= 0: break
if amt >= 250: break
if flip(0.6) == "H":
amt = amt * (1+frac)
print(ct)
ct += 1
else:
amt = amt * (1-frac)
print(ct)
ct += 1
return amt
# experiment with the frac
ans = []
fracs = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9] # we can put any value between 0 and 1 in this list, but we already know 0.2 works best!
for frac in fracs:
if proportional_bet(frac) > 249: # replace 249 with whatever! we have tried with 200,225,240 and 250
ans.append(frac)
ans
|
d75a4a4f72f2eb4acc80955c0a51169354b16d39 | iluoyi/Codera | /src/top_k_closest.py | 661 | 3.53125 | 4 | import random
def _quickfind(array, x, k):
p = random.randint(0, len(array)-1)
array[0], array[p] = array[p], array[0]
pivot = array[0]
left = [y for y in array if y < pivot]
if k <= len(left):
return _quickfind(left, x, k)
elif k == len(left) + 1:
return left + [pivot]
right = [y for y in array[1:] if y >= pivot]
return left + [pivot] + _quickfind(right, x, k-len(left)-1)
def quickfind(a, x, k):
return [v for (_, v) in _quickfind([(abs(y-x), y) for y in a], x, k)]
if __name__ == "__main__":
print quickfind([4,1,3,2,7,4], 5.2, 2)
print quickfind([4,1,3,2,7,4], 6.5, 3)
|
887043bddd190b77e00e14489e8f0ca2d8cc42b6 | CMalatesta/Aprendiendo | /HoshenFuntions.py | 1,913 | 3.53125 | 4 | """
"""
import matplotlib.pyplot as plt
def _hoshen():
m, n = b.shape
x = 2
def etiquetar(e, s1, s2, clases, x):
if e == 1:
if s2 != 0 and s1 != 0:
while clases[s2] < 0:
s2 = -clases[s2]
while clases[s1] < 0:
s1 = -clases[s1]
if s1 < s2:
clases[s2] = -s1
return s1, x
elif s1 > s2:
clases[s1] = -s2
return s2, x
else:
return s2, x
elif s2 != 0:
return s2, x
elif s1 != 0:
return s1, x
else:
return x, x + 1
else:
return 0, x
def recorrer(b, clases):
# primer elemento, primera fila
b[0, 0], x = etiquetar(e=b[0, 0], s1=0, s2=0, clases=clases, x=x)
for i in range(1, n):
# resto de la primer fila
b[0, i], x = etiquetar(e=b[0, i], s1=b[0, i - 1], s2=0, clases=clases, x=x)
for i in range(1, m):
# primeros elementos del resto de las filas
b[i, 0], x = etiquetar(e=b[i, 0], s1=0, s2=b[i - 1, 0], clases=clases, x=x)
for j in range(1, n):
# resto de los elementos de las filas
b[i, j], x = etiquetar(e=b[i, j], s1=b[i - 1, j], s2=b[i, j - 1], clases=clases, x=x)
recorrer()
corregir_vector()
corregir_imagen()
if __name__ == '__main__':
# parametros de entrada
M = 8 # filas
N = 8 # columnas
p = 0.7 # probabilidad
# imagen de entrada
a = (np.random.rand(M, N)) < p
# Hoshen
matriz = np.array(a, dtype=int) # genero copia de tipo entero
vector = np.arange((M * N) // 2) # vector de clases
recorrer(b=matriz, clases=vector)
print(matriz)
print(vector)
|
195ebc7b0574365251a463b5ad5d7631f8fca50e | Paulware/piPair | /SpriteSheet.py | 4,295 | 3.5625 | 4 | #import random
#import copy
import os
import pygame
# Create a class to read in a spriteSheet and chop it into images
# attributes:
# data is a list, each element has an image, and an index attribute at this level
# subsequent levels will add attributes to each data element such as x,y,width,height,name
class SpriteSheet:
# numImages is the total number of images
# coverIndex is the zero-based index that points to the back cover
def __init__(self, filename, numColumns, numRows, numImages, coverIndex):
self.numImages = numImages
self.coverIndex = coverIndex
print ( 'coverIndex is: ' + str(coverIndex))
if os.path.exists (filename):
print ( 'This file exists ' + filename )
else:
print ( filename + ' does not exist' )
self.filename = filename
self.numColumns = numColumns
self.numRows = numRows
if os.path.exists (filename):
self.image = pygame.image.load (filename).convert()
(width,height) = self.image.get_size()
self.spriteWidth = int(width/numColumns)
self.spriteHeight = int(height/numRows)
print ( 'sprite [width,height]: [' + str(self.spriteWidth) + ',' + str(self.spriteHeight) + ']' )
self.data = self.loadSpriteImages ()
else:
print( 'This filename does not exist: ' + filename)
exit(1)
# Get the image of a specific index such as cover image
def getIndexImage (self,index):
image = None
x = 0
y = 0
h = 0
for i in range (self.numColumns * self.numRows):
if i == index:
obj = type ('Object', (object,), {})
rect = pygame.Rect(( x,y,self.spriteWidth,self.spriteHeight))
image = pygame.Surface(rect.size).convert()
# Find the next x/y for the next sprite
h = h + 1
if h == self.numColumns:
x = 0
y = y + self.spriteHeight
h = 0
else:
x = x + self.spriteWidth
if image is None:
print ( 'Could not find the image for index: ' + str(index) + ' in the spritesheet?' )
exit(1)
return image
def length(self):
return len(self.data)
def loadSpriteImages (self):
x = 0
y = 0
h = 0
data = []
maxImages = self.numColumns * self.numRows
print ( 'maxImages: ' + str(maxImages) + ' coverIndex: ' + str(self.coverIndex))
for i in range (maxImages):
obj = type ('Object', (object,), {})
rect = pygame.Rect(( x,y,self.spriteWidth,self.spriteHeight))
image = pygame.Surface(rect.size).convert()
image.blit(self.image, (0, 0), rect)
obj.image = image
obj.sheetIndex = i
obj.canDealCard = True
obj.tapped = False
obj.hide = False
obj.drag = False
obj.deleted = False
if i < self.numImages:
data.append (obj)
if i == self.coverIndex:
print ( 'Setting self.coverImage' )
self.coverImage = image
# Find the next x/y for the next sprite
h = h + 1
if h == self.numColumns:
x = 0
y = y + self.spriteHeight
h = 0
else:
x = x + self.spriteWidth
print ( 'loaded ' + str(len(data)) + ' images' )
return data
def showCard (sheet, index, displaySurface):
image = sheet.data[index].image
print ( 'Showing index: ' + str(sheet.data[index].sheetIndex) )
width = sheet.spriteWidth
height = sheet.spriteHeight
position = (10,50)
displaySurface.blit(image, position)
pygame.display.update()
if __name__ == '__main__':
import Utilities
import pygame
pygame.init()
DISPLAYSURF = pygame.display.set_mode((1200, 800))
BIGFONT = pygame.font.Font('freesansbold.ttf', 32)
utilities = Utilities.Utilities (DISPLAYSURF, BIGFONT)
spriteSheet = SpriteSheet ('images/unoSpriteSheet.jpg', 10, 6, 53, 52)
showCard (spriteSheet,7,DISPLAYSURF)
(typeInput,data,addr) = utilities.read()
print ( 'Got (' + str(typeInput) + ',' + str(data) + ',' + str(addr) + ')' )
|
6daaa998a5f8576b566b1dab821ae689851688e1 | Prasantacharya/Leetcode-pratice | /206.py | 573 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None:
return head
itr = head
temp = ListNode()
while itr != None:
temp.val = itr.val
if itr.next != None:
temp2 = ListNode()
temp2.next = temp
temp = temp2
itr = itr.next
return temp
|
9a106946eb73303550becaf30897b462a33714e9 | mmnonato/curso-python | /Atividades/função - EquaçãoQuadrática.py | 599 | 3.96875 | 4 | import math
def delta (a, b, c):
return b ** 2 - 4 * a * c
def x1 (b, a):
return (- b + math.sqrt(d)) / (2 * a)
def x2 (b, a):
return (- b - math.sqrt(d)) / (2 * a)
a = float(input("Informe a letra A: "))
b = float(input("Informe a letra B: "))
c = float(input("Informa a letra C: "))
d = delta(a, b, c)
if d < 0:
print("esta equação não possui raízes reais")
else:
x1 = x1(b, a)
x2 = x2(b, a)
if d == 0:
print("a raiz desta equação é", x1)
elif d > 0:
if x1 < x2:
print("as raízes da equação são", x1, "e", x2)
else:
print("as raízes da equação são", x2, "e", x1) |
1afdc188831f78066d0d3edfa4bfacac75b61fc5 | ayush9304/Tic-Tac-Toe | /tictactoe/util.py | 3,965 | 3.921875 | 4 | """
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
x,o = 0,0
for row in board:
x += row.count(X)
o += row.count(O)
if x>o:
return O
else:
return X
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
moves = set()
for row in range(len(board)):
for col in range(len(board[0])):
if board[row][col] == None:
moves.add((row,col))
return moves
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
if action[0] not in [0,1,2] and action[1] not in [0,1,2]:
raise Exception('Wrond index for action')
if board[action[0]][action[1]] != None:
raise Exception('Index already filled for action')
turn = player(board)
state = copy.deepcopy(board)
state[action[0]][action[1]] = turn
return state
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
#Horizontal Check
for row in board:
if row[0]==row[1] and row[1]==row[2] and row[0] != None:
return row[0]
#Vertical Check
for i in range(len(board[0])):
if board[0][i]==board[1][i] and board[1][i]==board[2][i] and board[0][i] != None:
return board[0][i]
#Diagonal Check
if board[0][0]==board[1][1] and board[1][1]==board[2][2] and board[0][0] != None:
return board[0][0]
if board[0][2]==board[1][1] and board[1][1]==board[2][0] and board[0][2] != None:
return board[0][2]
return None
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if (winner(board) != None):
return True
for row in board:
if row.count(None) > 0:
return False
return True
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
val = winner(board)
if val==X:
return 1
elif val==O:
return -1
else:
return 0
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
if terminal(board):
return None
turn = player(board)
last_action = None
if turn==X:
last_v = -math.inf
for action in actions(board):
v=min_value(result(board,action))
if last_v < v:
last_v = v
last_action = action
return last_action
elif turn==O:
last_v = math.inf
for action in actions(board):
v=max_value(result(board,action))
if last_v > v:
last_v = v
last_action = action
return last_action
def max_value(board):
"""
Returns the maximum utility of the current board.
"""
v = -math.inf
if terminal(board):
return utility(board)
for action in actions(board):
v = max(v, min_value(result(board,action)))
return v
def min_value(board):
"""
Returns the minimum utility of the current board.
"""
v = math.inf
if terminal(board):
return utility(board)
for action in actions(board):
v = min(v, max_value(result(board,action)))
return v
def get_matrix(matrix):
matrix2 = []
row = []
for index,data in enumerate(matrix):
if index == 3 or index == 6:
matrix2.append(row)
row = []
if data == '0':
row.append(None)
else:
row.append(data)
matrix2.append(row)
return matrix2 |
6d7a6933205fd6e7b476d4e9bf41f5319a7a2d88 | han-tun/Resources | /Python/Ml/rmse.py | 359 | 3.5625 | 4 | """
------------------------------------
Creation date : 09/02/2018 (fr)
Last update : 09/02/2018
Author(s) : Nicolas DUPONT
Tested on Python 3.6
------------------------------------
"""
def rmse(y_test,y_pred):
#import numpy as np
#rmse = math.sqrt(np.mean((y_pred - y_test) ** 2))
rmse = np.sqrt(np.mean((y_pred - y_test) ** 2))
return rmse
|
5840b04f42252c7dd4fc4c893e685b1a54517ad3 | ederortega/python_t01 | /flow/cp03_flow_05.py | 1,294 | 4.0625 | 4 | # Apply basic operations (+, -, *, /) with for loop
operations = ['a', 'm', 'x', 'd', 5]
operand_1 = 11
operand_2 = 3
result = 0
for op in operations:
if op == 'a':
result = operand_1 + operand_2
print('{} + {} = {}'.format(operand_1, operand_2, result))
elif op == 'm':
result = operand_1 - operand_2
print('{} - {} = {}'.format(operand_1, operand_2, result))
elif op == 'x':
result = operand_1 * operand_2
print('{} * {} = {}'.format(operand_1, operand_2, result))
elif op == 'd':
result = operand_1 / operand_2
print('{} / {} = {}'.format(operand_1, operand_2, result))
# operations and values
operations = [('a', 5, 3), ('m', 8, 6), ('x', 12, 5), ('d', 18, 3)]
for op, operand_1, operand_2 in operations:
if op == 'a':
result = operand_1 + operand_2
print('{} + {} = {}'.format(operand_1, operand_2, result))
elif op == 'm':
result = operand_1 - operand_2
print('{} - {} = {}'.format(operand_1, operand_2, result))
elif op == 'x':
result = operand_1 * operand_2
print('{} * {} = {}'.format(operand_1, operand_2, result))
elif op == 'd':
result = operand_1 / operand_2
print('{} / {} = {}'.format(operand_1, operand_2, result))
|
0ef933f8893f6feacfb131f41b5f03c3db0341fe | viert/Pyrr | /pyrr/plane.py | 3,396 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""Provide functions for the creation and manipulation of Planes.
Planes are represented using a numpy.array of shape (4,).
The values represent the plane equation using the values A,B,C,D.
The first three values are the normal vector.
The fourth value is the distance of the plane from the origin, down the normal.
.. seealso: http://en.wikipedia.org/wiki/Plane_(geometry)
.. seealso: http://mathworld.wolfram.com/Plane.html
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy
import numpy.linalg
from pyrr import vector
def create_identity():
"""Creates a plane that runs along the X,Y plane.
It crosses the origin with a normal of 0,0,1 (+Z).
:rtype: numpy.array
:return: A plane that runs along the X,Y plane.
"""
return numpy.array( [ 0.0, 0.0, 1.0, 0.0] )
def create_from_points( vector1, vector2, vector3 ):
"""Create a plane from 3 co-planar vectors.
The vectors must all lie on the same
plane or an exception will be thrown.
The vectors must not all be in a single line or
the plane is undefined.
The order the vertices are passed in will determine the
normal of the plane.
:param numpy.array vector1: a vector that lies on the desired plane.
:param numpy.array vector2: a vector that lies on the desired plane.
:param numpy.array vector3: a vector that lies on the desired plane.
:raise ValueError: raised if the vectors are co-incident (in a single line).
:rtype: numpy.array
:return: A plane that contains the 3 specified vectors.
"""
# make the vectors relative to vector2
relV1 = vector1 - vector2
relV2 = vector3 - vector2
# cross our relative vectors
normal = numpy.cross( relV1, relV2 )
if numpy.count_nonzero( normal ) == 0:
raise ValueError( "Vectors are co-incident" )
# create our plane
return create_from_position(
position = vector2,
normal = normal
)
def create_from_position( position, normal ):
"""Creates a plane at position with the normal being above the plane
and up being the rotation of the plane.
:param numpy.array position: The position of the plane.
:param numpy.array normal: The normal of the plane. Will be normalised
during construction.
:rtype: numpy.array
:return: A plane that crosses the specified position with the specified
normal.
"""
# -d = a * px + b * py + c * pz
n = vector.normalise( normal )
d = -numpy.sum( n * position )
return numpy.array( [ n[ 0 ], n[ 1 ], n[ 2 ], d ] )
def invert_normal( plane ):
"""Flips the normal of the plane.
The plane is **not** changed in place.
:rtype: numpy.array
:return: The plane with the normal inverted.
"""
# flip the normal, and the distance
return -plane
def position( plane ):
"""Extracts the position vector from a plane.
This will be a vector co-incident with the plane's normal.
:param numpy.array plane: The plane.
:rtype: numpy.array
:return: A valid position that lies on the plane.
"""
return plane[ :3 ] * plane[ 3 ]
def normal( plane ):
"""Extracts the normal vector from a plane.
:param numpy.array plane: The plane.
:rtype: numpy.array
:return: The normal vector of the plane.
"""
return plane[ :3 ]
|
6ef4c868f3132a82b29fa5e61536c02eefa5a7b6 | annamalo/py4e | /Exercises/ex_10_01/ex_10_02.py | 631 | 3.65625 | 4 | fname = input('Enter a file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
time = []
counts = {}
# break each line into a list of words
for line in fhand:
words = line.split()
if len(words) < 4 or words[0] != 'From' : continue
# add all timestamps to a list
time = words[5]
# find the hour position and ad whats after the @ sign to a domain variable
hour = time[:2]
# count each hour using counts dictionary
counts[hour] = counts.get(hour,0)+1
# print a sequence sorted by key order by using a for loop
for k, v in sorted(counts.items()):
print(k, v)
|
bdf708d2f209510667bb81bccf708d4e12dc4705 | ttomchy/LeetCodeInAction | /others/q1480_running_sum_of_1d_array/solution.py | 416 | 3.5 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
FileName: solution.py
Description:
Author: Barry Chow
Date: 2020/10/25 3:29 PM
Version: 0.1
"""
class Solution(object):
def runningSum(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
arr = [nums[0]]+[0]*(len(nums)-1)
for j in range(1,len(nums)):
arr[j] = nums[j] +arr[j-1]
return arr |
4afdbc0e3906174a830bd23b996541e9d7dcfe7a | AmorphousAnemone/py4e | /exercise7/ex7.2/ex7.2.py | 1,200 | 4.125 | 4 | # Write a program to prompt fr a file name, and the read through the file and look for lines of the form:
# X-DSPAM-Confidence: 0.8475
#
# When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart the line
# to extract the floating-point number on the line. Count these lines and then compute
# the total of the spam confidence values from these lines. When you reach the end of the file,
# print out the average spam confidence
# prompt
#fname = input('Enter the file name: ')
fname = input('Enter the file name: ')
#easter egg
if fname == 'na na boo boo':
print('NA NA BOO BOO TO YOU - You have been punk\'d!')
quit()
try:
xfile = open(fname)
except:
print('File cannot be opened: ' + fname)
quit()
# count = 0
# fvalue = 0
# for line in xfile:
# if 'X-DSPAM-Confidence:' in line:
# # Adds the float value found after the colon to the previous values
# fvalue = fvalue + float(line[line.find(':')+1:].strip())
# count = count + 1
# print(fvalue / count)
numlist = list()
for line in xfile:
if 'X-DSPAM-Confidence:' in line:
numlist.append(float(line[line.find(':')+1:].strip()))
print(sum(numlist) / len(numlist)) |
2191c3c4e7f6a8d927c06cc53099fd4f1f32e73a | SobuleacCatalina/Instructiunea-IF | /problema_15_IF.py | 445 | 3.734375 | 4 | """
Elevii clasei a V-a se repartizează în clase câte 25 în ordinea mediilor clasei a IV-a. Radu este pe locul x în ordinea mediilor. În ce clasa va fi repartizat (A, B, C, D sau E)?.
Exemplu : date de intrare : x=73 date de ieşire : C
"""
x=int(input("Radu e pe locul"))
if x//25==0:
print("A")
elif x//25==1:
print("B")
elif x//25==2:
print("C")
elif x//25==3:
print("D")
else:
print("E") |
a3b05f7aedf215b6c60a0638c9138d508b8b1986 | kh4r00n/Aprendizado-de-Python | /ex031.py | 262 | 3.546875 | 4 | passagem = float(input('Qual a distância em km da sua viagem?'))
if passagem <=200:
p1 = passagem * 0.50
print('A sua passagem custa {:.2f} R$'.format(p1))
else:
p2 = passagem * 0.45
print('A sua passagem custa {:.2f} R$'.format(p2))
|
57cd6fdcd6482b4ac8d791fb924a47a5952cb69a | DavidHulsman/euler | /problems/problem9.py | 287 | 3.625 | 4 | # Special Pythagorean triplet
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#
# a**2 + b**2 = c**2
#
# For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
|
e6d667d6f8318fa6388359861110932740e38e0c | nanicode/CS-251-Software-systems- | /lab 04 inlab/taskB_inlab/task3.py | 678 | 3.671875 | 4 | #!/usr/bin/env python
def transposeit(matrix,m,n):
new = [[None for a in range(m)] for b in range(n)]
for i in range(m):
for j in range(n):
new[j][i] = matrix[i][j]
return new
with open('matrix.txt','r') as f:
mn = f.readline()
mn = mn.split()
m = int(mn[0])
n = int(mn[1])
matrix = [[None for a in range(n)] for b in range(m)]
p = f.readlines()
for j in range(m):
lin = p[j].split( )
for k in range(len(lin)):
matrix[j][k] = lin[k]
matrix = transposeit(matrix,m,n)
file = open('transpose.txt','w')
file.write('{0} {1}\n'.format(n,m))
for i in range(n):
for j in range(m):
file.write(str(matrix[i][j])+" ")
file.write('\n')
file.close()
|
56364a848c1d4d9f4cd973ec06c768e41c03235c | lukecalton/Pythonforeverybody | /Assignment15_Week5.py | 806 | 3.90625 | 4 | # Import relevant libraries. ET to arrange xml data and urllib to prevent bad data extraction accessing web data
import xml.etree.ElementTree as ET
import urllib.request, urllib.parse, urllib.error
# Ask for user input and protect against bad user input
try:
xml_data = input("Please enter a URL: ")
except:
print("Sorry, that didn't work, Luke. ")
# Read in the xml data into a variable "data" using urllib
data = urllib.request.urlopen(xml_data).read()
#convert data into an element tree using fromstring
tree = ET.fromstring(data)
# Find all the comments/comment/counts tags and store in new "lst" variable
lst = tree.findall('comments/comment/count')
# Loop through list and add up the numbers
total = 0
for count in lst:
total += int(count.text)
# Print the sum
print("Total: ", total)
|
fdbc4eaa03de445821d75f66eb07b379c8f72fc6 | dotalf/reboot | /scripts/tuple_sort.py | 1,703 | 3.59375 | 4 | # encoding:utf-8
# list[(1,4), (5,1), (2,3)],根据每个元组的中的较大值进行排序
# 期待结果 [(2,3), (1,4), (5.1)]
# 要求用sorted和lambda完成
# 级别1: 用Lambda和max
# 级别2:用lambda不用max
# 提示: True * 4 == 4 False *2 == 0
list1 = [(1, 4), (5, 1), (2, 3)]
# method 1
def sort_array(array):
for i in range(0, len(array)-1):
for j in range(0,len(array)-1-i):
if max(array[j]) > max(array[j+1]):
array[j],array[j+1] = array[j+1], array[j]
return array
# print sort_array(list1)
# method 2
def sort_array(array,getmax):
for i in range(0, len(array)-1):
for j in range(0,len(array)-1-i):
if getmax(array[j]) > getmax(array[j+1]):
array[j],array[j+1] = array[j+1], array[j]
return array
# print sort_array(list1,lambda x : max(x))
# method 3
list1 = [(1, 4), (5, 1), (2, 3)]
list2 = [{'name' : 'lf11'}, {'name' : 'lf1'}, {'name' : 'lf3'} ]
def cmp(x, y):
if x > y:
return True
else:
return False
def sort_array(array,getmax,cpm):
array = array[:]
for i in range(0, len(array)-1):
for j in range(0,len(array)-1-i):
if cpm(getmax(array[j]), getmax(array[j+1])):
array[j],array[j+1] = array[j+1], array[j]
return array
list2 = [{'name' : 'if11'}, {'name' : 'of1'}, {'name' : 'lf3'} ]
list2.sort(key=lambda x : x.get('nname'))
print __name__
if __name__ == '__main__':
print sort_array(list1,lambda x : max(x),cmp)
print sort_array(list2,lambda x : x['name'],cmp)
print list2
|
517b52499c1c51e3024389575cd5abab22aad8df | mindis/Practice | /Python/NetworkX/practice1.py | 543 | 3.890625 | 4 | import networkx as nx
# Practice1: Read and write graphs
if __name__ == '__main__':
# Create a graph
G = nx.Graph() # Undirected Graph
directedG = nx.DiGraph() # Directed Graph
# Add nodes
G.add_node(1)
G.add_nodes_from([2, 3])
# Add edges between nodes
G.add_edge(1, 2)
e = (2, 3)
G.add_edge(*e) # Unpack tuple
# Print properties of graph
print(G.number_of_nodes())
print(G.number_of_edges())
nodes = list(G.nodes())
print(nodes)
edges = list(G.edges())
print(edges)
|
c005675e6f20b8e9d32de0a68a21f65d64d10c78 | MuhammadMigo/word-count-project | /main.py | 254 | 3.53125 | 4 | print("Migo")
# x= input("What is your age ")
# print(x)
y=(5/2)
z=(5//2)
# print(type(x))
print((y))
print((z))
print(int("bcdf",16))
print(hex(48351))
iq=int(5)
print(iq)
PI = 3.14
fn=input("INPUT F NAME ")
ln=input("INPUT L NAME ")
print(fn+" "+ln)
|
c81a728929b6cf22e027fa4a2eb8bf3bcf2f9e51 | HaganShane/CMPSC122 | /Midterm - Coding.py | 3,369 | 4.59375 | 5 | #####################################################
# CMPSC 122 - Intermediate Programming
# Midterm Exam - Coding
#
# This part of the Midterm is worth 50 total points. 5 Points are
# for the code runs error free and the remaining points are detailed below.
#
# Use this code to solve the problems list below. Each problem will
# have a # and description of what I want you to do.
#
# Program Description:
# This program will feature a class dealing with house information.
# The user will input data and the program will output the details after.
#
# Student Name: Shane Hagan
#
#####################################################
#####################################################
# Problem #1: Create a Class that will store the
# address of the house and the year built. Call the
# Class HouseInfo.
# The to_string function is already created. See that
# for the names of the attributes
# (10 Points)
#####################################################
class HouseInfo:
'''Will store the adress of the house and year built'''
def __init__(self, address, year):
self.address = address
self.year = year
def to_string(self):
return "The house at {0} was built in {1}.".format(self.address, self.year)
class House:
''' The rectangle represents the house '''
def __init__(self, houseInfo, width=0, length=0):
self.__width = width
self.__length = length
self.__houseInfo = houseInfo
def getWidth(self):
return self.__width
def setWidth(self, w):
self.__width = w
def getLength(self):
return self.__length
def setLength(self, l):
self.__length = l
#####################################################
# Problem #2: Create a function to set and get the
# houseInfo Object. The address and year should be
# passed into the set function. Both values (address
# and year) are required fields.
# (10 Points)
#####################################################
def getInfo(self):
return self.__houseInfo
def setInfo(self, address, year):
self.address = address
self.year = year
#####################################################
# Main Program
#####################################################
houseWidth = float(input("In feet, how wide is your house: "))
houseLength = float(input("In feet, how long is your house: "))
address = input("What is the address for your house: ")
year = input("What year was the house built: ")
#####################################################
# Problem #3: Create the HouseInfo and House objects
# based on the data entered above. Name them houseInfo
# and house, respectfully.
# (10 Points per Object)
#####################################################
HouseInfo = HouseInfo(address, year)
house = House(HouseInfo, houseWidth, houseLength)
#####################################################
# Problem #4: Use the HouseInfo's to_string to output
# the HouseInfo data.
# (5 Points)
#####################################################
print(HouseInfo.to_string())
print("The house is {0} x {1}".format(house.getWidth(), house.getLength()))
print("That is a Sq Ft of {0}.".format(house.getWidth() * house.getLength()))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.