blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f3059d2733e8637518dc102b66b596bfb07f9c5d | sanskarjain2507/full-stack-development | /python/list40.py | 86 | 3.765625 | 4 | list=['L1','L2']
if 'L1' in list:
print("present")
else:
print('not present')
|
00b1230c16298db372c1cec1696b6a7c7f0b3d28 | Cptgreenjeans/python-workout | /ch03-lists-tuples/e12b2_popular_shells.py | 445 | 3.5 | 4 | #!/usr/bin/env python3
"""Solution to chapter 3, exercise 12, beyond 2: shells_by_popularity"""
from collections import Counter
import operator
def shells_by_popularity(filename):
shells = Counter(one_line.split(':')[-1].strip()
for one_line in open(filename)
if not one_line.startswith(('#', '\n')))
return sorted(shells.items(),
key=operator.itemgetter(1), reverse=True)
|
06cded12396dc422c4d93af4d15efd991e619b51 | janania/python | /exercises/find_less.py | 263 | 3.734375 | 4 | l = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
new_lis = []
def less_five (lis):
for num in lis:
if num < 5:
new_lis.append(num)
new_lis.sort()
else:
continue
print(set(new_lis))
less_five(l)
|
1799e4d81d75ce5a5ad2c35cb1baad155c9c0369 | yimonima/git | /python_for_pygame/DrawCircle.py | 687 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#导入包
import pygame,sys
from pygame.locals import *
#屏幕初始化
pygame.init()
screen=pygame.display.set_mode((600,500))
pygame.display.set_caption("Draw Circle")
#事件处理机制
while True:
for event in pygame.event.get():
if event.type in (QUIT,KEYDOWN):
sys.exit()
#屏幕颜色初始化
screen.fill((255,255,255))
#定义园所需要的参数
circleColor=255,0,0
circlePosition=300,250
circleRadius=100
circleWidth=100
#开始画圆
pygame.draw.circle(screen,circleColor,circlePosition,circleRadius,circleWidth)
#页面刷新
pygame.display.update()
|
7a44934a650fb7fe441710674a70c580b46a93da | espiercy/py_junkyard | /python_udemy_course/51 class.py | 284 | 3.90625 | 4 |
#create class. You need to begin with an uppercase letter
class Person:
name=""
age=0
def show(self, n, a):
self.name=n
self.age=a
print(self.name, self.age)
#instance of class
p1=Person()
#method call
p1.show('Evan',22)
print(p1.name, p1.age) |
597c3444a008ff67fe262213bb9d9136bc55f9a7 | whitepaper2/data_beauty | /leetcode/057_insert.py | 1,230 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/28 下午1:05
# @Author : pengyuan.li
# @Site :
# @File : 057_insert.py
# @Software: PyCharm
from typing import List
def insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
"""
note: 顺序插入,遇到重叠的则合并
:param intervals:
:param newInterval:
:return:
"""
n = len(intervals)
cur_i = 0
out_stack = []
while cur_i < n and intervals[cur_i][1] < newInterval[0]:
out_stack.append(intervals[cur_i])
cur_i = cur_i + 1
while cur_i < n and intervals[cur_i][0] <= newInterval[1]:
newInterval[0] = min(intervals[cur_i][0], newInterval[0])
newInterval[1] = max(intervals[cur_i][1], newInterval[1])
cur_i = cur_i + 1
out_stack.append(newInterval)
while cur_i < n:
out_stack.append(intervals[cur_i])
cur_i = cur_i + 1
return out_stack
# Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
# Output: [[1,2],[3,10],[12,16]]
if __name__ == "__main__":
intervals = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]]
newInterval = [4, 8]
print(insert(intervals, newInterval))
pass
|
10eb30511f29adce39b1e02ef82f976bc2ba792d | disatapp/Operating-Systems | /Operating Systems/Homework2/Problem4.py | 726 | 4.15625 | 4 | # Pavin Disatapundhu
# disatapp@onid.oregonstate.edu
# CS344-400
# homework#2 Question4
import math
import sys
def findprime(prime):
i = 0
n = 2
isprime = True
while i < prime:
for j in range(2,int(math.sqrt(n)+1)):
if (n % j) == 0:
isprime = False
if isprime == True:
i += 1
if i == prime:
nprime = n
n += 1
isprime = True
print nprime
if __name__ == '__main__':
if(len(sys.argv) == 2):
prime = int(sys.argv[1])
if 1 <= prime <= 2300:
findprime(prime)
else:
sys.exit('Invalid: please enter a number between 1 and 2300')
else:
sys.exit('Invalid: please enter 2 arguments.')
|
06f5133e6d93d8bcc620da508f43474fc1984ab8 | brcsomnath/competitive-programming | /graph/maze.py | 1,251 | 4.25 | 4 | '''
The Maze II
There is a ball in a maze with empty spaces and walls. The ball can go through
empty spaces by rolling up, down, left or right, but it won't stop rolling until
hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, find the shortest
distance for the ball to stop at the destination. The distance is defined by the
number of empty spaces traveled by the ball from the start position (excluded) to
the destination (included). If the ball cannot stop at the destination, return -1.
The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty
space. You may assume that the borders of the maze are all walls. The start and
destination coordinates are represented by row and column indexes.
'''
directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
def dfs(src, dest, maze, cost, visited):
visited[src] = True
if src == dest:
return cost
for d in directions:
row, col = list(map(add, src, d))
if not visited[src] and maze[row][col] == 0:
ans = dfs([row, col], dest, maze, cost + 1, visited)
if ans >= 0:
return ans
return -1
def process(start, end, maze):
|
32da9e6b13808d61df60c7fa9cfa924b011efd30 | steja2891/Python_Practice-coding-files- | /min,max,avg.py | 312 | 3.515625 | 4 | n = int(input())
s = set()
l1 = []
for i in range(n):
l1.append(list(map(str, input().rstrip().split())))
print(l1)
dict = {"A":0,"B":0,"C":0}
for i in range(n):
if int(l1[i][2][0]) > int(l1[i][2][2]):
dict[l1[i][0][0]]
elif int(l1[i][2][0]) == int(l1[i][2][2]):
else:
print(dict)
|
f752a9b5302e2a7c036c474477dc8ba912402d44 | goaguilar/GoAguilar_CS50_Projects | /goaguilar-cs50-2017-fall-sentimental-credit/credit.py | 844 | 3.703125 | 4 | from cs50 import get_int
sum1 = 0
sum2 = 0
print("Number: ")
card = get_int()
tempcard1 = card
tempcard2 = card//10
while tempcard1> 0:
sum1 += tempcard1%10
tempcard1 //= 100
while tempcard2>0:
if ((tempcard2 % 10) *2 > 9 ):
sum2 += ((tempcard2 % 10)*2) // 10
sum2 += ((tempcard2 % 10)*2) % 10
else:
sum2 += (tempcard2%10)*2
tempcard2 //= 100
sumtotal = sum1 + sum2
if(sumtotal%10 == 0):
if((card >= 340000000000000 and card < 350000000000000) or (card >= 370000000000000 and card < 380000000000000)):
print("AMEX\n")
elif(card >= 5100000000000000 and card < 5600000000000000):
print("MASTERCARD\n")
elif((card >= 4000000000000 and card < 5000000000000) or (card >= 4000000000000000 and card < 5000000000000000)):
print("VISA\n")
else:
print("INVALID") |
e2b65e7caccb22dc37c1ff3402e20bca6c40f370 | andyballer/playingWithPython | /TypingDistance.py | 1,075 | 3.90625 | 4 | '''
Created on Nov 26, 2012
@author: Andy
'''
#returns the number of keys one has to traverse in order to type a message.
#uses a linear "keyboard" input to check how far apart the letters are
def minDistance(keyboard,word):
counter = []
library = []
for index, letter in enumerate(keyboard):
library += [(letter, index)]
print library
for char in word:
for letter in library:
if char in letter:
print letter[1]
counter.append(letter[1])
print counter
final = 0
x = 0
y = 0
for num in range(len(counter)):
if num+1 < len(counter):
final += abs((int(counter[num]) - int(counter[num+1])))
return final
#below a typical qwerty keyboard is represented by the first string. q is the first letter and m
#is the last, so there are 25 keys between them. The word below will have a total distance of
#1225, or 25 x 49.
print minDistance("qwertyuiopasdfghjklzxcvbnm","qmqmqmqmqmqmqmqmqmqmqmqmqmqmqmqmqmqmqmqmqmqmqmqmqm") |
0964c7b91b40a532ae1b5316d82105cd22b310bc | thiago-ximenes/curso-python | /pythonteste/aula13.py | 142 | 4 | 4 |
soma = 0
for c in range(0, 3):
n = int(input('Digite um valor: '))
soma += n
print('Fim')
print('O simatório foi: {}.'.format(soma)) |
da0370eeb4848ab5518ebbf2e7baae6891aecddb | b1ueskydragon/PythonGround | /codeit_kr/merge-sort.py | 1,657 | 4.21875 | 4 | def merge(list1, list2):
"""
merge binary lists.
each lists should be sorted.
this yields a new merged list.
:param list1: sorted list
:param list2: sorted list
:return: merged list
"""
merged = []
while list1 and list2:
if list1[0] <= list2[0]:
merged.append(list1.pop(0))
else:
merged.append(list2.pop(0))
while list1:
merged.append(list1.pop(0))
while list2:
merged.append(list2.pop(0))
return merged
def merge_index(list1, list2):
"""
same as `merge`
not pop, with index traverse
"""
merged = []
i1, i2 = 0, 0
while i1 < len(list1) and i2 < len(list2):
if list1[i1] <= list2[i2]:
merged.append(list1[i1])
i1 += 1
else:
merged.append(list2[i2])
i2 += 1
while i1 < len(list1):
merged.append(list1[i1])
i1 += 1
while i2 < len(list2):
merged.append(list2[i2])
i2 += 1
return merged
def merge_sort(my_list):
# edge case
if len(my_list) < 2:
return my_list
# Divide recursively
pivot = len(my_list) // 2
lows = my_list[:pivot]
# print(lows)
highs = my_list[pivot:]
# print(highs)
# Conquer recursively
return merge(merge_sort(lows), merge_sort(highs))
# test merge
print(merge([1, 3, 4], [-5, -4, -3, -2, 2, 8]))
print(merge_index([1, 3, 4], [-5, -4, -3, -2, 2, 8]))
print(merge([2], [1]))
print(merge_index([2], [1]))
print(merge([], [-1]))
print(merge([], [-1]))
# test merge_sort
some_list = [11, 3, 6, 4, 12, 1, 2]
print(merge_sort(some_list))
|
10a70e468758e501105cf77324bcd6a0efd7de82 | snarkfog/python_hillel | /lesson_09/number_digit.py | 1,519 | 4.28125 | 4 | """
10. Написать функцию, циклически сдвигающую целое число на N разрядов вправо или влево, в зависимости от третьего
параметра функции. Функция должна принимать три параметра: в первом параметре передаётся число для сдвига, второй
параметр задаёт количество разрядов для сдвига (по умолчанию сдвиг на 1 разряд), 3-й булевский параметр задаёт
направление сдвига (по умолчанию влево (False)).
"""
def num_dig(num, dig=1, way=False):
num = str(num)
if not way:
res = num[len(num) - dig:len(num)] + num[:len(num) - dig]
else:
res = num[dig:len(num)] + num[:dig]
return res
fact_num = int(input("Введите число: "))
fact_dig = int(input("Введите величину сдвига: "))
fact_way = None
while True:
fact_way = input("Введите направление сдвига (l - влево, r - вправо): ")
if fact_way == 'r':
fact_way = False
break
elif fact_way == 'l':
fact_way = True
break
else:
print("Необходимо вводить только 'l' или 'r'")
continue
fact_res = num_dig(fact_num, fact_dig, fact_way)
print("Результат сдвига:", fact_res)
|
7f9dbc50455ea03dc54045b90141a0a3df33104b | FluTheFire/Python-Algorithm-30-Days-Challenge | /Day-5 Longest Common Prefix [Runtime 20 ms].py | 377 | 3.640625 | 4 | def longestCommonPrefix(strs):
if strs == []:
return ""
s1, s2 = min(strs), max(strs)
i = 0
while i < len(s1) and i < len(s2) and s1[i] == s2[i]:
i += 1
return s1[:i]
raw_list = ["flower","flow","flight"]
raw_list2 = ["dog","racecar","care"]
raw_list3 = []
raw_list4 = ["aa", "a"]
print(longestCommonPrefix(raw_list4))
|
6c7ee61b2c7663d223bbcd1b02d146e9c4a6e532 | maddalen-ma/LorenzAttractor | /lorenz/solver.py | 12,539 | 3.65625 | 4 | """
This file may contain the ODE solver
"""
import numpy as np
np.seterr(over='raise') # raise error for floating-point overflow
class lorenz_solver(object):
"""
This is a class for managing parameters and calculating trajectories of a
Lorenz attractor.
The lorenz_solver class is constructed to associate a calculated trajectory
with a set of parameters. This means that if the trajectory has already
been calculated for a given object and a parameter of that object
is updated, then the trajectory will be deleted from the object.
Attributes:
sigma (float): A system parameter, ex 10.
beta (float): A system parameter, ex 3/8.
rho (float): A system parameter, ex 6.
init (list): A set of corrdinates, the starting point for the
calculation, [x,y,z].
N (int): Number of steps in the calculation.
t (float): Stepsize for the calculation.
euler_path (numpy.ndarray): The x,y,z trajectory returned by euler,
3 columns and N rows.
"""
def __init__(self, sigma, beta, rho, init, N=20000, t=0.02):
"""
The constructor for lorenz_solver class.
Parameters:
sigma (float): A system parameter, ex 10.
beta (float): A system parameter, ex 3/8.
rho (float): A system parameter, ex 6.
init (list): A set of coordinates, the starting point for the
calculation, [x,y,z].
N (int): Number of steps in the calculation.
t (float): Stepsize for the calculation.
"""
self._sigma = sigma
self._beta = beta
self._rho = rho
self._init = init
self._N = N
self._t = t
@property
def sigma(self):
"""
A class method to return the current value of the sigma property.
Parameter:
self: a lorenz_solver class object.
Returns:
float: the current sigma attribute value of self.
example
self.sigma
"""
return self._sigma
@sigma.setter
def sigma(self, sigma):
"""
A class method to update the current value of the sigma property.
If the lorenz_solver object contains an euler_path attribute when
the sigma value is updated the euler_path attribute is erased.
Parameter:
self: a lorenz_solver class object.
sigma (float): A system parameter.
Returns:
None
example
self.sigma = 14
"""
if sigma != self._sigma:
print("Updating sigma")
self._sigma = sigma
if hasattr(self,'_euler_path'):
print('Erasing existing trajectory')
delattr(self, '_euler_path')
else:
print("Supplied value is identical to current sigma parameter.")
@property
def beta(self):
"""
A class method to return the current value of the beta property.
Parameter:
self: a lorenz_solver class object.
Returns:
float: the current sigma attribute value of self.
example
self.beta
"""
return self._beta
@beta.setter
def beta(self, beta):
"""
A class method to update the current value of the beta property.
If the lorenz_solver object contains an euler_path attribute when
the beta value is updated the euler_path attribute is erased.
Parameter:
self: a lorenz_solver class object.
beta (float): A system parameter.
Returns:
None
example
self.beta = 13/3
"""
if beta != self._beta:
print("Updating beta")
self._beta = beta
if hasattr(self, '_euler_path'):
print('Erasing existing trajectory')
delattr(self, '_euler_path')
else:
print("Supplied value is identical to current beta parameter.")
@property
def rho(self):
"""
A class method to return the current value of the rho property.
Parameter:
self: a lorenz_solver class object.
Returns:
float: the current rho attribute value of self.
example
self.rho
"""
return self._rho
@rho.setter
def rho(self, rho):
"""
A class method to update the current value of the rho property.
If the lorenz_solver object contains an euler_path attribute when
the rho value is updated the euler_path attribute is erased.
Parameter:
self: a lorenz_solver class object.
rho (float): A system parameter.
Returns:
None
example
self.rho = 28
"""
if rho != self._rho:
print("Updating rho")
self._rho = rho
if hasattr(self, '_euler_path'):
print('Erasing existing trajectory')
delattr(self, '_euler_path')
else:
print("Supplied value is identical to current rho parameter.")
@property
def init(self):
"""
A class method to return the current value of the init property.
Parameter:
self: a lorenz_solver class object.
Returns:
list: the current init attribute value of self.
example
self.init
"""
return self._init
@init.setter
def init(self, init):
"""
A class method to update the current value of the init property.
If the lorenz_solver object contains an euler_path attribute when
the init property is updated the euler_path attribute is erased.
Parameter:
self: a lorenz_solver class object.
init (list): A system parameter.
Returns:
None
example
self.init = [0.1,0.1,1]
"""
if not np.shape(init) == (3,):
print('The shape and format of init should be: [x,y,z]')
return False
if init != self._init:
print("Updating init")
self._init = init
if hasattr(self, '_euler_path'):
print('Erasing existing trajectory')
delattr(self, '_euler_path')
else:
print("Supplied value is identical to current init parameter.")
@property
def N(self):
"""
A class method to return the current value of the N property.
Parameter:
self: a lorenz_solver class object.
Returns:
int: the current N attribute value of self.
example
self.N
"""
return self._N
@N.setter
def N(self, N):
"""
A class method to update the current value of the N property.
If the lorenz_solver object contains an euler_path attribute when
the N value is updated the euler_path attribute is erased.
Parameter:
self: a lorenz_solver class object.
beta (int): A system parameter.
Returns:
None
example
self.N = 50000
"""
if N <= 0:
print('The number of steps (N) cannot be less than 0.')
return False
if N != self._N:
print("Updating N")
self._N = N
if hasattr(self, '_euler_path'):
print('Erasing existing trajectory')
delattr(self, '_euler_path')
else:
print("Supplied value is identical to current N parameter.")
@property
def t(self):
"""
A class method to return the current value of the t property.
Parameter:
self: a lorenz_solver class object.
Returns:
float: the current t attribute value of self.
example
self.t
"""
return self._t
@t.setter
def t(self, t):
"""
A class method to update the current value of the t property.
If the lorenz_solver object contains an euler_path attribute when
the t value is updated the euler_path attribute is erased.
Parameter:
self: a lorenz_solver class object.
t (float): A system parameter.
Returns:
None
example
self.t = 0.01
"""
if t <= 0:
print('The stepsize (t) cannot be less than 0.')
return False
if t != self._t:
print("Updating t")
self._t = t
if hasattr(self, '_euler_path'):
print('Erasing existing trajectory')
delattr(self, '_euler_path')
else:
print("Supplied value is identical to current t parameter.")
@property
def euler_path(self):
"""
A class method to return the current value of the euler_path property.
Parameter:
self: a lorenz_solver class object.
Returns:
numpy.ndarray: the current N attribute value of self.
example
self.euler_path
"""
if hasattr(self, '_euler_path'):
return self._euler_path
else:
print('An euler_path attribute does not exist for this object.')
return False
def euler(self):
"""
A class method to calculate the trajectory of the Lorenz attractor
for the given parameter set. The trajectory is added to self as a
euler_path attribute.
Parameter:
self: a lorenz_solver class object.
Returns:
None
example
self.euler()
"""
if not np.shape(self._init) == (3,):
print('The shape and format of init should be: [x,y,z]')
return False
if self._N <= 0:
print('The number of steps (N) cannot be less than 0.')
return False
if self._t <= 0:
print('The stepsize (t) cannot be less than 0.')
return False
# initialize array of zeros with shape nrow = N and ncol = 3
path = np.zeros(shape=(self._N, 3))
# initialize the path array with the input coordinates from class obj.
path[0, :] = self._init
# the solver initiates in the second row of path with first row values
# as input, i.e. n = 1
n = 1
while n < self._N: # calculate the path over N cycles
# calculate x coordinate for the n'th step
try:
s = self._sigma * (path[n - 1, 1] - path[n - 1, 0])
path[n, 0] = (s * self._t + path[n - 1, 0])
except FloatingPointError:
raise Warning('euler: Floating point error when calculating '+
'position in x for step '+
'{} out of {} steps'.format(n, self._N))
return False
# calculate y coordinate for the n'th step
try:
r = self._rho - path[n - 1, 2]
path[n, 1] = ((path[n - 1, 0] * r - path[n - 1, 1]) * self._t
+ path[n - 1, 1])
except FloatingPointError:
print('euler: Floating point error when calculating '+
'position in y for step '+
'{} out of {} steps'.format(n, self._N))
return False
# calculate z coordinate for the n'th step
try:
b = self._beta * path[n - 1, 2]
path[n, 2] = ((path[n - 1, 0] * path[n - 1, 1] - b) * self._t
+ path[n - 1, 2])
except FloatingPointError:
print('euler: Floating point error when calculating '+
'position in z for step '+
'{} out of {} steps'.format(n, self._N))
return False
n += 1 # increment n by 1
self._euler_path = path
return
|
acbb3a30aaf6bd23138080044f720044915bdc72 | williamsyb/mycookbook | /algorithms/BAT-algorithms/Search & Sort/1-归并.py | 2,112 | 3.71875 | 4 | """
一、介绍
基本思想:
将数组array[0,...,n-1]中的元素分成两个子数组:array1[0,...,n/2]
和array2[n/2+1,...,n-1]。分别对这两个数组单独排序,然后将已排序的
两个子数组归并成一个含有n个元素的有序数组
二、步骤
递归实现
三、时间复杂度:O(N*logN)
四、归并排序的两点改进
* 在数组长度比较短的情况下,不进行递归,而是选择其他排序方案,如插入排序
* 归并过程中,可以用记录数组下标的方式代替申请新内存空间;从而避免array和
辅助数组间的频繁数据移动
"""
def merge(left, right): # 合并两个有序数组
l, r = 0, 0
result = []
while l < len(left) and r < len(right):
if left[l] <= right[r]:
result.append(left[l])
l += 1
else:
result.append(right[r])
r += 1
result += left[l:]
result += right[r:]
return result
def merge_sort(nums):
if len(nums) <= 1:
return nums
num = len(nums) >> 1
left = merge_sort(nums[:num])
right = merge_sort(nums[num:])
return merge(left, right)
# ------------------- 按第二个改进的修改----------------------------
temp = [0] * 100
def Merge(nums, low, mid, high):
i = low
j = mid + 1
size = 0
while i <= mid and j <= high:
if nums[i] < nums[j]:
temp[size] = nums[i]
i += 1
else:
temp[size] = nums[j]
j += 1
size += 1
while i <= mid:
temp[size] = nums[i]
size += 1
i += 1
while j <= high:
temp[size] = nums[j]
size += 1
j += 1
for i in range(size):
nums[low + i] = temp[i]
def Merge_sort(nums, low, high):
if low >= high:
return
mid = (low + high) >> 1
Merge_sort(nums, low, mid)
Merge_sort(nums, mid + 1, high)
Merge(nums, low, mid, high)
if __name__ == '__main__':
nums = [54, 26, 93, 17, 77, 31, 44, 55, 20]
Merge_sort(nums, 0, len(nums) - 1)
print(nums)
|
6f4555f3ded92b1d7eff489dededda89818cb45e | secfordoc23/MyFirstRepository | /GroupAssignment/Starbucks Junior.py | 3,077 | 3.59375 | 4 | """
Program: Starbucks Junior
File: StarbucksJunior.py
Author: Jason J Welch, Rita Allen, Eric Gavin
Date: 9/26/2019
Purpose: we are selling coffee for $2.00, tea for $1.75, and latte for $4.00;
in three sizes: tall with price factor of 1, grande with price factor
of 1.5, venti for price factor of 2
"""
from Validation import *
# constant variables
COFFEE_PRICE = 2.00
TEA_PRICE = 1.75
LATTE_PRICE = 4.00
TALL_PRICE_FACTOR = 1
GRANDE_PRICE_FACTOR = 1.5
VENTI_PRICE_FACTOR = 2
orderDescription = ""
# ============= main ================================
def main():
while True:
print("***************************************************************")
print("\t*** STARBUCKS JUNIOR ***")
print("\t*** Point of Sales ***")
print("***************************************************************\n")
print("*** Initial Menu ***")
print("\t1. Place Order")
print("\t2. Exit")
userSelection = input_menu_option("Option Selection: ", 2)
if userSelection == 2:
break
orderTotal = place_order()
display_order(orderTotal)
# END main
# =========== place_order ===============================
def place_order():
orderTotal = 0
while True:
print("Current Order:")
print(orderDescription, "\n")
print("*** Order Menu ***")
print("\t1. Coffee")
print("\t2. Tea")
print("\t3. Latte")
print("\t4. Order Complete")
itemSelection = input_menu_option("Option Selection: ", 4)
if itemSelection == 4:
break
sizeSelection = size_menu()
orderTotal += float(calculate_order(sizeSelection, itemSelection))
return orderTotal
# END place_order
# ============ calculate_order ========================
def calculate_order(sizeSelection, itemSelection):
global orderDescription
if sizeSelection == 1:
size = "Tall"
factor = TALL_PRICE_FACTOR
elif sizeSelection == 2:
size = "Grande"
factor = GRANDE_PRICE_FACTOR
else:
size = "Venti"
factor = VENTI_PRICE_FACTOR
if itemSelection == 1:
item = "Coffee"
price = COFFEE_PRICE
elif itemSelection == 2:
item = "Tea"
price = TEA_PRICE
else:
item = "Latte"
price = LATTE_PRICE
total = price * factor
orderDescription += "{} {} - ${:0,.2f}\n".format(size, item, total)
return total
# END calculate_order
# ============ size_initial_menu ==========================
def size_menu():
print("\n*** Size Menu ***")
print("\t1. Tall")
print("\t2. Grande")
print("\t3. Venti")
sizeSelection = input_menu_option("Select size: ", 3)
return sizeSelection
# END size_initial_menu
# ============ display_order ==========================
def display_order(total):
print("\n**** RECEIPT ****")
print(orderDescription)
print("==================")
print("Order Total: ${,.2f}\n\n".format(total))
# END display_order
# call main function
main()
|
677ef0a1c3dd7e2decc85beb533637cdf4f5622b | bofh69/aoc | /day10/part1.py | 2,307 | 3.671875 | 4 | #!/usr/bin/env python3
import sys
def read_file(file):
file = open(file, "r")
text = file.read()
file.close()
return text
if len(sys.argv) != 2:
raise Exception("Expected one argument")
inp = read_file(sys.argv[1])
inp = inp.split('\n')
width = len(inp[0])
height = len(inp) - 1
astroids = []
for y in range(height):
for x in range(width):
if inp[y][x] == '#':
astroids.append((x, y))
blocking = dict()
count = dict()
def is_between(first, second, third):
if third >= first:
if second >= first and second <= third:
return True
else:
if second <= first and second >= third:
return True
return False
def is_blocked(first, second):
fx, fy = first
sx, sy = second
dx, dy = sx - fx, sy - fy
if (first, second) in blocking:
return blocking.get((first, second))
for third in astroids:
if third != first and third != second:
tx, ty = third
if is_between(fx, tx, sx) and is_between(fy, ty, sy):
if sx - fx != 0:
if tx - fx == 0:
continue
delta1 = (sy - fy) / (sx - fx)
delta2 = (ty - fy) / (tx - fx)
if delta1 == delta2:
blocking[(first, second)] = True
blocking[(second, first)] = True
return True
else:
if (ty - fy == 0) or (ty - fy == 0):
continue
delta1 = (sx - fx) / (sy - fy)
delta2 = (tx - fx) / (ty - fy)
if delta1 == delta2:
blocking[(first, second)] = True
blocking[(second, first)] = True
return True
blocking[(first, second)] = False
blocking[(second, first)] = False
return False
for first in astroids:
(fx, fy) = first
c = 0
for second in astroids:
if first != second:
if not is_blocked(first, second):
c = c + 1
count[first] = c
max = 0
monitor = (0,0)
for astroid in astroids:
if count[astroid] > max:
max = count[astroid]
monitor = astroid
print(monitor, max)
|
f502fe63b3d08f80e0b12ca7bb3557642d12eb40 | sumaiyasara/guvi-codekata | /evenno.py | 175 | 3.625 | 4 | lower_limit, upper_limit = input().split()
lower_limit= int(lower_limit)
upper_limit= int(upper_limit)
for i in range(lower_limit+1,upper_limit):
if(i%2 == 0):
print(i)
|
27fefeb76f0706781727f804484bb57a412e7268 | daozun/Python | /base_python/video/video_if_and_or.py | 464 | 3.671875 | 4 | # python的逻辑运算符
py = input('你python学好了么:')
js = input('你前端精通了么:')
money = int(input('你的财产总和:'))
if py == '是' and js == '是' and money > 10000:
print('你可以进京了')
else:
print('再好好学学','厉害了,我的哥')
# 在Python中 and表示两个条件同时满足是才为真(js中的&&),or表示只要一个条件为真就为真(js中的||),还有一个not是取反的意思。 |
3da128dde82f6a0ea72c28abee7d7e4e3834ff96 | GwangWoon/_python | /GW0921/GW0921/GW0921.py | 1,537 | 3.6875 | 4 | #class Movie :
# '''영화클래스입니다.'''
# title = "앤트맨"
# director = "모름"
# def __init__(self, title, director) :
# self.title = title
# self.director = director
# print(self.title + " 생성")
# def showInfo(self) :
# print(self.title + ", " + self.director)
# def __del__(self) : #소멸자
# print(self.title + " 소멸")
#m1 = Movie("설국열차1","봉준호")
#m2 = Movie("쥬라기공원2","스티븐스필버그")
#m1.age = 20 #인스턴스에서만 사용할 수 있는 변수 추가
#m1.showInfo()
#print(m1.age)
#print(m1.title)
#m1.__class__.title = "암살" #인스턴스에서 클래스의 값 변경
#print(m1.title)
#print(m1.__class__.title)
#print(m2.__class__.title)
#print(m1.__doc__) # 주석 출력
#print(type(m2))
#m2 = m1#얕은복사, 같은 주소를 가르키게됨
#m2.showInfo()
#print(m2.age)
#print(id(m1)) #id()주소값
#print(id(m2))
######################################
class Movie :
count = 0
def __init__(self, title, director) :
self.title = title
self.director = director
__class__.count+=1
print(self.title + " 생성")
@staticmethod
def showCount1() :
print(Movie.count)
@classmethod
def showCount2(cls) :
print(cls.count)
m1 =Movie("a","b")
print(m1.count)
Movie.showCount1()
Movie.showCount2()
m1.showCount1()
m1.showCount2()
m2 =Movie("c","d")
print(m2.count)
Movie.showCount1()
Movie.showCount2()
m1.showCount1()
m1.showCount2() |
b59cf7393aae35a9b2a81e2acdb188c0160c980d | ad-vasilchenko/Avito_Python_Exam | /utils.py | 882 | 3.546875 | 4 | import time
from typing import Callable
def time_report(str_in: str, str_out: str) -> Callable:
"""
Этот декоратор выводит выводит комментарий о начале работе функции
и о времени её работы
"""
def outer_wrapper(func: Callable) -> Callable:
def inner_wrapper(*args, **kwargs):
print(str_in)
t1 = time.time()
result = func(*args, **kwargs)
t2 = time.time()
time_elapsed = t2 - t1
# Точно помню, что можно делать строки шаблоны, но за 2 минуты не нагуглил, поэтому так
print(str_out.replace("{}", str(int(time_elapsed))))
return result
return inner_wrapper
return outer_wrapper
|
b3e6a1ed4b2aa616179807ff3ded322e9e0ee0e1 | udhayprakash/PythonMaterial | /python3/10_Modules/15_turtle_module/traffic_light.py | 2,135 | 3.921875 | 4 | #!/usr/bin/python
"""
Purpose: Traffic Light Simulation
"""
import turtle
def draw_signal_stand():
"""Draw a nice housing to hold the traffic lights"""
tess.pensize(3)
tess.color("black", "white")
tess.begin_fill()
tess.forward(80)
tess.left(90)
tess.forward(157)
tess.circle(40, 180)
tess.forward(157)
tess.left(90)
tess.end_fill()
def circle(t, ht, colr):
"""Position turtle onto the place where the lights should be, and
turn turtle into a big circle"""
t.penup()
t.forward(40)
t.left(90)
t.forward(ht)
t.shape("circle")
t.fillcolor(colr)
def advance_state_machine():
global state_num # The global keyword tells Python not to create a new local variable for state_num
if state_num == 0: # Transition from state 0 to state 1
henry.color("darkgrey")
alex.color("darkgrey")
tess.color("green")
wn.ontimer(
advance_state_machine, 3000
) # set the timer to explode in 3000 milliseconds (3 seconds)
state_num = 1
elif state_num == 1: # Transition from state 1 to state 2
henry.color("darkgrey")
alex.color("orange")
wn.ontimer(advance_state_machine, 1000)
state_num = 2
elif state_num == 2: # Transition from state 2 to state 3
tess.color("darkgrey")
wn.ontimer(advance_state_machine, 1000)
state_num = 3
else: # Transition from state 3 to state 0
henry.color("red")
alex.color("darkgrey")
wn.ontimer(advance_state_machine, 2000)
state_num = 0
if __name__ == "__main__":
# Create a playground for turtles
wn = turtle.Screen()
wn.bgcolor("skyblue")
# Create turtles
tess = turtle.Turtle()
alex = turtle.Turtle()
henry = turtle.Turtle()
draw_signal_stand()
circle(tess, 40, "green")
circle(alex, 100, "orange")
circle(henry, 160, "red")
# This variable holds the current state of the machine
state_num = 0
advance_state_machine()
wn.listen() # Listen for events
wn.mainloop() # Wait for user to close window
|
c4bcd6eb8ed1961d0c1983d8f9a639321f7792cb | vilhelmp/adapy | /adapy/libs/date.py | 1,956 | 3.640625 | 4 |
def jd2gd(jd):
"""
From http://www.astro.ucla.edu/~ianc/python/_modules/date.html
Task to convert a list of julian dates to gregorian dates
description at http://mathforum.org/library/drmath/view/51907.html
Original algorithm in Jean Meeus, "Astronomical Formulae for
Calculators"
These functions were taken from Enno Middleberg's site of useful
astronomical python references:
http://www.astro.rub.de/middelberg/python/python.html
"Feel free to download, use, modify and pass on these scripts, but
please do not remove my name from it." --E. Middleberg
"""
#~ import string
jd=jd+0.5
Z=int(jd)
F=jd-Z
alpha=int((Z-1867216.25)/36524.25)
A=Z + 1 + alpha - int(alpha/4)
B = A + 1524
C = int( (B-122.1)/365.25)
D = int( 365.25*C )
E = int( (B-D)/30.6001 )
dd = B - D - int(30.6001*E) + F
if E<13.5:
mm=E-1
if E>13.5:
mm=E-13
if mm>2.5:
yyyy=C-4716
if mm<2.5:
yyyy=C-4715
months=["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
daylist=[31,28,31,30,31,30,31,31,30,31,30,31]
daylist2=[31,29,31,30,31,30,31,31,30,31,30,31]
h=int((dd-int(dd))*24)
mins=int((((dd-int(dd))*24)-h)*60)
sec=86400*(dd-int(dd))-h*3600-mins*60
# Now calculate the fractional year. Do we have a leap year?
if (yyyy%4 != 0):
days=daylist2
elif (yyyy%400 == 0):
days=daylist2
elif (yyyy%100 == 0):
days=daylist
else:
days=daylist2
hh = 24.0*(dd % 1.0)
mins = 60.0*(hh % 1.0)
sec = 60.0*(mins % 1.0)
dd = dd-(dd%1.0)
hh = hh-(hh%1.0)
mins = mins-(mins%1.0)
#~ print str(jd)+" = "+str(months[mm-1])+ ',' + str(dd) +',' +str(yyyy)
#~ print string.zfill(h,2)+":"+string.zfill(mins,2)+":"+string.zfill(sec,2)+" UTC"
#~ print (yyyy, mm, dd, hh, mins, sec)
return (yyyy, mm, dd, hh, mins, sec)
|
387230b3f4f9ff9377f48b56b6bd620667227731 | skenpatel4/internship_tasks | /day03/task1.py | 317 | 3.96875 | 4 | a = int(input("enter five numbers : "))
b = int(input("enter five numbers : "))
c = int(input("enter five numbers : "))
d = int(input("enter five numbers : "))
e = int(input("enter five numbers : "))
print(a)
print(b)
print(c)
print(d)
print(e)
average = (a+b+c+d+e)/5
print("Average is = ",average) |
5c79cda3ef553592e4bff67785da79cc6694cf98 | jewells07/Python | /OS_module.py | 973 | 3.765625 | 4 | import os
# print(dir(os)) #It will show which function what OS module can do
# print(os.getcwd()) #It will get current directory (on which folder are you)
# os.chdir("c://") #It will change current directory (You can search file in this path )
# print(os.getcwd()) #The it will show the which director you are
# print(os.listdir()) #This will show all the files you want (Empty bracket means current directoy)
# print(os.listdir("c://")) #This will show you files in in C:// path
# os.mkdir("This") #This will make directory (folder)
# os.makedirs("This/That") #This will make sub directory (folder in folder)
# os.rename("ee", "aa") #It will rename ur file
# print(os.environ.get("Path")) #It will show the Path of environment variable
# print(os.path.exists("c:\Program Files")) #IT will show True or false if file exists or not
|
7dc8a7f5dc74c312a47f39792c7c3031a87d75d0 | nbtt/sokoban_solver | /make_game.py | 2,517 | 3.796875 | 4 | # Usage:
# space: toggle pen up/pen down. default is pen up (green)
# arrow key (up/down/left/right) to move
# press number key to change the pen:
# 0: ground or nothing
# 1: wall
# 2: box
# 3: goal
# 4: box on goal
# 5: player
# 6: player on goal
# Enter: Save and exit
from os import system
from pynput import keyboard as K
def print_game():
global is_pen_down, color_pre_down, color_pre_up, color_post, pen_x, pen_y, n_row, n_col
system('cls')
for i in range(n_row):
if i != pen_x:
print("".join(game[i]))
else:
print("".join(game[i][:pen_y]),
color_pre_down if is_pen_down else color_pre_up, game[i][pen_y], color_post,
"".join([] if pen_y == n_col - 1 else game[i][pen_y + 1:]), sep='')
def on_press(k):
global is_pen_down, pen_x, pen_y, pen, pen_idx, game
try:
key_char = k.char
if len(key_char) == 1 and '0' <= key_char <= '6':
pen_idx = int(key_char)
except AttributeError:
if k == K.Key.up:
if pen_x > 0:
pen_x -= 1
elif k == K.Key.down:
if pen_x < n_row - 1:
pen_x += 1
elif k == K.Key.left:
if pen_y > 0:
pen_y -= 1
elif k == K.Key.right:
if pen_y < n_col - 1:
pen_y += 1
elif k == K.Key.space:
is_pen_down = not is_pen_down
elif k == K.Key.enter:
f = open(file_name, 'w')
f.write(str(n_row) + '\n' + str(n_col) + '\n')
for i in range(n_row):
f.write("".join(game[i]) + '\n')
f.close()
return False
if is_pen_down:
game[pen_x][pen_y] = pen[pen_idx]
print_game()
if __name__ == "__main__":
# _: ground or out of board
# @: wall
# +: box
# o: goal
# *: box on goal
# i: player
# $: player on goal
global color_pre_up, color_pre_down, color_post, pen_x, pen_y, n_row, n_col, game
pen = "_@+o*i$"
is_pen_down = False
pen_x = 0
pen_y = 0
pen_idx = 0
color_pre_up = '\33[42m'
color_pre_down = '\33[43m'
color_post = '\33[0m'
file_name = 'game_input.txt'
n_row = int(input("Number of rows: "))
n_col = int(input("Number of columns: "))
game = []
for _ in range(n_row):
game.append(['_' for _ in range(n_col)])
print_game()
with K.Listener(on_press=on_press, suppress=True) as listener:
listener.join() |
fc03eb379c22988723aee8c2309b6f8a9d020326 | Ni3h/CodeWars | /Mumbling.py | 530 | 3.53125 | 4 | """
Solution for the Mumbling question on codewars
https://www.codewars.com/kata/5667e8f4e3f572a8f2000039/train/python
Pretty simple, only 'complex thing' is to ensure that the - does not get
added to the first iteration of the newString
@author Ni3h
"""
def accum(s):
newString = ""
for i, letter in enumerate(s):
newAdd = (letter * (i+1)).capitalize()
if i == 0:
newString = newAdd
else:
newString = "-".join([newString, newAdd.capitalize()])
return newString
|
1c652f2548d6aa8e5c9d548df3d272049dda7886 | Larissa-D-Gomes/CursoPython | /introducao/exercicio057.py | 447 | 3.875 | 4 | """
EXERCÍCIO 057: Validação de Dados
Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'.
Caso esteja errado, peça a digitação novamente até ter um valor correto.
"""
def main():
leitura = input('Digite o sexo [M/F]: ')
while leitura != 'M' and leitura != 'F':
leitura = input('Dado invalido. Digite o sexo [M/F]: ')
print('Valor aceito.')
if __name__ == '__main__':
main()
|
a9c2bc08b10542fcd15a4028d16cd2872312d50b | edzzn/hackerRank-interview-preparation-kit | /array/3-new-year-chaos.py | 689 | 3.65625 | 4 | #!/bin/python3
# https://www.hackerrank.com/challenges/new-year-chaos
def minimumBribes(q, n):
diff = 0
for i in range(n):
item_to_find = n - i
correct_index = n - i - 1
current_index = q.index(item_to_find)
index_diff = correct_index - current_index
diff += index_diff
if (index_diff > 2):
diff = 'Too chaotic'
break
if (index_diff > 0):
q = q[:current_index] + q[current_index + 1:correct_index+1] + \
[item_to_find] + q[correct_index+1:]
return diff
if __name__ == '__main__':
q = [2, 1, 5, 3, 4]
n = 5
result = minimumBribes(q, n)
print(result)
|
ecc9f65ea8209c6a18b6512602ad1c212e3ad58d | Aasthaengg/IBMdataset | /Python_codes/p02664/s409260937.py | 447 | 3.609375 | 4 | a = input()
t = list(a)
if t[len(t)-1] == "?":
t[len(t)-1] = "D"
if t[0] == "?":
if t[1] == "D" or t[1] == "?":
t[0] = "P"
else:
t[0] = "D"
for i in range(1, len(t)-1):
if t[i] == "?" and t[i-1] == "P":
t[i] = "D"
elif t[i] == "?" and t[i+1] == "D":
t[i] = "P"
elif t[i] == "?" and t[i+1] == "?":
t[i] = "P"
elif t[i] == "?":
t[i] = "D"
answer = "".join(t)
print(answer) |
845719d60a2a83a26a7f90e157cbb24ccc5166d6 | BIGSergio123/Uece | /Silva.py | 225 | 3.84375 | 4 |
"""
program that says if you have Silva / SILVA in your last name
by: BIG
"""
N = str(input("digite seu nome completo:"))
palavras = N.split()
if 'Silva' or 'SILVA' in palavras:
print('sim')
else:
print('Não')
|
6a0d623bfc87bff605d8a60d7850d23c1ff06ea2 | khourhin/pyGen | /common.py | 396 | 3.734375 | 4 | #-------------------------------------------------------------------------------
def get_lst_from_file(infile):
"""
From a file with one entry per line, get a python list of these entries
"""
with open(infile, "r") as f:
elmt_l = [ line.strip() for line in f]
return elmt_l
#-------------------------------------------------------------------------------
|
b5f6a0217fbe9261e63dfdd25e31c7912058d1cb | apoorva9s14/pythonbasics | /mysamples/decorator.py | 462 | 4.1875 | 4 | #Difference between functions and generator
def g():
print('inside generator')
yield 1
g()
#The function call does not print 'inside generator'
#When the generator function is called, the function code is not executed
#Instead the function call returns a generator object
def f():
print('inside function')
return 1
f()
#Function call prints 'inside function' and 1
#as the code in the function body gets executed with the function call
|
efd6348454b0d1363ab8829e262e158894537bdc | patricksile/code_folder | /code_wars/5kyu_ascii_hex_converter.py | 1,620 | 4.28125 | 4 | #!/usr/bin/env python3.5
# Solution: ASCII hex converter
"""
Write a module Converter that can take ASCII text and convert it to hexadecimal.
The class should also be able to take hexacadecimal and convert it to ASCII text.
Example:
<code>
Converter.to_hex("Look mom, no hands") => "4c6f6f6b206d6f6d2c206e6f2068616e6473"
Converter.to_ascii("4c6f6f6b206d6f6d2c206e6f2068616e6473") => "Look mom, no hands"
</code>
"""
# My solution:
from codecs import encode, decode
class Converter():
# def __init__(self, h, s):
# self.h = hexadecimal
# self.s = string
@staticmethod
def to_ascii(h):
return decode(h, "hex")
@staticmethod
def to_hex(s):
return encode(s, "hex")
z = Converter()
print(z.to_ascii('6364'))
# Other Solutions:
# Solution 1: by g0loob, BartN, and 100 more other warriors
class Converter():
@staticmethod
def to_ascii(h):
return h.decode("hex")
@staticmethod
def to_hex(s):
return s.encode("hex")
# This solution will perfectly work in python 2 only since there is
# No more encode and decode in python 3 without the codecs libraries
# Solution 2: by EIOsoPolar, nkrause323
import binascii
class Converter():
@staticmethod
def to_ascii(h):
return binascii.a2b_hex(h)
@staticmethod
def to_hex(s):
return binascii.b2a_hex(s)
# Solution 3: By MMMAAANNN
class Converter():
@staticmethod
def to_ascii(h):
return ''.join(chr(int(h[i:i + 2], 16)) for i in range(0, len(h), 2))
@staticmethod
def to_hex(s):
return ''.join(hex(ord(char))[2:] for char in s)
|
8f7ab9d04f9b8e6a8cee051a2342845fe6c71b2a | lachesischan/comp20008-2021a1 | /parta1.py | 831 | 3.515625 | 4 | import pandas as pd
import argparse
import sys
url = 'https://covid.ourworldindata.org/data/owid-covid-data.csv'
df = pd.read_csv(url)
#add 'month' column into dataframe
df['date']= pd.to_datetime(df['date'])
df['month'] = df['date'].dt.month
#Select range of dates and columns needed and create a new dataframe
select_row = df.query("date >= '2020-02-24' and date <='2020-12-31'")
df1 = select_row[['location','month','total_cases','new_cases','total_deaths','new_deaths']]
# group the dataframe by location and month
pa1= df1.groupby(['location','month']).sum()
#Part A Task 1/2
pa1['case_fatality_rate'] = pa1['new_deaths']/pa1['new_cases']
cols = pa1.columns.tolist()
cols = cols[-1:] + cols[:-1]
pa1 = pa1[cols]
pa2 = pa1.head(5)
pa1.to_csv(sys.stdout)
filename = sys.argv[-1]
pa1.to_csv(filename)
print(pa2)
|
e10462eaa91dbb0d7659187bcb45d116982c8fd4 | MichelleZ/leetcode | /algorithms/python/expressionAddOperators/expressionAddOperators.py | 1,520 | 3.65625 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/expression-add-operators/
# Author: Miao Zhang
# Date: 2021-01-30
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
res = []
for i in range(1, len(num) + 1):
if i == 1 or (i > 1 and num[0] != '0'):
self.dfs(num[i:], num[: i], int(num[:i]), int(num[:i]), res, target)
return res
def dfs(self, num: str, path: str, cur: int, last: int, res: List[str], target: int) -> None:
'''
path: The intermediate process of each calculation
cur: the result of current path
last: the last num
res: return value
eg. num: 3, path: '1+2', cur: 3, last: 2
'+': num, path: '1+2+3', cur: cur + int(3) = 6, last: 3
'-': num, path: '1+2-3', cur: cur - int(3) = 0, last: -3
'*': num, path: '1+2*3', cur: cur - last + last * int(3) = 7, last: last * int(3) = 6
'''
if not num:
if cur == target:
res.append(path)
return
for i in range(1, len(num) + 1):
val = num[: i]
if i == 1 or (i > 1 and num[0] != '0'):
self.dfs(num[i:], path + '+' + val, cur + int(val), int(val), res, target)
self.dfs(num[i:], path + '-' + val, cur - int(val), -int(val), res, target)
self.dfs(num[i:], path + '*' + val, cur - last + last * int(val), last * int(val), res, target)
|
1013d8dc6a389fba6c2a6dce26e477ba0128cd24 | PPR123/Python_Programs | /ex009.py | 1,569 | 3.84375 | 4 | import math
import time
import emoji
import random
print(emoji.emojize(":car:"*random.randint(30,35),use_aliases=True))
print("Criando um usuário para jogar adivinhação em Python")
print(emoji.emojize(":car:"*random.randint(30,35),use_aliases=True))
n = 0
pnome = str(input("Digite seu Primeiro nome: ")).upper()
nome = str(input("Digite seu Nome completo {}: ".format(pnome))).upper().strip()
name = nome.split()
print("Seu nome completo é {}".format(" ".join(name)))
first = nome.split()
print("Seu nome de login será : {} {}".format(first[0],first[-1]))
certo = str(input("Digite o nome de usuário, que você quer ser chamado: "))
print("PROCESSANDO",end="")
while n < 8:
print("....",end="")
time.sleep(1.5)
n += 1
if len(certo) > len(nome):
print( "DIgite um nome de usuário válido: ")
else:
print(emoji.emojize("Usuário Cadastrado com sucesso: :thumbs_up:",use_aliases=True))
time.sleep(2)
import datetime
data = datetime.date.today()
print("-=-"*random.randint(30,35))
print("Bem Vindo ao Jogo da adivinhação sua primeira vez jogando este jogo cemeçou hoje: {}".format(data))
print("-=-"*random.randint(30,35))
vezes = 3
while vezes >= 1 :
resp = random.randint(0,5)
jogador = int(input("DIgite um número de 0 a 5: "))
if jogador == resp:
print("parabéns Você Ganhou")
break
else:
vezes -= 1
print("Você Perdeu tente novamente. resta apenas {} tentativas".format(vezes))
|
6374c04153457fd58a775611bbd43e18f326b4ac | mitant127/Python_Algos | /Урок 1. Практическое задание/task_9.py | 1,256 | 4.1875 | 4 | """
Задание 9. Вводятся три разных числа. Найти, какое из них является средним
(больше одного, но меньше другого).
Подсказка: можно добавить проверку, что введены равные числа
"""
NUMB_1 = int(input('Введите первое число: '))
try:
NUMB_1 = int(NUMB_1)
except ValueError:
print('Вы ввели не число')
NUMB_2 = int(input('Введите второе число: '))
try:
NUMB_2 = int(NUMB_2)
except ValueError:
print('Вы ввели не число')
NUMB_3 = int(input('Введите третье число: '))
try:
NUMB_2 = int(NUMB_2)
except ValueError:
print('Вы ввели не число!')
if NUMB_1 == NUMB_2 or NUMB_2 == NUMB_3 or NUMB_3 == NUMB_1:
print(f"Вы ввели одинаковые числа!")
else:
# MAX_NUMB = NUMB_1
if NUMB_1 < NUMB_2:
NUMB_1, NUMB_2 = NUMB_2, NUMB_1
if NUMB_2 < NUMB_3:
NUMB_2, NUMB_3 = NUMB_3, NUMB_2
if NUMB_3 > NUMB_1:
NUMB_3, NUMB_1 = NUMB_1, NUMB_3
if NUMB_1 < NUMB_2:
NUMB_1, NUMB_2 = NUMB_2, NUMB_1
print(f"Среднее число: {NUMB_2}")
|
7c58e4eb58790ad4a670a7d3e6ab1152369c806b | epanepucci/slic | /slic/utils/readable.py | 745 | 4 | 4 |
AVERAGE_WEEKS_PER_MONTH = 365.242 / 12 / 7
# each tuple gives a unit and the number of previous units which go into it
UNITS = (
("minute", 60),
("hour", 60),
("day", 24),
("week", 7),
("month", AVERAGE_WEEKS_PER_MONTH),
("year", 12)
)
def readable_seconds(secs):
# adapted from https://stackoverflow.com/a/18421524/655404
unit, number = "second", float(abs(secs))
for next_unit, ratio in UNITS:
next_number = number / ratio
# if the next number is small, don't go to the next unit.
if next_number < 2:
break
unit, number = next_unit, next_number
shown = int(round(number))
unit += "" if shown == 1 else "s"
return f"{shown} {unit}"
|
67dbbc1e80d646e0e892d64b7408b38a89112f12 | Anil-account/python-program | /square.py | 544 | 3.59375 | 4 | #to find power
# d=dict()
# for x in range(1,5):
# d[x]=x**2
# print(d)
#copy
# d1 = {'a':100, 'b':200}
# d2 = {'x':300, 'y':200}
# d = d1.copy()
# d.update(d2)
# print(d)
a=[]
dict ={'roll no' : [1,2,3,4,5], 'name' : ['ali','katy','sam','hasley','poppey'],'mark' : [55.0,99.8,78.0,67.0,45.0],'sex':['male','female','male','female','male']}
x = dict['sex']
for i in range(len(x)):
if (dict['sex'][i])=='male':
print("the roll of male is ", dict['roll no'][i] )
print("the name of student is ", dict['name'][i])
|
27212e85be48301f2b7aeecdfcb4e29016f777c5 | taech-95/python | /Beginner/CoffeeMachine/main.py | 3,485 | 3.75 | 4 |
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
"milk": 0,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
"money": 0
}#
money =0
#TODO Create a report which will show how much resources do we have
def printReport(resources):
report_water = resources["water"]
report_milk = resources["milk"]
report_coffee = resources["coffee"]
report_money=resources["money"]
print(f"Water: {report_water}")
print(f"Milk: {report_milk}")
print(f"Coffee: {report_coffee}")
print(f"Money: ${report_money }")
# printReport(resources,money)
#Todo Function which will serve menu
def serve_menu(user_choise):
money =0
if user_choise == "cappuccino" or user_choise =="espresso" or user_choise =="latte":
enough_resources=resources_sufficient(resources,user_choise)
if(enough_resources):
money = process_coins()
water_from_order = MENU[user_choise]["ingredients"]["water"]
coffee_from_order = MENU[user_choise]["ingredients"]["coffee"]
milk_from_order = MENU[user_choise]["ingredients"]["milk"]
resources["water"]-=water_from_order
resources["coffee"]-=coffee_from_order
resources["milk"]-=milk_from_order
print(f"Here is ${money} in change")
if money>MENU[user_choise]["cost"]:
resources["money"]+=(MENU[user_choise]["cost"])
print(f"Here is your {user_choise}! Enjoy")
else:
print("Sorry there is not enough money")
elif user_choise == "report":
printReport(resources)
else:
print("Wrong :(")
print(MENU["cappuccino"]["cost"])
#Todo Create functions which will check sufficient resources
def resources_sufficient(resources, order):
water_from_order = MENU[order]["ingredients"]["water"]
coffee_from_order = MENU[order]["ingredients"]["coffee"]
milk_from_order = MENU[order]["ingredients"]["milk"]
if resources["water"]>=water_from_order and resources["coffee"]>= coffee_from_order and resources["milk"]>=milk_from_order:
return True
elif resources["water"]<water_from_order:
print("Sorry there is not enough water")
return False
elif resources["milk"] < milk_from_order:
print("Sorry there is not enough milk")
return False
else:
print("Sorry there is not enough coffee")
return False
#Todo Create function which will processes coins
def process_coins():
print("Please insert coins.")
quarters = int(input("How many quarters?: "))
dimes = int(input("how many dimes?: "))
nickels = int(input("How many nickels?: "))
pennies = int(input("how many pennies?: "))
sum_of_coins = quarters*0.25 + dimes*0.10 + nickels*0.05 + pennies*0.01
return sum_of_coins
user_input_flag = True
while user_input_flag:
user_choise = input("What would you like? (espresso/latte/cappuccino): ").lower()
if user_choise=="exit":
user_input_flag=False
else:
serve_menu(user_choise)
|
8c5617b2811f20964956d698cda2e6ff64c8c803 | lapis2002/word-concordance | /a4/concordance.py | 3,700 | 3.59375 | 4 | import sys
import re
PATTERN = r'''^((\w|\-)+$'''
class KWOC:
def __init__(self, filename, exceptions):
self.text = (self.get_content(filename))
self.exclusion_words = self.get_exclusion_words(exceptions)
def get_content(self, filename):
input_txt = open(filename, "r")
content = []
for line in input_txt:
line = line.rstrip("\n")
content.append(line)
# print(content)
input_txt.close()
return content
# assume exceptions exists
def get_exclusion_words (self, exceptions):
exclusion_pat = ""
if (exceptions):
exclusion_input = open(exceptions, "r")
content = []
for line in exclusion_input:
line = line.rstrip("\n")
content.append(line)
# print(exclusion_words)
# print()
exclusion_input.close()
exclusion_words = ""
for i in range(len(content)):
exclusion_words += r"\b" + content[i]
if i != len(content)-1:
exclusion_words += r"\b|"
# print("exclude", exclusion_words)
exclusion_pat = r"\b(?!" + \
exclusion_words + r"\b)\w*['-]?\w+\b"
# print()
# print(exclusion_pat)
return exclusion_pat
# pattern not enough
def get_words(self):
pat = self.exclusion_words
if not pat:
pat = r"\b\w*'?\w+\b"
# pat = r"\b(?!the\b|a\b|or\b)w*'?\w+\b"
# print("pattern", pat)
# print("text", self.text)
# text = "\n".join(self.text)
# print("text", self.text)
# print("pattern", pat)
words = re.findall(pat, "\n".join(self.text), re.IGNORECASE)
# print(words)
return words
# fix this to handle more than 1 word in 1 line
def find_word(self, word):
# print(word)
pat = r"\b" + word + r"(?![-|'])\b"
# print(self.text)
res = []
for i in range(len(self.text)):
match = re.findall(pat, self.text[i], re.IGNORECASE)
if match:
# print(match)
# print()
res.append((self.text[i], i, len(match)))
return res
def words_preprocessing(self):
# self.text = self.text.split("\n")
words = self.get_words()
words = list(set([word.lower() for word in words]))
words.sort()
# print(words)
return words, len(max(words, key=lambda x: len(x)))
# text preprocessing
# no longer print the keyword
def print_word(self, word, longest_word_len):
match = self.find_word(word)
keyword_format = word.upper() + " "*(longest_word_len - len(word)+2)
res = []
# not handle more than two words appear in 1 line yet i.e (1*)
for i in range(len(match)):
if match[i][2] > 1:
res.append( keyword_format + match[i][0] + " (" + str(match[i][1]+1) + "*)")
else:
res.append(keyword_format +
match[i][0] + " (" + str(match[i][1]+1) + ")")
# print("match", match)
# print()
return res
def print_list(self):
word_list, max_len = len(self.words_preprocessing())
res = []
for word in word_list:
res.append(self.print_word(word, max_len))
def concordance(self):
word_list, max_len = self.words_preprocessing()
res = []
for word in word_list:
for s in self.print_word(word, max_len):
res.append(s)
return res
|
3520fd2169e9e2256c8a7d315c0e2670befc572d | caiquemarinho/python-course | /Exercises/Module 04/exercise_01.py | 124 | 4.09375 | 4 | """
Create a program that reads a int number and prints it.
"""
num = 4
print(f'Your number is {num}')
print(type(num))
|
dcf4adb951d4f0fd4cd967e54daf85fe85b1a5f4 | VictorYXL/Machine_Learning | /FP Growth/Node.py | 852 | 3.734375 | 4 | class Node:
def __init__(self, name, parent):
self.name = name
self.count = 1
self.parent = parent
self.children = {}
self.next = None
def inc(self, num = 1):
self.count += num
def show(self, ind = 1):
print("Deep %d: %s, %d" % (ind, self.name, self.count))
if self.parent == None:
print(" Parent: None")
else:
print(" Parent: %s" % self.parent.name)
childList = [child.name for child in self.children.values()]
print(" Children:%s" % str(childList))
for child in self.children.values():
child.show(ind + 1)
if __name__ == "__main__":
a = Node('a', 2, None)
b = Node('b', 1, a)
c = Node('c', 1, a)
d = Node('d', 0, b)
a.children = [b, c]
b.children = [d]
a.show()
|
5d4c83a85d8b52be9848d9de1e9a6fcdeda732d9 | sysPursuer/learnPy | /FurFunction.py | 544 | 3.71875 | 4 | #在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,
#这5种参数都可以组合使用。但是请注意:
#参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数
def f1(a,b,c=0,*agrs,**kw):
print('a=',a,'b=',b,'c=',c,'agrs=',agrs,'kw=',kw)
def f2(a,b,c=0,*,d,**kw):
print('a=',a,'b=',b,'c=',c,'d=',d,'kw=',kw)
f1(1,2)
f1(1,2,3)
f1(1,2,3,'a','b')
f1(1,2,3,'a','b',x=99)
f2(1,2,d=3,ext=None,hehe='hehe') |
85d3120f72558edc3a788fc6037d212f3ffb016b | tacenee/AFR | /剑指offer66/python/13调整数组顺序使奇数在偶数前面.py | 425 | 3.5625 | 4 | # -*- coding:utf-8 -*-
class Solution:
def reOrderArray(self, array):
# write code here
# 类似于选择排序,从后往前,如果前偶后奇就调换两个数字的位置
for i in range(len(array)):
for j in range(i, 0, -1):
if array[j] % 2 == 1 and array[j - 1] % 2 == 0:
array[j], array[j - 1] = array[j - 1], array[j]
return array
|
e2fca34394b09139da83a774ee39aebd49eb7c59 | KobiShashs/Python | /25_Advannced_Generators/4_pipelining_generators.py | 197 | 3.78125 | 4 | #integers (1-10) ----> squared(x^2) ----> negated(x*(-1))
integers = (i for i in range(1,11))
squared = (x * x for x in integers)
negated = (-y for y in squared)
for num in negated:
print(num) |
ffc61527526f16747b5b78d77af95036c644dffe | daniel-reich/ubiquitous-fiesta | /d6wR7bcs4M6QdzpFj_3.py | 298 | 3.609375 | 4 |
def repeat(lst, n):
k = lst[:]
for _ in range(n-1):
lst.extend(k)
return lst
def add(lst, x):
lst.append(x)
return lst
def remove(lst, i, j):
k = j - i + 1
for _ in range(k):
lst.pop(i)
return lst
def concat(lst, lst2):
lst.extend(lst2)
return lst
|
509b01b157f6d6a4dabdf57ad3726dc717b0b2b9 | moki298/HadoopMapReduce | /reducer.py | 1,760 | 3.78125 | 4 | #!/usr/bin/env python
from operator import itemgetter
import sys
#Declaring and intializing the variables
word = None
cur_count = 0
cur_word = None
max_sub = 0
max_sub_name = None
min_sub = 1
min_sub_name = None
list = []
for line in sys.stdin:
#stripping the whitespaces in data
line=line.strip()
#spliting the line to word,count
try:
word,count = line.split('\t\t')
except ValueError:
pass
#converting count variable from string to int
try:
count = int(count)
except ValueError:
continue
#The mapreduce framework automatically sorts the output of mapper program based on key, we are going to use it in counting
if cur_word == word:
cur_count += count
else:
if cur_word:
if max_sub < cur_count:
max_sub_name = cur_word
max_sub = cur_count
if min_sub >= cur_count:
min_sub_name = cur_word
min_sub = cur_count
print "%s\t%s" %(cur_word,cur_count)
list.append(cur_count)
cur_count = count
cur_word = word
if cur_word == word:
if max_sub < cur_count:
max_sub_name = cur_word
max_sub = cur_count
if min_sub > cur_count:
min_sub_name = cur_word
min_sub = cur_count
print "%s\t%s" %(cur_word,cur_count)
list.append(cur_count)
print "maximum_subject\t%s" %(max_sub_name)
print "minimum_subject\t%s" %(min_sub_name)
list.sort()
print "count_median\t%s" %(list[len(list)/2])
print "count_average\t%s" %(sum(list)/len(list))
|
3cd1eb502fee193f0576b6f81032c9842a8927dd | ronek22/ProjectEuler | /Python/027.py | 642 | 3.8125 | 4 | '''Quadratic primes'''
from math import sqrt; from itertools import count,islice
def isPrime(n):
return n>1 and all(n%i for i in islice(count(2), int(sqrt(n)-1)))
primes = set()
for i in range(1,10000):
if isPrime(i):
primes.add(i)
max_count = 0
formula = ""
max_a = 0
max_b = 0
for a in range(-999,1000):
for b in range(-1000,1001):
n=0
while (n*n+a*n+b) in primes:
n+=1
if(n>max_count):
max_count = n
formula = "n^2 + %dn + %d" % (a,b)
max_a, max_b = a,b
print "FORMULA: %s has %d primes" % (formula,max_count)
print "PRODUCT = %d" % (max_a*max_b)
|
6991b76e5b0501ef85bf4a1353d0bc9eb17b3623 | tegarimansyah/malas-cli | /malas-cli/malas_config/plugins/tegarimansyah/hello_world.py | 427 | 3.546875 | 4 | import click
from PyInquirer import prompt
questions = [
# Learn more in https://github.com/CITGuru/PyInquirer#question-types
{
'type': 'input',
'name': 'name',
'message': 'Your name?',
}
]
@click.command()
def command():
"""Do some greeting"""
answers = prompt(questions)
if answers:
name = answers.get("name")
click.echo(f"Welcome to the lazy world, {name}") |
fb890e9a8982ba826473ce5e78d0e6edfcfa4e1a | sreenivasgithub/tusk | /firstfile.py | 153 | 3.703125 | 4 | def add(a,b):
return a+b
obj = add(10,20)
print(obj,'enuf')
print(obj,'enuf')
print(obj,'enuf')
print(obj,'enuf')
print(obj,'enuf')
print(obj,'enuf') |
c387d1ddd8f3f9977a625db4d677fd9a388346c1 | noeljt/ComputerScience1 | /hws/hw4/hw4_part3.py | 815 | 3.515625 | 4 | """
Horror Movie Stuff.
Author: Joe Noel (noelj)
"""
def block(s, length):
sen = list(s)
sen.append(" ")
mystr = ""
line = []
n = 0
while n < (length*10):
line.append(n)
n += 1
while (mystr.count("\n")) < 9:
for x in line:
if (x+1) < len(sen) and (x+1)%length != 0:
mystr += sen[x]
elif (x+1) >= len(sen) and (x+1)%length != 0:
mystr += sen[(x)-len(sen)*(x/len(sen))]
elif (x+1)%length == 0:
mystr += sen[(x)-len(sen)*(x/len(sen))] + "\n"
print mystr
###############
## Main Code ##
###############
s = raw_input('Please enter a line ==> ')
print s
length = int(raw_input('Please enter a line length ==> '))
print length
block(s, length) |
d94cb3983ea29c2ff19b1e2369fcf13ba9d4c2f7 | palobde/INF8215---Introduction-to-AI | /Solving Travelling salesman problem using_Astar_2opt alg/code/A_star/A_star.py | 2,580 | 3.5625 | 4 | import time
time.clock()
import queue as Q
from Graph import Graph
SOURCE = 0
from Solution import Solution
class Node(object):
def __init__(self, v, sol, heuristic_cost=0):
self.v = v
self.solution = sol
self.heuristic_cost = heuristic_cost
def explore_node(self, heap):
for not_visited in self.solution.not_visited:
if not_visited==SOURCE and len(self.solution.not_visited)>1:
continue
else:
new_solution = Solution(self.solution)
new_solution.add_edge(self.v, not_visited)
new_node = Node(not_visited, new_solution, heuristic_cost=0)
heap.put((new_node.solution.cost,new_node))
## print(' Sol potentielle: ',new_node.solution.visited,' Cout (g) = ',new_node.solution.cost)
def __lt__(self, other):
if isinstance(other, Node):
isN2betterThanN1(other, self)
else:
raise ValueError('you should give a Node for comparison')
def main():
g = Graph('N12.data')
import Kruskal
Kruskal.kruskal = Kruskal.Kruskal(g)
heap = Q.PriorityQueue()
finish = 0
current_node = Node(SOURCE, Solution(g), heuristic_cost=0)
nCreated=1
nExplored=0
print('Debut: ',current_node.solution.visited)
trial = 0
while not finish and trial <= 1E9:
if len(current_node.solution.visited)>=g.N + 1:
finish = 1
trial = trial + 1
else:
current_node.explore_node(heap)
nExplored+=1
nCreated+=(len(current_node.solution.not_visited)-1)
current_node = heap.get()[1]
## print(' ')
## print('Voici la solution courante: ', current_node.solution.visited)
## print(' non-visites: ', current_node.solution.not_visited)
## print(' Cout: ', current_node.solution.cost)
## print(' Nb fils: ',len(current_node.solution.not_visited)-1,' Nb noeuds crees: ',nCreated,' Nb noeuds explores: ',nExplored)
trial = trial + 1
print(' ')
print('TERMINE')
print('Voici la solution finale: ', current_node.solution.visited)
print(' ')
print('SOLUTION PROPOSEE: ')
current_node.solution.print_solution()
print('Noeuds crees: ',nCreated,' Noeuds explores: ',nExplored)
print('CPU Time (sec): ',time.clock())
def isN2betterThanN1(N1, N2):
if N2.solution.cost <= N1.solution.cost:
return True
else:
return False
if __name__ == '__main__':
main()
|
e0d57e7e726eef80279eba9e511275b4cf20e506 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/point-mutations/44a2c3f5f71d4cf582bf2ba94e385d4d.py | 312 | 3.78125 | 4 | #!/usr/bin/env python
class DNA:
def __init__(self, sequence):
self.sequence = sequence
def hamming_distance(self, other_sequence):
distance = 0
for n1, n2 in zip(self.sequence, other_sequence):
if n1 != n2:
distance += 1
return distance
|
d6e793f67717eb8c3f673b6bab3eeb1b2b7183d6 | PythonCore051020/HW | /HW01/zoreastr/task_2.py | 183 | 3.78125 | 4 | print("What is your name?")
a = input("")
print("How old are you?")
b = input()
print("Where do you live?")
c = input("")
print("Hello",a,".","Your age is",b,".","You live in",c,".") |
ee50cdc39d432cd8ea9e2a41277a84621056236b | KomalNimbalkar30/Hackerrank-Python-Solutions- | /Collections_deque.py | 609 | 3.703125 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import deque
n=int(input())
d = deque()
for _ in range(n):
s=input().split()
if s[0]=='append':
d.append(s[1])
elif s[0]=='appendleft':
d.appendleft(s[1])
elif s[0]=='pop':
d.pop()
elif s[0]=='popleft':
d.popleft()
elif s[0]=='extend':
d.extend(s[1])
elif s[0]=='remove':
d.remove(s[1])
elif s[0]=='reverse':
d.reverse()
elif s[0]=='rotate':
d.rotate(s[1])
for i in d:
print(i,end=' ')
|
bfe030e6142ae90f6cd997ef3a25045b3f5077e6 | leo-ware/leetcode | /14. Longest Common Prefix.py | 587 | 3.828125 | 4 | """
https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
"""
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not len(strs):
return ""
prefix = []
for i in range(min(len(x) for x in strs)):
char = strs[0][i]
if all(x[i] == char for x in strs):
prefix.append(char)
else:
break
return "".join(prefix)
|
0730e6de761ab9080d6b3ec960e8e893c2290c70 | historybuffjb/leetcode | /problems/middle_of_the_linked_list.py | 1,011 | 4.28125 | 4 | """
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
"""
from test_utils import ListNode
def middle_node(head: ListNode) -> ListNode:
"""
Explanation
We could just loop through all the nodes putting their memory addresses in a list. Then we just get the median of
the list. But here we can use the turtle and the hair approach and have a fast pointer and a slow pointer. The
fast pointer moves twice as fast as the slow pointer and thus when the fast pointer reaches the end the slow pointer
should be in the middle.
"""
turtle = hair = head
while hair and hair.next:
turtle = turtle.next
hair = hair.next.next
return turtle
"""
Run DETAILS
Runtime: 28 ms, faster than 83.72% of Python3 online submissions for Middle of the Linked List.
Memory Usage: 14.2 MB, less than 76.47% of Python3 online submissions for Middle of the Linked List.
"""
|
e73a60c5f5846da19d9afe6386ac2759322c21bd | 0gravity000/IntroducingPython | /05/050501.py | 1,135 | 3.8125 | 4 | # 5.5.1 setdefault()とdefaultdict()による存在しないキーの処理
periodic_table = {'Hydrogen': 1, 'Helium': 2}
print(periodic_table)
carbon = periodic_table.setdefault('Carbon', 12)
carbon
periodic_table
helium = periodic_table.setdefault('Helium', 947)
helium
periodic_table
#
from collections import defaultdict
periodic_table = defaultdict(int)
periodic_table['Hydrogen'] = 1
periodic_table['Lead']
periodic_table
#
from collections import defaultdict
def no_idea():
return 'Huh?'
bestiary = defaultdict(no_idea)
bestiary['A'] = 'Abominable Snowman'
bestiary['B'] = 'Basilisk'
bestiary['A']
bestiary['B']
bestiary['C']
#
bestiary = defaultdict(lambda: 'Huh?')
bestiary['E']
from collections import defaultdict
food_counter = defaultdict(int)
for food in ['spam', 'spam', 'eggs', 'spam']:
food_counter[food] += 1
for food, count in food_counter.items():
print(food, count)
#
dict_counter = {}
for food in ['spam', 'spam', 'eggs', 'spam']:
if not food in dict_counter:
dict_counter[food] = 0
dict_counter[food] == 1
for food, count in dict_counter.items():
print(food, count) |
23623ffa940cfd772b6b56ff445330b963e7f8bf | nandoribera/PYTHON | /binario.py | 239 | 3.84375 | 4 | print("CONVERSOR DE BINARIO A DECIMAL")
print("Introduce el número binario")
binario = input()
binario = list(binario)
binario.reverse()
x = 0
num = 0
while x < len(binario):
if binario[x] == "1":
num += 2 ** x
x = x + 1
print(num) |
20e411ed4e52cb501b8daed143fd4e2068774011 | deanjingshui/Algorithm-Python | /8_动态规划/337. 打家劫舍 III.py | 2,446 | 4.5 | 4 | """
在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。
除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列
类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
示例 1:
输入: [3,2,3,null,3,null,1]
3
/ \
2 3
\ \
3 1
输出: 7
解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.
示例 2:
输入: [3,4,5,1,3,null,1]
3
/ \
4 5
/ \ \
1 3 1
输出: 9
解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/house-robber-iii
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
author:leetcode
date:2021.3.31
思路:树形动态规划
思路与“打家劫舍”一致
状态转移方程:
有2种前置状态
<1偷root节点:root.val + rob(root.left.left) + rob(root.left.right) + rob(root.right.left) + rob(root.right.right)
<2不偷root节点:rob(root.left) + rob(root.right)
rob(root) = max(<1, <2)
结果:大用例超出时间限制
"""
def rob(self, root: TreeNode) -> int:
if root is None:
return 0
money_1 = root.val
if root.left:
money_1 += self.rob(root.left.left) + self.rob(root.left.right)
if root.right:
money_1 += self.rob(root.right.left) + self.rob(root.right.right)
money_2 = self.rob(root.left) + self.rob(root.right)
return max(money_1, money_2)
node_1 = TreeNode(3)
node_2 = TreeNode(4)
node_3 = TreeNode(5)
node_4 = TreeNode(1)
node_5 = TreeNode(3)
node_6 = TreeNode(1)
node_1.left = node_2
node_1.right = node_3
node_2.left = node_4
node_2.right = node_5
node_3.right = node_6
my_sol = Solution()
print(my_sol.rob(node_1)) |
f0890b75c3c25dfcbb281f0881f8e215f9a72c1e | AK-1121/code_extraction | /python/python_23844.py | 138 | 3.515625 | 4 | # Python create tuples using function returning multiple values
new_list = [(name, value) + extra_info(name) for name, value in old_list]
|
998d2eed70afbff9022441332b85b2b50b446942 | alienlien/algorithm | /python/02/binary.py | 549 | 4 | 4 | #!/usr/bin/env python3
import math
def binary_search(in_list, x):
length = len(in_list)
if length == 0:
return []
if x < in_list[0]:
return [-1, 0]
if x > in_list[-1]:
return [length-1, length]
start = 0
end = length
while ((end - start) >= 2):
middle = math.floor((start + end)/2)
if in_list[middle] < x:
start = middle
else:
end = middle
return [start, end]
if __name__ == '__main__':
print(binary_search([1, 2, 4, 4, 5, 6, 9], 8))
|
bf03ac3b62b7740f12ddf5e5b10a706c788b9eea | chowdhurykaushiki/python-exercise | /PracticePython/Exercise25.py | 1,985 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
You, the user, will have in your head a number between 0 and 100.
The program will guess a number,
and you, the user, will say whether it is too high, too low, or your number.
At the end of this exchange,
your program should print out how many guesses it took to get your number.
"""
class inputError(Exception):
pass
class guessGame:
def guessNum(self,minRange,maxRange):
nguess=random.randint(minRange,maxRange)
return nguess
def printGuess(self,guess):
print('Guess: ',guess)
userInp=int(input("Press 1: if the guess was too high \n Press 2: if the guess was too low \n Press 3: if correct!\n"))
if userInp not in (1,2,3):
raise inputError
return userInp
if __name__=="__main__":
import random
try:
print("Hey there!\n pick a range of number and I will guess it!!")
minRange=int(input('minRange: '))
maxRange=int(input('maxRange: '))
numList=list(range(minRange,maxRange+1))
midNumIdx=numList[int(len(numList)/2)]
guess=numList[midNumIdx]
gOBJ=guessGame()
userInp=int(gOBJ.printGuess(guess))
count=1
print('count: ',count)
print('userInp: ',userInp)
while userInp != 3:
count=count+1
if userInp == 1:
maxRange=guess-1
guess=gOBJ.guessNum(minRange,maxRange)
userInp=int(gOBJ.printGuess(guess))
elif userInp==2:
minRange=guess+1
guess=gOBJ.guessNum(minRange,maxRange)
userInp=int(gOBJ.printGuess(guess))
else:
break
print('Viola! I guessed correct with ',count,' attempt!!')
except inputError :
print('invalid input')
except ValueError:
print('Invalid value entered,Better Luck next time!')
except Exception as e:
print('Error: ',e)
|
86f2116cf4d058acb5de42cd3cda7fdd628f1c3b | Vovanuch/python-basics-1 | /elements, blocks and directions/strings/string_template_format.py | 643 | 3.984375 | 4 | '''
strings format
'''
sentence = 'Moscow is the capital of Russia'
template = '{} is the capital of {}'
print(sentence)
print(template.format("Minsk", "Resp.Belarus'"))
print(template.format("Tegeran", "Iran"))
#print(str.format.__doc__)
# directly change the order of arguments
print()
print('directly change the order of arguments ')
template2 = '{1} is the capital of {0}'
print(template2.format("Iraq", "Bagdad"))
# named arguments
print()
print('named arguments')
template3 = '{capital} is the capital of {country}'
print(template3.format(country="Iraq", capital="Bagdad"))
print(template3.format(capital="Deli", country="India"))
|
38f35b84329018a569bf06546d9501866416c778 | AmineAouragh/PONG-2.0 | /testscreen.py | 1,838 | 3.8125 | 4 | # Import the pygame library and initialise the game engine
import pygame
import colors
from paddle import Paddle
from ball import Ball
pygame.init()
class GameScreen:
sprites_list = []
left_paddle = Paddle(colors.WHITE, 20, 120)
right_paddle = Paddle(colors.WHITE, 20, 120)
ball = Ball(colors.WHITE, 20, 20)
def __init__(self, size, color):
self.screen = pygame.display.set_mode(size)
self.color = self.screen.fill(color)
def create_sprites(self, color):
self.left_paddle = Paddle(color, 20, 120)
self.right_paddle = Paddle(color, 20, 120)
self.ball = Ball(color, 20, 20)
def position(self):
self.left_paddle.rect.x, self.left_paddle.rect.y = 50, 350
self.right_paddle.rect.x, self.right_paddle.rect.y = 1120, 350
self.ball.rect.x, self.ball.rect.y = 590, 440
def draw_sprites(self):
self.sprites_list = pygame.sprite.Group()
self.sprites_list.add(self.left_paddle, self.right_paddle, self.ball)
self.sprites_list.draw(self.screen)
pygame.display.set_caption("PONG 2.0")
# The clock will be used to control how fast the screen updates
clock = pygame.time.Clock()
# Initialise player scores
scoreA = 0
scoreB = 0
# ----Main program loop----
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.quit()
# Testing the creation of a screen object
# To display the screen object uncomment the 4 lines below
# classic = GameScreen((1200, 900), colors.BLACK)
# classic.create_sprites(colors.WHITE)
# classic.position()
# classic.draw_sprites()
# Updating the screen what we've drawn
pygame.display.flip()
|
504cececc991d8b0ef9ae42ad1502ec66e0ac9f8 | AnanyaDoshi728/PL_mini_project | /main.py | 11,109 | 3.609375 | 4 | from sqlite3.dbapi2 import connect, register_adapter
import tkinter as tkinter_instance
from tkinter import *
from tkinter import messagebox
import sqlite3
import main_window
import colors
#login window
def render_login_window():
def on_click_confirm_login():
try:
db_connection = sqlite3.connect("tasks.db")
db_cursor = db_connection.cursor()
except Exception as exception:
messagebox.showerror("Error","Error in connecting to database")
else:
try:
select_record_query = "SELECT * FROM tasks_data WHERE Username=? AND Password=?;"
db_cursor.execute(select_record_query,(login_username_input.get(),login_password_input.get()))
record = db_cursor.fetchall()
if len(record) == 1:
#messagebox.showinfo("Login successfull","User authentication succcessfull")
global global_username
global_username = login_username_input.get()
main_window.main_window_render(global_username)
"""
main_window = tkinter_instance.Toplevel()
screen_width = main_window.winfo_screenwidth()
screen_height = main_window.winfo_screenheight()
main_window.geometry(f"{screen_width}x{screen_height}")
#l = Label(main_window,text=global_username)
#l.pack()
#main_window.mainloop()
"""
else:
messagebox.showerror("Login failed","The user does not exsist")
except Exception as exception:
messagebox.showerror("Exception",exception)
print(exception)
login_window = tkinter_instance.Tk()
login_window.title("Login")
login_window.geometry(f"600x450+180+150")
login_window.resizable(False,False)
login_window.configure(background=colors.BLACK)
#create labels
login_label = Label(login_window,font=FONT_TUPLE_TITLE,text="Login",width=12,anchor="w",bg=colors.BLACK,fg=colors.CYAN)
login_username_label = Label(login_window,font=FONT_TUPLE_LABEL,text="Username",width=12,anchor="w",bg=colors.BLACK,fg=colors.CYAN)
login_password_label = Label(login_window,font=FONT_TUPLE_LABEL,text="Password",width=12,anchor="w",bg=colors.BLACK,fg=colors.CYAN)
#create entries
login_username_input = Entry(login_window,font=FONT_TUPLE_LABEL,width=18)
login_password_input = Entry(login_window,font=FONT_TUPLE_LABEL,width=18)
#create buttons
confirm_login_button = Button(login_window,font=FONT_TUPLE_LABEL,text="Confirm login",command=on_click_confirm_login,bg=colors.CYAN,fg=colors.BLACK)
go_to_register_button = Button(login_window,font=FONT_TUPLE_LABEL,text="Go to Register",command=render_signup_window,bg=colors.CYAN,fg=colors.BLACK)
#place labels
login_label.place(x=240,y=60)
login_username_label.place(x=95,y=150)
login_password_label.place(x=95,y=230)
#place entries
login_username_input.place(x=245,y=150)
login_password_input.place(x=245,y=230)
#place buttons
confirm_login_button.place(x=95,y=310)
go_to_register_button.place(x=300,y=310)
login_window.mainloop()
def render_signup_window():
def on_click_confirm_signup():
#validation
flag = -1
while flag == -1:
if username_input.get() == "" or password_input.get() == "" or email_input.get() == "":
messagebox.showwarning("Empty field(s)","All fields are required")
break
elif higher_priority__input.compare("end-1c", "==", "1.0"):
messagebox.showwarning("Empty tasks","PLease enter some tasks")
break
elif lower_priority_input.compare("end-1c","==","1.0"):
messagebox.showwarning("Empty tasks","PLease enter some tasks")
break
elif len(username_input.get()) < 8:
messagebox.showwarning("Invalid username","Username must be atleast 8 charachters")
break
elif len(password_input.get()) < 8:
messagebox.showwarning("Invalid password","Password must be atleast 8 charachters")
break
else:
flag = 0
#add email validation
if flag == 0:
try:
db_connection = sqlite3.connect("tasks.db")
db_cursor = db_connection.cursor()
except Exception as exception:
messagebox.showerror("Error","Could not connect to database")
print(exception)
#create table if it does not exsist
try:
table_creation_query = "CREATE TABLE IF NOT EXISTS tasks_data (Username text,Password text,Email text,Higher_Priority text,Lower_Priority text);"
db_cursor.execute(table_creation_query)
db_connection.commit()
except Exception as exception:
messagebox.showerror("Error","Could not create table")
print(exception)
#check if email or username exsist
try:
check_redundancy_query = "SELECT * FROM tasks_data WHERE Username=? OR Email=?;"
db_cursor.execute(check_redundancy_query,(username_input.get(),email_input.get()))
redundant_record = db_cursor.fetchall()
#if username or email exsist clear fields
if len(redundant_record) != 0:
messagebox.showerror("Could not create record","The username or email already exsists.Please try again")
username_input.delete(0,END)
email_input.delete(0,END)
#if username or email doeb not exsist insert data
else:
new_record_insertion_query = "INSERT INTO tasks_data(Username,Password,Email,Higher_Priority,Lower_Priority) VALUES(?,?,?,?,?);"
db_cursor.execute(new_record_insertion_query,(username_input.get(),password_input.get(),email_input.get(),higher_priority__input.get(1.0,END),lower_priority_input.get(1.0,END)))
db_connection.commit()
global global_username
global_username = username_input.get()
messagebox.showinfo("User created","User successfully created")
#insert record and set global variables
username_input.delete(0,END)
password_input.delete(0,END)
email_input.delete(0,END)
higher_priority__input.delete("1.0",END)
lower_priority_input.delete("1.0",END)
print(global_username)
except Exception as exception:
messagebox.showerror("Error","New record creation failed")
print(exception)
#window
signup_window = tkinter_instance.Tk()
signup_window.title("Sign up")
signup_window.geometry(f"1100x650+180+150")
signup_window.configure(background=colors.BLACK)
signup_window.resizable(False,False)
#create labels
username_label = Label(signup_window,font=FONT_TUPLE_LABEL,text="Username",width=12,anchor="w",bg=colors.BLACK,fg=colors.CYAN)
password_label = Label(signup_window,font=FONT_TUPLE_LABEL,text="Password",width=12,anchor="w",bg=colors.BLACK,fg=colors.CYAN)
email_label = Label(signup_window,font=FONT_TUPLE_LABEL,text="Email",width=12,anchor="w",bg=colors.BLACK,fg=colors.CYAN)
tasks_label = Label(signup_window,font=FONT_TUPLE_LABEL_BOLD,text="Tasks",width=12,anchor="w",bg=colors.BLACK,fg=colors.CYAN)
higher_priority_label = Label(signup_window,font=FONT_TUPLE_LABEL,text="Higher priority",width=12,anchor="w",bg=colors.BLACK,fg=colors.CYAN)
lower_priority_label = Label(signup_window,font=FONT_TUPLE_LABEL,text="Lower priority",width=12,anchor="w",bg=colors.BLACK,fg=colors.CYAN)
#create input fields
username_input = Entry(signup_window,font=FONT_TUPLE_LABEL,width=18)
password_input = Entry(signup_window,font=FONT_TUPLE_LABEL,width=18)
email_input = Entry(signup_window,font=FONT_TUPLE_LABEL,width=18)
higher_priority__input = Text(signup_window,font=FONT_TUPLE_TASK_INPUT,width=27,height=8)
lower_priority_input = Text(signup_window,font=FONT_TUPLE_TASK_INPUT,width=27,height=8)
#create buttons
signup_button = Button(signup_window,text="Confirm Signup",font=FONT_TUPLE_LABEL,command=on_click_confirm_signup,bg=colors.CYAN,fg=colors.BLACK)
login_button = Button(signup_window,text="Go To Login",font=FONT_TUPLE_LABEL,command=render_login_window,bg=colors.CYAN,fg=colors.BLACK)
#place labels
username_label.place(x=30,y=20)
password_label.place(x=30,y=100)
email_label.place(x=30,y=180)
tasks_label.place(x=552,y=240)
higher_priority_label.place(x=30,y=300)
lower_priority_label.place(x=560,y=300)
#place inputs
username_input.place(x=240,y=20)
password_input.place(x=240,y=100)
email_input.place(x=240,y=180)
higher_priority__input.place(x=240,y=300)
lower_priority_input.place(x=760,y=300)
#place buttons
signup_button.place(x=30,y=550)
login_button.place(x=280,y=550)
signup_window.mainloop()
#main
#constanst
FONT_TUPLE_TITLE = ("Helvetica",33)
FONT_TUPLE_LABEL = ("Helvetica",20)
FONT_TUPLE_LABEL_BOLD = ("Helvetica",20,"bold")
FONT_TUPLE_TASK_INPUT = ("Helvetica",15)
#global variable
global global_username
#global global_password
#global global_email
initial_window = tkinter_instance.Tk()
initial_window.title("Notes and Tasks")
initial_window.geometry(f"600x450+180+150")
initial_window.resizable(False,False)
initial_window.configure(background=colors.BLACK)
#create labeld and buttons
title_label = Label(initial_window,text="Notes and Tasks",font=FONT_TUPLE_TITLE,bg=colors.BLACK,fg=colors.CYAN)
login_button = Button(initial_window,text="Login",font=FONT_TUPLE_LABEL,height=1,width=7,command=render_login_window,bg=colors.CYAN,fg=colors.BLACK)
signup_button = Button(initial_window,text="Sign up",font=FONT_TUPLE_LABEL,height=1,width=7,command=render_signup_window,bg=colors.CYAN,fg=colors.BLACK)
#place labels and buttons
title_label.place(x=133,y=100)
login_button.place(x=230,y=180)
signup_button.place(x=230,y=260)
initial_window.mainloop()
|
153d9116d2f7969c27601a20ee8b065e72078120 | DanielBarcenas97/AlgorithmsAndDataStructures | /AlgorithmsPython/topoSort.py | 2,073 | 3.53125 | 4 |
class vertex:
def __init__(self,i): #Constructor
self.id=i
self.visitado=False
self.nivel=-1
self.vecinos=[]
#self.costo=9999999
def agregarVecino(self,v):
if v not in self.vecinos:
self.vecinos.append(v)
def eliminarVecino(self,v):#Pasar a graph, recibe vertices
if v in self.vecinos:
self.vecinos.remove(v)
class graph:
d =[]
def __init__(self):
self.vertices={}
def agregarVertice(self,v): #instanciar a la clase para generar un objeto
if v not in self.vertices:
vert=vertex(v) #instancia de la clase vertex
self.vertices[v]=vert #Agregar el objeto al diccionario
def agregarArista(self,a,b):
if a in self.vertices and b in self.vertices:
self.vertices[a].agregarVecino(b)
#self.vertices[b].agregarVecino(a)
def imprimirGrafica(self):
print("Grafica: ")
for v in self.vertices:
print("Vertice, costo: ", self.vertices[v].id, self.vertices[v].costo)
print(self.vertices[v].vecinos)
def DFS(self, r):
if r in self.vertices:
self.vertices[r].visitado = True
#self.vertices[r].nivel = n
for v in self.vertices[r].vecinos:
if self.vertices[v].visitado == False:
self.DFS(v)
self.d.append([v,self.n])
self.n = self.n -1
def topoSort(self):
self.n = len(self.vertices)
for v in self.vertices:
if self.vertices[v].visitado == False:
self.DFS(v)
self.d.append([v,self.n])
self.n = self.n -1
class main:
g=graph()
v=input()
a=input()
v=v.split(",")
v[0]=v[0][1:len(v[0])]
v[len(v)-1]=v[len(v)-1][0:len(v[len(v)-1])-1]
for i in range(len(v)):
v[i] = int(v[i])
a=a.replace("[", "")
a=a.replace("]", "")
a=a.split(",")
for i in range(len(a)):
a[i] = int(a[i])
for x in v:
g.agregarVertice(x)
for y in range(0, len(a), 2):
g.agregarArista(a[y], a[y+1])
g.topoSort()
#print(a)
#print(v)
for i in g.d:
print("({0}, {1})".format(i[0], i[1]))
#g.imprimirGrafica() |
93685a98fb920de46ffb4dd0b0f0108b88b695fe | abrarulhaque/spaceinvader | /bullet.py | 1,080 | 4.0625 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""a class to manage bullet fired from the ship"""
def __init__(self,ai_settings,screen,ship):
"""create a bullet object at the position of the ship"""
super(Bullet,self).__init__()
self.screen=screen
#create a bullet rect at (0,0) position then set correct position
self.rect=pygame.Rect(0,0,ai_settings.bullet_width,ai_settings.bullet_height)
self.rect.centerx=ship.rect.centerx
self.rect.top=ship.rect.top
#store bullet's position as a decimal value
self.y=float(self.rect.y)
self.colour=ai_settings.bullet_colour
self.speed_factor=ai_settings.bullet_speed_factor
def update(self):
"""move the bullet up the screen"""
#update the decimal position of the bullet
self.y-=self.speed_factor
#update the rect position
self.rect.y=self.y
def draw_bullet(self):
"""draw the bullet in the screen"""
pygame.draw.rect(self.screen,self.colour,self.rect)
|
f61ad8aa893fb2c0e98e41baad68a7b5762de883 | DongusJr/HangmanPA6 | /Game_folder/Game.py | 2,110 | 4.0625 | 4 | #Imports
from Game_folder.Score import Score
# Main
class Game:
''' Class that holds information for each game played
Class variables
---------------
is_win : bool
Indicates wheter player won or not
guess_tuple : tuple with ints
Holds how many wrong guesses were and what was max guess count
difficulty_str : str
Indicates what difficulty the player was on, used to calculate score
win_streak : int
Indicates how many wins in a row the player has
score_obj : Score
Object to calculate score
'''
def __init__(self, difficulty_str, total_score = 0, win_streak = 0):
self.is_win = None
self.guess_tuple = (None, None)
self.difficulty_str = difficulty_str
self.win_streak = win_streak
self.score_obj = Score(win_streak)
def __str__(self):
''' Prints out information for the game history '''
win_str = "Win" if self.is_win else "Loss"
print(win_str, self.guess_tuple[0], self.guess_tuple[1], self.difficulty_str, self.score_obj.get_score())
return "{:<10}{}/{:<8}{:<14}{:<10}".format(win_str, self.guess_tuple[0], self.guess_tuple[1], self.difficulty_str, self.score_obj.get_score())
def set_guess_tuple(self, guesses, max_guesses):
''' set wrong guesses and max guesses of a games '''
self.guess_tuple = (guesses, max_guesses)
def get_game_score(self):
''' Function that returns the score for the game '''
return self.score_obj.get_score()
def mark_is_win(self, bool_val):
''' Function that marks a game as a win or loss depending on a boolean '''
self.is_win = bool_val
if bool_val:
self.score_obj.increment_win_streak() # Increase the win streak
else:
self.score_obj.reset_win_streak() # Reset the win streak
def calculate_score(self):
''' Function that calculates the score after game '''
self.score_obj.calculate_and_add_score(self.guess_tuple, self.difficulty_str)
|
efdae5745f07197c04066fddf01005962b9475f5 | smossavi7/steamlite_examples | /streamlit_example.py | 1,542 | 3.796875 | 4 | import streamlit as st
import pandas as pd
import plotly.express as px
st.write('# Avocado Prices dashboard') #st.title('Avocado Prices dashboard')
st.markdown('''
This is a dashboard showing the *average prices* of different types of :avocado:
Data source: [Kaggle](https://www.kaggle.com/datasets/timmate/avocado-prices-2020)
''')
st.header('Summary statistics')
@st.cache
def load_data(path):
dataset = pd.read_csv(path)
return dataset
avocado = load_data('https://raw.githubusercontent.com/liannewriting/streamlit_example/main/avocado.csv')
avocado_stats = avocado.groupby('type')['average_price'].mean()
st.dataframe(avocado_stats)
st.header('Line chart by geographies')
with st.form('line_chart'):
selected_geography = st.selectbox(label='Geography', options=avocado['geography'].unique())
submitted = st.form_submit_button('Submit')
if submitted:
filtered_avocado = avocado[avocado['geography'] == selected_geography]
line_fig = px.line(filtered_avocado,
x='date', y='average_price',
color='type',
title=f'Avocado Prices in {selected_geography}')
st.plotly_chart(line_fig)
with st.sidebar:
st.subheader('About')
st.markdown('This dashboard is made by Just into Data, using **Streamlit**')
st.sidebar.image('https://streamlit.io/images/brand/streamlit-mark-color.png', width=50)
# coding: utf-8
import urllib.request
import ssl
|
bfd5842f9ae67b3fde89300a6bb032836c84966c | ShivaLuckily/pythonBasicProgramming | /overRiding.py | 484 | 4.09375 | 4 | '''class overiding:
i=10
def display(self):
print("parent class")
class over(overiding):
i=20
def display(self):
print("child class")
c=over()
c.display()
print(c.i)'''
######## overloading #########
class overloading:
def display(self,a=None,b=None):
if a!=None and b!=None:
print(" a & b")
elif a!=None:
print("a")
else:
print("empty")
c=overloading()
c.display(10,20) # a & b
|
fdaa15e5b0952ae7bdf12060e374888d06b2e82d | zlatnizmaj/Xu_ly_anh | /Moj Python/Numpy/linspace().py | 1,249 | 3.859375 | 4 | """
numpy.linspace() in Python
About :
numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None) :
Returns number spaces evenly w.r.t interval.
Similiar to arange but instead of step it uses sample number.
Parameters :
-> start : [optional] start of interval range. By default start = 0
-> stop : end of interval range
-> restep : If True, return (samples, step). By deflut restep = False
-> num : [int, optional] No. of samples to generate
-> dtype : type of output array
Return :
-> ndarray
-> step : [float, optional], if restep = True
"""
# Code 1: explain linspace function
# numpy.linspace method
import numpy as np
import pylab as p
# restep set to True
print("B\n", np.linspace(2.0, 3.0, num=5, endpoint=False, retstep=True), "\n")
# to evaluate sin() in long range
# x = np.linspace(0, 2, 10)
# print("x vector:\n", x)
# print("A, sin(x)\n", np.sin(x))
# Graphical represnetation of numpy.linsapce() using matplotlib module- pylab
# start = 0
# end = 2
# smaples to generate = 10
x1 = np.linspace(0, 10, 5, endpoint=True, retstep=True)
x2 = np.linspace(0, 10, 5, endpoint=False, retstep=True)
print(11/5.0)
y1 = np.ones(10)
print(x1)
print(x2)
# p.plot(x1, y1, '*')
# p.xlim((-0.2, 1.8))
# p.show() |
90ba8a1c99afb6741f8bf660242753587862477a | srijan-singh/Hacktoberfest-2021-Data-Structures-and-Algorithms | /Data Structures/Disjoint Set/DisjointSet.py | 1,834 | 4.28125 | 4 | class DisjointSet:
"""
Disjoint Set data structure (Union–Find), is a data structure that keeps track of a
set of elements partitioned into a number of disjoint (nonoverlapping) subsets.
Methods:
find: Determine which subset a particular element is in. Takes an element of any
subset as an argument and returns a subset that contains our element.
union: Join two subsets into a single subset. Takes two elements of any subsets
from disjoint_set and returns a disjoint_set with merged subsets.
get: returns current disjoint set.
"""
_disjoint_set = list()
def __init__(self, init_arr):
self._disjoint_set = []
if init_arr:
for item in list(set(init_arr)):
self._disjoint_set.append([item])
def _find_index(self, elem):
for item in self._disjoint_set:
if elem in item:
return self._disjoint_set.index(item)
return None
def find(self, elem):
for item in self._disjoint_set:
if elem in item:
return self._disjoint_set[self._disjoint_set.index(item)]
return None
def union(self,elem1, elem2):
index_elem1 = self._find_index(elem1)
index_elem2 = self._find_index(elem2)
if index_elem1 != index_elem2 and index_elem1 is not None and index_elem2 is not None:
self._disjoint_set[index_elem2] = self._disjoint_set[index_elem2]+self._disjoint_set[index_elem1]
del self._disjoint_set[index_elem1]
return self._disjoint_set
def get(self):
return self._disjoint_set
|
7fe5c6afef908698c2c8bce79bb860b1a273cd2d | cryjun215/c9-python-getting-started | /python-for-beginners/06 - Dates/format_date.py | 669 | 4 | 4 | # 현재 날짜와 시간을 얻으려면 datetime 라이브러리를 사용해야합니다.
from datetime import datetime
# now 함수는 현재 날짜와 시간을 리턴합니다.
today = datetime.now()
# 일, 월, 년, 시, 분, 초 function 사용해 날짜의 일부만 표시할 수 있습니다.
# 이 모든 함수는 정수(integer) 값을 반환합니다.
# 다른 문자열에 연결(concat)하기 전에 문자열로 변환해야 합니다.
print('Day: ' + str(today.day))
print('Month: ' + str(today.month))
print('Year: ' + str(today.year))
print('Hour: ' + str(today.hour))
print('Minute: ' + str(today.minute))
print('Second: ' + str(today.second))
|
def1708abba279cbeb55d25f527ec2bdf7b2e9bb | karthiklingasamy/Python_Sandbox | /B02_T3_Strings_WorkingWithTextualData.py | 282 | 3.703125 | 4 | greeting = 'Hello'
name = 'karthik'
# print(dir(name)) # It will show us all the methods and attributes that we have access [to] with [that] variable now
# print(help(str)) # To get more info about string class
print(help(str.lower)) # To get specific info about function |
ee99597f8e3de1a02f8340162e108342dd8a4d8d | ducdmdo/algorithms | /python/udacity_recursion.py | 316 | 3.625 | 4 | def get_fib(position):
if position == 0:
return position
print ("position = 0")
if position == 1:
return position
print ("position = 1")
print ("position is at %s" % position)
result = get_fib(position-1) + get_fib(position-2)
return result
print (get_fib(8))
|
8b1cbfc51f482f7d7cb099980f6287d8d57c340a | zubrik13/coding_intrv_prer | /repeated_string.py | 557 | 3.828125 | 4 | """
There is a string, s, of lowercase English letters
that is repeated infinitely many times.
Given an integer, n, find and print the number of letter a's
in the first n letters of the infinite string.
"""
s = "abcac"
n = 14
multiplicator = n // len(s)
count_a = 0
for letter in s:
if letter == "a":
count_a += 1
delta = n % len(s)
count_delta_a = 0
if delta != 0:
sub_s = s[:delta]
for letter in sub_s:
if letter == "a":
count_delta_a += 1
num_a = multiplicator * count_a + count_delta_a
print(num_a) |
180a12e149dafd29a46ba2e0cdab9c461e001ca7 | serashioda/code-katas | /src/sort_cards.py | 1,614 | 4.15625 | 4 | """Implementation of the Sort Cards Kata."""
class PriorityQueue(object):
"""Priority list queue."""
def __init__(self, iterable=None):
"""Construct priority queue."""
self.queues = {}
self.num_items = 0
if iterable is not None:
for data, priority in iterable:
self.insert(data, priority)
def length(self):
"""Give length of card deck."""
return self.num_items
def insert(self, data, priority=0):
"""Test insert into pq."""
self.num_items+1
if priority in self.queues:
self.queues[priority].insert(0, data)
else:
self.queues[priority] = [data]
def pop(self):
"""Test pop from pq."""
self.length-1
for priority in sorted(self.queues):
if len(self.queues[priority]) > 0:
return self.queues[priority].pop()
raise IndexError('Cannot pop from empty priority queue.')
def peek(self):
"""Peek at the highest priority tuple."""
for priority in sorted(self.queues):
if len(self.queues[priority]) > 0:
return self.queues[priority][-1]
def sort_cards(cards):
"""Sorted Cards Priority list queue."""
sort_dict = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13}
dec = PriorityQueue()
for card in cards:
dec.insert(card, sort_dict[card])
sorted_deck = []
while dec.length() > 0:
pop_card = dec.pop()
sorted_deck.push(pop_card)
return sorted_deck
|
90c15631f2c5034457375a217f6f0e603e70daba | sachinjose/Coding-Prep | /PythonPrep/Object Oriented Programming/R2_4.py | 448 | 3.71875 | 4 | class Flower:
def __init__(self):
name = ''
petals = 0
price = 0.0
def updatename(self,a):
self.name = a
def getname(self):
print (self.name)
def updatepetals(self,a):
self.petals = a
def getpetals(self):
print(self.petals)
def updateprice(self,a):
self.price = a
def getprice(self):
print (self.price)
a = Flower()
a.updatename('Rose')
a.updateprice(100.5)
a.updatepetals(10)
a.getname()
a.getprice()
a.getpetals() |
969e1452da763ad2bf042c2c0aa5370cf14a4e73 | szbrooks2017/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 265 | 4.03125 | 4 | #!/usr/bin/python3
def uppercase(str):
for c in range(len(str)):
if (ord(str[c]) >= 97) and (ord(str[c]) <= 122):
alpha = chr(ord(str[c]) - 32)
else:
alpha = str[c]
print("{}".format(alpha), end='')
print('')
|
86d6588dc43d50a8cd91e34d0303f5bed249e4e4 | Ruhshan/back-to-basics | /1.Arrays&Strings/IsUnique.py | 304 | 3.90625 | 4 | def is_unique(str):
is_present = [False]*26
for c in str:
if is_present[ord(c)-97]:
return False
else:
is_present[ord(c)-97]=True
return True
if __name__ == "__main__":
print(is_unique("abcdef"))#True
print(is_unique("ttxder"))#False |
a83fd596c85f121e2ca3ce9d9a9659c9808f8bb7 | alparty/labs | /techlead/versions.py | 2,140 | 4.0625 | 4 | """Version numbers are strings that are used to identify unique states of software products. A version number is in the format a.b.c.d. and so on where a, b, etc. are numeric strings separated by dots. These generally represent a hierarchy from major to minor changes. Given two version numbers version1 and version2, conclude which is the latest version number. Your code should do the following:
If version1 > version2 return 1.
If version1 < version2 return -1.
Otherwise return 0.
Note that the numeric strings such as a, b, c, d, etc. may have leading zeroes, and that the version strings do not start or end with dots. Unspecified level revision numbers default to 0.
Example:
Input:
version1 = "1.0.33"
version2 = "1.0.27"
Output: 1
#version1 > version2
Input:
version1 = "0.1"
version2 = "1.1"
Output: -1
#version1 < version2
Input:
version1 = "1.01"
version2 = "1.001"
Output: 0
#ignore leading zeroes, 01 and 001 represent the same number.
Input:
version1 = "1.0"
version2 = "1.0.0"
Output: 0
#version1 does not have a 3rd level revision number, which
defaults to "0"
Here's a starting point
"""
class Solution:
def compareVersion(self, version1, version2):
m = max(len(version1), len(version2))
v = ".0" * m
v1 = "".join(map(str, map(int, (version1+v).split('.')[0:m])))
v2 = "".join(map(str, map(int, (version2+v).split('.')[0:m])))
if v1<v2: return -1
if v1>v2: return 1
return 0
version1 = "1.0.1"
version2 = "1"
# Output: 1
print(Solution().compareVersion(version1, version2) == 1)
version1 = "1.0.33"
version2 = "1.0.27"
# Output: 1
print(Solution().compareVersion(version1, version2) == 1)
#version1 > version2
version1 = "0.1"
version2 = "1.1"
# Output: -1
print(Solution().compareVersion(version1, version2) == -1)
#version1 < version2
version1 = "1.01"
version2 = "1.001"
print(Solution().compareVersion(version1, version2) == 0)
# Output: 0
#ignore leading zeroes, 01 and 001 represent the same number.
version1 = "1.0"
version2 = "1.0.0"
# Output: 0
print(Solution().compareVersion(version1, version2) == 0)
#version1 does not have a 3rd level revision number, which
|
5c77b47e726d715deb742f9d05579a7d869c0263 | trezum/ML-Course | /lektion7/opgave3.py | 2,215 | 3.546875 | 4 | from sklearn import datasets
from sklearn.cluster import KMeans # This will be used for the algorithm
import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import PCA
from sklearn.feature_selection import SelectKBest
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
from sklearn.metrics import confusion_matrix, precision_score, f1_score
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import confusion_matrix, classification_report, precision_score, recall_score
from sklearn.neighbors import KNeighborsClassifier
def doKnn(X_train, X_test, y_train, y_test):
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
print("Model is trained")
predictions = knn.predict(X_test)
print("Evaluating performance: Confusion matrix")
matrix = confusion_matrix(y_test, predictions)
print(matrix)
# output is the confusion matrix
print("precision: " + str(precision_score(y_test, predictions, average='weighted')))
print("recall: " + str(recall_score(y_test, predictions, average='weighted')))
print("F1 score: " + str(f1_score(y_test, predictions, average='weighted')))
print(classification_report(y_test, predictions))
iris_df = datasets.load_iris()
X, y = iris_df.data, iris_df.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print("-----KNN with full featureset-----")
doKnn(X_train, X_test, y_train, y_test)
pca = PCA(n_components=2)
print(X.shape)
pca.fit(X_train)
X_train_reduced_two = pca.transform(X_train)
X_test_reduced_two = pca.transform(X_test)
print("-----X_train_reduced to two-----")
print(X_train_reduced_two)
print("-----KNN with the two features-----")
doKnn(X_train_reduced_two, X_test_reduced_two, y_train, y_test)
pca = PCA(n_components=1)
print(X.shape)
pca.fit(X_train)
X_train_reduced_one = pca.transform(X_train)
X_test_reduced_one = pca.transform(X_test)
print("-----X_train_reduced to two-----")
print(X_train_reduced_one)
print("-----KNN with one features-----")
doKnn(X_train_reduced_one, X_test_reduced_one, y_train, y_test)
|
750a635c96b09b84a321099570a2148c065a4ed3 | itorres1994/MapReduce | /MRTemperatureObservations2.py | 1,357 | 3.640625 | 4 | from mrjob.job import MRJob
import sys
class MRTemperatureObservations2(MRJob):
def mapper(self, key, line):
# sys.stderr.write("MAPPER INPUT: ({0},{1})\n".format(key, line)) # displays intermediate values of mapper
data = line.split(',') # take the input from the text file and parse it with respect to (',')
# print 'This is data[7] -> ', data[7]
yield (data[3], data[6]), data[7] # (data[3]: continent, data[6]: year), data[7]: temperature
def reducer(self, continent_year, data):
# sys.stderr.write("REDUCER INPUT: ({0},{1})\n".format(continent_year, data)) # displays reducer values
temps = list(data) # data: generating function -> make it into a list of temperatures
data_list = list(continent_year)
continent = data_list[0]
year = data_list[1]
total = 0
# print 'continent -> ', continent
# print 'year -> ', year
for d in range(len(temps)):
total += float(temps[d])
if len(temps) > 50: # is the number of temperature readings in a distinct year greater than 100
yield (continent, year), round((total/len(temps)), 2) # print to console the distinct continent and
# year coupled with the average temperature readings
if __name__ == '__main__':
MRTemperatureObservations2.run()
|
907416a2984b91061abaed2120e8ec9892be6b31 | gstamatakis/python_algorithms | /n_queens/SimulatedAnnealing.py | 5,124 | 4 | 4 | import time
from random import randint
from random import random
import numpy as np
class SimulatedAnnealing:
def __init__(self, suppress, t0, tmin, cool, eps, sn=100):
self.board = None # The Queens are represented in this 1d array. The array position and the cell number are the Queen's 'coordinates' in the board.
self.results = {} # Dictionary that holds the results of the experiments.
self.eps = eps # Epsilon number (ε). Every number below this is considered '0'. This is used to cutoff some very low SA costs that "keep the algo moving".
self.T0 = t0 # Starting temperature used in SA, can't be set to more that 1.0 or lower than eps (see above).
self.T_min = tmin # Ending temperature used in SA, set
self.cool = cool # SA cooling factor.
self.search_neighbours = sn # Amount of neighbours to search before quitting
self.suppress = suppress # Chose whether board and other messages will be printed to stdout.
self.numOfQueens = None # Board size
self.moves = {} # Average moves done in order to solve the problem
def __str__(self):
return '\nSimulated Annealing'
# Run the algorithm a few times and time it. Board is generated randomly.
def run(self, start, stop, step, repeat):
for n in range(start, stop + 1, step):
run = []
self.board = list([randint(0, n - 1) for _ in range(n)]) # Start by randomly generating the board.
moves = 0
for j in range(repeat):
start_time = time.time()
self.numOfQueens = n
moves = self.anneal(n) / repeat # Run the algorithm to solve the problem.
end_time = time.time()
run.append((end_time - start_time)) # Save the time it took to solve this board and move on.
self.board[:] = list([randint(0, n - 1) for _ in range(n)])
self.results[n] = run
self.moves[n] = moves
def successor_function(self, n):
state = self.get_neighbour(self.board, n)
cost = self.cost(state, n)
return state, cost
def anneal(self, n):
T = self.T0 # Starting temperature
cool = self.cool # Cooling factor
T_min = self.T_min # Ending temperature
loops = 0 # This param is used in order to avoid an endless annealing process. It basically stops the loop after 100 times (is usually 1-2).
moves = -1
while self.cost(self.board, n) != 0: # Goal test
while T - T_min >= self.eps:
currentCost = self.cost(self.board, n)
neighbours = self.search_neighbours
while neighbours > 0:
nextState, nextCost = self.successor_function(n) # Get the next state
moves += 1 # Count the new move (used for statistics later on)
e = (np.float128) = -(nextCost - currentCost) / T # This kills our performance but stops an arithmetic overflow.
if np.exp(e) > random(): # Perform the SA standard check
self.board = nextState # Jump to the next state.
currentCost = nextCost
if currentCost == 0: # Goal test
self.print_board()
return moves
neighbours -= 1
T *= cool
# If the original hyper params weren't good enough, adapt and retry.
cool = min(1 - self.eps, cool * 1.1) # Increase the cooling factor (so it cools slower !!) by 10% but don't go over 1.0.
T = self.T0
T_min = self.T_min
loops += 1
if not self.suppress:
print('Adapting: {0} {1} {2} No{3}'.format(T, cool, T_min, loops), flush=True)
if loops > 100:
print("\n\nToo many loops...") # Mostly for debug or REALLY bad hyper params.
exit(-2)
@staticmethod
def get_neighbour(queens, n): # Chose a random neighbour to jump to.
queensTemp = queens[:]
queensTemp[randint(0, n - 1)] = randint(0, n - 1)
return queensTemp[:]
@staticmethod
def cost(queens, n): # Counts the number of conflicts across the board.
conflicts = 0
for i in range(n):
for j in range(i + 1, n):
if i != j and (queens[i] == queens[j] or abs(queens[i] - queens[j]) == abs(i - j)): # Horizontally and diagonally
conflicts += 1
return conflicts
def print_board(self):
if self.suppress: # Don't print if suppress is enabled.
return
print('\n\n\n{2} solution for {0} queens flat board: {1}'.format(self.numOfQueens, self.board, self))
to_print = ''
for r in range(len(self.board)):
for c in range(len(self.board)):
if self.board[c] == r:
to_print += "Q "
else:
to_print += "x "
to_print += "\n"
print(to_print)
|
9777569b94a94a42b5740654833ff33c79a480af | ivni195/mat1-projekt | /fermat_factorization.py | 801 | 4.21875 | 4 | #! /usr/bin/python3
import math
# Try to find factors of the form n=(a-b)(a+b) for an odd n.
def fermat_factorize(n):
a = int(math.ceil(math.sqrt(n)))
b2 = a * a - n
# Look for a such that b = a^2 - n is a perfect square.
while math.sqrt(b2) != math.floor(math.sqrt(b2)):
a += 1
b2 = a * a - n
# Returns the smaller factor. Note that a-b is the biggest factor of n smaller that sqrt(n).
# Thus, if the return value is equal to 1, then n is a prime.
return a - int(math.sqrt(b2))
def main():
a = 7
b = 5959
print(f'Factorize {a}: {fermat_factorize(a)}. Found factor is {fermat_factorize(a)} so {a} is prime.')
print(f'Factorize {b}: {fermat_factorize(b)}. Found factor is {fermat_factorize(b)}.')
if __name__ == '__main__':
main()
|
e92b0c4092082f76504bc5dae481b7c3398da37c | jocelo/rice_intro_python | /practice_excercises/week_5a/02_circle_clicking.py | 1,178 | 4.09375 | 4 | # Circle clicking problem
###################################################
# Student should enter code below
import simplegui
import math
# define global constants
RADIUS = 20
RED_POS = [50, 100]
GREEN_POS = [150, 100]
BLUE_POS = [250, 100]
# define helper function
def dist(p, q):
return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
# define mouseclick handler
def click(pos):
if dist(pos,RED_POS) < RADIUS:
print 'Red'
elif dist(pos,BLUE_POS) < RADIUS:
print 'Blue'
elif dist(pos, GREEN_POS) < RADIUS:
print 'Green'
# define draw
def draw(canvas):
canvas.draw_circle(RED_POS, RADIUS, 1, "Red", "Red")
canvas.draw_circle(GREEN_POS, RADIUS, 1, "Green", "Green")
canvas.draw_circle(BLUE_POS, RADIUS, 1, "Blue", "Blue")
# create frame and register handlers
frame = simplegui.create_frame("Echo click", 300, 200)
frame.set_mouseclick_handler(click)
frame.set_draw_handler(draw)
# start frame
frame.start()
###################################################
# Sample output
#Clicked red ball
#Clicked green ball
#Clicked blue ball
#Clicked green ball
#Clicked red ball
#Clicked green ball
#Clicked blue ball
|
6d183d6a339d306e249739a2c9f5b73e037a95b9 | Sqweejum/Ch.01_Version_Control | /1.2_turtorial.py | 1,253 | 3.9375 | 4 | '''
Modify the starter code below to create your own cool drawing
and then Pull Request it to your instructor.
Turtle Documentation: https://docs.python.org/3.3/library/turtle.html?highlight=turtle
'''
import turtle
tina = turtle.Turtle()
tina.shape('turtle')
tina.penup()
tina.right(90)
tina.forward(180)
tina.right(90)
tina.forward(180)
tina.right(90)
tina.pendown()
tina.pencolor("red")
tina.forward(300)
tina.right(90)
tina.pencolor("orange")
tina.forward(300)
tina.right(90)
tina.pencolor("yellow")
tina.forward(250)
tina.right(90)
tina.pencolor("green")
tina.forward(250)
tina.right(90)
tina.pencolor("blue")
tina.forward(251)
tina.right(135)
tina.pencolor("indigo")
tina.forward(130)
tina.right(45)
tina.pencolor("violet")
tina.forward(110)
tina.right(62)
tina.pencolor("red")
tina.forward(105)
tina.penup()
tina.backward(90)
tina.right(180)
tina.forward(17)
tina.right(28)
tina.pendown()
tina.pencolor("orange")
tina.forward(90)
tina.right(38)
tina.pencolor("yellow")
tina.forward(85)
tina.backward(85)
tina.left(128)
tina.pencolor("green")
tina.forward(110)
tina.right(37)
tina.pencolor("blue")
tina.forward(112)
tina.backward(112)
tina.left(127)
tina.pencolor("indigo")
tina.forward(90)
turtle.exitonclick() #Keeps pycharm window open
|
147d6849ff8a19775e6018581b42d2a760a527bd | unicoe/LeetCode | /python_src/349. Intersection of Two Arrays.py | 429 | 3.765625 | 4 | class Solution(object):
def intersection(self, nums1, nums2):
"""
so easy。。。
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
resSet = set()
for i in nums1:
for j in nums2:
if i == j:
resSet.add(i)
return list(resSet)
s = Solution()
res = s.intersection([1,2,3,1],[1])
print(res) |
06f920a352b1713c50882d5d6371a756e50b373f | ankushSsingh/allassigns | /redeem/q3.py | 569 | 3.765625 | 4 | #!/usr/bin/env python
def printtree(arr,left,right):
l=right-left
if(l==0):
#print arr[right]
return
for i in range(left,left+int(l/2)):
print " ",
print arr[left+int(l/2)]
printtree(arr,left,left+int(l/2))
printtree(arr,left+int(l/2)+1,right)
def main():
str=raw_input().split(' ')
arr = [int(num) for num in str]
l=len(arr)
for i in range(l):
t=arr[i]
for j in range(i+1,l):
if(arr[i]>arr[j]):
arr[i]=arr[j]
arr[j]=t
t=arr[i]
print arr
#print int(l/2)
printtree(arr,0,l-1)
print arr[l-1]
if __name__ == '__main__':
main() |
e3a9e43537bb6de62f980f2cb4d3655bc5797d5e | jagrvargen/coursera_algos_datastructures | /week_2_exercises/lcm_naive.py | 224 | 3.640625 | 4 | def lcm_naive(a, b):
if a < b:
a, b = b, a
min = a * b
for i in range(min, a, -1):
if i % a == 0 and i % b == 0:
min = i
return min
print(lcm_naive(int(input()), int(input())))
|
1343cfd2e6c1f2f0125a06993d197c35e66905f1 | mghasemi19/python_sample | /Basic/D5_String.py | 4,111 | 4.03125 | 4 | s = 'abcde'
print(s[1:3]) # bc
print(s[1:-1]) # bcd
print(s[1:4]) # bcd
print(s[::-1]) # edcba
s = 'shirafkan'
print(len(s)) # 9
print(max(s)) # s
print(min(s)) # a
print(ord('s')) # 115
print(ord('a')) # 97
print(chr(97)) # a
s = 'python'
print( 'th' in s) # True
print( 'xh' not in s) # True
print( s == 'python') # True
print( s < 'sara') # True
print(s.islower())
print(s.isupper())
print(s.isalnum())
print(s.isalpha())
s = 'python3'
print(s.isalnum()) # True
print(s.isalpha()) # False
s = '#python3'
print(s.isalnum()) # False
print(s.isalpha()) # False
s = '123'
print(s.isdigit()) # True
print('\t'.isspace())
print('\n===============================')
s = '12a3bcd4'
k = 0
for ch in s:
if ch.isdigit() == True:
k += int(ch)
print(k) # 10 : 1+2+3+4
s = 'welcom to python'
print(s.startswith('we')) # True
print(s.endswith('thon')) # True
print(s.find('o')) # 4
print(s.index('o')) # 4
print(s.find('f')) # -1
#print(s.index('f')) # ValueError
print(s.find('o',5)) # 8
print(s.find('o',10)) # 14
print(s.count('o')) # 3
print(s.count('o',5)) # 2
s = 'farshid@ut.ac.ir'
i = s.find ('@')
print(s[i+1:]) # ut.ac.ir
s = 'welcom to python'
print(s.capitalize()) # Welcom to python
print(s.title()) # Welcom To Python
s = 'PyThon'
print(s.lower()) # python
print(s.upper()) # PYTHON
print(s.swapcase()) # pYtHON
s = 'shirafkan'
print(s.replace('afkan','del')) # shirdel
s = '$$pyt$hon$$$'
print(s.strip('$')) # pyt$hon
print(s.lstrip('$')) # pyt$hon$$$
print(s.rstrip('$')) # $$pyt$hon
s = '##ali$$$'
print(s.lstrip('#').rstrip('$')) # ali
s = 'www.sanjesh.org'
print(s.lstrip('www.')) # sanjesh.org
s = 'Python created by Rossum'
a = s.split(' ')
print(a) # ['Python', 'created', 'by', 'Rossum']
b = ['Python', 'created', 'by', 'Rossum']
c =' '.join(b)
print(c)
name = 'ali.py'
a = name.split('.')
print(a) # ['ali', 'py']
print(a[1]) # py
print(repr(a[1])) # 'py'
s = 'sara@gmail.com'
u ,d = s.split('@')
print(u) # sara
print(d) # gmail.com
s = 'ali\nreza'
a = s.split('\n')
print(a) # ['ali', 'reza']
b = s.splitlines()
print(b) # ['ali', 'reza']
s = '127.02.0.001'
b = s.split('.')
a = '.'.join([str(int(i)) for i in b])
print(a) # 127.2.0.1
f = '001'
print(int(f)) # 1
print(str(int(f))) # 1
s = '12'
print(s.zfill(5)) # 00012
print(s.zfill(3)) # 012
s = 'sara'
print(s.ljust(7,'+')) # sara+++
print(s.rjust(7,'+')) # +++sara
print(s.center(7,'+')) # ++sara+
year = 2020
e = 'referendum'
print(f'Results of the {year} {e}') # Results of the 2020 referendum
#############################################
print('# format #')
fname = 'sara'
lname = 'shirafkan'
print('name:{0} family:{1}'.format(fname,lname))
# name:sara family:shirafkan
s = 'ali'
print(f'name : {s}') # ali
print(f'name : {s!r}') # 'ali'
print('name:{}'.format(s)) # ali
print('name:{!r}'.format(s)) # 'ali'
n = 14
print('{:d}'.format(n)) # 14
print('{0:d}'.format(n)) # 14
print('{:5d}'.format(n)) # 14
a = 12
b = 15
print('{0:f} {1:d}'.format(a,b)) # 12.000000 15
print('{1:f} {0:d}'.format(a,b)) # 15.000000 12
print('{0:d} {1:f}'.format(a,b)) # 12 15.000000
f = 15.999
print('{:.2f}'.format(f)) # 16.00
f = -15.999
print('{:.2f}'.format(f)) # -16.00
p = 0.83
print('{:.2%}'.format(p)) # 83.00%
a = 20000000
print('{:,}'.format(a)) # 20,000,000
n = 14
print('{:X}'.format(n)) # E
print('{:#X}'.format(n)) # 0XE
print('{:b}'.format(n)) # 1110
print('{:#b}'.format(n)) # 0b1110
n = 35
print('{:*>6d}'.format(n)) # ****35
print('{:*<6d}'.format(n)) # 35****
print('{:*^6d}'.format(n)) # **35**
|
a7dfc4f96f6a666e5cf9f3d07a253a770442b344 | WillyNathan2/Python-Dasar | /PR04_2072037/PR04A_2072037.py | 774 | 3.71875 | 4 | #File : PR04A_2072037.py
#Nama : Willy Natanael Sijabat 2072037
#Deskripsi : Membuat program value total bintang(*) maupun garis lurus (|) , sama dengan n
# Dengan Ketentuan perjarak dari variabel m dengan memberikan tanda garis lurus
# (|)
# n = integer
# m = integer
# i = integer
def main ():
#Program
#input
n = int(input("n: "))
m = int(input("m :"))
i = 0
garis = 1
#process include output
while (i < n):
if((garis%m) == 0):
garis = garis + 1
print("|", end = " ")
else:
garis = garis + 1
print("*", end = " ")
i += 1
if __name__ == '__main__':
main()
|
56f27a334e7529aa2a0c457ec5ba93ef52f3e974 | AlexNewson/ProjectEuler | /python/000-050/euler016.py | 347 | 3.640625 | 4 | import time
import euler
euler.print_problem(16)
start = time.time()
# ==================================================
number = 2**1000
n = 0
for i in str(number):
n += int(i)
print("The Answer is: %i" % n)
# ==================================================
end = time.time()
time = end - start
print("This took %s seconds" % time)
|
756487450d6ddb1f86497cabce3606d32b8e00ec | elviswong-cn/python_basic | /part1_basic/chapter1_basic.py | 800 | 3.859375 | 4 | #1.1
# print(2+3*6)
# print((2+3)*6)
# print(48565878 * 578453)
# # 幂
# print(2 ** 8)
# print (23 / 7)
# # 取整
# print( 23 // 7)
# # 取余
# print ( 23 % 7)
# print(2+2)
#1.3
# print('Alice' + 'Bob')
# # 字符串打印5次 * Int
# print('Alice' * 5)
#1.4
# spam = 50
# print(spam)
# eggs = 2
# print(spam + eggs)
# spam=spam+eggs
# print(spam)
#1.5 This program says hello and asks from my name
# print('Hello World!')
# print("What's your name?")
# myName = input()
# print('It is good to meet you,'+myName)
# print('The length of your name is:')
# print(len(myName))
# print("what's your age?")
# myAge = input()
# print('You will be'+str(int(myAge)+1)+' in a year.')
#1.8
print(round(0.5)) #此处结果为0,而不是1
print(round(0.6))
print(round(1.5))
print(round(1.4))
|
7df2dec29d404117970e06425342547fc28853ae | will-i-amv-books/Functional-Python-Programming | /CH4/ch04_ex2.py | 3,440 | 3.9375 | 4 | #!/usr/bin/env python3
"""Functional Python Programming
Chapter 4, Example Set 4
Definitions of mean, stddev, Pearson correlation
and linear estimation.
http://en.wikipedia.org/wiki/Mean
http://en.wikipedia.org/wiki/Standard_deviation
http://en.wikipedia.org/wiki/Standard_score
http://en.wikipedia.org/wiki/Normalization_(statistics)
http://en.wikipedia.org/wiki/Simple_linear_regression
"""
###########################################
# Imports
###########################################
from math import sqrt
###########################################
# Using any() and all() as reductions
###########################################
def isprime(number):
if number < 2: return False
if number == 2: return True
if number % 2 == 0: return False
return not any(
number % p == 0
for p in range(3, int(sqrt(number)) + 1, 2)
)
primes = [
'2', '3', '5', '7', '11', '13', '17', '19', '23', '29',
'31', '37', '41', '43', '47', '53', '59', '61', '67', '71'
]
# Check if there are a number that is not prime
areThereNonprimes = not all(isprime(int(x)) for x in primes)
areThereNonprimes = any(not isprime(int(x)) for x in primes)
###########################################
# Using sums and counts for statistics
###########################################
# Basic sum functions
def s0(samples):
return len(samples) # sum(x**0 for x in samples)
def s1(samples):
return sum(samples) # sum(x**1 for x in samples)
def s2(samples):
return sum(x**2 for x in samples)
# Basic statistical functions
def calc_mean(samples):
"""Arithmetic mean.
>>> d = [4, 36, 45, 50, 75]
>>> calc_mean(d)
42.0
"""
return s1(samples)/s0(samples)
def calc_stdev(samples):
"""Standard deviation.
>>> d = [ 2, 4, 4, 4, 5, 5, 7, 9 ]
>>> calc_mean(d)
5.0
>>> calc_stdev(d)
2.0
"""
N = s0(samples)
return sqrt((s2(samples)/N) - (s1(samples)/N)**2)
def calc_normalized_score(x, mean_x, stdev_x):
"""
Compute a normalized score (Z).
>>> d = [ 2, 4, 4, 4, 5, 5, 7, 9 ]
>>> list(
calc_normalized_score(x, calc_mean(d), calc_stdev(d))
for x in d
)
[-1.5, -0.5, -0.5, -0.5, 0.0, 0.0, 1.0, 2.0]
The above example recomputed mean and standard deviation.
Not a best practice.
"""
return (x - mean_x) / stdev_x
def calc_correlation(samples1, samples2):
"""Pearson product-moment correlation.
>>> xi= [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65,
... 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83,] # Height (m)
>>> yi= [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29,
... 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46,] # Mass (kg)
>>> round( calc_correlation( xi, yi ), 5 )
0.99458
"""
m_1, s_1 = calc_mean(samples1), calc_stdev(samples1)
m_2, s_2 = calc_mean(samples2), calc_stdev(samples2)
z_1 = (calc_normalized_score(x, m_1, s_1) for x in samples1)
z_2 = (calc_normalized_score(x, m_2, s_2) for x in samples2)
r = sum(zx1*zx2 for zx1, zx2 in zip(z_1, z_2)) / len(samples1)
return r
xi = [
1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65,
1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83,] # Height (m)
yi = [
52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29,
63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46,] # Mass (kg)
round(calc_correlation( xi, yi ), 5)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.