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 |
|---|---|---|---|---|---|---|
d85efdbf7e4b40051bf2026e43254286c014e3f8 | SueAli/cs-problems | /LeetCode/Intersection_of_Two_Arrays.py | 743 | 3.640625 | 4 |
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
Let's say len(nums1) = n & len(nums2)=m
Total time complexity = O(min(n,m)) + O(n * logn) + O(m * log m)
Auxilary space compexity = O(1)
"""
inter= set()
i = 0
j = 0
nums1.sort()
nums2.sort()
while j < len(nums2) and i < len(nums1):
if nums1[i] == nums2[j]:
inter.add(nums2[j])
j += 1
i += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return list(inter) |
2ec167e6cf4f0ae7c47029c30fa9d4028ad13b3e | J21TK/GuessGame | /GuessGame_3.py | 2,738 | 3.875 | 4 | #coding: utf-8
import random
class Player:
def __init__(self, test_range):
self.low = 1
self.high = test_range
self.history = []
def interpreter(self, func_name):
if func_name == 1:
return self.random_guess
elif func_name == 2:
return self.half_guess
elif func_name == 3:
return self.designed_guess_randomfirst
def renew(self, tpl):
if tpl[0] == "low":
self.low = tpl[1]
elif tpl[0] == "high":
self.high = tpl[1]
def random_guess(self):
tmp = random.randint(self.low + 1, self.high - 1)
self.history.append(tmp)
return tmp
def half_guess(self):
tmp = (self.low + self.high) // 2
while tmp in self.history:
tmp += 1
self.history.append(tmp)
return tmp
def designed_guess_randomfirst(self):
if len(self.history) == 0:
return self.random_guess()
else:
return self.half_guess()
print("What is your name?")
name = input("> ")
maxi = 100
print("Which of the rules do you want this program to use?\n(Enter the number)")
print(" 1. Random guess")
print(" 2. Middle suggestion")
print(" 3. First random, then middle suggestion")
while True:
try:
que = int(input("> "))
break
except:
print("Hey {}, check your input!".format(name))
print("Hi{}, imagine a number between 1 to {}. I will find your number within 6 guess".format(name, maxi))
counter = 6
total = counter
pc = Player(maxi)
func = pc.interpreter(que)
while counter != 0:
try:
if counter == 1:
print("This is the last round.")
else:
print("I have another {} chance(s)".format(counter - 1))
pc_guess = func()
print("Is it {}?".format(pc_guess))
print("If yes, enter 'yes', if this is smaller than yours, enter 'low', if larger, enter 'high'.")
while True:
response = input("> ")
if response not in ["yes", "low", "high"]:
print("Hey {}, check your input!".format(name))
else:
break
if response == "yes":
print("Whoopee! Let's enjoy again!")
break
else:
tpl = (response, pc_guess)
pc.renew(tpl)
counter -= 1
print("")
except:
print("Hey {}, check your input!".format(name))
if counter == 0:
print("What a bummer! Could you tell me your number?")
ans = int(input("> "))
if ans < pc.low or ans > pc.high or ans in pc.history:
print("You are lying to me!")
else:
print("You win. Give me one more chance!")
|
75acbd59c9dd91a23a6501c2bf21cd925e3ab93f | waterwheel31/datastructure_algoithm_1 | /Task2.py | 1,160 | 3.984375 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""
tel_number = ""
max_time = 0
total_time = {}
for call in calls:
time = int(call[3])
phone1 = call[0]
phone2 = call[1]
try: total_time[phone1] += time
except: total_time[phone1] = time
try: total_time[phone2] += time
except: total_time[phone2] = time
if total_time[phone1] > max_time:
max_time = total_time[phone1]
tel_number = phone1
if total_time[phone2] > max_time:
max_time = total_time[phone2]
tel_number = phone2
print("{}spent the longest time,{} seconds, on the phone during".format(tel_number, max_time) )
|
1832690e4d251f909954ec86aa3cdef3bbfc6424 | Rapt0r399/HackerRank | /Python/Introduction/Print Function.py | 279 | 3.625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
x = raw_input()
x = int(x)
i = 1
p = 0
while (i<=x) :
if i< 10 :
p = p*10 + i
elif i>=10 and i<100 :
p = p*100 +i
elif i>=100 and i<10000 :
p = p*1000 +i
i = i+1
print p |
0a829bccb2463a108e2d99be621c41dca24c8268 | jaylyerly/python_demo | /some_builtins.py | 1,888 | 4.28125 | 4 | #!/usr/bin/env python
# Built-in python functions
# Most import -- help() and dir()
# help(foo) -- return the docstring for foo. Most built-ins are documented
# this way.
help(open) # display the docs for 'open' (used to open files)
help("foo".lstrip) # display the docs for the string method lstrip
# dir(foo) -- show the attributes of foo
# dir() -- the current namespace
dir("foo") # display all the methods and attributes available on
# the string "foo"
# this is invaluable as you play with new objects and interfaces
myList = ["a", "b", "c"]
# other useful builtin functions
enumerate(myList) # returns a list of tuples which contain an index and an item
# from the list
for index, item in enumerate(myList):
print "item", item, "at index", index
# print out
# item a at index 0
# item b at index 1
# item c at index 2
# filter(func, sequence) -- takes each element of a sequence and passes it to
# 'func'. If 'func' returns true, that element is put in the returned list.
# If 'func' returns false, it's dropped
def checkDigit(x):
return x.isdigit()
print filter(checkDigit, "abc123") # prints out "123"
# map(func, sequence) -- takes each element of the sequence and passes it to
# 'func'. The return values of 'func' are passed back in a list.
def makeUpperCase(x):
return x.upper()
print map(makeUpperCase, "abc123") # prints out "ABC123"
# Warning -- contrived example -- .upper() works on whole strings
# reduce(func, sequence[, initial]) -- takes the sequence and uses func to reduce
# it to a single value. For example
#
def addTwo(x,y):
return x+y
print reduce( addTwo, [1,2,3,4,5]) # would execute ((((1+2)+3)+4)+5)
# and print out 15
# the optional 'initial' paramater primes the sequence
|
bbb4755a86a912ca506911d40454da7d63943c47 | alane001/Comp-Methods | /Week2/Ex1.py | 1,555 | 3.859375 | 4 | import numpy as np
#This is for a general integration, the function must be calculated before putting it through this subroutine. These functions take in two arrays, on as the x value and one as the y value from the input of x into the y function
#Trapezoidal rule
def trapez(x, y):
# Trapezoid equation: I = h [0.5*f(a) + 0.5*f(b) + (sum of all f(a+kh))]
# I is integral, this is first part of integral, 1/2f(a) + 1/2f(b)
#f(a) and f(b) correspond to the first(a) and last(b) of the y array
#y.shape0 -1 gives the last value in the y array
# h is the distance between the x array values
h = (x[1] - x[0])
#This just sums up the values of array y from second value (1) to final value
S = np.sum(y[1:y.shape[0]-1])
#Full integral
I = (0.5*y[0] + 0.5*y[y.shape[0]-1] + S)
# Last part to to multiply by outside h
I = h * I
return I
#The simpson's rule
def simpson(x, y):
# The simpson equation: I = (1/3)*h [f(a) + f(b) + (4 * (sum of odd f(a+kh))) + (2 * (sum of even f(a+kh)))]
#Slice width, difference between x arrays
h = x[1] - x[0]
# 1st part of equation, 1st and last of y array
I1 = y[0] + y[y.shape[0]-1]
#Sum up odd numbers, 1 start, up to N, by values of 2 (1,3,5) etc
#keeps I1 separate so can multiply by 4
# N = y.shape[0]-1 for book example
I2 = 0.0
for k in range(1, y.shape[0]-1, 2):
I2+= y[k]
I2 = I2 * 4
#Sum up even numbers
I3 = 0.0
for j in range(2, y.shape[0]-1, 2):
I3 += y[j]
I3 = I3 * 2
#makes full integral
I = I1 + I2 + I3
# finishes up equation
I = (I * h) / 3.
return I
|
2e6981efe05195bf6357a09c1cc4d5fe387429e1 | Bertram-Liu/Note | /NOTE/15_Data_analysis/day04/demo06_aaa.py | 302 | 3.734375 | 4 | """
demo06_aaa.py 轴向汇总
"""
import numpy as np
data = np.arange(1, 13).reshape(3, 4)
print(data)
# 轴向汇总
def func(ary):
return np.max(ary), np.mean(ary), \
np.min(ary)
r = np.apply_along_axis(func, 1, data)
print(r)
r = np.apply_along_axis(func, 0, data)
print(r)
|
17e558516903ce093450d17f34ed4b15e35791af | negibokken/sandbox | /leetcode/2085_count_common_words_with_one_occurrence/main.py | 734 | 3.515625 | 4 | #!/usr/bin/python3
from typing import List
import json
from bplib.butil import TreeNode, arr2TreeNode, btreeconnect
class Solution:
def countWords(self, words1: List[str], words2: List[str]) -> int:
mp = {}
for w in words1:
if w not in mp:
mp[w] = 0
mp[w] += 1
mp2 = {}
for w in words2:
if w not in mp2:
mp2[w] = 0
mp2[w] += 1
ans = 0
for k, v in mp2.items():
if v != 1:
continue
if k in mp and mp[k] == 1:
ans += 1
return ans
arr1 = json.loads(input())
arr2 = json.loads(input())
sol = Solution()
print(sol.countWords(arr1, arr2))
|
57e46a78bc76176251772eb087f691be1ff8bf1b | LauraValentinaHernandez/Taller-estructuras-de-control-selectivo | /Ejercicio9.py | 1,941 | 4.3125 | 4 | """
En una tienda efectúan un descuento a los clientes dependiendo del monto de la compra.
El descuento se efectúa con base en el siguiente criterio:
a. Si el monto es inferior a $50.000 COP, no hay descuento.
b. Si está comprendido entre $50.000 COP y $100.000 COP inclusive,
se hace un descuento del 5%.
c. Si está comprendido entre $100.000 COP y $700.000 COP inclusive,
se hace un descuento del 11%.
d. Si está comprendido entre $700.000 COP y $1.500.000 COP inclusive,
el descuento es del 18.
e. Si el monto es mayor a $1500000, hay un 25% de descuento.
Calcule y muestre el nombre del cliente, el monto de la compra, monto a pagar
y descuento recibido.
"""
N=input("Digite nombre del cliente: ")
C=int(input("Digite total de la compra: "))
if(C>0 and C<50000):
print("Nombre del cliente: "+ str(N))
print("Total de la compra: $ {:.0f}".format(C))
print("No hay descuento")
print("Monto a Pagar: $ {:.0f}".format(C))
elif(C>=50000 and C<100000):
D=(C*0.05)
Totalpagar=(C-D)
print("Nombre del cliente: "+ str(N))
print("Monto de la compra: $ {:.0f}".format(C))
print("Descuento Recibido: $ {:.0f}".format(D))
print("Monto a Pagar: $ {:.0f}".format(Totalpagar))
elif(C>=100000 and C<700000):
D=(C*0.11)
Totalpagar=(C-D)
print("Nombre del cliente: "+ str(N))
print("Monto de la compra: $ {:.0f}".format(C))
print("Descuento Recibido: $ {:.0f}".format(D))
print("Monto a Pagar: $ {:.0f}".format(Totalpagar))
elif(C>=700000 and C<1500000):
D=(C*0.18)
Totalpagar=(C-D)
print("Nombre del cliente: "+ str(N))
print("Monto de la compra: $ {:.0f}".format(C))
print("Descuento Recibido: $ {:.0f}".format(D))
print("Monto a Pagar: $ {:.0f}".format(Totalpagar))
elif(C>=1500000):
D=(C*0.25)
Totalpagar=(C-D)
print("Nombre del cliente: "+ str(N))
print("Monto de la compra: $ {:.0f}".format(C))
print("Descuento Recibido: $ {:.0f}".format(D))
print("Monto a Pagar: $ {:.0f}".format(Totalpagar))
else:
print("ERROR") |
5a60c70ad95dc80dee999928ea3b5c12206fbbef | dbomard/BingMap | /TileSystem.py | 5,345 | 3.625 | 4 | """
Adaptation en Python d'après fichier microsoft initialement écrit en C# par Joe Schwartz
30/05/2020
David Bomard
"""
from math import cos, pi, sin, log, atan, exp
EARTH_RADIUS = 6378137
MIN_LATITUDE = -85.05112878
MAX_LATITUDE = 85.05112878
MIN_LONGITUDE = -180
MAX_LONGITUDE = 180
def Clip(n, min_value, max_value):
"""
clips a number to the specified minimum and maximum values
:param n: the value to clip
:param min_value: Minimum allowable value
:param max_value: Maximum allowable value
:return: The clipped value
"""
return min(max(n, min_value), max_value)
def MapSize(level_of_detail):
"""
Determines the map width and height (in pixels) at a specified level of detail.
:param level_of_detail:Level of detail, from 1 (lowest detail) to 23 (highest detail)
:return: The map width and height in pixels
"""
return 256 << level_of_detail
def GroundResolution(latitude, level_of_detail):
"""
Determines the ground resolution (in meters per pixel) at a specified
latitude and level of detail
:param latitude: Latitude (in degrees) at which to measure the
ground resolution
:param level_of_detail: Level of detail, from 1 (lowest detail)
to 23 (highest detail)
:return: The ground resolution, in meters per pixel
"""
latitude = Clip(latitude, MIN_LATITUDE, MAX_LATITUDE)
return cos(latitude * pi / 180) * 2 * pi * EARTH_RADIUS / MapSize(level_of_detail)
def LatLongToPixelXY(latitude, longitude, level_of_detail):
"""
Converts a point from latitude/longitude WGS-84 coordinates (in degrees)
into pixel XY coordinates at a specified level of detail
:param latitude: Latitude of the point, in degrees
:param longitude: Longitude of the point, in degrees
:param level_of_detail:Level of detail, from 1 (lowest detail)
to 23 (highest detail)
:return: a tuple (the X coordinate in pixels, the Y coordinate in pixels)
"""
latitude = Clip(latitude, MIN_LATITUDE, MAX_LATITUDE)
longitude = Clip(longitude, MIN_LONGITUDE, MAX_LONGITUDE)
x = (longitude + 180) / 360
sin_latitude = sin(latitude * pi / 180)
y = 0.5 - log((1 + sin_latitude) / (1 - sin_latitude)) / (4 * pi)
map_size = MapSize(level_of_detail)
pixel_x = int(Clip(x * map_size + 0.5, 0, map_size - 1))
pixel_y = int(Clip(y * map_size + 0.5, 0, map_size - 1))
return pixel_x, pixel_y
def PixelXYToLatLong(pixel_x, pixel_y, level_of_detail):
"""
Converts a pixel from pixel XY coordinates at a specified level of detail
into latitude/longitude WGS-84 coordinates (in degrees
:param pixel_x: X coordinate of the point, in pixels
:param pixel_y: Y coordinates of the point, in pixels
:param level_of_detail: Level of detail, from 1 (lowest detail)
to 23 (highest detail)
:return: a tuple (latitude in degrees, longitude in degrees)
"""
map_size = MapSize(level_of_detail)
x = (Clip(pixel_x, 0, map_size - 1) / map_size) - 0.5
y = 0.5 - (Clip(pixel_y, 0, map_size - 1) / map_size)
latitude = 90 - 360 * atan(exp(-y * 2 * pi)) / pi
longitude = 360 * x
return latitude, longitude
def PixelXYToTileXY(pixel_x, pixel_y):
"""
Converts pixel XY coordinates into tile XY coordinates of the tile containing
the specified pixel
:param pixel_x: Pixel X coordinate
:param pixel_y: Pixel X coordinate
:return: tuple (tile x coordinate, tile y coordinate
"""
tile_x = int(pixel_x / 256)
tile_y = int(pixel_y / 256)
return tile_x, tile_y
def TileXYToPixelXY(tile_x, tile_y):
"""
Converts tile XY coordinates into pixel XY coordinates of the upper-left pixel
of the specified tile
:param tile_x: Tile X coordinate
:param tile_y: Tile Y coordinate
:return: tuple (pixel x coordinate, pixel y coordinate)
"""
pixel_x = tile_x * 256
pixel_y = tile_y * 256
return pixel_x, pixel_y
def TileXYToQuadKey(tile_x, tile_y, level_of_detail):
"""
Converts tile XY coordinates into a QuadKey at a specified level of detail
:param tile_x: Tile X coordinate
:param tile_y: Tile Y coordinate
:param level_of_detail: Level of detail, from 1 (lowest detail)
to 23 (highest detail)
:return: A string containing the QuadKey
"""
quadkey = ''
for i in range(level_of_detail, 0, -1):
digit = 0
mask = 1 << (i - 1)
if (tile_x & mask) != 0:
digit += 1
if (tile_y & mask) != 0:
digit += 2
quadkey = quadkey + str(digit)
return quadkey
def QuadKeyToTileXY(quad_key):
"""
Converts a QuadKey into tile XY coordinates
:param quad_key: QuadKey of the tile
:return: tuple (tile X coordinate, tile Y coordinate, level of detail)
"""
tile_x = 0
tile_y = 0
level_of_detail = len(quad_key)
for i in range(level_of_detail, 0, -1):
mask = 1 << (i - 1)
switcher = quad_key[level_of_detail - i]
if switcher == '0':
break
elif switcher == '1':
tile_x |= mask
elif switcher == '2':
tile_y |= mask
elif switcher == '3':
tile_x |= mask
tile_y |= mask
else:
raise ValueError('Invalid Quadkey digit sequence')
return tile_x, tile_y, level_of_detail
|
4e754c0af31bf67635c80c77ba7dca756660e98e | kdockman96/CS0008-f2016 | /Ch6-Ex/ch6-ex5.py | 384 | 3.71875 | 4 | # Define the main function
def main():
# Initiate an accumulator variable
total = 0
# Open the numbers.txt file
infile = open('numbers.txt', 'r')
# Read the numbers from the file
for line in infile:
amount = int(line)
total += amount
# Close the file
infile.close()
# Print the total
print(total)
# Call the main function
main() |
e58fb669809b04bbdb729c07306e2e9fdf439d4b | Helen-Sk-2020/Loan_Calculator | /Topics/Elif statement/The farm/main.py | 716 | 3.796875 | 4 | chicken = 23
goat = 678
pig = 1296
cow = 3848
sheep = 6769
count = 1
money = int(input())
if money < chicken:
print('None')
elif goat > money >= chicken:
n = money // chicken
if n == count:
print(f'{n} chicken')
else:
print(f'{n} chickens')
elif pig > money >= goat:
n = money // goat
if n == count:
print(f'{n} goat')
else:
print(f'{n} goats')
elif cow > money >= pig:
n = money // pig
if n == count:
print(f'{n} pig')
else:
print(f'{n} pigs')
elif sheep > money >= cow:
n = money // cow
if n == count:
print(f'{n} cow')
else:
print(f'{n} cows')
else:
n = money // sheep
print(f'{n} sheep')
|
413fa2dc4777dbfc4c4ae27ba0ecf39bb1546937 | ydwng/UCI_MATH_10 | /sections/sec_05/Vector.py | 1,014 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
class VectorV5:
'''define the vector''' # this is the document string
dim = 2 # this is the attribute
def __init__(self, x=0.0, y=0.0): # any method in Class requires the first parameter to be self!
'''initialize the vector by providing x and y coordinate'''
self.x = x
self.y = y
def norm(self):
'''calculate the norm of vector'''
return math.sqrt(self.x**2+self.y**2)
def __add__(self, other):
'''calculate the vector sum of two vectors'''
return VectorV5(self.x + other.x, self.y + other.y)
def __repr__(self): #special method of string representation
'''display the coordinates of the vector'''
return 'Vector(%r, %r)' % (self.x, self.y)
def __mul__(self, scalar):
'''calculate the scalar product'''
return VectorV5(self.x * scalar, self.y * scalar)
string = 'Python'
def print_hello():
print("Hello")
|
450e6a25d0f8f8d6f8e6d32d1796b397e3a6bd0f | rpm1995/LeetCode | /1057_Campus_Bikes.py | 1,012 | 3.609375 | 4 | import heapq
class Solution:
def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> List[int]:
distances = []
for worker, (work_x, work_y) in enumerate(workers):
distance = []
for bike, (bike_x, bike_y) in enumerate(bikes):
manhattan = abs(work_x - bike_x) + abs(work_y - bike_y)
distance.append([manhattan, worker, bike])
distance.sort(reverse=True)
distances.append(distance)
queue = []
seen = set()
ans = [-1 for _ in range(len(workers))]
for worker in range(len(workers)):
queue.append(distances[worker].pop())
heapq.heapify(queue)
while len(seen) < len(workers):
_, worker, bike = heapq.heappop(queue)
if bike not in seen:
seen.add(bike)
ans[worker] = bike
else:
heapq.heappush(queue, distances[worker].pop())
return ans
|
98712493db3f1057a20001b30678b4d2b2070495 | magedu-pythons/python-14 | /tianwei/week11/Sentence.py | 572 | 3.8125 | 4 | #根据字典,从一个抹去空格的字符串里面提取出全部单词组合,并且拼接成正常的句子:
#例如: 输入一个字符串:"thisisanexample", 程序输出: "this is an example"
dic={'1':'this','2':'is','3':'an','4':'example','5':'hello'}
str="thisisanexample"
def sentence(dic,str):
strout=""
start=0
while True:
if start==len(str):
break
for v in dic.values():
n=len(v)
if str[start:n+start]==v:
strout=strout+v+" "
start+=n
return strout
print(sentence(dic,str))
|
1017748992394a10c00a4ee3e8f9d9a081e12bab | SebastianMaciasI/Mision-02 | /auto.py | 547 | 3.71875 | 4 | # Autor: Sebastian Macias Ibarra, A01376492
# Descripcion: Sacar los kilómetros recorridos para 7 y 4.5 horas y el tiempo para 791 km
# Escribe tu programa después de esta línea.
velocidad = int (input ("Escribe la velocidad del auto en km/h: "))
distancia1 = velocidad * 7
distancia2 = velocidad * 4.5
tiempo = 791 / velocidad
print(" ")
print("Distancia recorrida por el auto en 7 h: ", distancia1, "km")
print("Distancia recorrida por el auto en 4.5 h: ", distancia2, "km")
print("Tiempo necesario para recorrer 791 km: ", format(tiempo, ".1f"), "horas")
|
a84b4ab62861e5466f6b40e26c9c152986a06d8b | Talha089/Python-for-Everybody | /Using Python to Access Web Data/Week2_RegEx/extractingdata1.py | 190 | 3.9375 | 4 | import re
# matching and extracting numbers
#[0-9] one digit
# + means that it will give the one or more digit
x = 'My 2 favorite numbers are 19 and 42'
y = re.findall('[0-9]+', x)
print(y) |
3e20b402579636bc2c55132c22587a7d52c3293b | srajulu/Python-basics | /sumfunction.py | 176 | 3.6875 | 4 | def sum4(l):
"Print sum of four numbers"
s=sum(l)
return s
l=[]
for i in range(0,4):
l.append(int(input("Enter num: ")))
k=sum4(l)
print("Sum is: ",k)
|
22fc995c5ed441448e9647e8a5c5a03954a6fbfe | sharozraees802/Data_Structure-python- | /A1/A.py | 2,947 | 3.796875 | 4 | import numpy as Array
# import nparray as ar
user = int(input("Enter a number of Element: "))
fib = Array.array([0 for i in range(user+1)])
fib1 = Array.array([0 for i in range(user+1)])
fib2 = Array.array([0 for i in range(user+1)])
# s = ar.array([0 for i in range(user+1)])
# fib=Array.insert()
fib[0]=0
fib[1]=1
f = 0
s = 1
fseries = "fibonacci series:"
print(fseries, end=" ")
print(f , end="" + " " + str(s)+" ")
for i in range(2,len(fib)):
fib[i] = fib[i - 1] + fib[i - 2]
if user == fib[i]:
print(str(fib[i]), end=" ")
break
else:
print(fib[i], end=" ")
insert = "insert value:"
print(insert, end="")
index = 0
value = user
temp = Array.array([0 for i in range(len(fib)+1)])
j = 0
for i in range(len(temp)):
if i == index:
temp[i]=value
else:
temp[i]=fib[j]
j +=1
fib = temp
for i in range(len(fib)):
print(fib[i], end=" ")
primnum = "prime number:"
print(primnum, end=" ")
for i in range(2,len(temp)):
v = False
if temp[i] != 1:
d=2
while(d<i):
if temp[i]%d==0 :
if temp[i]%d:
v = True
break
d +=1
else:
# fib1 = temp
v = True
print(temp[i], end=" ")
# if len(fib)>1:
# for i in range(2, len(fib)):
# if fib[i] % i ==0:
# break
# else:
# print(fib[i], end=" ")
# for num in range (2,len(fib)):
#if fib[i] != 1:
# d=2
# while(d<=fib[num]/2):
# if fib[num]%d==0 :
# if fib[num]%d:
# break
# d +=1
# else:
# fib1 = fib
# print(fib1[num], end=" ")
# for y in range(1,len(fib)):
# x = int(y)
# for x in range(2,x):
# if (y/x).is_integer():
# len(fib).append(x)
# if len(fib) < 2:
# fib1.append(y)
#
# print(fib1)
# def prime(num):
# s =0
# flag = 0
# for i in range(s, num/2):
# if num%i ==0:
# flag = 1
# break
# s+=1
# if flag==1:
# return 0
# else:
# return 1
#
#
#
#
# loop=0
# length = int(len(fib)/len(fib[0]))
# for i in range(loop,length):
# print(fib[loop])
# loop+=1
# lower = 0
# uper = 0
# c = 0
# counter = 3
# for num in range(c,user):
# lower = int(fib[num] / 2)
# for i in range(2,lower):
# if fib[num]%i ==0:
# fib1[num]=fib[num]
# uper = 1
# break
#
#
# if uper ==0:
# if fib[num] >=2:
# fib2[num] = fib[num]
# else:
# fib1[num] = fib[num]
#
#
# for i in range(2,len(fib1)):
# if fib1[i] == 0:
# continue
# print(fib1[i], end=" ")
# for num in range(lower, len(fib)+1):
# if num > 1:
# for i in range(2,num):
# if num%i == 0:
# break
# else:
# print(num, end=" ")
#
#
#
|
1a6389725f0431e487b35900823fcc4cf7a51eb1 | Muhammad12344/ca117 | /week07/lab1/point_071.py | 302 | 3.71875 | 4 | from math import sqrt
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def reflect(self):
self.x = -self.x
self.y = -self.y
def distance(self, p):
dist = sqrt((p.x - self.x) ** 2 + (p.y - self.y) ** 2)
return dist
|
c3b996bf62b6cbd83e724bde3f307c2c7164ce14 | Nuhvok/Work-Show- | /functions.py | 526 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: cp1252 -*-
def main():
print_name()
give_temp()
if_test()
give_temp()
def print_name():
fname = input("Enter your first name: ")
lname = input("Enter your last name: ")
fullname = fname + " " + lname
print("Your name is:", fullname)
def give_temp():
print("temp is 88F"*3)
def if_test():
result = input("is this true?(1 for true")
if result == True:
print("true")
else:
print("false")
main() |
86d14c67fee0480429d3bed5d61866ed91dbd84f | kuljotanand/cornell-tech | /crypto/hw1/MyFeistel.py | 9,239 | 4.03125 | 4 | # Homework 1 (CS5830)
# Daniel Speiser and Haiwei Su
from cryptography.hazmat.primitives import hashes, padding, ciphers
from cryptography.hazmat.backends import default_backend
import base64
import binascii
import os
def xor(a,b):
"""
xors two raw byte streams.
"""
assert len(a) == len(b), "Lengths of two strings are not same. a = {}, b = {}".format(len(a), len(b))
return ''.join(chr(ord(ai)^ord(bi)) for ai,bi in zip(a,b))
"""
Part 2: Why Feistel encryption needs a minimum of four rounds
Solution:
For 1 round of Feistel, after encryption the new left portion of the output ciphertext is the same as the right portion of the original text. This - in plain text - reveals the input.
For 2 rounds of Feistel, let's look at the process of each round:
L' <- R
R' <- L + f(R)
L'' <- R'
R'' <- L' + f(R')
where f() is a round function. We can see that two messages with the same right half such that m1 = L1 * R, m2 = L2 * R. We also notice that for 2nd round Feistel, L1'' = L1 + f(R), and L2'' = L2 + f(R). Therefore, we have L1'' + L2'' = L1 + L2 which is equivalent to saying use a one time pad on the left side.
For 3 rounds of Feistel, let function F be the following algorithm:
(1). F get input L1 and R1 from input data, and put them into the encrypt function encrypt(L1, R1) to get encrypted ciphertext, S1, and T1 respectively.
(2). F then chooses an element L2 != L1 and get encrypted text such that encrypt(L2, R1) to get corresponding encrypted cipher text S2 and T2.
(3). Finally, we perform a decrypt where decrypt(S2, T2 + L1 + L2) to S3 and T3. If we test if R3 = S2 + S1 + R1 and this is always true if only 3 round.
References:
1) https://courses.cs.washington.edu/courses/cse599b/06wi/lecture4.pdf
2) https://eprint.iacr.org/2008/036.pdf
-------- Note: + is a bitwise xor, and * is string concatenation --------
Attacks for 4, 5, and 6 rounds of feistel (6th round in O(2^(2n))) exist, but we could not 'decipher' how to apply them.
Link to description of these attacks can be found here:
https://www.iacr.org/archive/asiacrypt2001/22480224.pdf
"""
class MyFeistel:
def __init__(self, key, num_rounds, backend=None):
if backend is None:
backend = default_backend()
key = base64.urlsafe_b64decode(key)
assert len(key) == 16, "Key must be 16 url-safe base64-encoded bytes. Got: {} ({})".format(key, len(key))
self._num_rounds = num_rounds
self._encryption_key = key
self._backend = backend
self._round_keys = [self._encryption_key \
for _ in xrange(self._num_rounds)]
for i in xrange(self._num_rounds):
if i==0: continue
self._round_keys[i] = self._SHA256hash(self._round_keys[i-1])
self._iv = os.urandom(16)
def _SHA256hash(self, data):
h = hashes.Hash(hashes.SHA256(), self._backend)
h.update(data)
return h.finalize()
def _pad_string(self, data):
"""Pad @data if required, returns a tuple containing a boolean
(whether it is padded), and the padded string.
"""
h_data = data.encode('hex')
n = len(data)
if n%2 == 0:
return False, data
l,r = h_data[:n], h_data[n:]
# pad at the beginning
# can be done at the end as well
l = '0' + l
r = '0' + r
return True, (l+r).decode('hex')
def _unpad_string(self, is_padded, padded_str): # Not tested!
if not is_padded:
return padded_str
n = len(padded_str)
assert n % 2 == 0, "Padded string must of even length. You are probably passing faulty data."
l, r = padded_str[:n/2], padded_str[n/2:]
return (l.encode('hex')[1:] + r.encode('hex')[1:]).decode('hex')
"""
The Function instantiates AES in CBC mode with a static IV
to act as a round function, a.k.a. pseudorandom function generator.
"""
def _prf(self, key, data):
padder = padding.PKCS7(ciphers.algorithms.AES.block_size).padder()
padded_data = padder.update(data) + padder.finalize()
encryptor = ciphers.Cipher(ciphers.algorithms.AES(key),
ciphers.modes.CBC(self._iv),
self._backend).encryptor()
return (encryptor.update(padded_data) + encryptor.finalize())[:len(data)]
# Can also instantiate the round function using a SHA256 hash function.
def _prf_hash(self, key, data):
"""Just FYI, you can also instantiate round function ushig SHA256 hash
function. You don't have to use this function.
"""
out = self.SHA256hash(data+key)
while len(out)<len(data):
out += self.SHA256hash(out+key)
return out[:len(data)]
def _clear_most_significant_four_bits(self, s):
"""
Clear the first four bits of s and set it to 0.
e.g, 0xa1 --> 0x01, etc.
"""
assert len(s) == 1, "You called _clear_most_significant_four_bits function, but I only work with 1 byte."
return ('0' + s.encode('hex')[1]).decode('hex')
"""
For each round of encryption we check whether the given data needs to get padded.
The function self._pad_string handles both cases (even length not needing padding,
and odd length cases which need padding). We call self._feistel_round_enc for self._num_rounds
times, which encrypts and unpads the message each time before beginning next round of encryption.
We iterate until we the number of rounds required defined by self._num_rounds.
"""
def encrypt(self, data):
ctx = data
for i in range(self._num_rounds):
is_padded, padded_data = self._pad_string(ctx)
ctx = self._feistel_round_enc(padded_data, i)
ctx = self._unpad_string(is_padded, ctx)
return ctx
"""
The decrypt function has a similar algorithm to that of the encrypt function.
The only difference is that the iteration is done in the reverse order as that
of encrypt, since we need to use the opposide order that the encryption keys were
given in, in order to use the correct one for the corresponding round. The logic
otherwise is the same.
"""
def decrypt(self, ctx):
data = ctx
for i in range(self._num_rounds - 1, -1, -1):
is_padded, padded_ctx = self._pad_string(data)
data = self._feistel_round_dec(padded_ctx, i)
data = self._unpad_string(is_padded, data)
return data
"""
According to the definition of a Feistel cipher, we first divide the input data
into left and right portions of equal length. Next, we xor the left hand side of the
data with the right hand side of the data combined with the _prf (round function). Finally
the new left hand portion of the data is the xor data calculated (as stated above) and the
right hand portion is the original left hand of the data. We return their concatenation as
the encrypted data from this round.
"""
def _feistel_round_enc(self, data, round_num):
"""This function implements one round of Fiestel encryption block.
"""
mid = len(data) / 2
L, R = data[:mid], data[mid:]
Ri = xor(L, self._prf(self._round_keys[round_num], R))
print "ENC Round {0} key: {1}".format(round_num, binascii.b2a_hex(self._round_keys[round_num]))
print "ENC Round {0} ctx: {1}".format(round_num, binascii.b2a_hex(Ri + R))
return Ri + R
"""
Decrypt is similar to encrypt, without loss of generality.
"""
def _feistel_round_dec(self, data, round_num):
"""This function implements one round of Fiestel decryption block.
"""
mid = len(data) / 2
Ri = data[mid:]
Li = xor(data[:mid], self._prf(self._round_keys[round_num], Ri))
print "DEC Round {0} key: {1}".format(round_num, binascii.b2a_hex(self._round_keys[round_num]))
print "DEC Round {0} ctx: {1}".format(round_num, binascii.b2a_hex(Li + Ri))
return Li + Ri
"""
This class is a simplified wrapper class of what we've implemented above. We do
not allow a user to change the number of rounds, or the length of the data in order
to prevent them from instantiating a cryptographic primitive in an insecure way.
"""
class LengthPreservingCipher(object):
def __init__(self, key, length=5):
self._length = length
self._num_rounds = 10 # Hard code this. Don't leave this kind
# of parameter upto the developers.
self._feistel = MyFeistel(key, self._num_rounds)
# Calls MyFeistel's encrypt method.
def encrypt(self, data):
assert len(data) == self._length, "Data size must equal the length defined in the instantiation of LengthPreservingCipher."
return self._feistel.encrypt(data)
# Calls MyFeistel's decrypt method.
def decrypt(self, data):
assert len(data) == self._length, "Data size must equal the length defined in the instantiation of LengthPreservingCipher."
return self._feistel.decrypt(data)
|
ee4cfef63d5ba17af1242afe7d5aadfdb023d11b | Poojapanchal1208/Poojapanchal1208 | /Pooja Docs/PoojaAssignment#1.py | 3,088 | 4.09375 | 4 | import sys
def Menu():
print("...........Menu.........")
print("1:Grilled Sandwich $10 ")
print("2:Hakka Noodles $22 ")
Snacks = int(input("Choose your snack:"))
if Snacks == 1:
price = 10
return price, str("Grilled Sandwich")
else:
price = 22
return price, str("Hakka Noodles")
def Afterorder():
global totalprice,invoice
price, selectedsnacks = Menu()
quantity = input("Total amount of today's snack :")
print(".....Your snacks.....")
print("Order \t Item Amt \t Item Price \t Total")
price = int(price)
quantity = int(quantity)
totalprice = price * quantity
totalprice = str("{:.2f}".format(totalprice))
invoice=str(selectedsnacks) + "\t " + str(quantity) + "\t $" + str("{:.2f}".format(price)) + "\t $" + totalprice
print(invoice)
def custinfo():
print("Warm Welcome to Amazing Eats")
firstname = input("Enter Firstname:")
lastname = input("Enter Lastname:")
print("........Home Adress.......")
streetno = input("Enter Street No:")
streetname = input("Enter Street Name:")
city = input("Enter City:")
province = input("Enter province:")
postalcode = input("Enter postal code:")
instruction = input("Enter instruction:")
phonenumber = input("Enter phone number:")
def Confirmsnack():
conf=input("Would you like to confirm your snack: \n Press Y|y or y \n Press N|n \n Select your choice: ")
return conf
def Student():
conf = input("Are you Student? \n Press Y|y to confirm \n Press N|n to deny \n Select your choice:")
return conf
def showStudentinvoice(amount,GSTAmount,totalprice):
print("Order \t snack Amount \t snack Price \t Total")
print(invoice)
print("10% Savings \t \t \t \t -$"+str("{:.2f}".format(amount)))
print("\t \t \t \t Total \t \t $"+str("{:.2f}".format(totalprice-amount)))
print("\t \t \t \t Tax (13 %) \t $"+str("{:.2f}".format(GSTAmount)))
print("\t \t \t \t \t \t FinalAmount \t $"+str("{:.2f}".format(GSTAmount+totalprice-amount)))
#print("\t \t \t Total -$"+GSTAmount)
def showCustinvoice(GSTAmount,totalprice):
print("Order \t Snack amount \t Snack amount \t Total")
print(invoice)
print("\t \t \t \t \t Total \t \t $"+str("{:.2f}".format(totalprice)))
print("\t \t \t \t \t Tax (13 %) \t $"+str("{:.2f}".format(GSTAmount)))
print("\t \t \t \t \t TOTAL \t $"+str("{:.2f}".format(GSTAmount+totalprice)))
custinfo()
Menu()
c = Confirmsnack()
if c=="Y" or c=="y":
ans=Student()
if ans=="Y" or ans=="y":
tempamt = float(totalprice)
studentAmt=(tempamt * 10)/100
GSTAmount=((tempamt - studentAmt) * 13)/100
showStudentinvoice(float(studentAmt),float(GSTAmount),float(totalprice))
elif ans=="N" or ans=="n":
tempamt = float(totalprice)
GSTAmount=((tempamt) * 13)/100
showCustinvoice(float(GSTAmount),float(totalprice))
elif Confirmsnack()=="N" or Confirmsnack()=="n":
Menu() |
a82c6a7bb32d56383b67c7b815ed73c048eeaa57 | Lesuz/Python-Application-Course | /Applications/Week 9-10 Morse Coder.py | 2,803 | 3.6875 | 4 | #Week 9-10 Morse Coder
from tkinter import *
class MorseCoder:
morseCode = {'A':'.-',
'B':'-...',
'C':'-.-.',
'D':'-..',
'E':'.',
'F':'..-.',
'G':'--.',
'H':'....',
'I':'..',
'J':'.---',
'K':'-.-',
'L':'.-..',
'M':'--',
'N':'-.',
'O':'---',
'P':'.--.',
'Q':'--.-',
'R':'.-.',
'S':'...',
'T':'-',
'U':'..-',
'V':'...-',
'W':'.--',
'X':'-..-',
'Y':'-.--',
'Z':'--..',
'1':'.----',
'2':'..---',
'3':'...--',
'4':'....-',
'5':'.....',
'6':'-....',
'7':'--...',
'8':'---..',
'9':'----.',
'0':'-----',
' ': ' '}
morse = ''
#Converts text to morse code
#textToMorse = {v: k for k,v in morseCode.items()}
def __init__(self,parent):
self.frame1 = Frame(parent)
self.frame1.pack()
self.inputTextLabel = Label(self.frame1,text="Input Text: ")
self.inputTextLabel.pack(side=TOP)
self.inputText = Text(self.frame1,width=50,height=10)
self.inputText.pack(side=LEFT)
self.frame2 = Frame(parent)
self.frame2.pack()
self.submitButton = Button(self.frame2,text="Text into morse code")
self.submitButton.pack(side=BOTTOM)
self.submitButton.bind("<Button-1>", self.submit_click)
self.outputTextLabel = Label(self.frame2,text="Morse Code: ")
self.outputTextLabel.pack(side=TOP)
self.outputText = Text(self.frame2,width=50,height=10)
self.outputText.pack(side=LEFT)
def morserer(self):
for x in self.textUpper:
self.morse += str(self.morseCode.get(x)) + ' '
def clearOutput(self):
self.morse = ''
self.outputText.delete("1.0","end")
#Event handler for when SUBMIT -button is clicked
# GEts inputed text and Turns users text into morse code
def submit_click(self,event):
print("Button clicked")
self.clearOutput()
self.text = self.inputText.get("1.0","end-1c")
self.textUpper = self.text.upper()
#for x in self.textUpper:
# self.morse += str(self.morseCode.get(x)) + ' '
self.morserer()
self.outputText.insert(END,self.morse)
root = Tk()
root.title("Morse Coder")
root.geometry("500x450")
morsecoder = MorseCoder(root)
root.mainloop() |
7ab19b2979a4c7d0bef776a7e2dcd43ec87ba180 | az-cheng/Invaders_Game_Project | /invaders/wave.py | 15,537 | 4.1875 | 4 | """
Subcontroller module for Alien Invaders
This module contains the subcontroller to manage a single level or wave in the Alien
Invaders game. Instances of Wave represent a single wave. Whenever you move to a
new level, you are expected to make a new instance of the class.
The subcontroller Wave manages the ship, the aliens and any laser bolts on screen.
These are model objects. Their classes are defined in models.py.
Most of your work on this assignment will be in either this module or models.py.
Whether a helper method belongs in this module or models.py is often a complicated
issue. If you do not know, ask on Piazza and we will answer.
# Annie Cheng zc375; Ruitong rl699
# November 29, 2018
"""
from game2d import *
from consts import *
from models import *
import random
# PRIMARY RULE: Wave can only access attributes in models.py via getters/setters
# Wave is NOT allowed to access anything in app.py (Subcontrollers are not permitted
# to access anything in their parent. To see why, take CS 3152)
class Wave(object):
"""
This class controls a single level or wave of Alien Invaders.
This subcontroller has a reference to the ship, aliens, and any laser bolts on screen.
It animates the laser bolts, removing any aliens as necessary. It also marches the
aliens back and forth across the screen until they are all destroyed or they reach
the defense line (at which point the player loses). When the wave is complete, you
should create a NEW instance of Wave (in Invaders) if you want to make a new wave of
aliens.
If you want to pause the game, tell this controller to draw, but do not update. See
subcontrollers.py from Lecture 24 for an example. This class will be similar to
than one in how it interacts with the main class Invaders.
#UPDATE ME LATER
INSTANCE ATTRIBUTES:
_ship: the player ship to control [Ship]
_aliens: the 2d list of aliens in the wave [rectangular 2d list of Alien or None]
_bolts: the laser bolts currently on screen [list of Bolt, possibly empty]
_dline: the defensive line being protected [GPath]
_lives: the number of lives left [int >= 0]
_time: The amount of time since the last Alien "step" [number >= 0]
As you can see, all of these attributes are hidden. You may find that you want to
access an attribute in class Invaders. It is okay if you do, but you MAY NOT ACCESS
THE ATTRIBUTES DIRECTLY. You must use a getter and/or setter for any attribute that
you need to access in Invaders. Only add the getters and setters that you need for
Invaders. You can keep everything else hidden.
You may change any of the attributes above as you see fit. For example, may want to
keep track of the score. You also might want some label objects to display the score
and number of lives. If you make changes, please list the changes with the invariants.
LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY
_direction: the direction in which the aliens are moving [0 or 1]
_step: the number of steps until the aliens fire [random int bewteen 1 and BOLT_RATE]
_time2: the amount of time since the last Alien firing bolt [number >= 0]
_aliensleft: the number of aliens left [int >=0]
_crossline: True if any alien has crossed the defense line, False otherwise
[bool]
_alienscoords: coordinates of active aliens [list of tuples, possibly empty]
_alienspeed: the speed in which the aliens are moving [number >= 0]
_movesound: a list of the move Sound objects when aliens move [list]
_move: the number of move aliens taken since the first move sound
[int between 0 and 3]
_sounds: a list of all Sound objects being used in class Wave [list]
_score: current score [int >= 0]
"""
# GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM)
def getShip(self):
"""
Returns the number of lives left.
"""
return self._ship
def setShip(self):
"""
Set the _ship attribute.
"""
self._ship = Ship(source0='ship.png')
def getLives(self):
"""
Returns the number of lives left.
"""
return self._lives
def getAliensLeft(self):
"""
Returns the number of aliens left.
"""
return self._aliensleft
def getCrossLine(self):
"""
Returns the _crossline attribute.
"""
return self._crossline
def getAlienSpeed(self):
"""
Returns the _alienspeed attribute.
"""
return self._alienspeed
def setAlienSpeed(self,s):
"""
Set the alien speed to s.
Parameter s: the desired speed
Precondition: a number >= 0
"""
self._alienspeed = s
def getSounds(self):
"""
Returns the _sounds attribute.
"""
return self._sounds
def setSounds(self,n):
"""
Set the volume of sounds to n.
Parameter n: the desired volume
Precondition: n is either 0 or 1
"""
for i in self._sounds:
i.volume = n
def getScore(self):
"""
Returns the current score.
"""
return self._score
def setScore(self, n):
"""
Set the score from the previous wave.
Parameter n: the score needs to be carried over
Precondition: n is an int >= 0
"""
self._score = n
# Three main wave methods
def __init__(self):
"""
Initializes the class Wave and its attributes.
"""
self._aliens = self._aliensList()
self._ship = Ship(source0='ship.png')
self._dline = GPath(points=[0,DEFENSE_LINE,GAME_WIDTH,DEFENSE_LINE],
linewidth=1, linecolor='black')
self._time = 0
self._direction = 0
self._bolts = []
self._step = random.randrange(1,BOLT_RATE+1)
self._time2 = 0
self._lives = SHIP_LIVES
self._aliensleft = ALIEN_ROWS*ALIENS_IN_ROW
self._crossline = False
self._alienscoords = []
self._alienspeed = ALIEN_SPEED
self._sounds = [Sound('pew1.wav'),Sound('pop2.wav'),Sound('blast1.wav')]
self._movesound = [Sound('move1.wav'),Sound('move2.wav'),
Sound('move3.wav'),Sound('move4.wav')]
self._move = 0
for i in self._movesound:
self._sounds.append(i)
self._score = 0
def update(self,input,dt):
"""
Animates the ship, aliens, and laser bolts.
Parameter input: the user input, used to change state
Precondition: instance of GInput; it is inherited from GameApp
Parameter dt: The time since the last animation frame.
Precondition: dt is a number (int or float)
"""
self._shipUpdate(input)
self._aliensUpdate(dt)
self._firePlayerBolt(input)
self._fireAlienBolt(dt)
self._collision()
def draw(self,view):
"""
Draw the ship, aliens, defensive line and bolts.
Parameter: The view window
Precondition: view is a GView.
"""
# draw aliens
for row in self._aliens:
for alien in row:
if alien != None:
alien.draw(view)
# draw ship
if self._ship != None:
self._ship.draw(view)
# draw dline
self._dline.draw(view)
# draw bolts
for bolt in self._bolts:
bolt.draw(view)
# HELPER METHODS
def _aliensList(self):
"""
Create a 2d list of aliens.
"""
a = []
y1 = GAME_HEIGHT-ALIEN_CEILING-(ALIEN_V_SEP+ALIEN_HEIGHT)* \
(ALIEN_ROWS-1)-ALIEN_HEIGHT/2
for r in range(ALIEN_ROWS):
b = []
for i in range(ALIENS_IN_ROW):
b.append(Alien(x0=ALIEN_WIDTH*(1/2+i)+(i+1)*ALIEN_H_SEP, y0=y1+
(ALIEN_H_SEP+ALIEN_HEIGHT)*r, source0=ALIEN_IMAGES[int
(r/2)%len(ALIEN_IMAGES)]))
a.append(b)
return a
def _shipUpdate(self,input):
"""
Update the ship upon key presses.
Parameter input: the user input, used to change state
Precondition: instance of GInput; it is inherited from GameApp
Key press method adopted from arrows.py by Walker M. White
"""
# detect key press
da = 0
if input.is_key_down('right'):
da += SHIP_MOVEMENT
if input.is_key_down('left'):
da -= SHIP_MOVEMENT
# move the ship
if self._ship != None:
self._ship.x += da
# prevent the ship from moving out of the screen
if self._ship.x < 0:
self._ship.x = SHIP_WIDTH/2
if self._ship.x > GAME_WIDTH:
self._ship.x = GAME_WIDTH-SHIP_WIDTH/2
def _aliensMove(self,direction,dt):
"""
Move the aliens to the left/right with specified speed.
Parameter direction: specifies the direction the aliens are removing
Precondition: 0 or 1; 0 for moving right and 1 for moving left
Parameter dt: The time since the last animation frame.
Precondition: dt is a number (int or float)
"""
if self._time > self._alienspeed:
self._alienscoords = []
for r in range(ALIEN_ROWS):
for c in range(ALIENS_IN_ROW):
if self._aliens[r][c] != None:
self._aliens[r][c].x += direction
self._alienscoords.append((r,c))
# play the move sound
self._movesound[self._move].play()
if self._move <= len(self._movesound)-1:
self._move += 1
if self._move == len(self._movesound):
self._move = 0
self._time = 0
else:
self._time += dt
def _aliensDown(self):
"""
Move the aliens down when the end reaches the edge of the screen and
check to see if it has crossed the defense line.
"""
for row in self._aliens:
for alien in row:
if alien != None:
# move down
alien.y -= ALIEN_V_WALK
# counter the horizontal walk
if self._direction == 0:
alien.x -= ALIEN_H_WALK
if self._direction == 1:
alien.x += ALIEN_H_WALK
# check to see if any aliens crossed the defense line
if alien.y-ALIEN_HEIGHT/2 < DEFENSE_LINE:
self._crossline = True
def _aliensUpdate(self,dt):
"""
Update the aliens using _aliensMove, _aliensDown and _aliensExtreme
helpers.
Parameter dt: The time since the last animation frame.
Precondition: dt is a number (int or float)
"""
# when aliens are moving right
if self._direction == 0:
self._aliensMove(ALIEN_H_WALK,dt)
if self._alienscoords != []:
m,n = max(self._alienscoords,key=lambda item:item[1])
if self._aliens[m][n] != None and self._aliens[m][n].x > \
GAME_WIDTH-ALIEN_H_SEP-ALIEN_WIDTH/2 and self._direction != 1:
self._aliensDown()
self._direction = 1
#when aliens are moving left
if self._direction == 1:
self._aliensMove(-ALIEN_H_WALK,dt)
if self._alienscoords != []:
m,n = min(self._alienscoords,key=lambda item:item[1])
if self._aliens[m][n] != None and self._aliens[m][n].x < \
ALIEN_H_SEP+ALIEN_WIDTH/2 and self._direction != 0:
self._aliensDown()
self._direction = 0
def _firePlayerBolt(self,input):
"""
Fire a bolt upon player pressing the spacebar and delete any off
offscreen bolt.
Parameter input: the user input, used to change state
Precondition: instance of GInput; it is inherited from GameApp
"""
# fire player bolt
if input.is_key_down('spacebar'):
try:
for bolt in self._bolts:
assert bolt.isPlayerBolt() == False
a = Bolt(self._ship.x,SHIP_BOTTOM+SHIP_HEIGHT+BOLT_HEIGHT/2)
a._playerbolt = True
self._bolts.append(a)
self._sounds[0].play()
except:
pass
for bolt in self._bolts:
if bolt._playerbolt:
bolt.y += bolt.getVelocity()
else:
bolt.y -= bolt.getVelocity()
# delete any offscreen bolt
i = 0
while i < len(self._bolts):
a = self._bolts[i]
if a.y-BOLT_HEIGHT/2 > GAME_HEIGHT or a.y+BOLT_HEIGHT/2 < 0:
del self._bolts[i]
else:
i += 1
def _fireAlienBolt(self,dt):
"""
Fire a bolt upon from a random alien within self._step
Parameter dt: The time since the last animation frame.
Precondition: dt is a number (int or float)
"""
if self._time2 > self._step*self._alienspeed:
#find a nonempty column
for i in range(ALIENS_IN_ROW):
b = random.randrange(ALIENS_IN_ROW)
if not all(v is None for v in [row[b] for row in self._aliens]):
break
else:
continue
#find the bottom alien that's not None
for i in range(ALIEN_ROWS):
r = i
if self._aliens[i][b] != None:
break
else:
continue
#fire the alien bolt
if self._aliens[r][b] != None:
a=Bolt(self._aliens[r][b].x,self._aliens[r][b].y-ALIEN_HEIGHT/2)
a._playerbolt = False
self._bolts.append(a)
self._step = random.randrange(1,BOLT_RATE+1)
self._time2 = 0
else:
self._time2 += dt
def _collision(self):
"""
Check to see if there's any collision between bolt and alien or bolt and
ship. Then make changes accordingly.
"""
for i in self._bolts:
# when player bolt collides with alien
if i.isPlayerBolt():
for r in range(ALIEN_ROWS):
for c in range(ALIENS_IN_ROW):
if self._aliens[r][c]!= None and \
self._aliens[r][c].collides(i):
self._aliens[r][c] = None
self._aliensleft -= 1
self._bolts.remove(i)
self._sounds[1].play()
self._alienspeed *= SPEED_FACTOR
self._score += BASIC_SCORE*(int(r/2)+1)
# when alien bolt collides with ship
else:
if self._ship != None and self._ship.collides(i):
self._ship = None
self._bolts.remove(i)
self._lives -= 1
self._sounds[2].play()
|
d7e36ef7cd85974b4136cbf59bc9f92c80418e7d | Szymchack/CIT228 | /Chapter10/glossary.py | 2,994 | 3.953125 | 4 | import json
def menu():
selection= int(input("1-create file, 2-read file, 3-add to file, 4-quit"))
while selection!=1 and selection!=2 and selection!=3 and selection!=4:
print("You made an invalid selection, please try it again")
return selection
def create(object):
overwrite = input("You are about to create a new file, existing data will be overwritten (q to quit, any key to continue) ")
if overwrite !="q":
with open("Chapter10/glossary.json", "w") as write_file:
json.dump(object, write_file, indent=4, sort_keys=True)
print("glossary.json has been created")
def append(new_word):
with open("Chapter10/glossary.json", "r+") as add_file:
glossary_Dictionary = json.load(add_file)
glossary_Dictionary.update(new_word)
add_file.seek(0)
json.dump(glossary_Dictionary, add_file, indent=4, sort_keys=True)
print("The new word" + new_word + "has been add to the file")
def read():
try:
with open ("Chapter10/glossary.json") as read_file:
glossary_Dictionary = json.load(read_file)
except FileNotFoundError:
print("The file cannot be found or does not exist")
print("Please make a different selection")
else:
for key, value in glossary_Dictionary.item():
print(key.title(), "Please enter a new term", value)
def get_key():
word=input("Enter the new term you would like to use")
new_word = word.split[0]
new_word = new_word.lower()
return new_word
def get_value():
new_definition=str(input("Enter the definition to the new term"))
return new_definition
glossary={
'dictionary':'A collection of key-value pairs.',
'key value pairs':'is an unordered collection of data values, used to store data values like a map',
'variables':'are nothing but reserved memory locations to store values.',
'tuple':'is one of 4 built-in data types in Python used to store collections of data which is ordered and unchangeable',
'data types':'Since everything is an object in Python, data types are actually classes and variables are instance of these classes.',
'del':'command used to remove a key:value pair from the dictionary',
'key':'value used to access data stored in the dictionary or glossary',
'conditional test':'a comparison between two values',
'boolean':'an expression that evaluates to "true" or "false"',
'value':'an item associated with a key in dictionary or glossary'
}
choice=menu()
while choice != 4:
if choice == 1:
create(new_definition)
elif choice == 2:
read()
elif choice == 3:
new_word=get_key()
new_definition=get_value()
new_definition_entry={new_word:new_definition}
append(new_definition_entry)
else:
print("The option you selected is not available, please try again")
choice=menu() |
6889b62ada6c775a00c29b47f0bbd26af6ecc622 | yotaroy/python_algorithms | /algorithm/basic/gcd.py | 603 | 3.90625 | 4 | # 最大公約数を求める
def gcd(x, y):
if x < y:
x, y = y, x
if y == 0:
return x
return gcd(y, x % y)
# 再帰を使わないバージョン
def gcd2(x, y):
if x < y:
x, y = y, x
while y != 0:
r = x % y
x = y
y = r
return x
if __name__ == '__main__':
problems = [(60, 36), (1085, 1015)]
print('最大公約数を求めるアルゴリズム')
for a, b in problems:
print('{}と{}の最大公約数は{}'.format(a, b, gcd(a, b)))
print('{}と{}の最大公約数は{}'.format(a, b, gcd2(a, b)))
|
33c953df48ee51816304e94012b6058200b3068b | leeeeeoy/Algorithm_Study | /Problems/5th_week/leetCode92/mingyu/Reverse_Linked_List_2.py | 2,619 | 3.84375 | 4 | """
LeetCode 92. 역순 연결 리스트 2
url: https://leetcode.com/problems/reverse-linked-list-ii/
writer: Mingyu
Language: Python3
Date: 2021.02.14
Status: , Runtime: ms, Memory Usage: KB
"""
# 리스트노드의 구조
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
# head가 비어있거나 m과 n이 같은 경우, 즉 변경할 부분이 없는 경우에는 head를 그대로 리턴한다
if not head or m == n:
return head
# m부터 n까지의 숫자를 역순으로 재정렬할 리스트
num = list()
# 우선 head에 있는 val을 모두 받아서 그대로 num에 저장한다.
while head:
num.append(head.val)
head = head.next
# num의 m번째부터 n번째까지의 수를 역순으로 재정렬
num[m-1:n] = reversed(num[m-1:n])
# root와 num_linked_list를 따로 정의한 이유는 num_linked_list에서 노드의 추가 작업을 실시한 후
# root 자체를 불러옴으로써 연결리스트 전체를 가져오기 위함이다.
# num_linked_list를 바로 쓰지 못하는 이유는 하단 for문에서 next를 반복하며 num_linked_list가 가리키는 위치가 맨 끝이 되어버리기 때문
root = num_linked_list = ListNode(0)
# num_linked_list에 num에 있는 숫자를 ListNode의 형태로 추가해준다
# num_linked_list는 계속해서 next를 해주어 다음 노드를 가리킬 수 있도록 한다.
for i in num:
num_linked_list.next = ListNode(i)
num_linked_list = num_linked_list.next
# root를 리턴하면 ListNode(0), 즉 0도 같이 나오게 된다. 그러니 root의 next부터 리턴해주도록 한다.
return root.next
''' 주석 없는 코드
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
if not head or m == n:
return head
num = list()
while head:
num.append(head.val)
head = head.next
num[m-1:n] = reversed(num[m-1:n])
root = num_linked_list = ListNode(0)
for i in num:
num_linked_list.next = ListNode(i)
num_linked_list = num_linked_list.next
return root.next
''' |
392f5a9ab92ef7e8bf18a65930dc9b2756ea48b0 | opencodeiiita/Road-CS | /Submission/Lalit(Week-4)/brute.py | 1,003 | 3.65625 | 4 | import zipfile
import argparse
def extractFile(zFile, password):
try:
zFile.extractall(pwd=password)
print "[+] Found password = " + password
return True
except:
return False
def main():
parser = argparse.ArgumentParser("%prog -f <zipfile> -d <dictionary>")
parser.add_argument("-f", dest="zname", help="specify zip file")
parser.add_argument("-d", dest="dname", help="specify dictionary file")
args = parser.parse_args()
if (args.zname == None):
print parser.usage
exit(0)
elif (args.dname == None):
zname = args.zname
dname = 'passwords.txt'
else:
zname = args.zname
dname = args.dname
zFile = zipfile.ZipFile(zname)
passFile = open(dname)
for line in passFile.readlines():
password = line.strip("\n")
found = extractFile(zFile, password)
# Exit if password found
if found == True:
exit(0)
# If it makes it here password has not been found...
print '[-] Password not found'
if __name__ == "__main__":
main() |
b94da4860518ca7474a2a6f0f24ce9973c182343 | Atuan98/Demo_py1 | /Lession_11/btvn_1.py | 369 | 3.84375 | 4 | class Dog:
species = 'animal'
def __init__(self, name, age):
self.name = name
self.age = age
def get_biggest_number(*args):
max_ = args[0]
print(args)
for i in args:
if i > max_:
max_ = i
print(f"The oldest dog is {max_} year old")
dog1 = Dog('Fake', 2)
dog2 = Dog('Mickey', 7)
dog3 = Dog('Fuk', 5)
get_biggest_number(dog1.age,dog2.age,dog3.age) |
dfbd9966b4359c0f891f9ead454a000a3a8d8006 | ruraj/stackoverflow-python | /iterm.py | 827 | 3.765625 | 4 | """http://stackoverflow.com/questions/24825366/python-how-to-cut-a-list-which-contains-lists/24827627#24827627
"""
list1 = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ]
list2 = [ [50,45,40,35], [30,25,20,15], [10,9,5,0] ]
list3 = [ [101,2,3,33], [11,22,30,1], [1,22,33,] ]
def func_index(reference, number):
index = 0
for ind1, value1 in enumerate(reference):
for ind2, value2 in enumerate(value1):
index += 1
if value2 == number:
return index
def func_slice(lst, index):
count = 0
temp = []
for ind1, value1 in enumerate(lst):
for ind2, value2 in enumerate(value1):
count += 1
if count == index:
temp.append(value1[:ind2+1])
return temp
temp.append(value1)
list2 = func_slice(list2, func_index(list1, 9))
list3 = func_slice(list3, func_index(list1, 2))
print list2
print list3
|
87f2df453df6318368fc482aa517c1ac294f7354 | number09/atcoder | /code_thanks_festival_2017-a.py | 102 | 3.65625 | 4 | li_t = list()
for i in range(8):
li_t.append(int(input()))
print(sorted(li_t, reverse=True)[0])
|
8a85ff96e2e4a4ff613d1f9a1d9bccd89e457407 | gssasank/Basic-Algorithms-Projects | /Search-in-a-Rotated-Sorted-Array/problem_2.py | 2,333 | 4.375 | 4 | def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
number:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
if len(input_list) == 0 or number is None:
return -1
first = 0
last = len(input_list) - 1
try:
max_element_index = input_list.index(max(input_list))
except KeyError:
return -1
if max_element_index == -1:
return binary_search(input_list, first, last, number)
else:
if input_list[max_element_index] == number:
return max_element_index
elif number >= input_list[0]:
return binary_search(input_list, 0, max_element_index-1, number)
else:
return binary_search(input_list, max_element_index-1, last, number)
# Used Non-Recursive Binary Search
def binary_search(array, start_index, end_index, target):
while start_index <= end_index:
mid_index = (start_index + end_index) // 2
mid_element = array[mid_index]
if target == mid_element:
return mid_index
elif target < mid_element:
end_index = mid_index - 1
else:
start_index = mid_index + 1
return -1
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass")
else:
print("Fail")
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 4])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
test_function([[0], 0])
test_function([[0, 0, 0, 0, 0, 0, 0], 0])
# edge test 1 empty string
test_function([[], 1])
# edge test 2 large list
test_list = [i for i in range(1011, 10000)] + [i for i in range(0, 1011)]
test_function([test_list, 6])
# edge test 3 large list with negative numbers
test_list = [i for i in range(1011, 10000)] + [i for i in range(-1000, 1011)]
test_function([test_list, -60])
|
dbdf72419af77fbd44e41188c97063c06e13b207 | klrkdekira/adventofcode | /2021/15/main.py | 1,649 | 3.625 | 4 | import heapq
grid = []
with open("input") as file:
grid = list(map(lambda x: x.strip(), file))
def lookup(grid, p=(0, 0)):
return int(grid[p[1]][p[0]])
adjacent = [
(0, 1),
(1, 0),
(0, -1),
(-1, 0),
]
def find_neighbours(grid, start=(0, 0)):
x, y = start
n = []
for dx, dy in adjacent:
x1, y1 = x + dx, y + dy
if y1 >= 0 and y1 < len(grid) and x1 >= 0 and x1 < len(grid[y1]):
n.append((x1, y1))
return n
def find_exit(grid):
x, y = 0, 0
y = len(grid) - 1
x = len(grid[y]) - 1
return x, y
def search(grid):
start = (0, 0)
end = find_exit(grid)
history = {}
history[start] = None
cost = {}
cost[start] = 0
pq = [(0, start)]
while pq:
_, current = heapq.heappop(pq)
if current == end:
break
for n in find_neighbours(grid, current):
new_cost = cost[current] + lookup(grid, n)
if n not in cost or new_cost < cost[n]:
cost[n] = new_cost
heapq.heappush(pq, (new_cost, n))
history[n] = current
return history, cost, cost[end]
def expand(grid):
new_grid = []
for y in range(5):
for row in grid:
new_row = ""
for x in range(5):
for col in row:
c = (int(col) + x + y - 1) % 9 + 1
new_row += str(c)
new_grid.append(new_row)
return new_grid
print("part 1")
history, cost, total_cost = search(grid)
print(total_cost)
print("part 2")
history, cost, total_cost = search(expand(grid))
print(total_cost)
|
c44b1fbbada2c3e198a9de8fd37e5d985461826b | tomasmu/aoc2020 | /aoc09.py | 1,171 | 3.59375 | 4 | # imports
import collections
import functools
import itertools
import os
import re
# input
file = os.path.basename(__file__).replace('.py', '_input.txt')
raw_input = open(file).read()
if re.search('\n\n', raw_input):
puzzle = raw_input.split('\n\n')
else:
puzzle = raw_input.splitlines()
puzzle = [int(n) for n in puzzle]
# puzzle 1
def find_nonsummable_number(array, preamble_len):
for i in range(preamble_len, len(array)):
preamble = array[i - preamble_len:i]
pairs = itertools.combinations(preamble, 2)
next_number = array[i]
if all(a + b != next_number for a, b in pairs):
return next_number
return None
answer1 = find_nonsummable_number(puzzle, 25)
print(answer1)
# puzzle 2
def contiguous_set(array, answer):
for length in range(2, len(array) + 1):
arr_sum = sum(array[0:length])
for i in range(len(array) - length):
if arr_sum == answer:
arr = array[i:i+length]
return min(arr) + max(arr)
arr_sum -= array[i]
arr_sum += array[i+length]
return None
answer2 = contiguous_set(puzzle, answer1)
print(answer2)
|
2de9c3ded00b7c2089146c2a1fbad81518d18606 | Jose0Cicero1Ribeiro0Junior/Curso_em_Videos | /Python_3/Modulo 3/2 - Listas em Python/Exercício_079_Valores_únicos_em_uma_Lista_v0.py | 708 | 4.25 | 4 | #Exercício Python 079: Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado. No final, serão exibidos todos os valores únicos digitados, em ordem crescente.
lista_num = []
while True:
num = int(input('Digite um número: '))
if num not in lista_num:
lista_num.append(num)
print('Foi adicionado com sucesso!')
else:
print('O número e duplicato não sera adicionado!')
s_n = ' '
while s_n not in 'SN':
s_n = str(input('Quer continuar: [S/N]: ')).strip().upper()
if s_n == 'N':
break
print(f'Você digitou os valores {lista_num}')
|
e3fe1734f9c19a9dc5ea92f9340e501c8b8a8e03 | papan36125/python_exercises | /concepts/Exercises/list_functions.py | 651 | 3.875 | 4 | lucky_numbers = [4,8,15,16,23,42]
friends = ['Kevin', 'Karen', 'Jim', 'Oscar','Toby']
print(lucky_numbers)
print(friends)
friends.extend(lucky_numbers)
print(friends)
friends.append('Creed')
print(friends)
friends.insert(1,'Kelly')
print(friends)
friends.remove('Jim')
print(friends)
friends.clear()
print(friends)
lucky_numbers = [42,8,15,16,23,42]
friends = ['Kevin', 'Karen', 'Jim', 'Jim', 'Oscar','Toby']
friends.pop()
print(friends)
print(friends.index('Kevin'))
print(friends.count('Jim'))
lucky_numbers.sort()
print(lucky_numbers)
lucky_numbers.reverse()
print(lucky_numbers)
friends2 = friends.copy()
print(friends2)
|
d36156c309b1ab80fa001162ada4a51694e851d1 | cchlanger/python-bookclub | /101 python excercises_part1_MP.py | 2,033 | 3.890625 | 4 | import numpy as np
print(np.__version__)
np.arrange(0,10,1)
np.ones((3,3), dtype=np.bool_)
np.ones((3,3), dtype=bool)
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr[1::2]
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr[1::2]=-1
arr
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
arr_copy=arr.copy()
arr_copy[1::2]=-1
arr
arr_copy
arr=np.arange(10)
arr.reshape((2,5))
np.vstack([a,b])
np.hstack([a,b])
np.r_[np.repeat(a, 3), np.tile(a, 3)]
#11. How to get the common items between two python numpy arrays?
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
c=np.intersect1d(a,b) #not from the book
c
#12. How to remove from one array those items that exist in another?
a = np.array([1,2,3,4,5])
b = np.array([5,6,7,8,9])
c = np.setdiff1d(a,b) #still didn't figure that out myself
#13. How to get the positions where elements of two arrays match?
a = np.array([1,2,3,2,3,4,3,4,5,6])
b = np.array([7,2,10,2,7,4,9,4,9,8])
c= np.where(a==b)
c #still couldn't find the proper function
#14. Q. Get all items between 5 and 10 from a.
a = np.array([2, 6, 1, 9, 10, 3, 27])
b = np.where((a>=5) & (a<=10))
a[b]
#15. Convert the function maxx that works on two scalars, to work on two arrays.
def maxx(x, y):
"""Get the maximum of two items"""
if x >= y:
return x
else:
return y
pair_max = np.vectorize (maxx, otypes=[float])
a = np.array([5, 7, 9, 8, 6, 4, 5])
b = np.array([6, 3, 4, 8, 9, 7, 1])
pair_max(a,b)
#16. Swap columns 1 and 2 in the array arr
arr = np.arange(9).reshape(3,3)
arr
arr[:, (1,0,2)]
#17. Swap rows 1 and 2 in the array arr
arr = np.arange(9).reshape(3,3)
arr[(1,0,2),:]
#18. Reverse the rows of a 2D array arr
arr = np.arange(9).reshape(3,3)
arr[(2,1,0),:]#my solution
arr[::-1]#their solution
#19. Reverse the columns of a 2D array arr.
arr[:,(2,1,0)] #my solution
arr[:, ::-1] #their solution
#20. Create a 2D array of shape 5x3 to contain random decimal numbers between 5 and 10
rand_arr = np.random.randint(low=5, high=10, size=(5,3)) + np.random.random((5,3)) |
8fc8598e20b8dc322be8b8dedc8f9134b31de25a | oratun/Py-LeetCode | /rotate_48.py | 1,011 | 3.84375 | 4 | """
48 旋转数组
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
变换过程:
matrix[i][j] -> matrix[j][n-1-i]
matrix[j][n-1-i] -> matrix[n-1-i][n-1-j]
matrix[n-1-i][n-1-j] -> matrix[n-1-j][i]
matrix[n-1-j][i] -> matrix[i][j]
"""
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
if n % 2 == 0:
m = k = n // 2
else:
m = (n + 1) // 2
k = (n - 1) // 2
for i in range(m):
for j in range(k):
tmp = matrix[i][j]
matrix[i][j] = matrix[n - 1 - j][i]
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]
matrix[j][n - 1 - i] = tmp
if __name__ == '__main__':
s = Solution()
ma = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
s.rotate(ma)
print(ma)
|
3a2ab445be28e3da8491cc57473ba43252435d4a | ravisjoshi/python_snippets | /Strings/LongestUncommonSubsequenceI.py | 1,496 | 4.21875 | 4 | """
Given two strings, you need to find the longest uncommon subsequence of this two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other string.
A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.
The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.
Input: a = "aba", b = "cdc" / Output: 3
Explanation: The longest uncommon subsequence is "aba",
because "aba" is a subsequence of "aba",
but not a subsequence of the other string "cdc".
Note that "cdc" can be also a longest uncommon subsequence.
Input: a = "aaa", b = "bbb" / Output: 3
Input: a = "aaa", b = "aaa" / Output: -1
Constraints:
Both strings' lengths will be between [1 - 100].
Only letters from a ~ z will appear in input strings.
"""
class Solution:
def findLUSlength(self, strA, strB):
if strA == strB:
return -1
elif len(strA) == len(strB):
return len(strA)
return len(strA) if len(strA) > len(strB) else len(strB)
if __name__ == '__main__':
s = Solution()
strA = "aaa"
strB = "bbb"
print(s.findLUSlength(strA, strB))
|
9a1951007bd2fbc1c6654b51947a2ed0d951c5f4 | AveryHuo/PeefyLeetCode | /src/Python/701-800/746.MinCostClimbingStairs.py | 601 | 3.671875 | 4 |
class Solution:
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
p_2, p_1 = cost[0], cost[1]
for c in cost[2:]:
p_2, p_1 = p_1, min(p_1 + c, p_2 + c)
return min(p_2, p_1)
if __name__ == '__main__':
solution = Solution()
print(solution.minCostClimbingStairs([10, 15, 20]))
print(solution.minCostClimbingStairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]))
print(solution.minCostClimbingStairs([10, 15, 20, 10]))
print(solution.minCostClimbingStairs([0, 1, 2, 2]))
else:
pass
|
b281e50c15c0924adf57f766175f4865f44ad76a | FrancescoPenasa/UNITN-CS-2018-Intro2MachineLearning | /exercise/exercise1.py | 1,007 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 08:59:26 2019
@author: francesco
"""
# EXERCISE 1:
#Given a list of integers, without using any package or built-in function, compute and print:
# - mean of the list
# - number of negative and positive numbers in the list
# - two lists that contain positives and negatives in the original list
input = [-2,2,-3,3,10]
# - mean of the list
tot = 0;
for n in input:
tot += n
print("Mean = ", tot/len(input))
# - number of negative and positive numbers in the list
positive = negative = 0
for n in input:
if n >= 0:
positive += 1
else:
negative += 1
print("Positive numbers: ", positive)
print("Negative numbers: ", negative)
# - two lists that contain positives and negatives in the original list
positive = []
negative = []
for n in input:
if n >= 0:
positive.append(n)
else:
negative.append(n)
print("positive list: ", positive)
print("negative list: ", negative) |
d1d434292e892e72863a15da07423d262e15fd0f | BLACKGOATGG/python | /basic-knowledge/py_7_类及类模块/class:使用类和实例.py | 3,347 | 4.0625 | 4 | # ===========================================================
print('\n使用类和实例')
# 可以使用类来模拟现实世界中的很多情景。
# 类编写好后,你的大部分时间都将花在使用根据类创建的实例上。
# 你需要执行的一个重要任务是修改实例的属性。
# 你可以直接修改实例的属性,也可以编写方法以特定的方式进行修改。
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
"""
将里程表读数设置为指定的值
禁止将里程表读数往回调
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""
将里程表读数增加指定的量
禁止将里程表读数往回调
"""
if miles >= 0:
self.odometer_reading += miles
else:
print("You can't roll back an odometer!")
my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
print('\n给属性指定默认值')
# 类中的每个属性都必须有初始值,哪怕这个值是0或空字符串。
# 在有些情况下,如设置默认值时,在方法__init__()内指定这种初始值是可行的;
# 如果你对某个属性这样做了,就无需包含为它提供初始值的形参。
my_new_car.read_odometer()
print('\n修改属性的值')
# 可以以三种不同的方式修改属性的值:
# 直接通过实例进行修改;
# 通过方法进行设置;
# 通过方法进行递增(增加特定的值)。
print('\n1. 直接修改属性的值')
# 1. 直接修改属性的值
# 要修改属性的值,最简单的方式是通过实例直接访问它。下面的代码直接将里程表读数设置为23:
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
# 有时候需要像这样直接访问属性,但其他时候需要编写对属性进行更新的方法。
print('\n2. 通过方法修改属性的值')
# 2. 通过方法修改属性的值
# 如果有替你更新属性的方法,将大有裨益。这样,你就无需直接访问属性,而可将值传递给一个方法,由它在内部进行更新。
my_new_car.update_odometer(25)
my_new_car.read_odometer()
my_new_car.update_odometer(23)
my_new_car.read_odometer()
print('\n3. 通过方法对属性的值进行递增')
# 3. 通过方法对属性的值进行递增
# 有时候需要将属性值递增特定的量,而不是将其设置为全新的值。
my_new_car.increment_odometer(1)
my_new_car.read_odometer()
my_new_car.increment_odometer(3)
my_new_car.read_odometer()
my_new_car.increment_odometer(-1)
my_new_car.read_odometer()
|
7d407755c4c92cc788ec1098f1217f4881af146e | zaXai558/CodeForces_Easy | /codeforces/Team.py | 148 | 3.59375 | 4 | n=int(input())
num=0
while(n!=0):
n-=1
k=input()
if(k.count('1')>=2):
num+=1
print(num)
|
9455b284047330f32a659d3ab45dade636135c5a | Maxim-Kazliakouski/Python_tasks | /Programmers_names.py | 649 | 4 | 4 | num = 0
while num != 1001:
num = int(input("Введите новое число программистов: "))
if (num % 10 == 0) or (5 <= num % 10 <= 9) \
or num == 11 or num == 12 or num == 13 or num == 14 \
or num % 100 == 11 or num % 100 == 12 or num % 100 == 13 or num % 100 == 14:
print(num, "программистов")
elif 2 <= num % 10 <= 4:
print(num, "программиста")
elif num % 10 == 1:
print(num, "программист")
if num == 1001:
print("Вы ввели максимальное количество программистов!") |
65ef7708db1ca5337651df3d75ef8ee249e6a62c | Kristof95/LearnPythonTheHardway | /ex36.py | 990 | 3.953125 | 4 | def story():
print("Welcome AHYA!")
print("""Your name is AHYA
You're a warrior, in a merciless world
your purpose is protect your village
from the trolls, if you want to
make an end of trolls attack,
you must kill them.""")
def fight():
begin = input("Do you want to kill some trolls?:")
if begin.lower() == "y":
attack_form()
elif begin.lower() == "n":
print("A real fighter never give up!")
noob()
else:
quit()
def attack_form():
attack = input("Which fight form will you choose assa or curse?")
if attack == "assa":
print("The trolls dead.")
congratulation()
elif attack == "curse":
print("The curse is add more strength to the trolls, you died.")
noob()
else:
quit()
def congratulation():
print("You completed your purpose Congrat!! You're a real fighter!")
def noob():
print("do harakiri yourself you're not a real fighter you're a bunny!")
story()
fight()
|
69218353bd392839439d6084fed19cfedd4b57b0 | cristinasofia/coding-practice | /graphs/python/bfs/word-ladder.py | 1,043 | 3.53125 | 4 | def ladderLength(beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
import string
q = [[beginWord,1]]
while q:
w, l = q.pop(0)
if w == endWord:
return l
for i in range(len(w)):
for c in string.ascii_lowercase:
x = w[:i] + c + w[i+1:]
if x in wordList:
wordList.remove(x)
q.append([x, l + 1])
return 0
def ladderLength_optimized(beginWord, endWord, wordList):
chars = set(w for word in wordList for w in word)
q = [[beginWord,1]]
while q:
w, l = q.pop(0)
if w == endWord:
return l
for i in range(len(w)):
for c in chars:
x = w[:i] + c + w[i+1:]
if x in wordList:
wordList.remove(x)
q.append([x, l + 1])
return 0 |
e94d78ed9fbfa89018541fb7477076bd4d906035 | CPE202-PAR/project-1-enzosison | /perm_lex.py | 499 | 3.78125 | 4 | # string -> List of strings
# Returns list of permutations for input string
# e.g. 'ab' -> ['ab', 'ba']; 'a' -> ['a']; '' -> []
def perm_gen_lex(str_in):
list = []
if not str_in:
return []
if len(str_in) == 1:
return [str_in]
for i in range(len(str_in)):
new_string = str_in.replace(str_in[i], '')
permutation = perm_gen_lex(new_string)
for letter in permutation:
list.append(str_in[i] + letter)
return list
|
c014d57f3e5d7fb5e83032c0f0295e179594d5ae | Lok-Aravind-Palu/python-practice | /Practice/AbstractExample.py | 365 | 3.796875 | 4 | from abc import ABC, abstractmethod
class ExampleAbstractMethod(ABC):
@abstractmethod
def move(self):
print("Can walk and run....")
class ExampleImportAbstractMethod(ExampleAbstractMethod):
def move(self):
print("can crawl")
def main():
a = ExampleImportAbstractMethod()
a.move()
if __name__ == '__main__':
main()
|
50972ff56a9607b3d72b9c526c20a03fe7b9d55b | gu9/testpython- | /pg01_gu9.py | 11,816 | 3.578125 | 4 | import time
#ASSIGNMENT Submitted by Gurpreet Singh(1446185-Student_id)
#provide Numeric input in the timeout varible otherwise program will not give required output
#I have written this whole code by myself so there will be no external refrence link except python.org , stackoverflow.com and class notes
#I am using class because I used to do C++ prgramming and i am familiar with the classes and the usage of user defined objects
class IPac(object):
counter=0 #init(constructor) function is predefined function in Python which is called implicitly by the interpreter.
def __init__(self): #self is similar to this-> object in java ,it is use to intialize the attributes of the class
i=raw_input("<HOST_ID>:")
self.pcname=i
i=raw_input("<MAC ADDR>:") #pcname,mac,ip,timeout are the attributes of the class IPac which will be unique for the each instance
self.mac=i
i=raw_input("<ip addr>:")
self.ip=i
i=raw_input("<time_out>:")
self.timeout=i
class res_address(object): #This class provide funcationality to do resolve address in the ARP
def __init__(self,k,t):
self.pcSource=k
self.macResolve=''
self.ipResolve=t
self.timeCache=time.time()
def cache_search(self,p,hid,ipaddress):
#if input ip does not exit
if check_ip(p,ipaddress)==0:
print(hid,'could not resolve ',ipaddress)
return 0
else:
for i in xrange(len(p)):
if p[i].ip == self.ipResolve: #resolve the address by storing the mac in the host
self.macResolve=p[i].mac
return
#print'ARP response',p[i].mac,check_mac(p,hid),ipaddress
def arpsend(p,name,tip):
for j in xrange(len(p)):
if p[j].pcname==name:
temp_mac=p[j].mac
temp_ip=p[j].ip
print 'ARP request',p[j].mac,'FF:FF:FF:FF:FF:FF',p[j].ip,tip
def arpresponse(p,hid,ipaddress,c):
for i in range(len(p)):
if p[i].ip == ipaddress:
print'ARP response',p[i].mac,check_mac(p,hid),ipaddress,check_host_ip(p,hid)
def print_out(p):
for k in range(len(p)):
print p[k].pcSource,p[k].timeCache
def print_out_cach(p):
os.system("clear")
print "We are inside print"
check=raw_input('Enter HOST_ID:')
for k in range(len(p)):
if check == p[k].pcSource:
print p[k].pcSource,p[k].macResolve,p[k].ipResolve
def dup_check(p,ptemp,c):
message='FF:FF:FF:FF:FF:FF' #Duplicate check function if condition is true than the ipList[] will be updated
for i in range(len(p)):
if p[i].pcname==ptemp.pcname:
print "hostname in List updated"
p[i].mac=ptemp.mac
p[i].ip=ptemp.ip
p[i].timeout=ptemp.timeout
print 'ARP request',p[i].mac,message,p[i].ip,p[i].ip
return 9
def print_connected(p,c): #ip_conflit and gratious ARP request
message='FF:FF:FF:FF:FF:FF'
print p[c].pcname,'Connected \n'
print 'ARP request',p[c].mac,message,p[c].ip,p[c].ip
for i in range(len(p)):
if p[c].ip==p[i].ip and p[c].pcname!=p[i].pcname:
print "\nARP Reply",p[c].mac, p[c].ip,p[c].ip, "\n"
print "\nError:Host detected IP Conflit",p[count].pcname , "has been disconnected.\n"
p.pop()
return 1
return 0
def check_pc(p,check):
for k in range(len(p)): #return the pc name
if check == p[k].pcname:
return 1
return 0
def check_ip(p,check):
#return the ip of the host
for k in range(len(p)):
if check == p[k].ip:
return 1
return 0
def check_entry(c,check_host,check_addr):
for k in range(len(c)):
if check_host == c[k].pcSource and check_addr==c[k].ipResolve:
return c[k].timeCache
return 0
def check_pos(p,hostaddr):
for i in xrange(len(p)):
if p[i].ip==hostaddr:
return p[i].pcname
return 0
def check_mac(p,hostaddr):
for i in xrange(len(p)):
if p[i].pcname==hostaddr:
return p[i].mac
return 0
def check_host_ip(p,phost):
for i in xrange(len(p)):
if p[i].pcname==phost:
return p[i].ip
return 0
def check_tabel(plist,recdata,hostn,c,ipaddress):
for i in range(len(plist)): #if cache has the entries than message will be printed resolved other wise ARP expires
if hostn == plist[i].pcname:
orignal= plist[i].timeout
break
curtime=time.time()
time.sleep(1)
xd=curtime-recdata
if float(orignal)>xd:
for k in range(len(c)):
if hostn == c[k].pcSource and ipaddress==c[k].ipResolve:
print hostn,'Resolved ',ipaddress,'to',c[k].macResolve
c[k].timeCache=curtime
#print'\nUpdated'
else:
print('ARP expires for this')
for o in range(len(c)):
if hostn == c[o].pcSource and ipaddress==c[o].ipResolve:
c.remove(c[o])
break
def print_pro(hostnam,p,c): #print entries in the cache or show no entries message and Unknown Pc
#than remove the old cache entries
flag=0
if len(c)==0 :
print'NO entries'
return 0
for i in xrange(len(p)):
if hostnam==p[i].pcname:
orignal=p[i].timeout
break
curtime=time.time()
try:
for i in range(len(c)):
if hostnam==c[i].pcSource:
flag=1
recdata=c[i].timeCache
xd=0
xd=curtime-recdata
if float(orignal)>xd:
print c[i].macResolve,c[i].ipResolve,'(',float(orignal)-xd,'seconds)'
else:
print('ARP expires')
for o in range(len(c)):
if hostnam ==c[o].pcSource:
print 'Deleting cache entry',c[i].macResolve,c[i].ipResolve
c.remove(c[i])
break
except:print'\n'
if flag==0:
print'no entry'
def check_tab(pList,ip_h,c,ipaddr): #printing the resolved message by retriving from the cache entries
for k in range(len(c)):
if ip_h == c[k].pcSource and ipaddr==c[k].ipResolve:
print ip_h,'Resolved ',ipaddr,'to',c[k].macResolve
def ip_conflit(p,c):
for i in range(len(p)):
if p[c].ip==p[i].ip:
print "\nARP Reply", p[c].pcname,p[c].mac, p[c].ip,p[c].ip, "\n"
print "\nHost",p[count].pcname , "has been disconnected.\n"
p.pop()
return 1
return 0
ipList = []
cache_items=[]
count=0
#Taking the run time input from user and match according to the variable data
data=raw_input('WELCOME TO ARP SIMULATOR v1.0 ENTER THE Commands\nconfig\nresolve\nprint\nquit\n')
while data!='quit':
if data=='config':
#append the host in ipList and cache values in cache_items list
if count==0:
ipList.append(IPac()) #calling the init function implicitly by the class and appending to the list
print_connected(ipList,count)
count=count+1
else:
d=IPac()
#checking for duplicates and the ip conflit
if dup_check(ipList,d,cache_items)!=9:
ipList.append(d)
z=print_connected(ipList,count)
count=count+1-z
elif data=='print':
jput=raw_input('<Host_ID>:')
#print_out_cach(cache_items)
if len(cache_items)==0:
print'Cache Empty'
#print_out(cache_items)
elif check_pc(ipList,jput)!=0: #after host resolved the entries can be check by running the print command
t=print_pro(jput,ipList,cache_items)
else:
print'Error:unknown pc',jput
elif data=='resolve':
ip_host=raw_input("Host_ID:") #user input for ARP
#storing value for RARP(reverse ARP)
ip_addr=raw_input("<ip addr>:")
rhostname=check_pos(ipList,ip_addr)
rhostip=check_host_ip(ipList,ip_host)
check_val=check_pc(ipList,ip_host)
#ck_ip=check_ip(ipList,ip_addr)
if(check_val==0):
print('Error: Unknown Host',ip_host)
#checking PC name in the ipList
rectime=check_entry(cache_items,ip_host,ip_addr)
rectime2=check_entry(cache_items,rhostname,rhostip) #retriving the cache time
if rectime!=0 :
z=ctable=check_tabel(ipList,rectime,ip_host,cache_items,ip_addr)
#if rectime2!=0:
# print '\nUpdate table ARP (peers)'
# z=ctable=check_tabel(ipList,rectime2,rhostname,cache_items,rhostip)
#print 'Entry found\n',rectime #Entry found in the cache and ARP has been resolved for both ARP and RARP time will be updated on the peers
#if z>=0:
# cache_items.pop(z)
#if rectime2!=0:
# z=ctable=check_tabel(ipList,rectime2,rhostname,cache_items,rhostip)
# if z>=0:
# cache_items.pop(z)
else:
if check_val!=0 :
arpsend(ipList,ip_host,ip_addr) #ARP send function
pksend=res_address(ip_host,ip_addr)
pkrecv=res_address(rhostname,rhostip)
check_r=pksend.cache_search(ipList,ip_host,ip_addr)
arpresponse(ipList,ip_host,ip_addr,cache_items) #ARP response function
check_rec=pkrecv.cache_search(ipList,rhostname,rhostip)
if check_r!=0:
cache_items.append(pksend) #if entry is not in the cache than append the cache_items
check_tab(ipList,ip_host,cache_items,ip_addr)
if check_rec!=0:
cache_items.append(pkrecv)
data=raw_input('\nconfig\nresolve\nprint\nquit\nEnter Your Choice:')
|
d93ad9834f32f1cb3878d2983722d3822b930aca | omrigo13/Intro | /hw6/hw6_ques1.py | 2,092 | 3.75 | 4 | # *************** EXERCISE 6 ***************
# **************************************************************
# ************************ QUESTION 1 **************************
def partition(lst,values_lst,count_liora = 0, count_yossi = 0, mem = {}):
"""
gets a list of building prices to divide between Liora and Yossi
:param list lst: list of buildings prices to divide between liora and yossi
:param tuple values_lst: first cell represents the value liora should get
and second cell represents the value yossi should get
:param int count_liora: counts how much buildings goes to liora
:param int count_yossi: counts how much buildings goes to yossi
:param dict mem: memorization dictonary to save lists for better recursion
:return: a list of Liora and Yossi names in order of buildings prices each
one should get
:rtype: list
"""
if len(lst) == 1:
if values_lst[0] == 0:#base case
current_owner = "Yossi"
else:
current_owner = "Liora"
if not(0 in values_lst and lst[0] in values_lst):#base case
return []
elif count_yossi < 2 and current_owner != "Yossi":#base case
return []
elif count_liora <2 and current_owner != "Liora":#base case
return []
else:
if values_lst[0] == 0:#base case
return ["Yossi"]
else:
return ["Liora"]
key = (values_lst, count_liora, count_yossi)#memorization
if key not in mem:
if values_lst[0] >= lst[0]:
give_Liora = partition(lst[1:], (values_lst[0] - lst[0], values_lst[1]), count_liora+1,count_yossi, mem)#recursive call
if give_Liora:
mem[key] = ["Liora"] + give_Liora
return mem[key]
if values_lst[1] >= lst[0]:
give_Yosi = partition(lst[1:], (values_lst[0],values_lst[1] - lst[0]), count_liora,count_yossi+1, mem)#recursive call
if give_Yosi:
mem[key] = ["Yossi"] + give_Yosi
return mem[key]
return [] |
99b5c382820df7f9207d46408a4b171fb24d2f4b | liangyf22/test | /01_函数/递归函数.py | 719 | 3.859375 | 4 | '''
1、函数里调用函数本身
2、有递归边界
通过递归函数实现任意数的阶乘
'''
import json
def js(num):
if num == 1:
return 1
else:
return num * js(num - 1)
print(js(3))
# 斐波那契数列
# 斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13,特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。
def fbnq(n):
if n == 1:
return 0
elif (n == 2 or n == 3):
return 1
else:
return fbnq(n - 1) + fbnq(n - 2)
res = fbnq(7)
print(res)
def fib_loop_for(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib_loop_for(6)) |
14bf166c43a1d423aa1cb630ae934c21f1182010 | wangkangreg/LearnPython | /src/tuple/dict_sort.py | 483 | 4.21875 | 4 | # -*- coding:utf-8 -*-
'''
Created on 2015年11月6日
@author: Administrator
'''
dict = {'a':'apple', 'b':'banana', 'c':'orange', 'd':'banana'}
print dict #{'a': 'apple', 'c': 'orange', 'b': 'banana', 'd': 'banana'}
#按key排序
print sorted(dict.items(), key=lambda d: d[0]) #[('a', 'apple'), ('b', 'banana'), ('c', 'orange'), ('d', 'banana')]
#按value排序
print sorted(dict.items(), key = lambda d: d[1]) #[('a', 'apple'), ('b', 'banana'), ('d', 'banana'), ('c', 'orange')] |
1a837bc9795ecf80d983728bb22188f464160a31 | doronweiss/pythontesta | /AirTouch/SunCalc.py | 762 | 3.796875 | 4 | import math
from math import *
import plotly.express as px
import numpy as np
import matplotlib.pyplot as plt
# https://www.pveducation.org/pvcdrom/properties-of-sunlight/elevation-angle
# https://www.pveducation.org/pvcdrom/properties-of-sunlight/declination-angle
latitude = radians(31.240239)
longitude = radians(34.454592)
earthTilt = radians(23.45)
#HRA = radians(-90.0)
dayOfYear = 90
# calc
def calcAngle (HRA):
currDeclination = -earthTilt * cos(360.0/365.0 * (dayOfYear+10.0))
aux = sin(currDeclination)*sin(latitude) + cos(currDeclination)*cos(latitude)*cos(HRA)
return asin(aux)
hours=range(25)
angles = [degrees(calcAngle(radians(15*h))) for h in hours]
fig = px.line(x=hours, y=angles, title='Sun angle through the day')
fig.show()
|
1653d80773e66a6a61a2adaac0a57c0592ce1c3d | JerrodTanner/negative-strip-colorizer | /hw01_tanner.py | 4,178 | 3.578125 | 4 | '''
Author: Jerrod Tanner
Date: 20 February 2020
'''
import numpy as np
import cv2
import matplotlib.pyplot as plt
import sys
xTranslation = 0
yTranslation = 0
def translate(I, x, y):
''' Translate the given image by the given offset in the x and y directions.
'''
rows, cols = I.shape[:2]
M = np.array([[1, 0, x],
[0, 1, -y]], np.float)
img_translated = cv2.warpAffine(I, M, (cols, rows))
return img_translated
def compute_ssd(I1, I2):
''' Compute the sum-of-squared differences between two images.
Find the difference between the images (subtract), square the difference,
and then sum up the squared differences over all the pixels. This should
require no explicit loops. Potentially helpful method: np.sum().
Think carefully about math and data types.
'''
I1 = I1.astype(np.float)
I2 = I2.astype(np.float)
rows, cols = I1.shape[:2]
return np.sum((I1[2*rows//10:8*rows//10,2*cols//10:8*cols//10]-I2[2*rows//10:8*rows//10,2*cols//10:8*cols//10])**2,dtype= np.float)
def align_images(I1, I2):
''' Compute the best offset to align the second image with the first.
Loop over a range of offset values in the x and y directions. (Use nested
for loops.) For each possible (x, y) offset, translate the second image
and then check to see how well it lines up with the first image using the
SSD.
Return the aligned second image.
'''
first_diff = sys.maxsize
x = 0
y = 0
rows, cols = I2.shape[:2]
rows = int((rows//5)/2)
cols = int((cols//5)/2)
for i in range(-rows,rows):
for j in range(-cols,cols):
im = translate(I2, i, j)
#plt.imshow(cv2.cvtColor(im, cv2.COLOR_GRAY2RGB))
#plt.show()
if compute_ssd(I1,im) <= first_diff:
first_diff = compute_ssd(I1,im)
x = i
# print("x = ")
# print(x)
y = j
# print("y = ")
# print(y)
# print("________________")
#print("done")
global xTranslation
global yTranslation
if(abs(x) > abs(xTranslation)):
xTranslation = x
if(abs(y) > abs(yTranslation)):
yTranslation = y
new_img = translate(I2, x, y)
return new_img
# --------------------------------------------------------------------------
# this is the image to be processed
image_name = 'tobolsk.jpg'
img = cv2.imread(image_name)
def convert_gray(img): #this function convert an image to grayscale in order to make make the picel matrix two dimensional
new_img = img.astype(np.float)
b,g,r = cv2.split(new_img)
b = b*.07
g = g*.72
r = r*.21
grey = b+g+r
grey = grey.astype(np.uint8)
return grey
def crop(img): #this function crops an images based off of the larges absolute value translations x and y
rows, cols = img.shape[:2]
cropped = img[abs(yTranslation)+15:rows-15,abs(xTranslation)+25:cols-25]
return cropped
def colorize_image(imageName): #this function converts an image to grey, cuts it into 1/3s, assignes each to be an r, g, or b value,
#aligns r and g to b using the align images function, then merges them back together
img_grey = convert_gray(img)
rows, cols = img_grey.shape[:2]
b,g,r = img_grey[0:rows//3,0:cols], img_grey[rows//3:2*rows//3,0:cols], img_grey[2*rows//3:rows,0:cols]
rows, cols = b.shape[:2]
g = g[:rows,:cols]
r = r[:rows,:cols]
unaligned = cv2.merge((r,g,b))
g = align_images(b,g)
gAligned = cv2.merge((r,g,b))
r = align_images(b,r)
color_img = cv2.merge((r,g,b))
plt.imshow(unaligned)
plt.show()
plt.imshow(gAligned)
plt.show()
plt.imshow(color_img)
plt.show()
return color_img
cleaned = crop(colorize_image(img))
plt.imshow(cleaned)
plt.show()
new = cv2.cvtColor(cleaned, cv2.COLOR_RGB2BGR)
cv2.imwrite('colored_image.jpg',new)
|
5d52f6e0064d514e1663d27fffad0dbc8d468620 | bkz7354/python_sem4 | /HW_1/task1.py | 1,248 | 3.953125 | 4 | #!/usr/bin/env python3
class Human:
default_name = "Aaron"
default_age = 40
def __init__(self, name=default_name, age=default_age):
self.name = name
self.age = age
self.__money = 0
self.__house = None
def info(self):
return self.name, self.age, self.__money, self.__house
@staticmethod
def default_info():
return Human.default_name, Human.default_age
def __make_deal(self, house, price):
self.__money -= price
self.__house = house
def earn_money(self):
self.__money += 10
def buy_house(self, house, discount):
if house.final_price(discount) > self.__money:
print("Insufficient money")
else:
self.__make_deal(house, house.final_price(discount))
class House:
def __init__(self, area, price):
self._area = area
self._price = price
def final_price(self, discount):
return self._price*(1 - discount/100)
class SmallHouse(House):
def __init__(self, price):
super().__init__(40, price)
print(Human.default_info())
A = Human("Jack", 20)
print(A.info())
sh = SmallHouse(5)
A.buy_house(sh, 0)
A.earn_money()
A.buy_house(sh, 10)
print(A.info())
|
6ba324b43d767a32fb32b6e60b14138838ff7478 | v1ktos/Python_RTU_08_20 | /Diena_6_lists/lists_g2.py | 2,537 | 3.671875 | 4 | # a1 = 5
# a2 = 6
# a3 = 7
my_list = [5, 6, 7]
print(my_list)
my_list[0]
gen_list = my_list + ["Valdis", "Līga", True, 3.14]
print(gen_list)
print(min(my_list), max(my_list))
sum(my_list)
sum(gen_list)
gen_list
gen_list[:3]
gen_list[-3:]
gen_list
gen_list[1::2]
gen_list[1:4:2]
gen_list[::-1]
6 in gen_list
8 in gen_list
"Valdis" in gen_list
"al" in gen_list
needle = "al"
for item in gen_list:
if type(item) == str and needle in item:
print(f"Found {needle=} in {item=}")
gen_list.append("alus") # in-place modifies gen_list
gen_list
gen_list += "kalējs" # this will be a bit surprising result
gen_list.index("k")
gen_list = gen_list[:8]
# out of place meaning we need to assign to some variable
gen_list += ["kalējs"] # gen_list = gen_list + ['kalējs']
gen_list
find_list = []
for item in gen_list:
if type(item) == str and needle in item:
print(f"Found {needle=} in {item=}")
find_list.append(item)
print(find_list)
# above could be done with list comprehensions a little simpler
len(gen_list), len(find_list)
find_list[-1]
last_one = find_list.pop() # in place deletes last item
last_one
find_list
numbers = [1, 4, -5, 3.16, 10, 9000, 5]
sorted_num_asc = sorted(numbers) # out of place does not modify
sorted_num_asc
sorted_num_desc = sorted(numbers, reverse=True)
sorted_num_desc # of course we could have done sorted_number_asc[::-1]
numbers.sort() # in place modifies numbers
numbers
numbers.remove(10) # find first element containing 10!!
numbers
min(numbers), max(numbers), sum(numbers)
# how to find 2nd largest
numbers = [1, 4, -5, 3.16, 10, 9000, 5]
sorted(numbers)[-2]
numbers[-2]
total = 0
for n in numbers:
total += n
print(total)
print(sum(numbers))
sentence = "Quick brown fox jumped over a sleeping dog"
word_list = sentence.split() # by default splits on whitespace
word_list
# lists are mutable unlike strings!
word_list[2] = "bear"
word_list
new_sentence = " ".join(word_list) # crucial that we are joining all strings
new_sentence
food = "kartupelis"
letters = list(food)
letters
letters[5] = "M"
letters
# new_food = " :X: ".join(letters)
new_food = "".join(letters)
new_food
numbers = list(range(10))
numbers
squares = []
for n in numbers:
squares.append(n**2)
squares
# list comprehension to replace above code
squares_2 = [n**2 for n in numbers]
squares_2
char_codes = [ord(c) for c in food]
char_codes
char_codes_list = [[c, ord(c)] for c in food]
char_codes_list
char_codes_list[0]
char_codes_list[0][0]
char_codes_list[-1]
char_codes_list[-1][-1]
|
85273bf25f97a8620b33dcb00a660fcec4fd142f | CodeForContribute/Algos-DataStructures | /DP/matrixChainOrder.py | 1,275 | 4.1875 | 4 | """
Problem Statement
=================
Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We
need to write a function matrix_chain_order() that should return the minimum number of multiplications needed to
multiply the chain.
Video
-----
* https://youtu.be/vgLJZMUfnsU
Note
----
In the code below we give matrices length as an array and each matrix takes 2 indices from the array.
For e.g. {2, 3, 4} represents two matrices (2, 3) and (3, 4) in (row, col) format.
Complexity
----------
Time Complexity: O(n^3)
Reference
---------
* http://www.geeksforgeeks.org/dynamic-programming-set-8-matrix-chain-multiplication/
"""
def matrix_chain_multiplication(matrices):
matrices_length = len(matrices)
dp = [[0] for _ in range(matrices_length) for _ in range(matrices_length)]
for gap in range(2, matrices_length):
for i in range(0, matrices_length - gap):
j = i + gap
dp[i][j] = 1000
for k in range(i + 1, j):
temp = dp[i][k] + dp[k][j] + matrices[i] * matrices[k] * matrices[j]
if temp < dp[i][j]:
dp[i][j] = temp
return dp[0][-1]
if __name__ == '__main__':
matrices = [4, 2, 3, 5, 3]
|
39f466dd693667723a126509177a4871f35bd9fe | RainEnigma/Final_project-ITEA | /contact_book/main_functional/main.py | 1,153 | 3.90625 | 4 | import file_operstions, input_contact,finding_contact
import CONSTANCE
def main():
while True:
print()
inputed_letter = input("-=Please type what you want to do with your adressbook?=-\n"
"a - add a user\n"
"c - close\n"
"f - find user\n"
"s - show all contact book:\n"
)
if inputed_letter.lower() == "s":
reading_file = file_operstions.File.read_file(None)
for iterat in reading_file:
print("\n")
for key, value in dict(iterat).items():
print(f"{key} - {value}")
elif inputed_letter.lower() == "a":
input_contact.add_contact(CONSTANCE.file_name, CONSTANCE.file_extention)
elif inputed_letter.lower() == "f":
finding_contact.finding_obj(input("Please print what to search: "))
elif inputed_letter.lower() == "c":
print("!!!BYE!!!")
break
else:
print("wrong letter, please try again!\n")
main()
|
0e2354791d7115ea89589234f2f2b9c5ec50aeca | TyrannousHail03/PythonProjects | /DiceRollingGame.py | 1,083 | 4.34375 | 4 | '''This program rolls a pair of dice and asks the user to guess the sum of the dice. If the user guesses correctly, they
win. his program was initially written during my run through of CodeAcademy's Python course.'''
from random import randint
from time import sleep
def get_user_guess():
guess = int(input("What is your guess?"))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print("Maximum Value: %d" % max_val)
guess = get_user_guess()
if guess > max_val:
print("Sorry, that number is too high.")
else:
print("Rolling... ")
sleep(2)
print("1st Roll: %d" % first_roll)
sleep(1)
print("2nd Roll: %d" % second_roll)
total_roll = first_roll + second_roll
print("Total Roll: %d" % total_roll)
sleep(1)
if guess == total_roll:
print("Congratulations, you've won!")
else:
print("Sorry, you have lost.")
roll_dice(6)
|
bacaf5bce0f805d33fc4754a7c03c0e7735a62f9 | moon729/PythonAlgorithm | /2.배열/max_of_test_randint.py | 455 | 3.84375 | 4 | #배열 원소의 최댓값을 구해서 출력하기(원솟값을 난수로 생성)
import random
from max import max_of
print('난수의 최댓값 구하기')
num = int(input('난수의 개수 입력 : ' ))
min = int(input('난수의 최솟값 입력 : ' ))
max = int(input('난수의 최댓값 입력 : ' ))
x = [None] * num
for i in range(num):
x[i] = random.randint(min, max)
print(f'{x}')
print(f'배열에서 최댓값은 {max_of(x)}임')
|
b342f84f9a2bb44e8d8ffb00e6330024956c8a7a | Autodidact7999/Attendance-System-Using-Face-Identification | /sample.py | 2,564 | 3.71875 | 4 | import tkinter as tk
window=tk.Tk()
window.title("Face_Recogniser")
dialog_title = 'QUIT'
dialog_text = 'Are you sure?'
# answer = messagebox.askquestion(dialog_title, dialog_text)
# window.geometry('1280x720')
window.configure(background='black')
# window.attributes('-fullscreen', True)
window.grid_rowconfigure(0, weight=1)
window.grid_columnconfigure(0, weight=1)
# path = "profile.jpg"
# Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
# img = ImageTk.PhotoImage(Image.open(path))
# The Label widget is a standard Tkinter widget used to display a text or image on the screen.
# panel = tk.Label(window, image = img)
# panel.pack(side = "left", fill = "y", expand = "no")
# cv_img = cv2.imread("img541.jpg")
# x, y, no_channels = cv_img.shape
# canvas = tk.Canvas(window, width = x, height =y)
# canvas.pack(side="left")
# photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(cv_img))
# Add a PhotoImage to the Canvas
# canvas.create_image(0, 0, image=photo, anchor=tk.NW)
# msg = Message(window, text='Hello, world!')
# Font is a tuple of (font_family, size_in_points, style_modifier_string)
message = tk.Label(window, text="Face-Recognition-Based-Attendance-Management-System" ,bg="Green" ,fg="white" ,width=50 ,height=3,font=('times', 30, 'italic bold underline'))
message.place(x=200, y=20)
lbl = tk.Label(window, text="Enter ID",width=20 ,height=2 ,fg="red" ,bg="yellow" ,font=('times', 15, ' bold ') )
lbl.place(x=400, y=200)
txt = tk.Entry(window,width=20 ,bg="yellow" ,fg="red",font=('times', 15, ' bold '))
txt.place(x=700, y=215)
lbl2 = tk.Label(window, text="Enter Name",width=20 ,fg="red" ,bg="yellow" ,height=2 ,font=('times', 15, ' bold '))
lbl2.place(x=400, y=300)
txt2 = tk.Entry(window,width=20 ,bg="yellow" ,fg="red",font=('times', 15, ' bold ') )
txt2.place(x=700, y=315)
lbl3 = tk.Label(window, text="Notification : ",width=20 ,fg="red" ,bg="yellow" ,height=2 ,font=('times', 15, ' bold underline '))
lbl3.place(x=400, y=400)
message = tk.Label(window, text="" ,bg="yellow" ,fg="red" ,width=30 ,height=2, activebackground = "yellow" ,font=('times', 15, ' bold '))
message.place(x=700, y=400)
lbl3 = tk.Label(window, text="Attendance : ",width=20 ,fg="red" ,bg="yellow" ,height=2 ,font=('times', 15, ' bold underline'))
lbl3.place(x=400, y=650)
message2 = tk.Label(window, text="" ,fg="red" ,bg="yellow",activeforeground = "green",width=30 ,height=2 ,font=('times', 15, ' bold '))
message2.place(x=700, y=650)
window.mainloop() |
b50bb8377fa39af919017d81b46de920f9e2273c | altanai/computervision | /colorspace/colorspace_rgb.py | 1,044 | 3.8125 | 4 | import cv2
image = cv2.imread('ramudroidimg.jpg')
# opencv's split function splits the image into each color index
B,G,R = cv2.split(image)
cv2.imshow("Red",R)
cv2.imshow("Green",G)
cv2.imshow("Blue",B)
# make the original image by merging the individual color components
merged = cv2.merge([B,G,R])
cv2.imshow("merged",merged)
# amplifying the blue color
mergedb = cv2.merge([B+100,G,R])
cv2.imshow("merged with blue amplify",mergedb)
# amplifying the red color
# mergedr = cv2.merge([B,G,R+100])
# cv2.imshow("merged with blue amplify",mergedr)
# amplifying the green color
# mergedg = cv2.merge([B,G+100,R])
# cv2.imshow("merged with green amplify",mergedg)
# representing the shape of individual color components.
# the output wuld be only two dimension whih wouldbe height and width, since third element of RGB component is individually represented
print("Shape of Blue color component ", B.shape)
print("Shape of Red color component ", R.shape)
print("Shape of Green color component ",G.shape)
cv2.waitKey(0)
cv2.destroyAllWindows() |
8aee25cff17263fca15fcfbe29870b79b00f70ee | mateoadann/Ej-por-semana | /Ficha 2/ejercicio2Ficha2.py | 639 | 4 | 4 | # 2. Descuento en medicinas
# Calcular el descuento y el monto a pagar por un medicamento cualquiera en una farmacia (cargar por teclado el precio de ese medicamento)
# sabiendo que todos los medicamentos tienen un descuento del 35%.
# Mostrar el precio actual, el monto del descuento y el monto final a pagar
# Dates
medicamento = float(input('¿Cual es el precio de su medicamento? '))
# Process
descuento = medicamento - (medicamento * 0.65)
precio_final = medicamento - descuento
# Results
print('Se le aplicará un descuento del 35%, que son ',descuento)
print('El precio final del producto con el descuento es de ', precio_final)
|
1a28b452ec8b00641d596b98374897d65a1b4ae2 | FalseF/Algorithms-and-Problem-Solving-with-Python | /FalsePositionMethod.py | 623 | 3.890625 | 4 | def FalsePosition(f,x1,x2,tol=1.0*10**-6,maxfpos=20):
xh = 0
fpos = 0
if f(x1) * f(x2) < 0:
for fpos in range(1,maxfpos+1):
xh = x2 - (x2-x1)/(f(x2)-f(x1)) * f(x2)
if abs(f(xh)) < tol: break
elif f(x1) * f(xh) < 0:
x2 = xh
else:
x1 = xh
else:
print("No root exists within the given interval.")
return xh,fpos
y = lambda x: x**3 + x - 1
x1 = float(input("Enter x1: "))
x2 = float(input("Enter x2: "))
r,n = FalsePosition(y,x1,x2)
print("The root = %f at %d false positions."%(r,n))
|
eabce618fad53351bf4d8557486ad4009b532939 | gabriellaec/desoft-analise-exercicios | /backup/user_282/ch23_2020_03_04_22_48_31_712702.py | 157 | 3.671875 | 4 | velocidade = int(input('qual eh a velocidade? '))
if velocidade>80:
print('multa de R${0}'.format((velocidade-80)*5))
else:
print('Não foi multado') |
6721bbc0b0db2e360b464fdb1526c983d3c327e5 | zouvier/Calculator | /TkinterCalculator.py | 4,863 | 3.828125 | 4 | # todo: [SOLVED] Create an interface for calculator
# ~used tkinter
# todo: [SOLVED] Work on multiplication function(figure out how to implement the function)
# ~ created an if/elif statement that takes in a global variable that is altered depending on the function
# ~ this allows me to keep track of which function. i.e (using button_mult func sets the attribute variable to 1
# ~ using button_sub sets the variable to 2) the attribute value is then used in the equal func (see below)
# todo: subtraction function: issue with the final output displaying a negative sign in front of the answer
# todo: [SOLVED] figure out why my global variables are not passing through to all functions.
# ~ the global variable needs to be called each time it is brought up in a function
from tkinter import *
root = Tk()
root.title("Calculator")
attribute = 0
holder2 = 0
# creates the entry box and prepares a grid to where the numbers will be placed
e = Entry(root, width=35, borderwidth=5)
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
# Buttons of the calculator
# Allows for numbers to be placed into the entry box
def button_digit(number):
current = e.get()
e.delete(0, END)
e.insert(0, str(current) + str(number))
# clear function that clears the entry box
def button_clearing():
e.delete(0, END)
def button_div():
global attribute
attribute = 3
global holder2
holder1 = int(e.get())
holder2 = holder1
e.delete(0, END)
# subtraction function
def button_sub():
global attribute
attribute = 2
global holder2
holder1 = int(e.get())
holder2 = holder1
e.delete(0, END)
# addition function
def button_add():
global attribute
attribute = 0
global holder2
holder1 = int(e.get())
holder2 = holder1
e.delete(0, END)
# multiplication function
def button_mult():
global attribute
attribute = 1
global holder2
holder1 = int(e.get())
holder2 = holder1
e.delete(0, END)
# the equal button.
def button_e():
if attribute == 0:
holder3 = int(e.get())
holder4 = int(holder3)
holder5 = holder4 + holder2
e.delete(0, END)
e.insert(0, holder5)
elif attribute == 1:
holder3 = int(e.get())
holder4 = int(holder3)
holder5 = holder4 * holder2
e.delete(0, END)
e.insert(0, holder5)
elif attribute == 2:
holder3 = int(e.get())
holder4 = int(holder3)
holder5 = holder4 - holder2
e.delete(0, END)
e.insert(0, holder5)
elif attribute == 3:
holder3 = int(e.get())
holder4 = int(holder3)
holder5 = holder4/holder2
e.delete(0, END)
e.insert(0, holder5)
# defined buttons (the numbers on the calculator)
button_1 = Button(root, text='1', padx=40, pady=20, command=lambda: button_digit(1))
button_2 = Button(root, text='2', padx=40, pady=20, command=lambda: button_digit(2))
button_3 = Button(root, text='3', padx=40, pady=20, command=lambda: button_digit(3))
button_4 = Button(root, text='4', padx=40, pady=20, command=lambda: button_digit(4))
button_5 = Button(root, text='5', padx=40, pady=20, command=lambda: button_digit(5))
button_6 = Button(root, text='6', padx=40, pady=20, command=lambda: button_digit(6))
button_7 = Button(root, text='7', padx=40, pady=20, command=lambda: button_digit(7))
button_8 = Button(root, text='8', padx=40, pady=20, command=lambda: button_digit(8))
button_9 = Button(root, text='9', padx=40, pady=20, command=lambda: button_digit(9))
button_0 = Button(root, text='0', padx=40, pady=20, command=lambda: button_digit(0))
button_addition = Button(root, text='+', padx=40, pady=20, command=button_add)
button_equal = Button(root, text='=', padx=140, pady=20, command=button_e)
button_clear = Button(root, text='Clear', padx=30, pady=20, command=button_clearing)
button_subbing = Button(root, text='-', padx=40, pady=20, command=button_sub)
button_multiply = Button(root, text='X', padx=40, pady=20, command=button_mult)
button_divide = Button(root, text='/', padx=40, pady=20, command=button_div)
# Button's being placed on the screen
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_0.grid(row=4, column=0)
button_clear.grid(row=5, column=0)
button_addition.grid(row=4, column=1)
button_subbing.grid(row=4, column=2)
button_multiply.grid(row=5, column=1)
button_divide.grid(row=5, column=2)
button_equal.grid(row=6, column=0, columnspan=3)
root.mainloop() |
12227a4840bfef6b0d127f8d2b4afca49599498e | Xnkr/py-vigilant-barnacle | /interactivepython/bubblesort.py | 464 | 3.78125 | 4 |
def bubblesort(a):
num_iter = len(a)-1
for passes in range(num_iter,0,-1):
for i in range(passes):
if a[i] > a[i+1]:
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
return a
def shortbubble(a):
exchange = True
num_iter = len(a)-1
while num_iter > 0 and exchange:
exchange = False
for i in range(num_iter):
if a[i] > a[i+1]:
a[i], a[i+1] = a[i+1], a[i]
exchange = True
num_iter -= 1
return a
print shortbubble(range(10,0,-1)) |
1f6c3c550438b9216aaa0b604fade3f6bb880883 | JDGC2002/Algoritmos-y-estructuras-de-datos | /Clases/CLASE 6-09/ejercicio4.py | 243 | 3.859375 | 4 | # convierta la siguiente frase en un diccionario:
words = "Biomédica:35-Medicina:14-Nutrición:22-Derecho:2"
words = words.replace(':', '-')
words1 = words.split('-')
print(words1)
it = iter(words1)
res_dct = dict(zip(it, it))
print(res_dct) |
0028ff8519ade12e06ef945b6439a4b36e17d851 | chevery/Project2 | /FINAL GAMES/CHARLIE.py | 12,512 | 3.5625 | 4 | #/usr/bin/python
"""
A simple game of whacking simple things with a hammer
"""
#import modules
import os, pygame
import sys
from random import choice
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GRAY80 = (26, 26, 26)
YELLOW = (255, 255, 0)
GRAY = (204, 204, 204)
screen = pygame.display.set_mode((1000, 800))
background_music = "music.wav"
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")
music_folder = os.path.join(game_folder, "music")
background_music = "wind.wav"
hitting_music = "hitsound.wav"
clock = pygame.time.Clock()
def draw_shield_bar(surf, x, y, pct):
if pct < 0:
pct = 0
BAR_LENGTH = 100
BAR_HEIGHT = 20
fill = (pct/100)* BAR_LENGTH
outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)
fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)
if pct > 70:
pygame.draw.rect(surf, GREEN, fill_rect)
elif pct > 40:
pygame.draw.rect(surf, YELLOW, fill_rect)
else:
pygame.draw.rect(surf, RED, fill_rect)
pygame.draw.rect(surf, WHITE, outline_rect, 2)
#define the classes for our game objects
class Player(pygame.sprite.Sprite):
'''controls the hammer sprite. This class is derived from the Pygame Sprite class'''
def __init__(self):
# we MUST call the Sprite init method on ourself
pygame.sprite.Sprite.__init__(self)
#load the image resource
self.image= pygame.image.load(os.path.join(img_folder, "hamerpin.png")).convert_alpha()
# get the rectangle describing the loaded image
self.rect=self.image.get_rect()
#set the transparency colour to the background of the image
self.image.set_colorkey(self.image.get_at((0, 0)), pygame.RLEACCEL)
#copy the base image into a backup for restoring
self.default=self.image
self.default_rect=self.rect
# define a flag sowe can tell what mode the hammer is in
self.whack = 0
# load a sound effect
def update(self):
'''The update method is called before redrawing the sprite each time
It's our chance to control any time-related behaviour and check status.'''
#move hammer to current mouse position
pos = pygame.mouse.get_pos()
self.rect.center = pos
#check if we are supposed to be hitting something
if self.whack:
#if so, we move the sprite a little, and rotate the image
self.rect.move_ip(8, 12)
self.image = pygame.transform.rotate(self.default, 45)
def dowhack(self, target):
"checks to see if hammer has hit a mike"
if not self.whack:
self.whack = 1
hitrect = self.rect.inflate(-50, -50)
return hitrect.colliderect(target.rect)
def reset(self):
'''put the hammer upright again and reset te flag'''
self.whack = 0
self.image=self.default
class Mike(pygame.sprite.Sprite):
"""implements a Mike"""
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image= pygame.image.load(os.path.join(img_folder, "screwpin6.png")).convert_alpha()
self.rect=self.image.get_rect()
self.image.set_colorkey(self.image.get_at((0, 0)), pygame.RLEACCEL)
self.default=self.image
self.default_rect=self.rect
# timer of 0 is default and means the Mike is not visible
self.timer=0
# if whacked = 0 it means nobody has hit this Mike
self.whacked=0
# a list of the possible locations for Mike to pop up at
self.locations=[(88, 430), (733, 570), (733, 430), (88, 430), (733, 230), (88, 230), (733, 570), (270, 590), (733, 570), (733, 430), (88, 430), (560, 590), (88, 230), (270, 590), (733, 430), (560, 590), (88, 230), (410, 590), (560, 590), (410, 590)]
def appear(self):
'''pops out of hole'''
# set the timer
#if you change this value, you will also have to alter the update method
self.timer=80
#use the Randome.choice() function to select a location from the list
self.loc=choice(self.locations)
def update(self):
'''run housekeeping'''
#check to see that a Mike should be on te screen
if self.timer:
# the Mike exists and is visible
# decrement counter to count down
self.timer -= 1
if self.timer > 60:
#appearing
xpos, ypos=self.loc
height=self.default.get_height()
#workout what fraction of the image we should draw
y=(height/20)*(self.timer-60)
#copy that surface from the backup to the main sprite image
self.image=self.default.subsurface(0,0,self.default.get_width(),height-y)
self.rect.left=xpos
#adjustthe Y position so it pops up
self.rect.top=ypos+y
if self.timer == 0:
#finished - disappear it
self.rect=self.default_rect
if self.timer < 12:
#vanishing
# like appearing, butin reverse
xpos, ypos=self.loc
height=self.default.get_height()
y=(height/12)*self.timer
self.image=self.default.subsurface(0,0,self.default.get_width(),y)
self.rect.left=xpos
self.rect.top=ypos-y+height
if self.whacked:
#make him suffer
self.whacked += 1
#if he is hit, we can use the flag as a counter and spin the sprite through 360 degrees
if self.whacked >= 10:
self.whacked = 0
self.image = self.default
else:
self.image =pygame.transform.rotate(self.default, self.whacked*36)
def is_hit(self):
"""things todo when object is hit"""
self.whacked=1
#make Mike squeal
def wait_for_key():
pygame.event.wait()
waiting = True
while waiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
waiting = False
pygame.quit()
quit()
if event.type == pygame.KEYUP:
waiting = False
game_intro()
def game_over():
background = pygame.image.load(os.path.join(img_folder, "background3.png")).convert_alpha()
background_rect = background.get_rect()
screen.blit(background, background_rect)
draw_text(screen, "GAME OVER", 60, 500, 300)
draw_text(screen, "Press any key to start", 30, 500, 400)
pygame.display.flip()
wait_for_key()
def main():
"""the main game logic"""
#Initialize Everything
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(os.path.join(music_folder, background_music))
screen = pygame.display.set_mode((1000, 800))
pygame.display.set_caption('Doomsday')
pygame.mouse.set_visible(0)
background = pygame.image.load(os.path.join(img_folder, "background3.png")).convert_alpha()
BGCOLOR = (0, 0, 0)
# set up a controlling timer for the game
clock = pygame.time.Clock()
pygame.time.set_timer(pygame.USEREVENT + 1 , 1000)
countdown = 90
hammer = Player()
mike=Mike()
score=0
#add the sprites to a rendering group
spritegroup= pygame.sprite.RenderPlain(( mike, hammer))
start_ticks=pygame.time.get_ticks()
running=True
pygame.mixer.music.play(loops =- 1)
# control loop
while running:
#adjust this timer to make the game harder or easier
clock.tick(80)
#check what events Pygame has caught
for event in pygame.event.get():
if event.type == pygame.QUIT or countdown == 0:
running=False
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running=False
pygame.quit()
elif event.key == pygame.K_p:
pause()
elif event.type == pygame.USEREVENT + 1:
countdown -= 1
elif event.type == pygame.MOUSEBUTTONDOWN:
#button means the hammer is being used
if hammer.dowhack(mike):
mike.is_hit()
score += 4
print(score)
elif event.type is pygame.MOUSEBUTTONUP:
hammer.reset()
#does a mike exist? if not, we should have one
if mike.timer==0:
mike.appear()
seconds=(pygame.time.get_ticks()-start_ticks)/1000
if score>=100:
import Shooter
if countdown<=0 and score>=100:
import Shooter
if countdown<=0 and score<=100:
game_over()
wait_for_key()
#refresh the screen by drawing everything again
#call the update methods of all the sprites in the group
spritegroup.update()
#redrawthe background
screen.blit(background, (0, 0))
#draw everything
spritegroup.draw(screen)
draw_text(screen, "TIMER " + str(countdown), 30, 900, 30)
draw_shield_bar(screen, 20, 20, score)
#flip the buffer
pygame.display.flip()
def show_pause_screen():
background = pygame.image.load(os.path.join(img_folder, "background3.png")).convert_alpha()
background_rect = background.get_rect()
screen.blit(background, background_rect)
draw_text(screen, "PAUSED", 70, 500, 100)
draw_text(screen, "Are you afraid to continue?", 40, 500, 250)
draw_text(screen, "Press C to continue or Q to Quit", 20, 500, 400)
def pause():
paused = True
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
paused = False
elif event.key == pygame.K_q:
import menu
show_pause_screen()
pygame.display.update()
clock.tick(60)
def draw_text(surf, text, size, x, y):
font_name = pygame.font.match_font('OCR A Extended')
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(screen, ac,(x,y,w,h))
if click[0] == 1 and action != None:
if action == main():
main()
pygame.quit()
else:
pygame.draw.rect(screen, ic,(x,y,w,h))
def game_intro():
pygame.init()
intro=True
while intro:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYUP:
intro=False
main()
pygame.display.flip()
pygame.display.set_caption('Doomsday')
background = pygame.image.load(os.path.join(img_folder, "backgroundhouse2.png")).convert_alpha()
screen.blit(background, (0, 0))
mouse = pygame.mouse.get_pos()
draw_text(screen, "PROTECT YOUR HOUSE", 39, 500, 55)
draw_text(screen, "Hit as many screws as possible", 32, 500, 92)
draw_text (screen, "Press any key to start", 30, 480, 300)
draw_text (screen, "Press P to pause", 30, 480, 340)
pygame.display.flip()
clock.tick(15)
pygame.quit()
quit()
game_intro()
main()
pygame.quit()
quit()
quit()
|
775e499117ecc325d71ac163d0a0895846a15e9b | CheesyModz/Python-Games | /Pacman/myPacmanSprites.py | 2,638 | 3.90625 | 4 | import pygame, random
class Cherry(pygame.sprite.Sprite):
'''A simple Sprite subclass to represent static Cherry sprites.'''
def __init__(self, screen):
# Call the parent __init__() method
pygame.sprite.Sprite.__init__(self)
# Set the image and rect attributes for the cherries
self.image = pygame.image.load("cherry.png")
self.rect = self.image.get_rect()
self.rect.centerx = random.randrange(0, screen.get_width())
self.rect.centery = random.randrange(0, screen.get_height())
class Pacman(pygame.sprite.Sprite):
'''A simple Sprite subclass to represent static Cherry sprites.'''
def __init__(self, screen, directionX, directionY):
# Call the parent __init__() method
pygame.sprite.Sprite.__init__(self)
self.directionX = directionX
self.directionY = directionY
self.window = screen
# Set the image and rect attributes for the pacman
self.image = pygame.image.load("pacman-right.png")
self.rect = self.image.get_rect()
self.rect.centerx = random.randrange(0, screen.get_width())
self.rect.centery = random.randrange(0, screen.get_height())
def go_left (self):
'''This function will display the Pacman going left'''
self.image = pygame.image.load ("pacman-left.png")
self.directionX = -5
self.directionY = 0
def go_right (self):
'''This function will display the Pacmman going right'''
self.image = pygame.image.load ("pacman-right.png")
self.directionX = 5
self.directionY = 0
def go_up (self):
'''This function will display the Pacman going up'''
self.image = pygame.image.load ("pacman-up.png")
self.directionX = 0
self.directionY = -5
def go_down (self):
'''This function will display the Pacman going down'''
self.image = pygame.image.load ("pacman-down.png")
self.directionX = 0
self.directionY = 5
def update(self):
'''Automatically called in the Refresh section to update our Box Sprite's position.'''
self.rect.left += self.directionX
self.rect.top += self.directionY
if self.rect.left < 0:
self.rect.right = self.window.get_width()
if self.rect.right > 640:
self.rect.left = 0
if self.rect.top < 0:
self.rect.bottom = self.window.get_height()
if self.rect.bottom > 480:
self.rect.top = 0
|
30692c110f46fb5517f4373d487517fceb39da54 | toujoursfatigue/ING231-Algoritma | /Alistirmalar-II/alistirma-1.py | 1,262 | 3.515625 | 4 | import random
def masterminddef():
try:
kullanici_sayisi = int(input("10 ile 98 arasinda bir sayi gir"))
if not 10<kullanici_sayisi<98:
masterminddef()
return kullanici_sayisi
except:
print("lütfen doğru rakam girin")
masterminddef()
bilgisayar_sayisi = random.randint(10,98)
kullanici_number = 0
dogru = 0
yanlis = 0
mastermind = True
kullanici_sayisi = masterminddef()
while mastermind:
while str(bilgisayar_sayisi)[0] == str(bilgisayar_sayisi)[1]:
bilgisayar_sayisi = random.randint(10, 98)
while kullanici_sayisi != bilgisayar_sayisi:
kullanici_sayisi = masterminddef()
if str(kullanici_sayisi)[0] == str(bilgisayar_sayisi)[0]:
dogru+=1
elif str(kullanici_sayisi)[1] == str(bilgisayar_sayisi)[1]:
dogru+=1
elif str(kullanici_sayisi)[0] != str(bilgisayar_sayisi)[0]:
yanlis+=1
elif str(kullanici_sayisi)[1] != str(bilgisayar_sayisi)[1]:
yanlis+=1
if kullanici_sayisi==bilgisayar_sayisi:
print("dogru sayiyi buldunuz")
print("bilgisayarin sayisi {} idi".format(bilgisayar_sayisi))
print("arti puaniniz{} /eksi puaniniz{}".format(dogru,yanlis))
|
c58c1723c8f60c68663bd485e289b6bfb91b4385 | yuanlanda/lt2212-v20-example-trigram | /trimodule.py | 9,937 | 3.5625 | 4 | import sys
import os
import random
class TrigramModel:
def __init__(self, inputstring):
self.tridict = {}
for position in range(len(inputstring) - 2):
char0 = inputstring[position]
char1 = inputstring[position + 1]
char2 = inputstring[position + 2]
if char0 in self.tridict:
if char1 in self.tridict[char0]:
if char2 in self.tridict[char0][char1]:
self.tridict[char0][char1][char2] += 1
else:
self.tridict[char0][char1][char2] = 1
else:
self.tridict[char0][char1] = {}
self.tridict[char0][char1][char2] = 1
else:
self.tridict[char0] = {}
self.tridict[char0][char1] = {}
self.tridict[char0][char1][char2] = 1
self.probdict = {}
for char0 in self.tridict.keys():
if char0 not in self.probdict:
self.probdict[char0] = {}
for char1 in self.tridict[char0].keys():
if char1 not in self.probdict[char0]:
self.probdict[char0][char1] = {}
for char2 in self.tridict[char0][char1].keys():
fullcount = sum(self.tridict[char0][char1].values())
self.probdict[char0][char1][char2] = self.tridict[char0][char1][char2]/fullcount
def __getitem__(self, item):
if len(item) != 3:
raise ValueError("Must be exactly 3 chars.")
return self.probdict[item[0]][item[1]][item[2]]
class TrigramModelWithDistribution(TrigramModel):
def predict(self, n, seed):
'''
Predicts n characters using random sampling from the
distribution starting with the seed.
'''
if len(seed) != 2:
raise ValueError("Need exactly two characters for prediction.")
inputchar0 = seed[0]
inputchar1 = seed[1]
outputstring = "{}{}".format(inputchar0,inputchar1)
for output in range(n):
choices = self.probdict[inputchar0][inputchar1]
randomval = random.random()
total = 0
mychoice = ''
for key in choices:
total += choices[key]
if randomval < total:
mychoice = key
break
#options = sorted(choices.keys(), key=lambda x: choices[x], reverse=True)
#print(options)
outputstring += mychoice
inputchar0 = inputchar1
inputchar1 = mychoice
return outputstring
class TrigramModelWithTopK(TrigramModel):
def __init__(self, inputstring, k=5):
super().__init__(inputstring)
self.k = k
def get_choices(self, inputchar0, inputchar1):
choices = self.probdict[inputchar0][inputchar1]
return sorted(choices.keys(), key=lambda x: choices[x], reverse=True)
def predict(self, n, seed):
'''
Predicts n characters using random sampling from the
distribution starting with the seed.
'''
if len(seed) != 2:
raise ValueError("Need exactly two characters for prediction.")
inputchar0 = seed[0]
inputchar1 = seed[1]
outputstring = "{}{}".format(inputchar0,inputchar1)
for output in range(n):
options = self.get_choices(inputchar0, inputchar1)
mychoice = random.choice(options[:5])
#print(options)
outputstring += mychoice
inputchar0 = inputchar1
inputchar1 = mychoice
return outputstring
import numpy as np
import random
from sklearn.linear_model import LogisticRegression
class TrigramMaxEnt(TrigramModelWithTopK):
def sample(self, n):
samples = []
for i in range(n):
char1 = random.choice(list(self.tridict.keys()))
char2 = random.choice(list(self.tridict[char1].keys()))
char3 = random.choice(list(self.tridict[char1][char2].keys()))
count = self.tridict[char1][char2][char3]
samples.append((char1, char2, char3, count))
return samples
def vectorize(self, feature, features):
empty = np.zeros(len(features))
empty[features.index(feature)] = 1
return empty
def make_model(self, vector_width=None):
self.model = LogisticRegression()
def __init__(self, inputstring):
super().__init__(inputstring)
#self.model = LogisticRegression()
self.features = set()
for x in self.tridict.keys():
self.features.add(x)
self.features = list(self.features)
self.make_model(len(self.features))
def process_samples(self, instances):
X = [x[0] for x in instances]
y = [x[1] for x in instances]
sample_weights = [x[2] for x in instances]
return X, y, sample_weights
def train(self, num_samples):
samples = self.sample(num_samples)
#print(samples, len(samples))
instances = []
for s in samples:
char1inst = self.vectorize(s[0], self.features)
char2inst = self.vectorize(s[1], self.features)
instances.append((np.concatenate([char1inst, char2inst]), s[2], s[3]))
inputs = self.process_samples(instances)
self.call_model(inputs)
def call_model(self, inputs):
self.model.fit(inputs[0], inputs[1], inputs[2])
def get_predictions_from_model(self, inputvec):
return self.model.predict_log_proba([inputvec])
def get_multiple_predictions_from_model(self, inputvec):
return self.model.predict_log_proba(inputvec)
def get_features(self):
return self.model.classes_
def get_choices(self, inputchar0, inputchar1):
inputvec = np.concatenate([self.vectorize(inputchar0, self.features), self.vectorize(inputchar1, self.features)])
predictions = self.get_predictions_from_model(inputvec)
#print(-predictions, len(-predictions))
sortedargs = np.argsort(-predictions[0])
#print(sortedargs, len(sortedargs))
return [self.get_features()[x] for x in sortedargs]
def perplexity(self, text):
samples_X = []
samples_y = []
for i in range(len(text) - 2):
char0 = text[i]
char1 = text[i+1]
char2 = text[i+2]
if char2 in list(self.get_features()):
samples_X.append(np.concatenate([self.vectorize(char0, self.features), self.vectorize(char1, self.features)]))
samples_y.append(list(self.get_features()).index(char2))
#print(samples_X[:2])
predictions = self.get_multiple_predictions_from_model(samples_X)
#print(predictions)
logprobs = [x[0][x[1]] for x in zip(predictions, samples_y)]
#print(logprobs)
#print(logprobs[0], logprobs[1])
logprobs = np.array(logprobs)
return np.power(2, -1/(len(logprobs)) * np.sum(logprobs))
class TrigramMaxEntExpandSamples(TrigramMaxEnt):
def process_samples(self, instances):
X = [x[0] for x in instances]
y = [x[1] for x in instances]
sample_weights = [x[2] for x in instances]
real_X = []
real_y = []
real_weights = []
for i in range(len(instances)):
multiplier = sample_weights[i]
real_X += [X[i]] * multiplier
real_y += [y[i]] * multiplier
real_weights += [1] * multiplier
return (real_X, real_y, real_weights)
import torch
from torch import optim
from torch import nn
import random
class TrigramPredictNN(nn.Module):
def __init__(self, input_size, output_size, hidden_size=10):
super().__init__()
self.linear0 = nn.Linear(input_size, hidden_size)
self.sigmoid = nn.Sigmoid()
self.linear1 = nn.Linear(hidden_size, output_size)
def forward(self, x):
m = self.linear0(x)
n = self.sigmoid(m)
o = self.linear1(n)
return o
class TrigramFFNN(TrigramMaxEnt):
def __init__(self, inputstring, k=5, epochs=3, lr=0.01):
super().__init__(inputstring)
self.epochs = epochs
self.lr = lr
def make_model(self, vector_size=None):
self.model = TrigramPredictNN(vector_size * 2, vector_size)
def eval(self):
self.model.eval()
def call_model(self, inputs):
"""
The training loop.
"""
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(self.model.parameters(), lr=self.lr)
for z in range(self.epochs):
print("Running epoch {}...".format(z))
for i in range(len(inputs[0])):
instance = torch.Tensor([inputs[0][i]])
label = torch.LongTensor([self.features.index(inputs[1][i])])
output = self.model(instance)
loss = criterion(output, label)
optimizer.zero_grad()
loss.backward()
optimizer.step()
newinputs = list(zip(inputs[0],inputs[1]))
random.shuffle(newinputs)
i0 = [x[0] for x in newinputs]
i1 = [x[1] for x in newinputs]
inputs = (i0,i1)
def get_predictions_from_model(self, inputvec):
torchvec = torch.Tensor([inputvec])
output = self.model(torchvec)
return torch.log_softmax(output, 1).detach().numpy()
def get_multiple_predictions_from_model(self, inputvec):
return self.get_predictions_from_model(inputvec)[0]
#print(result.shape)
#return result
def get_features(self):
return self.features
|
d06e7e5a61ffd9ea88f17011d4b48fa25af1cf24 | julianandrews/adventofcode | /2019/python/utils/primes.py | 571 | 3.90625 | 4 | def is_prime(n):
d = 2
while d * d <= n:
if n % d == 0:
return False
d += 1
return n > 1
def prime_factors(n):
i = 2
while i <= n:
while n and n % i == 0:
yield i
n //= i
i += 1
def primes_upto(limit):
is_prime = [False] * 2 + [True] * (limit - 1)
for n in range(int(limit**0.5 + 1.5)):
if is_prime[n]:
for i in range(n * n, limit + 1, n):
is_prime[i] = False
for i in range(limit + 1):
if is_prime[i]:
yield i
|
d44c25d0eed1b2f6881169bc9e8bc290fe22f620 | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/oslcon001/ndom.py | 1,259 | 3.8125 | 4 | # Conor O'Sullivan
# Convers to base 6 (visa versa)
# 4/01/2014
#ndom_to_decimal (a), that converts a Ndom number to decimal
def ndom_to_decimal(a):
dec = 0
for x in range(a+1):
ndom = decimal_to_ndom(x)
if ndom == a:
dec = x
break
return dec
#decimal_to_ndom (a), that converts a decimal number to Ndom
def decimal_to_ndom(a):
ndom = 0
while a != 0:
if a < 6:
ndom += a
a = 0
elif a <36:
num6 = (a//6)
ndom = ndom + num6*10
a -= num6*6
elif a <216:
num36 = (a//36)
ndom = ndom + num36*100
a -= num36*36
elif a <1296:
num216 = (a//216)
ndom = ndom + num216*1000
a -= num216*216
return ndom
#ndom_add (a, b), that adds 2 Ndom numbers
def ndom_add(a,b):
a= ndom_to_decimal(a)
b = ndom_to_decimal(b)
c = a + b
c = decimal_to_ndom(c)
return c
#ndom_multiply (a, b), that multiples 2 Ndom numbers
def ndom_multiply(a,b):
a= ndom_to_decimal(a)
b = ndom_to_decimal(b)
c = a*b
c = decimal_to_ndom(c)
return c |
661ce04901ef64076812556e6a273a2ca7663bb5 | pizza-steve/Minions-Quiz | /01_Menu_GUI_v1.py | 761 | 3.5 | 4 | from tkinter import *
class Quiz:
def __init__(self):
# formatting variables
background_color = "yellow"
# quiz main screen GUI
self.quiz_frame = Frame(width=300, height=300, bg=background_color)
self.quiz_frame.grid()
# minions quiz heading
self.minion_converter_label = Label(text="Minions Quiz",
font=("Arial", "30", "bold"),
bg=background_color,
padx=10,pady=10,)
self.minion_converter_label.grid(row=0,sticky='N')
# main routine
if __name__ == "__main__":
root = Tk()
root.title("Minion Quiz Menu")
something = Quiz()
root.mainloop()
|
65fa63d2793d2c595cdfdb3b2c52a134ac3565a3 | Sofia1306/Python_Clases | /Ejercicio_DecimalBinario.py | 329 | 3.859375 | 4 | """Ejercicio Decimal a Binario """
import math
numero = int(input('Ingresa un número: \n'))
binario = ''
while (numero > 0):
if (numero%2 == 0):
binario = '0' + binario
else:
binario = '1' + binario
numero = int(math.floor(numero/2))
print(f'El número en binario es {binario}')
|
ca1090d0d85c6eb9f5bbf95105ba801041f0c3d0 | BaronVladziu/Project-Euterpe | /notes/chord.py | 1,053 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from notes.pitch import Pitch
class Chord:
def __init__(self, pitches=list()):
"""
Set of pitches used as a whole.
"""
self._pitches = pitches
self._pitches.sort(
key=lambda x: x.get_cents_from_a()
)
def get_size(self) -> int:
return len(self._pitches)
def add_pitch(self, pitch:Pitch):
self._pitches.append(pitch)
self._pitches.sort(
key=lambda x: x.get_cents_from_a()
)
def get_pitch(self, voice_num:int) -> Pitch:
if voice_num < 0:
raise ValueError(
'[Chord::get_pitch('\
+ str(voice_num)\
+ ')] Voice number cannot be negative!'
)
elif voice_num >= len(self._pitches):
raise ValueError(
'[Chord::get_pitch('\
+ str(voice_num)\
+ ')] There is no pitch for this voice number!'
)
return self._pitches[voice_num]
|
fec521d95527ee3cac4d52514d1fa61148103433 | sidv/Assignments | /Ramya_R/Ass17Augd17/Employee/org.py | 1,854 | 4.0625 | 4 | #employees = {} #empty List
organization = {}
def org_menu():
print("\t1.Add organization")
print("\t2.view organization")
print("\t3.edit organization")
print("\t4.delete organization")
#print("\t5.exit")
def manage_all_organizations():
org_menu()
ch = int(input("\tEnter your choice "))
if ch == 1:
#Create organization
add_org()
elif ch == 2:
#display organization
display_org()
elif ch == 3:
#edit organization details
edit_org()
elif ch == 4:
#Delete organization
delete_org()
#elif ch == 5:
#exit
#break
else:
print("\tInvalid choice")
def add_org():
org_id = input("Enter org id: ")
organization[org_id] ={
"name":input("\tEnter name "),
"email":input("\tEnter email "),
"phno":input("\tEnter the phno "),
"address":input("\tEnter address ")
}
# else:
# print("\tid already Taken")
def edit_org():
#Change a employee detailes
print("\t Enter 1 for change name")
print("\t Enter 2 for change email ")
print("\t Enter 3 for change phno ")
print("\t Enter 4 for change address ")
choice = int(input("\tEnter the choice which u want to change: "))
org_id = input("\tEnter org id: ")
if choice == 1:
organization[org_id]['name'] = input("\tEnter new name: ")
if choice == 2:
organization[org_id]['email'] = input("\tEnter new email: ")
if choice == 3:
organization[org_id]['phno'] = input("\tEnter new phno: ")
if choice == 4:
organization[org_id]['address'] = input("\tEnter new Address: ")
#else:
#print("\t invalid choice")
def display_org():
#Display organization
print(organization)
for org_id,i in organization.items():
print(f"\t{org_id} | {i['name']} | {i['email']} | {i['phno']} | {i['address']}")
def delete_org():
org_id = input("\tEnter org id: ")
if org_id not in organization.keys():
print("\tWrong serial No")
else:
del organization[org_id]
|
9d3c3c06d6d0ab3c5c9c6c7929c62c722de46cbf | alpha-kwhn/Baekjun | /powerful104/10798.py | 221 | 3.5 | 4 | li=[]
max=0
for _ in range(5):
s=input().strip()
if max<len(s):
max=len(s)
li.append(s)
for i in range(max):
for j in range(5):
if len(li[j])>i:
print(li[j][i],end="") |
7afbae0e567b1d8662499fc6d7c05b73c630ff55 | suglanova/CodecademyChallenges | /Lists/lists_challenge0.py | 905 | 4 | 4 | #Advanced Python Code Challenges: Lists
def every_three_nums(start):
return list(range(start, 101, 3))
print(every_three_nums(91))
def remove_middle(lst, start, end):
lst = lst[:start] + lst[end+1:]
return (lst)
print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))
def more_frequent_item(lst, item1, item2):
if lst.count(item1) >= lst.count(item2):
return item1
else:
return item2
print(more_frequent_item([2, 3, 3, 2, 3, 2, 3, 2, 3], 2, 3))
def double_index(lst, index):
if index >= 0 and index < len(lst):
lst[index] *= 2
return lst
print(double_index([3, 8, -10, 12], 2))
import math
def middle_element(lst):
length = len(lst)
halfLength = math.floor(length / 2)
if length % 2 == 0:
item1 = lst[halfLength - 1]
item2 = lst[halfLength]
return (item1 + item2) / 2
else:
return lst[length // 2]
print(middle_element([5, 2, -10, -4, 4, 5])) |
86f3b004db37dc8eb69625dd958be6b713ac9271 | lfteixeira996/Coding-Bat | /Python/Warmup-2/last2.py | 621 | 4.1875 | 4 | import unittest
'''
Given a string, return the count of the number of times that a substring
length 2 appears in the string and also as the last 2 chars of the string,
so "hixxxhi" yields 1 (we won't count the end substring).
last2('hixxhi') -> 1
last2('xaxxaxaxx') -> 1
last2('axxxaaxx') -> 2
'''
def last2(str):
class Test_last2(unittest.TestCase):
def test_1(self):
self.assertEqual(last2('hixxhi'), 1)
def test_2(self):
self.assertEqual(last2('xaxxaxaxx'), 1)
def test_3(self):
self.assertEqual(last2('xaxxaxaxx'), 1)
if __name__ == '__main__':
unittest.main() |
4cfaf97cb4ac24e51aa7dc9a898f5e3db1497afa | CosmicTomato/ProjectEuler | /eul98.py | 2,323 | 4 | 4 | #Anagramic squares
#By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively, we form a square number: 1296 = 362. What is remarkable is that, by using the same digital substitutions, the anagram, RACE, also forms a square number: 9216 = 962. We shall call CARE (and RACE) a square anagram word pair and specify further that leading zeroes are not permitted, neither may a different letter have the same digital value as another letter.
#Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, find all the square anagram word pairs (a palindromic word is NOT considered to be an anagram of itself).
#What is the largest square number formed by any member of such a pair?
#NOTE: All anagrams formed must be contained in the given text file.
import letter_to_number
#letter_to_number.main(x) returns numerical value of the letter x
def main():
f=open('words.txt')
words_list=f.read().replace('"','').split(',')
f.close()
#creates list of all words in file. they are all uppercase and are separated by commas
words_sets = []
for i in range( 0 , len( words_list ) ):
words_sets.append( [ set( words_list[ i ] ) , words_list[ i ] ] )
#creates list that holds sets of all words in list (as well as all words in list)
just_sets = []
for i in range( 0 , len( words_sets ) ):
just_sets.append( words_sets[ i ][ 0 ] )
#creates list that holds just the sets of all words in list
pruned_words = []
for i in range( 0 , len( words_sets ) ):
if just_sets.count( words_sets[ i ][ 0 ] ) >= 2:
pruned_words.append( words_sets[ i ][ 1 ] )
#if duplicate, then add words to pruned words
#IMPORTANT: pruned_words represents all words that are part share all of their letters with at least one other word in the list
#(there are 295 words in the pruned_words list)
#NOTE: these words aren't necessarily part of an anagram pair, as there could be shorter words that share all of their letters
#TEST
print('pruned_words=',pruned_words)
#TEST
#TEST
word_lengths = []
for i in pruned_words:
word_lengths.append( len( i ) )
#TEST
#RESULT: MAX length of words with anagrams is 14
#sqrt(10^14) = 10^7
#i.e. 10^7 is the first number to have a square with more than 14 digits
return pruned_words
|
197869df44e1acf8980a5031681fe644c5f8ba68 | knight-peter/item-python-HeadFirst | /1.寻找自己的方式/猜数字游戏1.2.py | 486 | 3.8125 | 4 | #这两行代码用来生成随机数
from random import randint
secret=randint(1,10)
print("欢迎,这是一个猜数字游戏。")
guess=0
'''
检查答案是否等于那个secret变量中设定的随机数。
'''
while guess!=secret:
g=input("请输入一个数字:")
guess=int(g)
if guess==secret:
print("你猜对了!")
else:
if guess>secret:
print("太高了")
else:
print("太低了")
print("游戏结束。") |
97ff9a40ad1d6e9f83bedaba8d637946bfd569a5 | Adam-Hoelscher/ProjectEuler.py | /Problem52.py | 509 | 3.578125 | 4 | def Solve():
add = 0
target = 6
while True:
baseDigits = ['1'] + [d for d in str(add)]
test = int(''.join(baseDigits))
baseDigits.sort()
for m in range(2, target + 1):
mult = test * m
testDigits = [d for d in str(mult)]
testDigits.sort()
if baseDigits != testDigits:
break
elif m == target:
return(test)
add += 1
if __name__ == '__main__':
print(Solve())
|
1b76a6be56b08a028c19772d3c9f9c6927078cf9 | GeovaniSantosHub/Learning_Pyton | /Mundo 2/desafio 44.py | 678 | 3.75 | 4 | preco = float(input('Qual o preço das compras ?'))
print('''Qual opção de pagamento você deseja efetuar
[1] à vista/cheque
[2] à vista no cartão
[3] 2x no cartão
[4] 3x ou mais no cartão''')
opcão = int(input('Qual opção deseja ? '))
if opcão == 1:
print(f'Você pagará {preco * 90 / 100}, pois terá 10% de desconto')
elif opcão == 2:
print(f'Você pagará {preco * 95 / 100}, pois terá 5% de desconto')
elif opcão == 3:
print(f' Você pagará {preco} em duas parcelas de {preco / 2}')
else:
parcel = int(input('Em quantas parcelas ?'))
print(f'Você pagará {preco * 120 / 100} em {parcel} parcelas de {(preco * 120 / 100) / parcel:.2f}')
|
ad429ecf7e59dd704443e0be5de1354b70c69536 | LXYDETZT/zhangsan | /demo01.py | 2,319 | 4.03125 | 4 | '''
33333333333333
print('哈哈',2333,2.333)
print('哈哈'+'嘻嘻') #字符串的拼接,但是只能相同数据类型,不过整数和小数可以一起
print('哈哈'*3)
print(((1+2)*100-99)/2)
print(2>3)
print(4>3)
#变量和赋值-开始
#浪晋说变量必须是小写字母!为什么大写也没问题
name='张三' #把张三这个值赋值给了a这个变量
print(name)
#变量和赋值-结束
a=input('请输入:')
print(a)
a=input('请输入:')
b=input('请输入:')
print('input获取的内容:',a+b)
#数据格式的转换-开始
print(type('哈哈'))
print(type(2333))
print(type(2.333))
print(type(True))
print(type(()))
print(type([]))
print(type({}))
print(type('123'))
print(type(int('123')))
a=int(input())
b=int(input())
print(a+b)
#数据格式的转换-结束
a='caeriovouviuolefv'
print(len(a))
a=len(input('请输入:'))
b=len(input('请输入:'))
print('两段字符串总长度为:',a+b)
#元组,下标(从0开始编号)-开始
a=(1,2,'哈哈','哈哈','嘻嘻',True,False) #()里可以输入所有的数据类型
print(a)
print(a[4])
print(a[-1])
print(a.index('嘻嘻')) #index用于查找数据的下标
print(a.index('哈哈')) #index就近查找原则
print(a.count('哈哈')) #count用于统计某个数据的数量
print(a.count(1))
print(a.count(2))
print(a.count('嘻嘻'))
print(a.count(True))
print(a.count(False))
#元组,下标(从0开始编号)-结束
#二维元组-开始
a=(1,2,'哈哈','哈哈','嘻嘻',True,False) #()里可以输入所有的数据类型
b=(a,'哈哈','嘻嘻') #b里有3个值,a是个整体一个值
c=(b,'哈哈','嘻嘻')
print(a)
print(b)
print(c)
print(b[0])
print(b[0][5])
print(c[0])
#二维元组-结束
#二维数组-切片-开始
a=(1,2,'哈哈','哈哈','嘻嘻',True,False)
print(a[0:4]) #左闭右开,不写或者超出都表示到边界
print(a[:4])
print(a[0:10])
print(a[0:])
#二维数组-切片-结束
'''
#数组-开始 元组和数组的区别在于元组写好后不可以修改,但是数组可以修改
a=[1,2,'哈哈','哈哈','嘻嘻',True,False]
print(a[6])
a.append('append1')
a.append('append2')
a.insert(2,'insert')
print(a)
b=a.pop(0) #剪切
print(a)
print(b)
c=a.pop(0)
print(a)
print(c)
print(b+c)
#数组-结束 |
e0df06bbdb580cd320a913fe7ccc9be4d43876bf | Bacmel/Boids-Boids-Boids | /src/sim/perceptions/range.py | 871 | 3.515625 | 4 | # -*- coding: utf-8 -*-
from numpy.linalg import norm
from .perception import Perception
class Range(Perception):
"""The class implements a range based perception of the neighbors."""
def __init__(self, perception_range, border, perception=None):
"""Build a new Range perception.
Args:
perception_range (float): The maximum distance to a detected neighbors (in units).
border (Border): The border of the environment.
perception (Perception): The wrapped perception.
"""
super().__init__(border, perception)
self.perception_range = perception_range
def _filter(self, ind, pop):
return [
pop_ind
for pop_ind in pop
if pop_ind is not ind
and norm(self.border.vector(ind.pos, pop_ind.pos)) < self.perception_range
]
|
a32fa47fe2f8e571a862e53e89d76ab67efebc21 | Lalesh-code/PythonLearn | /Oops_Encapsulation.py | 1,484 | 4.4375 | 4 | # Encapsulation: this restrict the access to methods and variables. This can prevent the data from being get modified accidently or by security point of view. This is achived by using the private methods and variables.
# Private methods denoted by "__" sign.
# Public methods can be accessed from anywhere but Private methods is accessed only in their classes & methods.
class MyClass():
__a=100 # valiable a is defined here as private denoted as '__'
def display(self):
print(self.__a) # passed here the same __a variable private one.
obj=MyClass()
obj.display() # O/p = 100
# print(MyClass.__a) # __a private variable outsie of class cannot be accesed. AttributeError: type object 'MyClass' has no attribute '__a'
class MyClass():
def __display1(self): # Private Method
print("This is first display method")
def display2(self): # Public Method
print("This is second display method")
self.__display1()
obje=MyClass()
obje.display2() # only public method is accessed here. display1 private method cannot be.
# We can access private variables outside of class indiretly using methods:
class MyClass():
__empid=101 # Private variable
def getempid(self,eid):
self.__empid = eid # method to get the getempid.
def dispempid(self):
print(self.__empid) # method to get the dispempid.
obj=MyClass()
obj.getempid(105) # 105
obj.dispempid() # 101
|
3fdf3a936265b9c32c7570a993230b7c6d3f2897 | bilakuingat/Project-PBO | /Pencatatan Kas.py | 1,176 | 4.03125 | 4 | balance = 600
def withdraw(): # asks for withdrawal amount, withdraws amount from balance, returns the balance amount
counter = 0
while counter <= 2:
while counter == 0:
withdraw = int(input("Enter the amount you want to withdraw: "))
counter = counter + 1
while ((int(balance) - int(withdraw)) < 0):
print("Error Amount not available in card.")
withdraw = int(input("Please enter the amount you want to withdraw again: "))
continue
while ((float(balance) - float(withdraw)) >= 0):
print("Amount left in your account: " + str(balance - withdraw))
return (balance - withdraw)
counter = counter + 1
def deposit():
counter = 0
while counter <= 2:
while counter == 0:
deposit = int(input("Enter amount to be deposited: "))
counter = counter + 1
while ((int(balance) + int(deposit)) >= 0):
print("Amount left in your account:" + str(balance + deposit))
return (balance + deposit)
counter = counter + 1
balance = withdraw()
balance = deposit() |
a685464e7cfbc5424cac532db87abc56a451e9cc | anillava1999/Innomatics-Intership-Task | /Task 3/Task3.py | 924 | 4.25 | 4 |
'''
Therefore, .
Point is the midpoint of hypotenuse .
You are given the lengths and .
Your task is to find (angle , as shown in the figure) in degrees.
Input Format
The first line contains the length of side .
The second line contains the length of side .
Constraints
Lengths and are natural numbers.
Output Format
Output in degrees.
Note: Round the angle to the nearest integer.
Examples:
If angle is 56.5000001°, then output 57°.
If angle is 56.5000000°, then output 57°.
If angle is 56.4999999°, then output 56°.
Sample Input
10
10
Sample Output
45°
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
# Find Angle MBC in python - Hacker Rank Solution START
# -*- coding: UTF-8 -*-
import math
import sys
l1 = float(input())
l2 = float(input())
a = math.degrees(math.atan(l1/l2))
a = round(a)
print ("%.0f" % a,)
sys.stdout.softspace=0
print(u"\u00b0".encode('utf-8')) |
06723e712d519dc9bf4cf1c90ce0a05d833dc480 | ParkJongOh/python-starter | /week2/function4.py | 157 | 3.96875 | 4 | def is_odd(number):
if number%2==0:
print("짝수입니다.")
elif number%2!=0:
print("홀수입니다.")
aa = int(input())
is_odd() |
8cf084e2ad16f7ea359a6de1acb4e505f935be1e | awesaem/awesaem-python.saem | /st01.Python기초/py07선택문/py07_03ex5_큰수.py | 231 | 3.984375 | 4 | x = input("첫번째 정수 : ")
y = input("두번째 정수 : ")
#문자열로 비교할 때와 숫자열로 비교할 때의 값이 다르므로 주의해야 함
x = int(x)
y = int(y)
if x > y :
print(x)
else:
print(y) |
27d332a89a66214e7120f66c9f8fd2e77484090b | sowbhakya/python-programming | /multiplytable.py | 133 | 3.921875 | 4 | a=input("Enter the number")
b=input("enter the multiplication range")
for c in range(1,b):
print a,"*",c,"=",a*c
|
fd2c93cf36fd8c7ad51c3f45263c768beb9f4555 | Anjalkhadka/pycharmproject | /three.py | 105 | 3.65625 | 4 |
for i in range(4):
num = ('enter the positive number')
else:
num = ('enter the negative number') |
8e311469a7ab1545e29a5d80156e95cb4dffb0c2 | gabrielizalo/jetbrains-academy-python-coffee-machine | /Coffee Machine/task/machine/coffee_machine.py | 3,492 | 4.21875 | 4 | # Ini
machine_money = 550
machine_water = 400
machine_milk = 540
machine_beans = 120
machine_cups = 9
# Functions
def action_remaining():
print("The coffee machine has:")
print(machine_water, "of water")
print(machine_milk, "of milk")
print(machine_beans, "of coffee beans")
print(machine_cups, "of disposable cups")
print("$", machine_money, "of money")
print()
def action_buy():
global machine_money
global machine_water
global machine_milk
global machine_beans
global machine_cups
print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:")
coffee_type = input()
if coffee_type != "back":
if coffee_type == "1":
if machine_water >= 250 and machine_beans >= 16:
print("I have enough resources, making you a espresso coffee!")
machine_money = machine_money + 4
machine_water = machine_water - 250
machine_beans = machine_beans - 16
machine_cups = machine_cups - 1
else:
print("I don't have enough resources to make you a espresso coffee!")
elif coffee_type == "2":
if machine_water >= 350 and machine_milk >= 75 and machine_beans >= 20:
print("I have enough resources, making you a latte coffee!")
machine_money = machine_money + 7
machine_water = machine_water - 350
machine_milk = machine_milk - 75
machine_beans = machine_beans - 20
machine_cups = machine_cups - 1
else:
print("I don't have enough resources to make you a latte coffee!")
elif coffee_type == "3":
if machine_water >= 200 and machine_milk >= 100 and machine_beans >= 12:
print("I have enough resources, making you a cappuccino coffee!")
machine_money = machine_money + 6
machine_water = machine_water - 200
machine_milk = machine_milk - 100
machine_beans = machine_beans - 12
machine_cups = machine_cups - 1
else:
print("I don't have enough resources to make you a cappuccino coffee!")
def action_fill():
global machine_money
global machine_water
global machine_milk
global machine_beans
global machine_cups
print("Write how many ml of water do you want to add:")
user_water = int(input())
print("Write how many ml of milk do you want to add:")
user_milk = int(input())
print("Write how many grams of coffee beans do you want to add:")
user_beans = int(input())
print("Write how many disposable cups of coffee do you want to add:")
user_cups = int(input())
machine_water = machine_water + user_water
machine_milk = machine_milk + user_milk
machine_beans = machine_beans + user_beans
machine_cups = machine_cups + user_cups
def action_take():
global machine_money
print("I gave you $", machine_money)
machine_money = 0
# Main program
print("Write action (buy, fill, take, remaining, exit):")
action = input()
while action != "exit":
if action == "buy":
action_buy()
elif action == "fill":
action_fill()
elif action == "take":
action_take()
elif action == "remaining":
action_remaining()
print("Write action (buy, fill, take, remaining, exit):")
action = input()
|
df38b1d404b01498a368916adb754a496f354c1e | callumr1/Programming_1_Pracs | /Prac 4/number_list.py | 681 | 4.15625 | 4 | def main():
numbers = []
print("Please input 5 numbers")
for count in range(1, 6):
num = int(input("Enter number {}: ".format(count)))
numbers.append(num)
average = calc_average(numbers)
print_numbers(numbers, average)
def calc_average(numbers):
average = sum(numbers) / len(numbers)
return average
def print_numbers(numbers, average):
print("The first number is {}".format(numbers[0]))
print("The last number is {}".format(numbers[-1]))
print("The smallest number is {}".format(min(numbers)))
print("The largest number is {}".format(max(numbers)))
print("The average of the number is {}".format(average))
main() |
de9523d08674b05bfe0e84b4ebedb4f32da26b1f | mitkrieg/CS112-Spring2012 | /hw04/sect4_for.py | 946 | 4.15625 | 4 | #!/usr/bin/env python
from hwtools import *
print "Section 4: For Loops"
print "-----------------------------"
nums = input_nums()
total = 0
# 1. What is the sum of all the numbers in nums?
for i in range(0,len(nums)):
total += nums[i]
print "1.", total, "\n"
# 2. Print every even number in nums
print "2. even numbers:"
for a in range (0,len(nums)):
if nums[a] % 2 == 0:
print nums[a]
print ""
#CODE GOES HERE
# 3. Does nums only contain even numbers?
only_even=True
for x in range (0,len(nums)):
if nums[x] % 2 == 1:
only_even = False
print "3.",
if only_even == True:
print "only even"
else:
print "some odd"
print ""
# 4. Generate a list every odd number less than 100. Hint: use range()
odds=[]
for odd in range (1,100,2):
odds.append(odd)
print "4.", odds, "\n"
# 5. [ADVANCED] Multiply each element in nums by its index
for z in range (0,len(nums)):
nums[z] *= z
print "5.", nums
|
2a8e1683f2356ac2227718aa618cf7f4f4058646 | rossirahmayani/test-python | /exception.py | 262 | 3.765625 | 4 |
x = -5
y = 0
# raise
# if x < 0:
# raise Exception('x should be positive')
# assert
# assert(x >= 0), 'x is not positive'
# try catxh
try:
a = x / y
except Exception as e:
print('Error: {}'.format(e))
else:
print(a)
finally:
print('DONE') |
2cc56f3a35c9a2cba490750aa17aa7f01a42216f | angegon/Python | /001_Sintaxis_Basica.py | 590 | 4.1875 | 4 | # No hay ; en el fin de línea en python
print ("Hola Mundo")
# Práctica no recomendable, más de una instrucción en una línea
print ("Hola Ángel"); print("Adios")
# Para separar una instrucción en varias líneas usamos "\"
mi_nombre = "mi nombre es Juan!"
mi_nombre = "Mi nombre es\
Juan"
print(mi_nombre)
# El tipo de la variable lo define el contenido, en python todo son objetos
numero = 5
print(type(numero))
mensaje = """Esto es un mensaje
con tres saltos
de línea"""
print(mensaje)
# Operadores de comparación
if 2 < 3:
print("true")
else:
print("false") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.