blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
395896b47a59051b3749ac89db72d22441f46104
|
cpsolano/Nivelacion-Programaci-n
|
/23082019/000959.py
| 411 | 3.59375 | 4 |
given_list2 = [5,4,4,3,1,-2,-3,-5] #se genera lista
total5 = 0 #variable
i = 0 #variable contador
while True: #se pone condicion que siempre es verdad
total5 += given_list2[i] #se le suman los valores de la lista uno por uno a la variable
i += 1 #se le suma 1 al contador
if given_list2[i] <= 0: #condicion para poder cortar el loop
break #corta el loop
print total5 #se imprime la variable
|
9c6eb778cfc20002ae7aafb850e216e1f16e4a6c
|
kunzhang1110/COMP9021-Principles-of-Programming
|
/Quiz/Quiz 3/quiz_3.py
| 1,700 | 4.03125 | 4 |
# Prompts the user for a word and outputs the list of
# all subwords of the word of height 1.
#
# Written by Kun Zhang for COMP9021
def extract_subwords(word):
i = 0 # start index pointer
out = []
# elminate redundant whitespace
word = word.split()
word = "".join(word)
last_index = len(word) - 1
while i <= last_index:
P_count = 0 # parenthese counter
flag = 1 # flag to increment i
first_P_index = 0
# print("i=",i,word[i])
for j in range(i, last_index + 1):
# print("j=",j,word[j], "P_count =", P_count)
if word[j] == "(":
P_count += 1
if P_count == 0:
if word[j] == ",":
i = j + 1
flag = 0
break
elif P_count == 1:
if word[j] == "(":
P1 = j
if word[j] == ")":
out.append(word[i:j+1])
i = j + 1
flag = 0
break
else: # when P_count > 1
i = P1
break
if flag == 1:
i += 1
# insert back spaces
for i in range(len(out)):
for j in range(len(out[i])):
if out[i][j] == ",":
out[i] = out[i][:j] + ", " + out[i][j+1:]
return out
word = input('Enter a word: ')
#word = "f1(f2(f3(a,b), c), f2(a, f3(a,b)), f2(bcb), f2(0,f3(eeee)))"
print('The subwords of "{:}" of height 1 are:\n {:}'.
format(word, extract_subwords(word)))
|
c279136191fdde56581f148859ad1b808438d676
|
charlesmtz1/Python
|
/Ejercicios/Ejercicio30.py
| 302 | 4 | 4 |
#Ejercicio 30
#Para un número N imprimir su tabla de multiplicar.
def tabla_multiplicar(numero):
for valor in range(1,11):
print(f"{numero} x {valor} = {numero * valor}")
numero = int(input("Escribe un numero: "))
print("Se muestra su tabla de multiplicar:")
tabla_multiplicar(numero)
|
8e002898088f6b6c336967b73d0608b5c7239767
|
JAntonioMarin/PythonBootcamp
|
/Section12/81.py
| 1,567 | 3.984375 | 4 |
def func():
return 1
print(func())
def hello():
return "Hello!"
print(hello())
print(hello)
greet = hello
print(greet())
# del hello
# print(hello())
#
# Traceback (most recent call last):
# File "81.py", line 18, in <module>
# print(hello())
# NameError: name 'hello' is not defined
def hello2(name='Josele'):
print("The hello() function has been executed!")
def greet():
return '\t This is the greet() func inside hello!'
def welcome():
return "\t This is welcome() inside hello"
if name == 'Jose':
return greet
else:
return welcome
# print(greet())
# print(welcome())
# print("This is the end of hello function!")
my_new_func = hello2('Jose')
print(my_new_func())
# hello2()
# welcome()
# NameError: name 'welcome' is not defined
def cool():
def super_cool():
return "I am very cool!"
return super_cool
some_func = cool()
some_func()
def jelou():
return "Hi Jose!"
def other(some_def_func):
print('Other code runs here!')
print(some_def_func())
other(jelou)
def new_decorator(original_func):
def wrap_func():
print("Some extra code, before the original function")
original_func()
print("Some extra code, after the original function!")
return wrap_func
def func_need_decorator():
print("I want to be decorated!!")
decorated_func = new_decorator(func_need_decorator)
decorated_func()
@new_decorator
def func_need_decorator2():
print("I want to be decorated!!")
func_need_decorator2()
|
1baa2a86164bd18979758e596b5cb8701f04c2f9
|
EraSilv/day2
|
/class1/class.py
| 498 | 4.03125 | 4 |
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def printmy(self):
print("I am ", self.__name, "I am", self.__age)
class Person2:
def __init__(self, name, age):
self.name = name
self.age = age
def printmy(self):
print("I am ", self.name, "I am", self.age)
adam = Person2("Adam", 25)
adam.printmy()
print(adam.name)
adam = Person("Adam", 25)
# adam._Person__name = "men"
print(adam._Person__name)
|
e9f9c92e43e6856f571e46671dedd378585975d0
|
Erick-ViBe/Platzi
|
/PythonPlatzi/busquedaBinaria.py
| 738 | 4.0625 | 4 |
# -*- coding: utf-8 -*-
def run():
list_of_numbers = [2, 5, 8, 1, 6, 9, 3, 10, 4, 7]
number = int(raw_input('Numero a buscar: '))
result = binary_search(list_of_numbers, number)
if result is True:
print('Si esta en la lista')
else:
print('No esta en la lista')
def binary_search(list_of_numbers, number):
list_of_numbers.sort()
pivot = len(list_of_numbers)/2
if list_of_numbers[pivot] == number:
return True
elif list_of_numbers > number:
return binary_search(list_of_numbers[:pivot], number)
elif list_of_numbers < number:
return binary_search(list_of_numbers[pivot+1:], number)
else:
return False
if __name__ == '__main__':
run()
|
abf9144ab13fe4a821808079fb20d3555e7d414d
|
hoangnym/Python_project
|
/python_intermediate/secret_auction/main.py
| 598 | 3.84375 | 4 |
from art import logo
print(logo)
# Create empty dictionary
biddings = {}
keep_bidding = True
while keep_bidding:
name = input("What is your name?: ")
bid = int(input("What is your bid? €"))
biddings[name] = bid
additional = input("Are there other users who want to bid (yes / no)?: ").lower()
if additional == "no":
keep_bidding = False
#Clear window
print(chr(27) + "[2J")
amount = max(biddings.values())
highest_bidder = [k for k, v in biddings.items() if v == amount][0]
print(f"{highest_bidder} wins the secret auction with a bid of {amount}.")
|
a78c1c4b38a78d10a38df86607ed216650dd0015
|
ruinanzhang/Leetcode_Solution
|
/70-Restore IP Address.py
| 1,962 | 3.609375 | 4 |
# Tag:Backtracking
# 93. Restore IP Addresses
# -----------------------------------------------------------------------------------
# Description:
# Given a string containing only digits, restore it by returning all possible valid
# IP address combinations.
# A valid IP address consists of exactly four integers (each integer is between 0 and 255)
# separated by single points.
# -----------------------------------------------------------------------------------
# Example:
# Input: "25525511135"
# Output: ["255.255.11.135", "255.255.111.35"]
# -----------------------------------------------------------------------------------
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
class Solution:
def restoreIpAddresses(self, s):
# 思路:backtracking
# Term Condition: in total 4 ints are generated and no more left digits
# Limitation: 1. not latger than 255 , not smaller than 0 or start with 0
# 操作:选择1or2or3digits后加‘.’!!!主要画图的时候还是注意每一步(每一个分支)可以做什么operation
res = []
length = len(s)
def backtracking_dfs(split_times,start,s,sub_path):
# Term Condition
if start == length and split_times == 4:
res.append(sub_path[:-1])
return
if split_times >=4 and start <= length:
return
for i in range(1,4):
if i!= 1 and s[start] == '0':
return
if length-start < i or length-start>3*(4-split_times):
return
if i == 3 and int(s[start:start+i])>255:
return
else:
sub_path += s[start:start+i] + '.'
backtracking_dfs(split_times+1,start+i,s,sub_path)
sub_path= sub_path[:-(1+i)]
backtracking_dfs(0,0,s,"")
return res
|
7bcde5627ed004ff68db242d88af1d8d5db05954
|
licmnn/driving
|
/driving.py
| 371 | 3.984375 | 4 |
country = input('请问您是哪国人: ')
age = input('请输入您的年龄: ')
age = int(age)
if country == '台湾':
if age >= 18:
print('你可以考驾照')
else:
print('你还不能考驾照')
elif country == '美国':
if age >= 16:
print('你可以考驾照')
else:
print('你不可以考驾照')
else:
print('你只能输入台湾或者美国')
|
dfec94e674fd73fb4c64edd53c78b341dfb49082
|
nikhilgurram97/CS490PythonFall2017
|
/PythonLab2/task4.py
| 594 | 4.03125 | 4 |
import numpy as n
a=n.random.rand(15) #random function to generate 15 random values into a list
print("Previous Vector: ")
print(a)
b=max(a) #finding max value in the generated vector
for i in range(15): #loop to replace largest value with 100
if a[i]==b:
a[i]=100
c=i
print("\nMax Value: "+str(b)+", At Index "+str(c+1))
print("\nNew Vector: (Replacing Index "+str(c+1)+")")
print(a) #newly generated vector
|
95604cc9e863327ef75d04cc0e09b27498caebf8
|
FanJiang718/Courses-Exercises
|
/MAP556/TP1/MAP556_PC1_Exo1_2.py
| 633 | 3.640625 | 4 |
import numpy as np
import matplotlib.pyplot as plt
N = 1000
U = np.random.rand(N)
a = 1.
########
# Stocker dans X des simulations de la loi de Cauchy de parametre a
# en utilisant l'inverse de la fct de repartition
#
X = a*np.tan(np.pi*(U-0.5))
#
########
integers1toN = np.arange(1,N+1)
########
# Calculer et stocker dans la variable 'moyenneEmp' la suite des moyennes empiriques
#
moyenneEmp = 1./integers1toN * np.cumsum(X)
#
# Afficher la suite à l'aide de la fonction plot de matplotlib.pyplot
#
plt.plot(integers1toN, moyenneEmp, color="b", label="Moyenne empirique")
#
########
|
e4021908627f1d0b9ad6d1cbcc8179214a040bfd
|
chasemp/sup
|
/suplib/durations.py
| 789 | 3.5 | 4 |
import os
import time
class Timer(object):
def __enter__(self):
self.start = time.clock()
return self
def __exit__(self, *args):
self.end = time.clock()
self.interval = self.end - self.start
def ftimeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
"""http://stackoverflow.com/a/13821695"""
import signal
class TimeoutError(Exception):
pass
def handler(signum, frame):
raise TimeoutError()
# set the timeout handler
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout_duration)
try:
result = func(*args, **kwargs)
to = False
except TimeoutError:
to = True
result = default
finally:
signal.alarm(0)
return result, to
|
b6cbbca196ab6d3274f8e2940d584b7b17fa8146
|
Gabrielatb/Interview-Prep
|
/elements_of_programming/Heaps/sort_nearly_sorted_array.py
| 2,668 | 4.125 | 4 |
# Sort a nearly sorted (or K sorted) array
# Given an array of n elements, where each element is at most k away from its target position,
# devise an algorithm that sorts in O(n log k) time. For example, let us consider k is 2,
# an element at index 7 in the sorted array, can be at indexes 5, 6, 7, 8, 9 in the given array.
# Input : arr[] = {6, 5, 3, 2, 8, 10, 9}
# k = 3
# Output : arr[] = {2, 3, 5, 6, 8, 9, 10}
# Input : arr[] = {10, 9, 8, 7, 4, 70, 60, 50}
# k = 4
# Output : arr[] = {4, 7, 8, 9, 10, 50, 60, 70}
#this can be more efficiently sorted with a heap data structure taking into advantage
#the fact that the array is almost sorted
import heapq
import itertools
def almost_sorted_array(sequence, k):
min_heap = []
# Adds the first k elements into min_heap. Stop if there are fewer than k
# elements.
for x in itertools.islice(sequence, k):
heapq.heappush(min_heap, x)
result = []
# For every new element, add it to min_heap and extract the smallest.
for x in sequence:
smallest = heapq.heappushpop(min_heap, x)
result.append(smallest)
# sequence is exhausted, iteratively extracts the remaining elements.
while min_heap:
smallest = heapq.heappop(min_heap)
result.append(smallest)
return result
# def almost_sorted_array(array, k):
# min_heap = []
# #adding first k elements into min_heap
# for x in itertools.islice(array, k):
# heapq.heappush(min_heap, x)
# result = []
# #new elements add to min heap and extract the smallest
# for num in array:
# smallest = heapq.heappushpop(min_heap, num)
# result.append(smallest)
# while min_heap:
# smallest = heapq.heappop(min_heap)
# result.append(smallest)
# return result
print almost_sorted_array([3,-1,2,6,4,5,8], 2)
#################################################################################
#quick sort
# x
# def partition(lst, start, end):
# p_index = start
# pivot = lst[end]
# for i in range(start, end):
# if lst[i] < pivot:
# lst[i], lst[p_index] = lst[p_index], lst[i]
# p_index +=1
# lst[p_index], lst[end] = lst[end], lst[p_index]
# return p_index
# def quicksort(lst, start, end, k):
# k -=1
# if start < end:
# p_index = partition(lst, start, end)
# quicksort(lst, start, p_index - 1, k)
# quicksort(lst, p_index + 1, end, k)
# return lst
# def quicksort_start(lst, k):
# return quicksort(lst, 0, len(lst)-1, k)
# lst = [10, 9, 8, 7, 4, 70, 60, 50]
# print quicksort(lst, 0, len(lst)-1, 4)
|
03096cec7da3e4ef5f6c09fb3132c1fe7bf62a4b
|
THADEUSH123/python-noobs-programming-challenge
|
/prog-challenges/boxes.py
| 890 | 3.671875 | 4 |
"""Bython Challenge."""
my_rectangle1 = {
# coordinates of bottom-left corner
'left_x': 1,
'bottom_y': 2,
# width and height
'width': 3,
'height': 4,
}
my_rectangle2 = {
# coordinates of bottom-left corner
'left_x': 1,
'bottom_y': 5,
# width and height
'width': 2,
'height': 4,
}
def overlap(rec1, rec2):
"""Caculate overlap of two rectangles."""
grid = [[0 for _ in range(10)] for _ in range(10)]
for x in range(rec1['left_x'], rec1['left_x'] + rec1['width']):
for y in range(rec1['bottom_y'], rec1['bottom_y'] + rec1['height']):
grid[x][y] += 1
for x in range(rec2['left_x'], rec2['left_x'] + rec2['width']):
for y in range(rec2['bottom_y'], rec2['bottom_y'] + rec2['height']):
grid[x][y] += 1
for row in grid:
print row
overlap(my_rectangle1, my_rectangle2)
|
eea0dd0a4750d8b0c535cbd3b9774be5863a6a19
|
lukelee1220/Python
|
/zhishu2.py
| 365 | 4.0625 | 4 |
def isprime(y):
isprime=True
#print(y)
if y == 0:
return False
if y == 1:
return True
for a in range(2,y):
if y%a==0:
isprime=False
break
return isprime
#x=int(input("input a number"))
y=int(input("input a number"))
for a in range(y):
if(isprime(a)):
print (a,end=" ")
|
0b02ae6ebb9904199d280c27307e47f4377cf341
|
maih1/DAA
|
/PrimeFactor.py
| 1,051 | 3.75 | 4 |
import time
import math
a = []
prime = 2
def isPrime(n):
if n < 2:
return False
else:
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def intPrime_1(n):
global prime, a
if n == 1:
return a
elif n % prime == 0:
a.append(prime)
return intPrime_1(n // prime)
else:
prime += 1
return intPrime_1(n)
def intPrime_2(n):
a = []
prime = 2
while n > 1:
if n % prime == 0 :
a.append(prime)
n = n // prime
else:
prime = prime + 1
return a
n = int(input("Nhap so nguyen n: "))
time_start1 = time.time()
print("Phuong phap de quy:",intPrime_1(n))
time_end1 = time.time()
time1 = time_end1 - time_start1
print("Thoi gian de quy: ", time1, "s" )
time_start2 = time.time()
print("Phuong phap vong lap:",intPrime_2(n))
time_end2 = time.time()
time2 = time_end2 - time_start2
print("Thoi gian vong lap : ", time2, "s" )
|
413036d9d27f69d021f33c1f3877206268c2b353
|
wangyunge/algorithmpractice
|
/int/63_Search_in_Rotated_Sorted_Array_II.py
| 1,352 | 3.9375 | 4 |
'''
Follow up for Search in Rotated Sorted Array:
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
Have you met this question in a real interview? Yes
Example
Given [1, 1, 0, 1, 1, 1] and target = 0, return true.
Given [1, 1, 1, 1, 1, 1] and target = 0, return false.
'''
class Solution:
"""
@param A : an integer ratated sorted array and duplicates are allowed
@param target : an integer to be searched
@return : a boolean
"""
def search(self, A, target):
if not A:
return False
left = 0
right = len(A)-1
while left < right -1:
mid = (left+right)/2
if A[mid] == target:
return True
while left < mid and A[left] == A[mid]:
left += 1
if A[left] <= A[mid]:
if A[left] <= target and target <= A[mid]:
right = mid
else:
left = mid
elif A[mid] <= A[right]:
if A[mid] <= target and target <= A[right]:
left = mid
else:
right = mid
if A[left] == target or A[right] == target:
return True
else:
return False
|
347fdd373f491c8976ed48afc79d4b67f8940707
|
Ming-H/leetcode
|
/438.find-all-anagrams-in-a-string.py
| 774 | 3.734375 | 4 |
#
# @lc app=leetcode id=438 lang=python3
#
# [438] Find All Anagrams in a String
#
# @lc code=start
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
"""
The time complexity of this solution is O(n),
where n is the length of s.
"""
pCount = [0] * 26
sCount = [0] * 26
result = []
for char in p:
pCount[ord(char) - ord('a')] += 1
left = 0
for right in range(len(s)):
sCount[ord(s[right]) - ord('a')] += 1
if right - left + 1 > len(p):
sCount[ord(s[left]) - ord('a')] -= 1
left += 1
if pCount == sCount:
result.append(left)
return result
# @lc code=end
|
442ed6429cde676f837e17ea24709dedbc3d7154
|
TilletJ/ProjetInfo_TerrainFractal
|
/NEW/cours_eau.py
| 1,054 | 3.65625 | 4 |
# -*- coding: utf-8 -*-
class CoursEau():
def __init__(self, start, paysage):
self.points = [start]
self.paysage = paysage
def coule(self):
if self.points[0].est_3D :
pass
else : #2D
tolerance = 0.0 #Provoque des erreurs de dépassement de limite de récursion
point_act = self.points[-1]
vois1, vois2 = self.paysage.trouve_voisins(point_act)
if point_act.y > vois1.y - tolerance and point_act.y > vois2.y - tolerance:
if point_act.y - vois1.y > point_act.y - vois2.y :
self.points.append(vois1)
else:
self.points.append(vois2)
self.coule()
elif point_act.y > vois1.y - tolerance:
self.points.append(vois1)
self.coule()
elif point_act.y > vois2.y - tolerance:
self.points.append(vois2)
self.coule()
def __str__(self):
return str([str(p) for p in self.points])
|
3f084dba4683bb142a0ff378dd743a2f09ac3ce5
|
julianfrancor/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/1-number_of_lines.py
| 1,015 | 4.34375 | 4 |
#!/usr/bin/python3
"""
function that returns the number of lines of a text file
"""
def number_of_lines(filename=""):
"""
with:
It is good practice to use the "with" keyword when dealing
with file objects. This has the advantage that the file is
properly closed after its suite finishes,
even if an exception is raised on the way.
It is also much shorter than writing equivalent try-finally blocks
in the open function we don't have to put explicit the mode to read "r"
because by default if you don't put anything it will read.
You just have to specify the mode for the write "w"
Another way to do it:
number_lines = 0
for line in file:
number_lines += 1
return number_lines
--------------------------
number_lines = 0
while file.readline():
number_lines += 1
return number_lines
"""
with open(filename, mode="r", encoding="UTF8") as file:
return len(file.readlines())
|
04c65f0df52be3b0fb3cca8e43a59703adf5f135
|
MitsurugiMeiya/Leetcoding
|
/leetcode/Tree/构造二叉树/105. 从前序和中序遍历序列构造二叉树.py
| 1,086 | 3.96875 | 4 |
"""
前序遍历 preorder = [3,9,20,15,7] root left right
中序遍历 inorder = [9,3,15,20,7] left root right
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not preorder or not inorder:
return None
# 因为前序遍历,第一个节点总是root, 找到root以后就要对他进行一个分界了
root = TreeNode(preorder.pop(0))
# 中序遍历中, 在root左边的就是左子树, 在root右边的就是右子树
index = inorder.index(root.val)
# 因为对于preorder来说, root left, 所以下一个节点是左子树的,所以就先递归左子树
root.left = self.buildTree(preorder, inorder[:index])
root.right = self.buildTree(preorder, inorder[index + 1:])
return root
|
17a2e220da73d701e33de04a77443dd65617b0e4
|
AlvisonHunterArnuero/EinstiegPythonProgrammierung-
|
/PYTHON NOTEBOOKS/8.8_dictionary_questions_&_solutions.py
| 3,462 | 4.0625 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 23 17:32:12 2019
@author: giles
"""
'''
Question 1
Can you remember how to check if a key exists in a dictionary?
Using the capitals dictionary below write some code to ask the user to input
a country, then check to see if that country is in the dictionary and if it is
print the capital. If not tell the user it's not there.
'''
#capitals = {'France':'Paris','Spain':'Madrid','United Kingdom':'London',
# 'India':'New Delhi','United States':'Washington DC','Italy':'Rome',
# 'Denmark':'Copenhagen','Germany':'Berlin','Greece':'Athens',
# 'Bulgaria':'Sofia','Ireland':'Dublin','Mexico':'Mexico City'
# }
#
#user_input = input('Which country would you like to check?:> ')
#
#user_input = user_input.lower()
#
#
#
#while ('united kingdom' not in user_input and not user_input.isalpha()):
# if user_input == 'united states':
# break
# print('You must input a string')
# user_input = input('Which country would you like to check?:> ')
#
#user_input = user_input.title()
##print(user_input)
#if user_input in capitals:
# print(f'The capital of {user_input} is {capitals[user_input]}')
#else:
# print('No data available')
'''
Question 2
Write python code that will create a dictionary containing key, value pairs
that represent the first 12 values of the Fibonacci sequence
i.e {1:0,2:1,3:1,4:2,5:3,6:5,7:8 etc}
'''
#n = 12
#a = 0
#b = 1
#d = dict()
#for i in range(1,n+1):
# d[i] = a
# a,b = b,a+b
#print(d)
'''
Question 3
Create a dictionary to represent the open, high, low, close share price data
for 4 imaginary companies. 'Python DS', 'PythonSoft', 'Pythazon' and 'Pybook'
the 4 sets of data are [12.87, 13.23, 11.42, 13.10],[23.54,25.76,21.87,22.33],
[98.99,102.34,97.21,100.065],[203.63,207.54,202.43,205.24]
'''
#companies = ['Python DS', 'PythonSoft', 'Pythazon', 'Pybook']
#key_names = ['Open','High','Low','Close']
#prices = [[12.87, 13.23, 11.42, 13.10],[23.54,25.76,21.87,22.33],
#[98.99,102.34,97.21,100.065],[203.63,207.54,202.43,205.24]]
#
#d_1 = {}
#
#for i in range(len(key_names)):
# d_1[companies[i]] = dict(zip(key_names,prices[i]))
#
#print(d_1)
'''
Question 4
Go to the python module web page and find a module that you like. Play with it,
read the documentation and try to implement it.
'''
## Days until holiday!
#import datetime
#
#today = datetime.date.today()
#
#print(f"Today's date is {today}")
#holiday = datetime.date(2019,12,25)
#delta = holiday - today
#
#print(f"Just {delta.days} days until the holidays!")
'''
Question 5
Create a dictoinary containing as keys the letters from A-Z, the values should
be random numbers created from the random module. Can you draw a bar graph of
the results?
'''
#import random
#
#keys = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
#
#d = dict()
#
#for letter in keys:
# d[letter] = random.randint(1,100)
#
#print(d)
#
#import matplotlib.pyplot as plt
#
#x,y = zip(*d.items())
#
#plt.bar(x,y)
'''
Question 6
Create a dictionary containing 4 suits of 13 cards
['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King']
'''
suits = ['Spades','Clubs','Hearts','Diamonds']
rank = ['Ace','2','3','4','5','6','7','8','9','10','Jack','Queen','King']
deck = dict()
for i in suits:
deck[i] = rank
print(deck)
|
517f3f2e292248c2938781258e0dcc833a362908
|
soh200/PYTHON
|
/t9.py
| 176 | 3.78125 | 4 |
a=[1,2,3,4,5,6,7,8,9]
b=0
c=0
for n in a:
if(n%2==0):
b=b+1
else:
c=c+1
print("Number of even numbers: ",b)
print("Number of odd numbers: ",c)
|
11f7e2a05172e491e2dfdbfe42cd6677254c56a1
|
aRivieraDream/Learning-Python
|
/ex21.py
| 1,339 | 3.9375 | 4 |
print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newline and \t tabs.'
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires explanation
\n\t\twhere there is none.
"""
print "__________________"
print poem
print "__________________"
five = 10 -2 + 3 - 6
print "This should be five: %s" % five
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
def sentence(beans, jars, crates):
print "This replaces repeating strings"
print "We have %d beans, %d jars, and %d crates." % (beans, jars, crates)
# this is a helper method which unpacks a single var into three vars to be passed to
#sentence
def sen2(vars):
beans, jars, crates = vars
return sentence(beans, jars, crates)
print "With a starting point of: %d" % start_point
print "We have %d beans, %d jars, and %d crates." % (beans, jars, crates)
start_point = start_point / 10
print "We can also do that this way."
#print "We have %d beans, %d jars, and %d crates." % secret_formula(start_point)
#replace last line with call to function
print sen2(secret_formula(start_point))
|
f4ee1a2c6beb24257c016f10f974555950feec78
|
akshatakulkarni98/ProblemSolving
|
/DataStructures/arrays/pairs_are_divisible_by_k.py
| 849 | 3.5625 | 4 |
# https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/
# TC:
# SC:
class Solution:
def helper(self, arr, k):
"""
This will not work for many test cases
"""
s=sum(arr)
if s%k==0:
return True
else:
return False
def helper2(self, arr, k):
if len(arr)%2:
return False
hash_map=dict()
count=0
for i in range(len(arr)):
a=arr[i]
b=k-(a%k)
if b in hash_map and hash_map[b]>=1:
count+=1
hash_map[b]-=1
else:
hash_map[(a%k) or k]=hash_map.get(a%k,0)+1
return count == len(arr)//2
def canArrange(self, arr: List[int], k: int) -> bool:
return self.helper2(arr, k)
|
ef6d29777a2d60d9cbe15d20a803f06ffa04e870
|
pirhoo/python-course-fr
|
/teaching-demos/16.py
| 185 | 3.90625 | 4 |
# coding: utf-8
name = "Jens Finnäs"
length = len(name)
small_name = name.lower()
english_name = name.replace("ä", "a")
small_english_name = name.lower().replace("ä", "a")
print(length)
|
b93c2ff8b60cca00f81c1b0bd0a6cb1c2c44a1b6
|
mkodekar/PyOOPS
|
/square.py
| 1,077 | 4.03125 | 4 |
class Square:
def __init__(self, height=0, width=0):
self.height = height
self.width = width
@property
def height(self):
return self.__height
@property
def width(self):
return self.__width
def getArea(self):
return int(self.width) * int(self.height)
@height.setter
def height(self, value):
if str(value).isdigit():
self.__height = value
else:
print('Please enter a number for height')
@width.setter
def width(self, value):
if str(value).isdigit():
self.__width = value
else:
print('Please enter a number for width')
def main():
square = Square()
height = input('Enter the height of the square: ')
width = input('Enter the width of the square :')
square.height = height
square.width = width
print('Height of the square is', square.height)
print('Width of the square is', square.width)
print('Area of the square is ', square.getArea())
if __name__ == '__main__':
main()
|
a107264e45278f411f91f3b23f7f27445b02b481
|
cho010012/PyAI_Learning
|
/02_Pandas_DataFrame.py
| 658 | 3.609375 | 4 |
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.rand(6,4),columns=list('ABCD'))
# 數值在 0 到 1 之間 , 6 列 4 行的資料
print(df1)
print('')
#Random Normal distr 隨機常態 分配 , 6 列 4 行的資料
df2 = pd.DataFrame(np.random.randn(6,4),columns=list('ABCD'))
print(df2)
print('')
df1 = df1.append(df2,ignore_index=True) # 附加df2 到 df1, 忽略索引
print(df2)
print('')
df1 = df1.drop(list(range(2,8))) # 刪 掉一個範圍的列
print(df2)
print('')
df1 = df1.drop(columns = ['A','D']) # 刪掉 A 欄 跟 D 欄
print(df2)
print('')
df1 = df1.drop(11) # 刪掉 第 11 列
print(df1)
print('')
|
c14ef57a4c07a5984f6f8575411a84c898b09d36
|
carlysonviana/AulasPython
|
/nome_senha.py
| 265 | 3.984375 | 4 |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
while True:
nome = input("Digite o nome do usuario: ")
senha = input("Digite a senha do usuario: ")
if nome != senha and len(nome) >= 5 and len(senha) >= 5:
print("VÁLIDOS")
break
|
65f2b53b16e4272780e1e34b6924a6e57f63e832
|
nikist97/CodingChallenge
|
/DataModel.py
| 10,059 | 3.578125 | 4 |
from DataRandomizer import DataGenerator
from CustomErrors import InvalidPriceError, InvalidPositionError, DuplicateIdentifierError
from collections import deque
from math import log
class Event(object):
"""
this class represents the model of an Event with a unique identifier and 0 or more positive ticket prices
"""
currency = "$" # the main currency used for the tickets is dollar
def __init__(self, identifier, tickets):
"""
constructor for an Event object
:param identifier: the unique numeric identifier of the event
:param tickets: the container with all the ticket prices
:raises InvalidPriceError: if there is a ticker price <= 0
:raises TypeError: if the identifier is not an integer
"""
# ensure all tickets' prices are positive
if not all(ticket > 0 for ticket in tickets):
raise InvalidPriceError("All ticket prices must be greater than 0")
# ensure the identifier is an integer
if type(identifier) != int:
raise TypeError("Identifier must be of type int")
self.identifier = identifier
self.tickets = tickets
def get_id(self):
"""
get a formatted string of the unique id of the event
:return: a string of the id filled with 0s appended to its left so that the number of digits is equal to the
number of digits of the maximum id for a ticket, for example if max ticket id might be 400, then id 4 will
returned as '004' instead of '4'
"""
num_of_digits = int(log((GridWorld.grid_size*2 + 1)**2, 10)) + 1
formatted_id = str(self.identifier)
if len(formatted_id) < num_of_digits:
return "0"*(num_of_digits - len(formatted_id)) + formatted_id
else:
return formatted_id
def get_minimum_ticket_price(self):
"""
get the minimum ticket price from all ticket prices in this event
:return: a formatted string of the minimum float from the collection of ticket prices, rounded to 2 digits after
decimal point, 0s are also appended to the left to fit the format, e.g. 7.5 is returned as 07.50,
if there are no tickets, 'N/A' is returned
"""
if len(self.tickets) == 0:
return "N/A"
else:
num_of_digits = len(str(DataGenerator.max_ticket_price))
min_price = min(self.tickets)
min_price = '{0:.2f}'.format(min_price)
if len(min_price) < num_of_digits:
return Event.currency + "0"*(num_of_digits - len(min_price)) + min_price
else:
return Event.currency + min_price
class GridWorld(object):
"""
this class represents the model of a GridWorld containing a number of events
"""
grid_size = 10 # half of the size of the grid, e.g. if this is 10, world is in range [-10, 10]
def __init__(self, generate=True):
"""
constructor for a GridWorld object
:param generate: optional argument, True if data should be generated when initializing the object and False
otherwise, default value is True
"""
self.unique_identifiers = set() # a set is used to ensure the uniqueness of identifiers for events
self.grid = []
for row in range(self.grid_size*2 + 1):
self.grid.append([None]*(self.grid_size*2 + 1))
if generate:
self.generate_data()
def generate_data(self):
"""
a method which generates random data in the world
"""
DataGenerator.init_data(self, Event)
def get_event(self, x, y):
"""
a method which returns the event stored at position (x,y)
:param x: the x coordinate
:param y: the y coordinate
:return: the event at position (x, y) or None if there is no event at the position
"""
return self.grid[x + self.grid_size][y + self.grid_size]
def register_event(self, event, i, j):
"""
a method to register a new event in the world
:param event: the event object to register
:param i: the x coordinate of the event
:param j: the y coordinate of the event
:raises TypeError: if the event argument is not of type Event
:raises InvalidPositionError: if the coordinates for the event are out of bounds
:raises DuplicateIdentifierError: if the event's identifier is already in use
"""
if type(event) != Event:
raise TypeError("Event must be an object of type Event")
if not ((-1*self.grid_size) <= i <= self.grid_size and (-1*self.grid_size) <= j <= self.grid_size):
raise InvalidPositionError("Out of bounds coordinates when registering an event: {0}, {1}".format(i, j))
if event.identifier in self.unique_identifiers:
raise DuplicateIdentifierError("Identifier {0} is already in use".format(event.identifier))
self.grid[j + self.grid_size][i + self.grid_size] = event
self.unique_identifiers.add(event.identifier)
def get_nearest_positions(self, x, y, num_nearest_events):
"""
a method which returns the nearest positions to an input position in which there is a registered event
:param x: the input x coordinate
:param y: the input y coordinate
:param num_nearest_events: the number of nearest events to return
:return: a list of points represented by a tuple (x,y) which are the nearest positions with an event
:raises InvalidPositionError: when the input coordinates are out of bounds
"""
if not ((-1*self.grid_size) <= x <= self.grid_size and (-1*self.grid_size) <= y <= self.grid_size):
raise InvalidPositionError("Out of bounds coordinates when getting nearest events: {0}, {1}".format(x, y))
x, y = x + self.grid_size, y + self.grid_size
nearest_positions = []
if num_nearest_events == 0:
return nearest_positions
# check if the input coordinates contain an event
if self.grid[y][x] is not None:
nearest_positions.append((x - self.grid_size, y - self.grid_size))
# perform Breadth-First-Search to find the nearest events, by exploring neighbour positions
explored = set()
explored.add((x, y))
fringe = deque()
while len(nearest_positions) != num_nearest_events:
for position in self.get_available_moves(x, y):
if position in explored or position in fringe:
continue
fringe.append(position)
if len(fringe) == 0:
break
x, y = fringe.popleft()
explored.add((x, y))
if self.grid[y][x] is not None:
nearest_positions.append((x - self.grid_size, y - self.grid_size))
return nearest_positions
def get_nearest_events(self, x, y, num_nearest_events=5):
"""
a method to get the nearest events to an input position, prints the information about each of the nearest events
:param x: the input x coordinate
:param y: the input y coordinate
:param num_nearest_events: optional argument, the number of nearest events to return, default value is 5
:return: a list of the nearest event objects
"""
nearest_positions = self.get_nearest_positions(x, y, num_nearest_events)
nearest_events = []
print("\nClosest Events to ({0},{1}):\n".format(x, y))
for position in nearest_positions:
event = self.grid[position[1] + self.grid_size][position[0] + self.grid_size]
nearest_events.append(event)
print("Event {0} - {1}, Distance {2}\n".format(event.get_id(), event.get_minimum_ticket_price(),
self.get_manhattan_distance(x, y, position[0], position[1])))
return nearest_events
def pretty_print_world(self):
"""
a utility method which prints the 2D list representing the grid world
"""
for row in self.grid:
print(row)
@staticmethod
def get_available_moves(x, y):
"""
a method, which returns the valid moves given an input position,
expects the posituon to be positive, that is the indices of the 2D grid
:param x: the x coordinate of the input position
:param y: the y coordinate of the input position
:return: all the valid moves that can be made given the input position
:raises InvalidPositionError: if the input position is out of bounds
"""
def valid(pos):
"""
an inner function used to determine if a position is valid
:param pos: the position to check, should be transformed to positive coordinates (indices of the grid)
:return: true if the position is in bounds and false otherwise
"""
return 0 <= pos[0] <= 2*GridWorld.grid_size and 0 <= pos[1] <= 2*GridWorld.grid_size
# check for invalid input position
if not valid((x, y)):
raise InvalidPositionError("Out of bounds coordinates when getting available moves: {0}, {1}".format(x, y))
# generate all possible moves
positions = (x+1, y), (x, y+1), (x-1, y), (x, y-1)
# return only those moves that are valid
return (position for position in positions if valid(position))
@staticmethod
def get_manhattan_distance(x0, y0, x1, y1):
"""
a static method, which computes the manhattan distance between 2 points
:param x0: the x coordinate of the first point
:param y0: the y coordinate of the first point
:param x1: the x coordinate of the second point
:param y1: the y coordinate of the second point
:return: the manhattan distance between the two points
"""
return abs(x1 - x0) + abs(y1 - y0)
|
d3680771932c7f39bb8255281e3b05aea8bbad06
|
Frankiee/leetcode
|
/union_find/547_friend_circles.py
| 3,629 | 4.3125 | 4 |
# [Union-Find]
# https://leetcode.com/problems/friend-circles/
# 547. Friend Circles
# History:
# 1.
# Apr 28, 2019
# 2.
# Nov 13, 2019
# 3.
# May 4, 2020
# There are N students in a class. Some of them are friends, while some are
# not. Their friendship is transitive in nature. For example, if A is a
# direct friend of B, and B is a direct friend of C, then A is an indirect
# friend of C. And we defined a friend circle is a group of students who are
# direct or indirect friends.
#
# Given a N*N matrix M representing the friend relationship between students
# in the class. If M[i][j] = 1, then the ith and jth students are direct
# friends with each other, otherwise not. And you have to output the total
# number of friend circles among all the students.
#
# Example 1:
# Input:
# [[1,1,0],
# [1,1,0],
# [0,0,1]]
# Output: 2
# Explanation:The 0th and 1st students are direct friends, so they are in a
# friend circle.
# The 2nd student himself is in a friend circle. So return 2.
#
# Example 2:
# Input:
# [[1,1,0],
# [1,1,1],
# [0,1,1]]
# Output: 1
# Explanation:The 0th and 1st students are direct friends, the 1st and 2nd
# students are direct friends,
# so the 0th and 2nd students are indirect friends. All of them are in the
# same friend circle, so return 1.
#
# Note:
# N is in range [1,200].
# M[i][i] = 1 for all students.
# If M[i][j] = 1, then M[j][i] = 1.
class UnionFindSet(object):
def __init__(self, n):
self.parents = range(n)
def union(self, i, j):
i_root = self.find_root(i)
j_root = self.find_root(j)
self.parents[i_root] = j_root
def find_root(self, i):
# Not root
if i != self.parents[i]:
self.parents[i] = self.find_root(self.parents[i])
return self.parents[i]
class SolutionWithoutRank(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
if not M or not M[0]:
return 0
union_find_set = UnionFindSet(len(M))
for i in range(len(M) - 1):
for j in range(i + 1, len(M)):
if M[i][j] == 1:
union_find_set.union(i, j)
circles = set()
for i in range(len(M)):
circles.add(union_find_set.find_root(i))
return len(circles)
from collections import defaultdict
class UnionFindWithRank(object):
def __init__(self):
self.parents = {}
self.ranks = defaultdict(int)
def union(self, i, j):
i_root = self.find_root(i)
j_root = self.find_root(j)
if i_root == j_root:
return
if self.ranks[i_root] > self.ranks[j_root]:
self.parents[j_root] = i_root
elif self.ranks[i_root] < self.ranks[j_root]:
self.parents[i_root] = j_root
else:
self.parents[i_root] = j_root
self.ranks[j_root] += 1
def find_root(self, i):
if i not in self.parents:
self.parents[i] = i
else:
if self.parents[i] != i:
self.parents[i] = self.find_root(self.parents[i])
return self.parents[i]
class SolutionWithRank(object):
def findCircleNum(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
union_find = UnionFindWithRank()
circles = set()
for i in range(len(M)):
for j in range(i, len(M)):
if M[i][j] == 1:
union_find.union(i, j)
for i in range(len(M)):
circles.add(union_find.find_root(i))
return len(circles)
|
bdf55571c5a92d1e02ad71b889cdd22a52e96ad6
|
fishisnow/leetcode
|
/2.py
| 1,447 | 3.609375 | 4 |
#coding:utf-8
"""
#给你两个链表表示两个非负数字。数字存储在相反的顺序和每个节点包含一个数字。添加两个数字并返回一个链表。
#Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
#Output: 7 -> 0 -> 8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
"""
设x为l1节点值, y为l2节点值, 若为空则为0
sum = x + y + carry
carry = sum / 10
sum = sum % 10
循环结束后,判断carry是否为1, 是则添加数字1
"""
"""
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l = ListNode(0)
cat = 0
head = l
while(l1 is not None or l2 is not None):
val1 = l1.val if l1 is not None else 0
val2 = l2.val if l2 is not None else 0
sum = val1 + val2 + cat
if(sum > 9):
sum = sum % 10
l.next = ListNode(sum)
l = l.next
cat = 1
else:
l.next = ListNode(sum)
l = l.next
cat = 0
if l1 is not None: l1 = l1.next
if l2 is not None: l2 = l2.next
if cat == 1:
l.next = ListNode(1)
return head.next
|
bebf2b0ead87c4baa0e695b322e22b13d72d1d8a
|
Deepaksinghmadan/MITx-6.00.1x-Computer-Science-and-Programming-Using-Python
|
/both program.py
| 505 | 3.546875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 19 20:47:32 2018
@author: deepak
"""
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
n=int(input("Enter a number: "))
for j in range(1,n+1):
a=[]
for i in range(1,j+1):
print(i,sep=" ",end=" ")
if(i<j):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
|
f822ead8f75f5cd8d8b4a3e619c320ac2612bfca
|
Noba1anc3/Machine_Learning
|
/numpy/5.numpy的索引.py
| 728 | 3.546875 | 4 |
# coding: utf-8
# In[1]:
import numpy as np
# In[2]:
arr1 = np.arange(2,14)
print(arr1)
# In[3]:
print(arr1[2])#第二个位置的数据
# In[4]:
print(arr1[1:4])#第一到第四个位置的数据
# In[5]:
print(arr1[2:-1])#第二到倒数第一个位置的数据
# In[6]:
print(arr1[:5])#前五个数据
# In[7]:
print(arr1[-2:])#最后两个数据
# In[8]:
arr2 = arr1.reshape(3,4)
print(arr2)
# In[9]:
print(arr2[1])
# In[10]:
print(arr2[1][1])
# In[11]:
print(arr2[1,2])
# In[16]:
print(arr2[:,2])
# In[17]:
for i in arr2: #迭代行
print(i)
# In[18]:
for i in arr2.T:#迭代列
print(i)
# In[19]:
for i in arr2.flat:#一个一个元素迭代
print(i)
# In[ ]:
|
f8ecd3d4b9f1272e89dbd397fb5905a4f3e95edf
|
doedotdev/uc-data-mining
|
/untitled/hello.py
| 1,420 | 3.5 | 4 |
def get_integer_part(pre_decimal_string):
# special case of negative 0 being a prefix "-0.6"
if pre_decimal_string == "-0":
return "-0"
else:
num = int(pre_decimal_string)
return "{0:b}".format(num)
def get_decimal_part(post_decimal_string, string_builder, recurse):
recurse += 1
post_decimal_value = float("." + post_decimal_string)
if post_decimal_value == 0 or recurse > 10:
return string_builder
else:
temp_mult_str = str(post_decimal_value * 2)
temp_mult_split = temp_mult_str.split(".")
string_builder += temp_mult_split[0]
return get_decimal_part(temp_mult_split[1], string_builder, recurse)
def print_binary(number_string):
# handle case of no preceding 0 ".3" or
if number_string[0] == ".":
number_string = "0" + number_string
# handle case of no preceding 0 and is negative
if number_string[0:2] == "-.":
number_string = "-0" + number_string[1:]
if "." in number_string:
str_split = number_string.split(".")
print(get_integer_part(str_split[0]) + "." + str(get_decimal_part(str_split[1], "", 0)))
else:
print(get_integer_part(number_string))
test_values = "0 1234 -1234 12.4 0.6 -12.4 -0.6 -1234567890.123456789".split()
print(test_values)
for each in test_values:
print_binary(each)
# special cases
print_binary("-.7")
print_binary(".67")
|
f588a4c0c324ac5dbf34cf87d60a7e8a7c3dac52
|
pacewski/Bubblesort
|
/bubblesort.py
| 613 | 4.15625 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 14 11:42:00 2019
@author: pacew
"""
# A bubble sort app
import numpy as np
import random
def bubblesort(array):
lenght = len(array) - 1
for i in range(lenght):
for j in range(lenght):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
x = int(input("how long shout the array be? \n"))
randnums = np.random.randint(1, 101, x)
print("the array of numbers to sort is:")
print(randnums)
array = randnums
print("sorted array by bubble sort method:")
print(bubblesort(array))
|
332291c6387f9bf1bf25a20243c5508b38def7bf
|
ghamerly/nondeterminism
|
/prime.py
| 431 | 3.859375 | 4 |
from nondeterminism import *
@nondeterministic
def composite(n):
d = guess(range(2, n))
if n % d == 0:
accept()
else:
reject()
def prime(n):
if n < 2:
return False
else:
return not composite(n)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for n in numbers:
if prime(n):
print('The integer', n, 'is prime')
else:
print('The integer', n, 'is not prime')
|
d84b74457c7c5a3a9c08257c64d6cc5dbbd2eb9e
|
haekyu/python_tutoring_kh
|
/1029/0926hw.py
| 5,321 | 3.890625 | 4 |
# 1. list 연습1
# list 내 최대값 구하기.
# lst = [2, 3, 6, 2, -1, 0, 6, 2, 3] 이 주어져 있을 때 최대값인 6을 출력해보세요.
# 힌트1) 간단하게 max(lst) 로도 구할 수 있지만, max()를 쓰지 않고 loop로 해결해 보세요.
# 힌트2) skeleton code를 이용해도 좋습니다. ??? 을 채워 넣으면 됩니다.
# Target list
lst = [2, 3, 6, 2, -1, 0, 6, 2, 3]
def get_max_of_lst(lst):
# Initialize max_val
max_val = -999
# Get the maximum value in lst
for e in lst:
# Get the temporal max_val
if max_val < e:
# max_val is no longer the maximum value
# e should be the new maximum value
max_val = e
return max_val
max_val = get_max_of_lst(lst)
print(max_val)
# 2. list 연습2
# list 내 최대값을 갖는 원소가 몇 개인지 구해보세요.
# lst = [2, 3, 6, 2, -1, 0, 6, 2, 3] 이 주어져 있을 때, 최대값인 6은 2개 있습니다.
# 여기서 6의 개수인 2를 출력해 보세요.
# 이 때 다음과 같은 포맷으로 출력해 보세요: 'max = 6, num_max = 2'.
lst = [2, 3, 6, 2, -1, 0, 6, 2, 3]
def get_max_of_lst(lst):
max_val = -999
for e in lst:
if max_val < e:
max_val = e
return max_val
def get_num_max_of_lst(lst):
num_max = 0
for e in lst:
if max_val == e:
num_max = num_max + 1
return num_max
max_val = get_max_of_lst(lst)
num_max = get_num_max_of_lst(lst)
print('max = %d, num_max = %d' % (max_val, num_max))
# 3. list 연습3
# list 내 최대값을 갖는 원소의 index를 구해보세요.
# lst = [2, 3, 6, 2, -1, 0, 6, 2, 3] 이 주어져 있을 때,
# 최대값인 6의 index는 2, 6 입니다. 둘 중 하나를 출력해 보세요.
print("-" * 10)
lst = [-1, 2, 3, 6, 2, 0, 6, 2, 3]
max_val = get_max_of_lst(lst)
def get_index_max_of_lst(lst):
for idx in range(len(lst)):
print("idx:", idx)
if lst[idx] == max_val:
max_index = idx
return max_index
def get_index_max_of_lst2(lst):
for e in lst:
print("e:", e)
if lst[e] == max_val:
max_index = e
return max_index
max_index = get_index_max_of_lst(lst)
print(max_index)
print("-" * 10)
# 4. list 연습4
# 리스트 [1, 2, 3, 4, 5] 만들기.
# 다음 <start>, <end>, 그리고 <do> 안을 채워서 위의 리스트를 만들도록 해 보세요.
# lst = list()
# for i in range(<start>, <end>):
# <do>
# 힌트1) 어떤 list의 맨 마지막에 어떤 원소를 덧붙이고 싶을 때 append라는
# 함수를 사용할 수 있습니다.
# 예를 들어, lll이라는 리스트에 0 을 append 한다고 해 봅시다.
# lll = [3, 2, 1]
# lll.append(0)
# 을 하게 되면 lll은 [3, 2, 1, 0] 이 됩니다.
def make_list():
lst = list()
for i in range(1, 6):
lst.append(i)
return lst
print(make_list())
# 5. list 연습5
# 리스트 [1, 2, 3, 4, 5] 만들기.
# append를 쓰지 않고 1, 2, 3, 4, 5를 만들어 보세요.
# 단, hard-coding (내가 손으로 일일이 1, 2, 3, 4, 5 타이핑하기) 는 안됨.
def make_list2():
lst = [i for i in range(1, 6)]
return lst
print(make_list2())
# list comp 연습
# 1 부터 10 까지 자연수 중에서, 짝수인 것을 모은 리스트를 만들어 봅시다
[2, 4, 6, 8, 10]
lst = []
for i in range(1, 11):
if i % 2 == 0:
lst.append(i)
[i for i in range(1, 11) if i % 2 == 0]
# 6. string 연습1
# 스트링으로 된 문장 내부에 특정 word가 몇 번 포함되는지 찾기.
# 예를 들어, str과 같은 문장이 주어져 있고, 'an' 이라는 단어가 str 내부에 몇 번 나타나는지 찾기.
# str = 'Love is an open door! Love is an open door! Life can be so much more!'
# 일 때, an 이 두 번 있으니 2를 프린트하게 해 보세요.
# 힌트1) str을 ' ' (띄어쓰기) 기준으로 잘라 list에 보관할 수 있습니다.
# 예) lst = str.split(' ') 을 하게 되면
# lst 는 ['Love', 'is', 'an', ...] 이 됩니다.
str = 'Love is an open door! Love is an open door! Life can be so much more!'
lst = str.split(' ')
def num_str():
num_str = 0
for e in lst:
if e == 'an':
num_str = num_str + 1
return num_str
print(num_str())
# 7. string 연습2
# 스트링으로 된 문장 내부에 특정 문구가 몇 번 포함되는지 찾기.
# 예를 들어, str과 같은 문장이 주어져 있고, 'an' 이 str 내부에 몇 번 나타나는지 찾기.
# str = 'Love is an open door! Love is an open door! Life can be so much more!'
# 일 때, an 이 세 번 검색되고 있으니 3을 프린트하게 해 보세요.
# 세 번의 an 은 아래와 같이 검색됩니다. (*** 안에 있음.)
# Love is ***an*** open door!
# Love is ***an*** open door!
# Life c***an*** be so much more!
# 힌트1) string의 membership 기능을 이용하면 편리합니다.
# 어떤 string 안에 특정 string이 포함되는지 알 수 있습니다.
# 예를 들어, 'abc' 가 'xxabcxxxxxxx' 에 포함되는지 알고 싶으면
# 'abc' in 'xxabcxxxxxxx' 를 실행시켜 보세요. True 가 나옵니다.
# Short Ver.
str = 'Love is an open door! Love is an open door! Life can be so much more!'
print(str.count('an'))
# Long Ver.
str = 'Love is an open door! Love is an open door! Life can be so much more!'
lst = str.split(' ')
def num_str2():
num_str2 = 0
for e in lst:
if 'an' in e:
num_str2 = num_str2 + 1
return num_str2
print(num_str2())
|
76c24d757b8b28e26d053c22a6fa730e49659bce
|
rom-k/topcoder
|
/python/15.py
| 256 | 3.921875 | 4 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
for element in [1, 2, 3]:
print element
for element in (1, 2, 3):
print element
for key in {'one': 1, 'two': 2}:
print key
for char in "123":
print char
for line in open("tmp2"):
print line
|
7a9aa4e44c821e042f43e07f824de3899fa01692
|
snackjunio/jun
|
/Ex01.py
| 423 | 3.71875 | 4 |
def main():
try:
a = int(input('nを入力ください:'))
for r in range(1,a+1,1):
for b in range(1,(a-r)+1,1):
print('\t',end='')
for c in range(1,(2*r-1)+1,1):
print(' ',c,end='')
print('\n')
except:
raise
if __name__ == '__main__':
try:
main()
except Exception as e:
print(e)
|
e65b37be8bc3d1813cd85d1ff0297bdecbf146ae
|
JohannSaratka/AdventOfCode
|
/AoC_2016/Day05/Day05.py
| 3,937 | 4.0625 | 4 |
'''
--- Day 5: How About a Nice Game of Chess? ---
You are faced with a security door designed by Easter Bunny engineers that seem to
have acquired most of their security knowledge by watching hacking movies.
The eight-character password for the door is generated one character at a time by
finding the MD5 hash of some Door ID (your puzzle input) and an increasing integer
index (starting with 0).
A hash indicates the next character in the password if its hexadecimal representation
starts with five zeroes. If it does, the sixth character in the hash is the next
character of the password.
For example, if the Door ID is abc:
The first index which produces a hash that starts with five zeroes is 3231929,
which we find by hashing abc3231929; the sixth character of the hash, and thus
the first character of the password, is 1.
'''
import unittest
import hashlib
class TestGetSolution(unittest.TestCase):
def test_getCharFromHash_solution1(self):
self.assertEqual(getCharFromHash('abc3231929'), '1', "")
def test_getCharFromHash_solution2(self):
self.assertEqual(getCharFromHash('abc5017308'), '8', "")
def test_getCharFromHash_solution3(self):
self.assertEqual(getCharFromHash('abc5278568'), 'f', "")
@unittest.skip("brute force method takes to long")
def test_findPassword_solution1(self):
self.assertEqual(findPassword('abc'), '18f47a30', "")
def test_getCharFromHashPartTwo_solution1(self):
self.assertEqual(getCharFromHashPartTwo('abc3231929'), ('1','5'), "")
def test_getCharFromHashPartTwo_solution2(self):
self.assertEqual(getCharFromHashPartTwo('abc5357525'), ('4','e'), "")
def test_findPasswordPartTwo_solution1(self):
self.assertEqual(findPasswordPartTwo('abc'), '05ace8e3', "")
def findPassword(doorID):
i=0
password=''
while(len(password)<8):
passChar = getCharFromHash(doorID+str(i))
if passChar:
#print passChar
password+=passChar
i+=1
return password
def getCharFromHash(inputStr):
md5hash=hashlib.md5(inputStr).hexdigest()
if md5hash.startswith('00000'):
return md5hash[5]
return None
'''
--- Part Two ---
As the door slides open, you are presented with a second door that uses a slightly
more inspired security mechanism. Clearly unimpressed by the last version (in what
movie is the password decrypted in order?!), the Easter Bunny engineers have worked
out a better solution.
Instead of simply filling in the password from left to right, the hash now also
indicates the position within the password to fill. You still look for hashes that
begin with five zeroes; however, now, the sixth character represents the position (0-7),
and the seventh character is the character to put in that position.
A hash result of 000001f means that f is the second character in the password. Use
only the first result for each position, and ignore invalid positions.
For example, if the Door ID is abc:
The first interesting hash is from abc3231929, which produces 0000015...;
so, 5 goes in position 1: _5______.
'''
def findPasswordPartTwo(doorID):
i=0
password=[None]*8
while(None in password):
passPos,passChar = getCharFromHashPartTwo(doorID+str(i))
if passChar:
passPos=int(passPos,16)
if (passPos<8) and (password[passPos] is None):
password[passPos]=passChar
#print password
i+=1
return "".join(password)
def getCharFromHashPartTwo(inputStr):
md5hash=hashlib.md5(inputStr).hexdigest()
if md5hash.startswith('00000'):
return md5hash[5],md5hash[6]
return None,None
if __name__ == '__main__':
#print findPassword('ugkcyxxp')
print findPasswordPartTwo('ugkcyxxp')
|
2f8218ab0b36ff01afc17584587f4095ca95b854
|
DorotejaMazej/11-OOP
|
/age_years.py
| 215 | 3.6875 | 4 |
import time
from datetime import date
today = date.today()
le = 1979
my_birthday = date(1979, 2, 6)
time_to_brth = today.year - my_birthday.year
l = str(time_to_brth) + " " + "years" + " " + "old"
print l
|
f731d5ba918be2f1aa8a57a95a58c6cd94ddfcc4
|
Talk-To-Code/TalkToCode
|
/AST/output/program expected outputs/P Progs/isPrimeNumber.py
| 272 | 3.953125 | 4 |
import sys
def main():
n, c = 0, 2
print("Enter an integer\n")
n = input()
if(n == 2):
print("Prime number.\n")
else:
for c in range(2, n):
if(n % c == 0):
break
if(c != n):
print("Not prime.\n")
else:
print("Prime number.\n")
return
|
106585ee67b25d153714fad3ae8b9101bee88a0a
|
devinitpy/devinitpy.github.io
|
/mid/dictionaries.py
| 809 | 4.125 | 4 |
my_dictionary = { "name":"allan","school":"Makerere","physics":100,"biology":130}
#returns dictionry values
dictionary_values = my_dictionary.values()
my_school=my_dictionary["school"]
print my_school
value_list = []
for value in my_dictionary.values() :
value_list.append(value)
print value_list
for key in my_dictionary.keys():
print(key)
for item in my_dictionary.items():
print(item)
if "age" in my_dictionary:
print my_dictionary["age"]
#set age to zero if its not set
my_age=my_dictionary.get("age", 0)
my_height=my_dictionary.get("height", 1)
#adding new key value
if "height" not in my_dictionary:
my_dictionary["height"]=24
print my_dictionary
#does same thing as get method but its faster
my_dictionary.setdefault("country","uganda")
print my_dictionary
|
04879146b7f5e523d7b462ec890b1ce049480e5e
|
micaiahparker/python-utils
|
/flip.py
| 205 | 3.59375 | 4 |
def flip():
"""A fair coin simulator"""
from random import choice
while True:
r1, r2 = choice([0,1]), choice([0,1])
if bool(r1) ^ bool(r2): # exclusive or
yield r1
|
6a1bfebf7c42f8a94745da0474e2826cd0a1a6f4
|
yashkha3/Exercises
|
/test/ans10_b.py
| 333 | 4.03125 | 4 |
x = int(input("Enter x value: "))
y = int(input("Enter y value: "))
if(x > 0 and y > 0):
print("It is in First Quadrant")
elif(x < 0 and y > 0):
print("It is in Second Quadrant")
elif(x < 0 and y < 0):
print("It is in Third Quadrant")
elif(x > 0 and y < 0):
print("It is in Fourth Quadrant")
else:
print("Kindly Try Again")
|
9abcfadd7a4de11dbd810443260c000d7b1f6df7
|
goyal-aman/codeforces
|
/Hit the Lottery.py
| 346 | 3.734375 | 4 |
"""
by goyal-aman
https://codeforces.com/problemset/problem/996/A
"""
def notes(money):
currency = [1 , 5, 10, 20, 100]
notes = 0
for val in currency[::-1]:
notes += n//val
n = n%val
print(notes)
#solution 2
n = int(input)
def notes2(money):
print( (money//100) + (money%100)//20 + (money%20)//10 + (money%10)//5 + money%5)
|
933b3b97999120708626e1a34deb8334fe195bc6
|
saranya1999/sara
|
/20.py
| 59 | 3.6875 | 4 |
s=int(input())
for x in range(1,6):
print(s*x,end=" ")
|
9aeac075fb8f7c1ba8e61f9d7025f87672fed6b8
|
ankitkparashar/python
|
/Bootcamp/CofeeMachine/main.py
| 2,672 | 4.1875 | 4 |
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"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_in_machine = 0
def count_money():
coin_values = {"quarters": 0.25, "dimes": 0.10, "nickels": 0.05, "pennies": 0.01}
money_entered = 0
print("Please insert coins.")
for coin in coin_values:
num_of_coins = int(input(f"How many {coin}?: "))
money_entered += num_of_coins * coin_values[coin]
return money_entered
def make_the_drink(resources_needed, choice_entered):
global MENU
for ingredient in MENU[choice_entered]["ingredients"]:
resources_needed[ingredient] -= MENU[choice_entered]["ingredients"][ingredient]
print(f"Enjoy your {choice_entered}!")
return
def drink_is_possible(resources_needed, choice_entered):
global MENU
for ingredient in MENU[choice_entered]["ingredients"]:
if resources_needed[ingredient] < MENU[choice_entered]["ingredients"][ingredient]:
print(f"Sorry there's not enough {ingredient}. Money refunded.")
return False
return True
def print_resources_report(resources_remaining):
for key in resources_remaining:
print(f"{key.title()}: {resources_remaining[key]} " + ("g" if key == "coffee" else "ml"))
machine_on = True
while machine_on:
choice = input("What would you like? (espresso/latte/cappuccino): ").lower()
if choice in MENU:
money_provided = count_money()
cost_of_drink = MENU[choice]['cost']
if money_provided < cost_of_drink:
print("Sorry that's not enough money. Money refunded.")
else:
if drink_is_possible(resources, choice):
make_the_drink(resources, choice)
if money_provided > cost_of_drink:
print(f"Here's your change: ${round(money_provided - cost_of_drink, 2)}")
money_in_machine += cost_of_drink
elif choice == "report":
print_resources_report(resources)
print(f"Money: ${money_in_machine}")
elif choice == "off":
machine_on = False
else:
print("Invalid choice. Please enter from the given options.")
|
a0f0c6ea5a4a7ea38efd0a3fd010d14f7a52d25b
|
sachihiko/illumio-coding-challenge
|
/main/attributes.py
| 2,127 | 3.78125 | 4 |
'''
Classes for a firewall rule
'''
# Specifies the range of ports accepted for a rule
class Port():
def __init__(self, port_str: str):
if '-' in port_str:
self.start, self.end = (int(x) for x in port_str.split('-'))
else:
self.start, self.end = int(port_str), int(port_str)
def accepts_port(self, port) -> bool:
return self.start <= port <= self.end
# Specifies the range of IP Addresses for a rule
class IPAddress():
def __init__(self, ip_address_str: str):
if '-' in ip_address_str:
self.start, self.end = (str(x) for x in ip_address_str.split('-'))
self.start = [int(s) for s in self.start.split('.')]
self.end = [int(e) for e in self.end.split('.')]
else:
self.start = [int(s) for s in ip_address_str.split('.')]
self.end = [int(e) for e in ip_address_str.split('.')]
def accepts_ip(self, input_ip) -> bool:
for i in range(4):
# continue to next iteration if these digits are the same
if self.start[i] == self.end[i]:
continue
if self.start[i] < input_ip.start[i] < self.end[i]:
return True
return False
return True
# Specifies a rule
class Rule():
def __init__(self, direction: str, protocol: str, port_str: str, ip_str: str):
self.direction = direction
self.protocol = protocol
# range of ports allowed, inclusive
self.port_range = Port(port_str)
# range of ip addresses allowed, inclusive
self.ip_range = IPAddress(ip_str)
# checks if a network package is allowed
# the network package comes in the form of a rule
#
# this function is called by Firewall, which maps directions and protocols
# to IP Addresses
def accepts(self, net_package):
# input port and IP Address are single values
port = net_package.port_range.start
ip_address = net_package.ip_range.start
return self.port_range.accepts_port(port) and \
self.ip_range.accepts_ip(ip_address)
|
fa2cc4f60b8ce3f2dd2384f938f983b8778a14e2
|
xuefeihexue/Nanodegree
|
/project3.py
| 5,666 | 4.34375 | 4 |
# IPND Stage 2 Final Project
# You've built a Mad-Libs game with some help from Sean.
# Now you'll work on your own game to practice your skills and demonstrate what you've learned.
# For this project, you'll be building a Fill-in-the-Blanks quiz.
# Your quiz will prompt a user with a paragraph containing several blanks.
# The user should then be asked to fill in each blank appropriately to complete the paragraph.
# This can be used as a study tool to help you remember important vocabulary!
# Note: Your game will have to accept user input so, like the Mad Libs generator,
# you won't be able to run it using Sublime's `Build` feature.
# Instead you'll need to run the program in Terminal or IDLE.
# Refer to Work Session 5 if you need a refresher on how to do this.
# To help you get started, we've provided a sample paragraph that you can use when testing your code.
# Your game should consist of 3 or more levels, so you should add your own paragraphs as well!
sample = '''A ___1___ is created with the def keyword. You specify the inputs a ___1___ takes by
adding ___2___ separated by commas between the parentheses. ___1___s by default return ___3___ if you
don't specify the value to return. ___2___ can be standard data types such as string, number, dictionary,
tuple, and ___4___ or can be more complicated such as objects and lambda functions.'''
# The answer for ___1___ is 'function'. Can you figure out the others?
# We've also given you a file called fill-in-the-blanks.pyc which is a working version of the project.
# A .pyc file is a Python file that has been translated into "byte code".
# This means the code will run the same as the original .py file, but when you open it
# it won't look like Python code! But you can run it just like a regular Python file
# to see how your code should behave.
# Hint: It might help to think about how this project relates to the Mad Libs generator you built with Sean.
# In the Mad Libs generator, you take a paragraph and replace all instances of NOUN and VERB.
# How can you adapt that design to work with numbered blanks?
#In this version,use dictionary to encapsulate data
game_data = {
'easy': {
'quiz': '1___ is a game where you throw or shoot a ball through a hoop. A 1___ is an orange/brown color.it is opposite game for two 2___.Each 2___ has 3___ players and one 4___.Micheal 5___ is the greatst play in the history.',
'answers': ['basketball','team','five','coach','jordan']
},
'medium': {
'quiz': 'A 1___, beefburger or burger is a 4___ consisting of one or more cooked patties of ground meat, usually beef, placed inside a sliced bread roll or bun. The patty may be pan fried, barbecued, or flame broiled. 1___ is often served with 2___, lettuce, tomato, bacon, onion, pickles, or chiles; condiments such as mustard, mayonnaise, 3___, relish, or "special sauce"; and are frequently placed on sesame seed buns. A 1___ topped with 2___ is called a cheeseburger.',
'answers': ['hamburger','cheese','ketchup','sandwich']
},
'hard': {
'quiz': 'Canada is a 1___ in North America, located to the 2___ of the United States. Its land reaches from the Atlantic Ocean in the east to the Pacific Ocean in the 4___ and the Arctic Ocean to the 2___, covering 9.98 million square kilometres (3.85 million square miles), making it the 3___ second-largest 1___ by total area and the fourth-largest 1___ by land area. It has the 3___ longest coastline and is the only one to touch three oceans.',
'answers': ['country','north','world','west']
}
}
#The user should type one of the three level
def level_select():
print 'Please select a game difficulty by typing it in!'
print 'Possible choices include easy, medium, and hard.'
level=raw_input().lower()
option=['easy','medium','hard']
while level not in option: #use <element> in <list> instead of multipile 'or/and' parallel
if level in option:
print 'you select '+level+', enjoy the game!'
print ' '
break
print 'That is not an option!Possible choices include easy, medium, and hard.'
level=raw_input().lower()
return level
#it is a global varaible because more than one module will use it,and value does't change since the game difficultyis selected
level=level_select()
#this function is a reusable function, the input are:i is the number of blank word,like"1___";paragraph is the current passing paragraph;
def guess_game(i,paragraph):
print paragraph
print ' '
print 'What should be substituted in for '+str(i+1)+'___?'
max_try_time=3
index=0
user_input=raw_input().lower()
while user_input!=game_data[level]['answers'][i] and index<max_try_time:
if user_input==game_data[level]['answers'][i]:
#when user hits the right answer,the whole paragraph will be given,and game continues
break
print 'you have '+str(max_try_time-index)+' more chance'+'s'*((max_try_time-index)/2) #in oder to distinguish Single and Plural
user_input=raw_input().lower()
index+=1
if index==3:
print 'This is the correct answer for '+str(i+1)+'___,keep trying the next question'
#if the user can not type correct answer in 3 times, the correct answer will be given,and the game continues
print ' '
return paragraph.replace((str(i+1)+'___'),game_data[level]['answers'][i])
#this is the main function,the level is the user_input,there is not output but print the final answer
def game():
paragraph=game_data[level]['quiz']
i=0
while i<len(game_data[level]['answers']):
paragraph=guess_game(i,paragraph)
i+=1
print paragraph
print 'Awsome,you finished the game!'
game()
|
3956156cf04cb71dcae9d421ae1b439f6bbbeebb
|
marykamau2/katas
|
/python kata/birthday_count/birthday.py
| 221 | 4.0625 | 4 |
def main():
bdays={"newt":"18/12/1802","diana":"13/02/2005"}
print(bdays.keys)
name=input("enter a username")
if bdays[name]:
print(bdays[name])
else:
print("there is no such username")
|
d8c5e0bd5a290223b17ae6e4d7b136800af0e54e
|
jpdown/twitch-mod-log
|
/utils/humanReadableTime.py
| 532 | 4.1875 | 4 |
def time(seconds):
"""Function to convert seconds to human readable time"""
days = seconds // 86400
hours = seconds // 3600 % 24
minutes = seconds // 60 % 60
seconds = seconds % 60
#Create message string
message = ""
if days != 0:
message += "{0} Days ".format(days)
if hours != 0:
message += "{0} Hours ".format(hours)
if minutes != 0:
message += "{0} Minutes ".format(minutes)
if seconds != 0:
message += "{0} Seconds".format(seconds)
return(message)
|
aad7745ec5438f18a3d99649de0d922e0e0a9740
|
ChandanaBasavaraj/python_assignment2
|
/pgrm7.py
| 158 | 4.34375 | 4 |
#implement a program to reverse a string without using standard library function
string="enter the string"
print("reverse string is:")
print(string[::-1])
|
1e963851834d95a51210034435a616a8229c9a4b
|
benzoa/pythonStudy
|
/libraries/standard/dataclass.py
| 519 | 3.671875 | 4 |
from dataclasses import dataclass
from datetime import date
@dataclass
class User:
id: int
name: str
birthdate: date
admin: bool = False
__age: int = 0
@property
def get_name(self):
return self.name
@property
def age(self):
return self.__age
@age.setter
def age(self, val):
self.__age = val
user1 = User(id=1, name="Steve Jobs", birthdate=date(1955, 2, 24))
print(user1)
user1.name = "Ben"
print(user1.get_name)
user1.age = 21
print(user1.age)
|
8c41b0c401b2c14d35f425893656df41ab20b8a5
|
anzhihe/learning
|
/python/practise/learn-python/python_basic/none_and_range.py
| 2,381 | 3.78125 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@FileName: none_and_range.py
@Function: python None & range
@Author: Zhihe An
@Site: https://chegva.com
@Time: 2021/6/21
"""
"""一、对象None"""
"""
1、什么是对象None
对象None用于表示数据值的不存在
对象None是占据一定的内存空间的,它并不意味着"空"或"没有定义"
也就是说,None是"something",而不是"nothing"
"""
# 调用内置函数id查看对象None的内存地址
print(id(None)) # 4485465520
"""
2、对象None的使用场景
对象None经常用于变量的初始化,或将变量重置为"数据值不存在"的状态
"""
a = None
print(a) # None
b = 18
print(b) # 18
b = None
print(b) # None
"""二、序列类型range"""
"""
1、什么是range?
range是一种序列类型,range类型用于表示不可变的整数序列
可以调用内置函数range(类range的构造方法)创建range类型的对象,有三种调用方式:
(1) range(stop)
(2) range(start, stop)
(3) range(start, stop, step)
其中,整数序列的起始值的默认值是0,可以使用参数start指定
可以使用参数stop指定整数序列的结束值,创建的range对象不包含stop
整数序列的步长的默认值是1,可以使用参数step进行指定
内置函数range的返回值是一个迭代器对象。为了清楚地表示返回的迭代器对象所表示的整数序列,可以将其转换成列表
range类型的优点在于:不管range对象表示的整数序列有多长,所有range对象占用的内存空间都是相同的,
因为仅仅需要存储start、stop和step。只有当用到range对象时,才会去计算序列中的相关元素
"""
print(range(5)) # range(0, 5)
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(0, 5, 1))) # [0, 1, 2, 3, 4]
print(list(range(1, 5))) # [1, 2, 3, 4]
print(list(range(1, 5, 1))) # [1, 2, 3, 4]
print(list(range(0, 20, 4))) # [0, 4, 8, 12, 16]
print(list(range(0, -20, -4))) # [0, -4, -8, -12, -16]
"""
2、判断range对象中是否存在(不存在)指定的整数
可以使用运算符in(not in)检查range对象表示的整数序列中是否存在(不存在)指定的整数
"""
print(3 in range(5)) # True
print(8 not in range(5)) # True
|
341514cb47ba8012139dc42fdbdb4c8f02f90a23
|
DeyanGrigorov/Python-Advanced
|
/Multidimensional_lists./matrix_shuffle.py
| 1,117 | 3.6875 | 4 |
def print_matrix(matrix):
for i in range(m):
print(' '.join(matrix[i]))
def print_not_valid():
print('Invalid input!')
def valid_input(matrix, commands):
if command != 'swap':
print_not_valid()
elif len(args) != 4:
print_not_valid()
row_one, col_one, row_two, col_two = list((map(int, args)))
if row_one < 0 or row_one >= m \
or row_two < 0 or row_two >= m \
or col_one < 0 or col_one >= n \
or col_two < 0 or col_two >= n:
print_not_valid()
else:
return True
m, n = [int(i) for i in input().split()]
matrix = [[r for r in input().split()] for row in range(m)]
rows = len(matrix)
cols = len(matrix[0])
total_length = rows * cols
command, *args = input().split()
while command != 'END':
if valid_input(matrix, command):
row_one, col_one, row_two, col_two = list(map(int, args))
matrix[row_one][col_one], matrix[row_two][col_two] = matrix[row_two][col_two], matrix[row_one][col_one]
print_matrix(matrix)
else:
print_not_valid()
command, *args = input().split()
|
fae31e26f1be30947ed9d378146f84e7f2ed907d
|
pulum03/ML
|
/Practice/step_function.py
| 475 | 3.65625 | 4 |
"""
def step_function(x):
if x > 0:
return 1
else:
return 0
print(step_function(2))
"""
"""
import numpy as np
def step_function(x):
y = x > 0
return y.astype(np.int)
x = np.array([-1.0, 1.0, 2.0])
print(step_function(x))
"""
import numpy as np
import matplotlib.pylab as plt
def step_function(x):
return np.array(x > 0, dtype = np.int)
x = np.array(-5.0, 5.0, 0.1)
y = step_function(x)
plt.plot(x,y)
plt.ylim(-0.1, 1.1)
plt.show()
|
de709c32e41c47e0ca2d2e8705d07c117df77089
|
nasolim/ksp_mission_helper
|
/targetLanding.py
| 1,898 | 3.578125 | 4 |
# Script Name: targetLanding.py
# Author: Milo Sanu
# Created: 10/3/15
# Last Modified:
# Version: 1.0
# Modifications:
# Description: Script which provides the user with coordinates that are a predetermined
# distance from the original landing site.
from math import sin,cos,radians,pi,degrees
from kerbalformulae import orbiting_body
def py_theorem(d,ang):
''' Given a displacement (d) - meters - and angle - degrees;
Return vertical and lateral distance '''
dn = d * sin(radians(ang))
de = d * cos(radians(ang))
return dn,de
def perimeter_landing(Lat, Long, d, r):
''' Provide current location (Lat, Long), desired displacement (d),
and radius (r) of landed body in meters
Returns Coordinate'''
ang = [x for x in xrange(0,360,45)]
landings=[new_position(Lat, Long, d, i, r) for i in ang]
return landings
def new_position(Lat, Long, d, ang, r):
''' Provide current location(Lat, Long), displacement (d) of next landing, angle (ang) from current location
landed body radius in meters (r). 0 degree ang is East, 90 degree is North '''
deltLat = float(py_theorem(d,ang)[0])/float(r)
deltLong = float(py_theorem(d,ang)[1])/float(r) * cos(radians(Lat))
lat2 = Lat + degrees(deltLat)
long2 = Long + degrees(deltLong)
return lat2,long2
compass_dir = [
'East',
'North-East',
'North',
'North-West',
'West',
'South-West',
'South',
'South-East']
def epicenter():
latitude = float(raw_input('What is your Latitude?\n>'))
longitude = float(raw_input('What is your Longitude?\n>'))
displacement = float(raw_input('How far from your current location would you like to be?\n>'))
body,celestial_radius = orbiting_body('parked on')
position = [perimeter_landing(latitude,longitude, displacement, celestial_radius['radius'])]
for item in range(len(compass_dir)):
print compass_dir[item],'landing:\n','Lat: ',round(position[0][item][0],4),'Long: ',round(position[0][item][1],4)
|
fe3ad6c7be5530d99e5cebae04fe1b9c1bbefe32
|
heyb7/python_crash_course
|
/ch09/ex9-3.py
| 779 | 3.578125 | 4 |
class User():
def __init__(self, first_name, last_name, username, email, location):
self.first_name = first_name
self.last_name = last_name
self.username = username
self.email = email
self.location = location
def dcscribe_user(self):
print("\n" + self.first_name + " " + self.last_name)
print(" Username: " + self.username)
print(" Email: " + self.email)
print(" Location: " + self.location)
def greet_user(self):
print("\nwelcome back, " + self.username + "!")
eric = User("eric", "matthes", "e_matthes", "[email protected]", "alaska")
eric.dcscribe_user()
eric.greet_user()
willie = User("willie", "burger", "willieburger", "[email protected]", "alaska")
willie.dcscribe_user()
willie.greet_user()
|
9142aa2d93073d7143c590a82d8234dc7e8e786c
|
gabisala/Kattis
|
/Closing_the_Loop/closing_the_loop.py
| 1,952 | 3.828125 | 4 |
# -*- coding:utf-8 -*-
import sys
# Read data
data = [line.split() for line in sys.stdin]
def sort_segments(case):
"""
Sort the segments in blue and red
:param case: a list of test cases
:return: a tuple with blue and red segments lists sorted from big to small
"""
blue = []
red = []
for segment in case:
if segment[-1] == 'B':
blue.append(int(segment[:-1]))
else:
red.append(int(segment[:-1]))
# sort from big to small
blue.sort(reverse=True)
red.sort(reverse=True)
return blue, red
def create_loop(segments):
"""
Create loop of segments
:param segments: blue and red segments
:return: loop, pairs of blu, red from big to small
"""
blue, red = segments
loop = []
while len(blue) is not 0 and len(red) is not 0:
loop.append((blue[0], red[0]))
del blue[0]
del red[0]
return loop
def measure_rope(loop):
"""
Measure the rope
:param loop: pairs of blu, red from big to small
:return: maximum length of the rope loop that can be generated with the rope segments provided
"""
measure = []
# Note that pieces of string that have length 1, if used in making the cycle, might get reduced to just a pair of
# knots of total length 0. This is allowed, and each such piece counts as having been used.
for s in loop:
if s[0] > 1 and s[1] > 1:
measure.append(s[0] + s[1] - 1)
else:
measure.append(max(s[0], s[1]))
measure.append(-1)
return sum(measure)
# For each test case, output one line containing "Case #xx: " followed by the
# maximum length of the rope loop that can be generated with the rope segments provided.
for i, case in enumerate(data[2::2]):
segments = sort_segments(case)
loop = create_loop(segments)
measure = measure_rope(loop)
print 'Case #{}: {}'.format(i + 1, measure)
|
f4587f01a4badccd49f73f49a03eddffbd52e08b
|
joestalker1/leetcode
|
/src/main/scala/DeleteNodeLinkedList.py
| 421 | 3.578125 | 4 |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteNode(self, node):
last = None
while node.next:
node.val = node.next.val
last = node
node = node.next
last.next = None
l1 = ListNode(0)
l1.next = ListNode(0)
l1.next.next = ListNode(0)
sol = Solution()
sol.deleteNode(l1)
|
64052766b17e72615ffe4a6ec91b8625d3213582
|
saqeeb360/FSDP2019
|
/Day 11/area_of_state.py
| 1,522 | 3.671875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Tue May 21 12:09:30 2019
@author: Windows
Code Challenge
https://en.wikipedia.org/wiki/List_of_states_and_union_territories_of_India_by_area
Scrap the data from State/Territory and National Share (%) columns for top 6 states basis on National Share (%).
Create a Pie Chart using MatPlotLib and explode the state with largest national share %.
"""
from selenium import webdriver
from time import sleep
from collections import OrderedDict
from bs4 import BeautifulSoup
import requests
url ="https://en.wikipedia.org/wiki/List_of_states_and_union_territories_of_India_by_area"
browser = webdriver.Chrome("C:/Users/Windows/Desktop/Machine learning/chromedriver.exe")
browser.get(url)
sleep(2)
right_table = browser.find_element_by_xpath('//*[@id="mw-content-text"]/div/table[2]')
print(right_table)
#wiki = "https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India"
#source = requests.get(wiki).text
#soup = BeautifulSoup(source,"lxml")
#right_table=soup.find('table', class_='wikitable')
A=[]
B=[]
C=[]
D=[]
E=[]
F=[]
for row in right_table.find_elements_by_tag_name('tr'):
cells = row.find_elements_by_tag_name('td')
states = row.find_elements_by_tag_name('th')
if len(cells) == 7:
A.append(states[0].text.strip())
B.append(cells[1].text.strip())
C.append(cells[2].text.strip())
D.append(cells[3].text.strip())
E.append(cells[4].text.strip())
F.append(cells[5].text.strip())
|
fa8bb582d0df56754d483f956f9d022f0c0b6e8a
|
1UnboundedSentience/PythonTweeting
|
/request.py
| 1,709 | 3.546875 | 4 |
import oauth2 as oauth
import time
import random
import json
import math
import sys
import pprint
def grab_tweet():
query = '%20'.join(sys.argv[1:])
# Set the API endpoint
url = "https://api.twitter.com/1.1/search/tweets.json?q=" + query
token = oauth.Token("1035256117-JEcbtW3741GwyB820PmCHLCvq0Us18FhNSZdDBH", "8kpKfpzwVDGEKZFswcLHFVWylCripMILo3SxKLfIenX8Q")
consumer_key = '2VpE9wyPHAnfvz5aBF44G59Z4'
consumer_secret = 'C35EaRzDgk0Kf6vfxiLHXrFNlK5RnjqSBLCDoxnhG4DqksnqVY'
request_token_url = 'https://api.twitter.com/oauth/request_token'
access_token_url = 'https://api.twitter.com/oauth/access_token'
authorize_url = 'https://api.twitter.com/oauth/authorize'
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
# Request token URL for Twitter.
request_token_url = "https://api.twitter.com/1.1/search/tweets.json?q=" + query
# Create our client.
client = oauth.Client(consumer, token)
# The OAuth Client request works just like httplib2 for the most part.
resp, content = client.request(request_token_url, "GET")
#pretty print the JSON string
parsed = json.loads(content)
#print json.dumps(parsed, indent=4, sort_keys=True)
#convert response stringified JSON to python dict
j = '{"action": "print", "method": "onData", "data": '+ content +'}'
class Payload(object):
def __init__(self, j):
self.__dict__ = json.loads(j)
p = Payload(j)
#get psuedorandom tweet from selected
data_count = p.data['search_metadata']['count']
random_id = int(math.floor(data_count*random.random()))
tweet_url = p.data['statuses'][random_id]
print "Your search for '%s' returned %d tweets. This is the data for random tweet number %s:" % (query, data_count, random_id)
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(tweet_url)
grab_tweet()
|
d7606902c6e76501c7a941a4381a8122f5cabdb6
|
suhasreddy123/python_learning
|
/example programs/find square root of numbers.py
| 58 | 3.625 | 4 |
num=int(input())
square_root=num**0.5
print((square_root))
|
64c67d8c0d0765f1e73db81c8a20d4cade5dfd53
|
WKDavid/python_quiz_game
|
/ProjectQuizNew.py
| 5,380 | 3.921875 | 4 |
data = {
'easy': {
'text': '''\nGenerally, every ___1___ has to be within single
or double quotes. A ___1___ can be assigned to a ___2___. It is
a convention not to use capital letters in ___2___ naming.
A ___1___ can not be added to an ___3___, but they can be multiplied.
However, it is possible to add one ___1___ to another
in order to ___4___ them.\n''',
'answers': ['string', 'variable', 'integer', 'concatenate'],
'mistakes': 4
},
'medium': {
'text': """\nA ___1___ is created with the def keyword.
You specify the inputs a ___1___ takes by adding ___2___ separated
by commas between the parentheses. ___1___s by default return
___3___ if you don't specify the value to return. ___2___ can be
standard data types such as string, number, dictionary, tuple,
and ___4___ or can be more complicated such as objects and lambda
functions.\n""",
'answers': ['function', 'arguments', 'none', 'list'],
'mistakes': 3
},
'hard': {
'text': '''\nA ___1___ is a single file of python code that
can be implemented by using the ___2___ command. A ___3___ is a
collection of python ___1___s under a common namespace. In practice
one is created by placing multiple python ___1___s in a directory with
a special, ___4___ file. ___5___ is another python file, which usually
tells you that the ___1___ or the ___3___ you are about to install
has been ___3___d and distributed with Distutils, which is the standard
for distributing Python ___1___s. This allows you to easily install
Python ___3___s. Often it's enough to write: ___6___ command.\n''',
'answers': ['module', 'import', 'package', '__init__.py', 'setup.py','python setup'],
'mistakes': 2
}
}
name = raw_input("\nHello, please state your name: ")
incorrect = '\nYour answer is not correct ' + name + '. Number of attempts left: '
def greeting():
"""
Behavior: This function starts the program and greets a player using the global
variable 'name'. Global variables have been assigned in order to avoid
repetition of long lines. The function then guides user to the next step
of a difficulty selection.
"""
global name
welcome = '\nWelcome to the python quiz game, ' + name + '!'*3
print welcome
return play_game(choose_difficulty())
def choose_difficulty():
"""
Behaviour: The function asks user to choose a difficulty and returns it.
Small dictionary used in order to make the difficulty selection easier
and faster. The function alerts user in case of invalid selection and
asks to choose again until a valid answer has been given.
"""
choice = '\nPlease choose suitable difficulty: '
choice += 'E for easy, M for medium and H for hard\n'
choose = raw_input(choice).lower()
difficulties = {"e": 'easy', "m": 'medium', "h": "hard"}
while choose not in difficulties:
print "Invalid entry, please try again."
choose = raw_input(choice).lower()
print name + ', you chose ' + difficulties[choose] + " difficulty!"
return difficulties[choose]
def play_game(difficulty):
"""
Behaviour: This is the main function of the game. It takes difficulty as
an input. Based on an input it prints out the current text and asks to
fill in the current blank of the text. The function keeps track of attempts
and notifies user. Furthermore, it shares information about current
progress with the following function 'attempts_check'.
"""
text = data[difficulty]['text']
attempts = data[difficulty]['mistakes']
hits = 0
while hits < len(data[difficulty]['answers']) and attempts > 0:
print text
answer = raw_input('Fill in the ___' + str(hits + 1) + '___\n').lower()
if answer == data[difficulty]['answers'][hits]:
print "Correct!"
text = text.replace('___' + str(hits + 1) + '___', data[difficulty]['answers'][hits])
hits += 1
attempts_check(difficulty, attempts, text, hits)
else:
attempts -= 1
print incorrect + str(attempts)
attempts_check(difficulty, attempts, text, hits)
def attempts_check(difficulty, attempts, text, hits):
"""
Behaviour: Using the current information from the main 'play_game' function
as an input, this fuction ckecks, if the game should be ended and navigates
user accordingly to the last function 'game_over', if necessary.
"""
if attempts <= 0:
print "\nThank you for playing, " + name + " too many mistakes.\n"
game_over()
elif hits == len(data[difficulty]['answers']):
print text
print '\nCongratulations on completing the test ' + name + ' !!!\n'
game_over()
else:
return None
def game_over():
"""
Behaviour: This function prompts user to start the game over. It calls
the greeting function in case of positive asnwer and restarts the game.
Negative answer leaves the game. Invalid entry starts the function over.
"""
again_answ = raw_input('Would you like to start over ' + name + '? y/n: ' ).lower()
if again_answ == 'y':
greeting()
elif again_answ == 'n':
print '\nHave a wonderful time of the day!'
exit()
else:
print '\nInvalid answer\n'
game_over()
greeting()
|
521f1e7e6b99400a297b7d7366bc9094f3e02f0b
|
dannythorne/CSC115_SP16
|
/dthorne0/09_Loops/main.py
| 217 | 4.1875 | 4 |
print("Danny Thorne")
print("Loops Example")
listOfNumbers = [0,1,2,3,4,5,6,7,9]
for number in listOfNumbers:
print(number,end=" ")
print(number*number,end=" ")
print(number**3)
print("Bye, bye!")
|
25f6278d4ebe19957fbb685ee35e4e79c4634def
|
alexandraseg/appInPython
|
/sort_fruits.py
| 603 | 3.859375 | 4 |
#Read the file
f=open('unsorted_fruits.txt','r')
#Create an empty list
fruit_list=[]
#For every line in file
for fruit in f.readlines():
#Remove whitespace from the begin or end of the string
fruit=fruit.strip()
if len(fruit)==0:
continue
#Append to the list
fruit_list.append(fruit)
#Sort the list
fruit_list.sort()
#Close the file
f.close()
#Open the output files in write mode
output_file=open("sorted_fruits.txt","w")
#Iterate fruits in ascending order
for fruit in fruit_list:
#Write to the file
output_file.write(fruit+"\n")
#Close the file
output_file.close()
|
aa812db5f10c4281693030aa7b729bda75d46dda
|
PVyukov/GB_HW
|
/Lesson3_func/29012020.py
| 2,017 | 3.734375 | 4 |
# print(max(1, 2, 3, 4, 8))
# print(max('zz', 'aaa', key=len))
# print(round(7.5))
# for index, letter in enumerate(['a', 'b', 'c'], start=5):
# print(index, letter)
# def say_hello(name):
# print(f'Hello {name}!')
#
#
# say_hello('Ivan')
# say_hello('Petr')
# def average(numbers):
# count = len(numbers)
# my_sum = sum(numbers)
# answer = my_sum / count
# return answer
#
# qwe = average([1, 2, 3, 4, 5, 6])
# print(qwe)
#
# def my_func(x):
# pass
#
#
# my_func(1)
# def print(text):
# pass
# print('qwe')
# x = 100
#
#
# def test(w):
# w += 10
# return w
#
#
# x = test(x)
# print(x)
# def func(name, surname=''):
# print(name, surname)
# func('Ivan')
# func('Ivan', 'Petrov')
# def func(name, *args):
# что угодно
# print(name, args)
#
# func('Ivan', 50, 10, 30, 50, 80)
# func('Petr', 50, 1)
# def func(name, surname, age):
# """Описание функции"""
# print(name, surname, age)
#
# func(surname='Sidorov', name='Ivan', age=50)
# def func(name, surname, **kwargs):
# print(name, surname, kwargs)
#
# func(surname='Sidorov', name='Ivan', age=50, asd='qwe')
# names = ['Alex', 'Vova', 'Petr']
# surnames = ['Alexov', 'Vovanov', 'Petrov']
#
# # for name, surname in zip(names, surnames):
# # print(name, surname)
#
# print(list(zip(names, surnames)))
# print(dict(zip(names, surnames)))
# def my_pow(x):
# return x ** 2
# print(my_pow(5))
# data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 91]
# result = []
# for num in data:
# result.append(my_pow(num))
# print(result)
#
# print(list(map(my_pow, data)))
# def my_filter(x):
# return x > 0
# data = [1, 2, -3, 4, -5, 6, 7, 8, -9, 91]
# print(list(filter(my_filter, data)))
# print(list(filter(lambda x: x > 0, data)))
# print(list(map(lambda x: x ** 2, data)))
# print(list(map(lambda x: True if x % 2 == 0 else False, range(1, 11))))
# for _ in range(10):
# print('qwe')
my_list = [[10, 20, 30], [40, 50], [60], [70, 80, 90]]
print(sum(my_list, []))
|
50f737a4eebeb639fb053b75042f2882a575e1d1
|
joaopaulopires/teste3
|
/python/exe079.py
| 1,201 | 3.671875 | 4 |
print('\33[4;35m{:^40}\33[m'.format(' ANÁLISE DE LISTAS II'))
valor =[]
while True:
cont = 0
valor.append(int(input('\33[1;30mDigite um valor: \33[m')))
for num in valor:
if valor.count(num) == 2:
valor.pop()
cont = 1
if cont == 1:
print('\33[1;31mValor duplicado! Não vou adicionar...\33[m')
else:
print('\33[1;34mValor adicionado com sucesso!\33[m')
r = ' '
while r not in 'SN':
r = str(input('\33[1;30mQuer continuar? [S/N] \33[m')).strip().upper()[0]
if r in 'N':
break
print('\33[1;35m-\33[m'*20)
print('\33[1;35m=\33[m'*20)
valor.sort()
print(f'\33[1;36mVocê digitou os valores \33[4;36m{valor}\33[m')
print(' ')
print('Versão guanabara')
números = []
while True:
n = int(input('Digite um valor: '))
if n not in números:
números.append(n)
print('\33[1;34mValor adicionado com sucesso!\33[m')
else:
print('\33[1;31mValor duplicado! Não vou adicionar...\33[m')
r = str(input('\33[1;30mQuer continuar? [S/N] \33[m')).strip().upper()[0]
if r in 'N':
break
valor.sort()
print(f'\33[1;36mVocê digitou os valores \33[4;36m{números}\33[m')
|
7aa50a8dd2bbaed5881a752f464f1770bac733ee
|
Gedanke/StudyNote
|
/Math/codes/module_3/l_14_1.py
| 207 | 3.9375 | 4 |
# -*- coding: utf-8 -*-
left = 0
left_temp = 0
right = 0
for k in range(1, 100):
left_temp = 2 * k - 1
left += left_temp
right = k * k
if left == right:
print(str(k) + " is right!")
|
a338fe4e29d8a51a79118e51897f60fdb141ee98
|
sindhu-thanikonda/Assignment--1_Python-
|
/18.py
| 728 | 3.90625 | 4 |
"""
Write a program create a random list of length 10 and
print all the elements except the elements which are divisible by 4.
"""
list1 = [ ]
val = 0
for str1 in range(10):
str1 = raw_input("Enter Random List: ")
print "Random String: ", str1
val = len(str1)
print "Length of String: ", val
if val%4 != 0:
list1.append(str1)
print "List with Non_Divisibles of 4: ", list1
"""
list1 = [ ]
val = 0
for str1 in range(10):
str1 = raw_input("Enter Random List: ")
print str1
list1.append(str1)
val = len(str1)
print val
if val%4 == 0:
list1.pop()
print list1
"""
|
d4c6672f27cdf0792883ae52a3a5d733a536335e
|
AntonMir/Stepik
|
/Калькулятор в диапазоне.py
| 259 | 3.609375 | 4 |
a = int(input())
b = int(input())
c = int(input())
d = int(input())
for z in range(c,(d+1)):
print('\t',z, end='')
print()
for x in range(a,(b+1)):
print(x, end='')
for y in range(c,(d+1)):
print ('\t',x * y, end='')
print()
|
763a66828954066db9942d24349ccf32e2625377
|
krishnakatyal/philosophy
|
/ethics/utiltrolley.py
| 1,296 | 4.34375 | 4 |
"""
We implement a basic, simplified utilitarian method of reasoning to solve
the trolley problem. The problem consists of deciding whether to pull
a lever that would change the track of an incoming train such that it would
kill fewer people tied to the tracks.
Given a directed graph as an input file and a nonnegative integer attached to
each edge (the number of people tied to that track). Still, this argument has
its limits. It assumes each human has the same utility and that changing the
path the train would take is completely within our control. It also doesn't
address the question of what caused the scenario to begin with (e.g., how
did you find yourself in a case in which you have to resort to pullling a
lever to save the lives of others?)
"""
def trolley(y):
"""
Given input graph of the trolley problem, calculate the optimal route that kills the
fewest number of people. The input y is a list of dictionaries to describe the neighbors
and number of people trapped to each track. The dictionary should use each key as the node
and entries as the neighbors and number of people on the track connecting that node to neighbor.
"""
s = 0
p = []
f = 0
mini = min(y(d, s+d[f][t], p+[f],t) for t in d[f])
return f in p and s or mini
|
8367b534569a8312e6203fdc2a3650b5662b6b94
|
habroptilus/atcoder-src
|
/abc/077/python/code_b.py
| 260 | 4.0625 | 4 |
N = int(input())
def max_square(n):
"""
>>> max_square(10)
9
>>> max_square(81)
81
>>> max_square(271828182)
271821169
"""
base = 0
while (base + 1)**2 <= n:
base += 1
return base**2
print(max_square(N))
|
4dfd2f4dc915d0ba611ea2dfc59ef3eb738b9cc6
|
ZHHJemotion/algorithm008-class01
|
/Week_03/47.Permutations_II.py
| 1,219 | 3.546875 | 4 |
# Given a collection of numbers that might contain duplicates, return all possib
# le unique permutations.
#
# Example:
#
#
# Input: [1,1,2]
# Output:
# [
# [1,1,2],
# [1,2,1],
# [2,1,1]
# ]
#
# Related Topics Backtracking
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
# 递归回溯
def dfs(depth=0, path=[]):
# terminator
if depth == n:
res.append(path[:])
for i in range(n):
if not visited[i]:
# pruning the duplicates
if i > 0 and nums[i] == nums[i-1] and not visited[i-1]:
continue
# process current logic
visited[i] = True
path.append(nums[i])
# drill down
dfs(depth+1, path)
# backtrack
visited[i] = False
path.pop()
res = []
nums.sort()
n = len(nums)
visited = [False for _ in range(n)]
# leetcode submit region end(Prohibit modification and deletion)
|
0839c0e2c12f02fae003319ff5bc0e2e45572adc
|
haticeaydinn/Hello-World-with-Python
|
/GuessingGame.py
| 273 | 3.84375 | 4 |
guess_count = 0
magic_number = 9
guess_limit = 3
while guess_count < guess_limit:
guessed_number = int(input("Guess: "))
guess_count += 1
if guessed_number == magic_number:
print("You won!!!")
break
else:
print("You failed...")
|
0881febb52c8bac019042c99a56943a22ef93ab8
|
stani95/stani95
|
/CS166_final.py
| 25,498 | 3.921875 | 4 |
from matplotlib import pyplot as plt
import networkx as nx
import numpy as np
import math
np.random.seed(0)
#Each package has on origin, a destination, and a current position (a city or a road)
class Package:
def __init__(self, origin_index, destination_index, current_position):
self.destination_index = destination_index
self.origin_index = origin_index
self.current_position = origin_index
def set_destination(self, destination_index):
self.destination_index = destination_index
def get_destination(self):
return self.destination_index
def set_origin(self, origin_index):
self.origin_index = origin_index
def get_origin(self):
return self.origin_index
def set_current_position(self, current_position):
self.current_position = current_position
def get_current_position(self):
return self.current_position
#The network class:
class Delivery_Network:
'''
The network has the following attributes:
- network_size: The number of cities
- max_road_capacity: The theoretical maximum number of packages that can travel on the same road at once.
Each road has its own maximum capacity, typically smaller than max_road_capacity
- max_distance: The theoretical maximum distance between two cities
- m: The m variable in the initialization of the Barabasi-Albert graph. It indicates how many connections a newly added city has.
- max_packages: The theoretical maximum number of packages that can stay in a city at once.
Each city has its own maximum capacity, typically smaller than max_packages
- time: Keeps track of the amount of steps that have passed
- active_nodes_list: Contains a list of the "active" nodes - the ones that have not yet reached their maximum capacity
- active_edges_list_small_large: Contains a list of the "active" edges - the ones that have not yet reached their maximum capacity,
in the direction from the smaller index to the larger one.
- active_edges_list_large_small: Contains a list of the "active" edges - the ones that have not yet reached their maximum capacity,
in the direction from the larger index to the smaller one.
- delivered: Contains a list of the packages that have reached their final destination,
- total_num_packages: The total number of packages in the network.
'''
def __init__(self, network_size=10, max_road_capacity = 10, m = 3, max_distance = 5, max_packages = 50, time = 0, active_nodes_list = [], active_edges_list_small_large = [], active_edges_list_large_small = [], delivered = 0, total_num_packages = 0):
self.network_size = network_size
self.max_road_capacity = max_road_capacity
self.max_distance = max_distance
self.m = m
self.max_packages = max_packages
self.time = time
self.active_edges_list_small_large = active_edges_list_small_large
self.active_edges_list_large_small = active_edges_list_large_small
self.active_nodes_list = active_nodes_list
self.delivered = delivered
self.total_num_packages = total_num_packages
def get_delivered(self):
return self.delivered
def get_edges(self):
return self.graph.edges
def get_nodes(self):
return self.graph.nodes
def get_total(self):
return self.total_num_packages
def get_time(self):
return self.time
#This function doubles the maximum road capacity in both direction of a specified road
def double_max_road_capacity(self, node1, node2):
if (node1, node2) in self.graph.edges:
self.graph.edges[(node1, node2)]['max_road_capacity_small_large'] = 2*self.graph.edges[(node1, node2)]['max_road_capacity_small_large']
self.graph.edges[(node1, node2)]['max_road_capacity_large_small'] = 2*self.graph.edges[(node1, node2)]['max_road_capacity_large_small']
else:
raise Exception('ERROR DOUBLING MAX ROAD CAPACITY!!!')
#This function doubles the maximum city capacity to store packages of a specified city
def double_max_num_packages(self, node1):
if node1 in self.graph.nodes:
self.graph.nodes[node1]['max_num_packages'] = 2*self.graph.nodes[node1]['max_num_packages']
else:
raise Exception('ERROR DOUBLING MAX NUM PACKAGES!!!')
def initialize(self, seed_for_network_structure, saturation_level):
#The network has the structure of a Barabasi-Albert graph
self.graph = nx.barabasi_albert_graph(self.network_size, self.m, seed = seed_for_network_structure)
nodes_list = list(self.graph.nodes)
edges_list = list(self.graph.edges)
#Initially all nodes and edges are active
self.active_nodes_list = [i for i in nodes_list]
self.active_edges_list_small_large = [i for i in edges_list]
self.active_edges_list_large_small = [(i[1],i[0]) for i in edges_list]
#This function removes a node from a list
def remove_node(nodes_list, to_remove):
copy_nodes_list = [i for i in nodes_list]
copy_nodes_list.remove(to_remove)
return copy_nodes_list
for edge in self.graph.edges:
#The minimum road capacity in each direction is 5, and the capacities are assigned at random
self.graph.edges[edge]['max_road_capacity_small_large'] = np.random.randint(5,self.max_road_capacity)
self.graph.edges[edge]['max_road_capacity_large_small'] = np.random.randint(5,self.max_road_capacity)
#The minimum distance between two cities is 2, and the distances are assigned at random
self.graph.edges[edge]['distance'] = np.random.randint(2,self.max_distance)
#Each edge has a list of the packages that travel along it in each direction
self.graph.edges[edge]['packages_small_large'] = []
self.graph.edges[edge]['packages_large_small'] = []
#The node capacity to store packages is determined based on the connectivity of the node - the more connected it is,
#the more packages it can store. The expected max_num_packages is 0.8 times the proportion of connected cities to it
#times the theoretical maximum.
for node in self.graph.nodes:
self.graph.nodes[node]['max_num_packages'] = np.random.binomial(int(round((self.graph.degree(node)/float(self.network_size-1))*self.max_packages)), 0.8)
#Initializing the packages:
#Each city has a saturation level, which determines what proportion of the city's max capacity will be filled with packages.
#Each package's final destination is determined at random from the remaining nodes.
for node in self.graph.nodes:
self.graph.nodes[node]['packages'] = []
modified_nodes = remove_node(nodes_list, node)
for package_index in range(int(round(self.graph.nodes[node]['max_num_packages']*saturation_level))):
self.graph.nodes[node]['packages'].append(Package(node, np.random.choice(modified_nodes), node))
#Calculating the total number of packages in the network:
self.total_num_packages = sum(len(self.graph.nodes[node]['packages']) for node in nodes_list)
print "Total number of packages:", self.total_num_packages
#For the layout:
self.layout = nx.spring_layout(self.graph)
#Printing:
print "----------"
print "nodes_list=", nodes_list
print "edges_list=", edges_list
for node in self.graph.nodes:
#print "Node", node, "has max_num_packages=", self.graph.nodes[node]['max_num_packages']
#print "Node", node, "has this many packages:", len(self.graph.nodes[node]['packages'])
#for package in self.graph.nodes[node]['packages']:
#print "The characteristics of package", package, "are origin:", package.get_origin(), ", destination:", package.get_destination(), ", and curr_position:", package.get_current_position()
pass
for edge in self.graph.edges:
#print "Edge", edge, "has max_road_capacity_small_large=", self.graph.edges[edge]['max_road_capacity_small_large']
#print "Edge", edge, "has max_road_capacity_large_small=", self.graph.edges[edge]['max_road_capacity_large_small']
#print "Edge", edge, "has distance=", self.graph.edges[edge]['distance']
#print "Edge", edge, "has packages:", self.graph.edges[edge]['packages_small_large'], "and", self.graph.edges[edge]['packages_large_small']
pass
print "----------"
#The update function that exectues at each step after initialization
def update(self):
self.time += 1
nodes_list = list(self.graph.nodes)
edges_list = list(self.graph.edges)
#This function uses networkx's capabilities to find the shortest path between any two nodes and its distance
def find_shortest_path(node1, node2, number):
p = list(nx.shortest_simple_paths(self.graph, node1, node2, weight = 'distance'))
return p[number], len(p)
#The function that sends a package from a city to a road
def send_package_from_city(package):
if package.destination_index != package.current_position:
#Find shortest path and check if the first edge is active
count = 0 #counts the number of shortest paths tried
while True:
try_path = find_shortest_path(package.current_position, package.destination_index,count)[0]
success = True
if try_path[0] > try_path[1]:
if (try_path[0],try_path[1]) not in self.active_edges_list_large_small:
success = False
if try_path[0] < try_path[1]:
if (try_path[0],try_path[1]) not in self.active_edges_list_small_large:
success = False
if success == True:
#The edge is active
break
count += 1
if count >= find_shortest_path(package.current_position, package.destination_index,count-1)[1]:
#If all shortest paths have been tried and failed, we cannot send the package
break
if success==False:
#print "Could not send package from", package.current_position, "to", package.destination_index
pass
else:
#If we found a path to send the package on.
#Setting the current position as a triple: the two ends of the corresponding edge,
#and the position on that edge that the package currently occupies
package.set_current_position((try_path[0],try_path[1],0))
#If the package fills up the capacity of the edge, we need to remove the edge from the list of active edges.
#We then append the package to the list of packages on that road
if try_path[0]>try_path[1] and len(self.graph.edges[(try_path[1], try_path[0])]['packages_large_small']) == self.graph.edges[(try_path[1], try_path[0])]['max_road_capacity_large_small']-1:
self.active_edges_list_large_small.remove((try_path[0], try_path[1]))
self.graph.edges[(try_path[1], try_path[0])]['packages_large_small'].append(package)
elif try_path[0]<try_path[1] and len(self.graph.edges[(try_path[0], try_path[1])]['packages_small_large']) == self.graph.edges[(try_path[0], try_path[1])]['max_road_capacity_small_large']-1:
self.active_edges_list_small_large.remove((try_path[0], try_path[1]))
self.graph.edges[(try_path[0], try_path[1])]['packages_small_large'].append(package)
#Otherwise, we just append the package to the list of packages on that road
elif try_path[0]>try_path[1]:
self.graph.edges[(try_path[1], try_path[0])]['packages_large_small'].append(package)
else:
self.graph.edges[(try_path[0], try_path[1])]['packages_small_large'].append(package)
#If the release of the package from the city made it active again, we should reflect that
if try_path[0] not in self.active_nodes_list:
self.active_nodes_list.append(try_path[0])
self.graph.nodes[try_path[0]]['packages'].remove(package)
#If the destionation equals the current position, then something is wrong
else:
raise Exception('TRYING TO SEND A PACKAGE THAT IS ALREADY WHERE IT NEEDS TO BE!!!')
#The function that sends a package from a road to a city
def receive_package_from_road(package):
if package.current_position[2] != self.graph.edges[(package.current_position[0],package.current_position[1])]['distance']-1:
raise Exception('ERROR RECEIVING PACKAGE!!!')
else:
#If the package is indeed arriving at the destination:
if package.current_position[1] in self.active_nodes_list:
#The destination node should be active
self.graph.nodes[package.current_position[1]]['packages'].append(package)
if len(self.graph.nodes[package.current_position[1]]['packages']) == self.graph.nodes[package.current_position[1]]['max_num_packages']:
#If the addition of the package to the city fills up the capacity, we must remove the city from the list of active nodes
self.active_nodes_list.remove(package.current_position[1])
if package.current_position[0] > package.current_position[1]:
if len(self.graph.edges[(package.current_position[1], package.current_position[0])]['packages_large_small']) == self.graph.edges[(package.current_position[1], package.current_position[0])]['max_road_capacity_large_small']:
#If the release of the package from the road makes it active again, we need to reflect this
self.active_edges_list_large_small.append((package.current_position[0], package.current_position[1]))
self.graph.edges[(package.current_position[1], package.current_position[0])]['packages_large_small'].remove(package)
if package.current_position[0] < package.current_position[1]:
if len(self.graph.edges[(package.current_position[0], package.current_position[1])]['packages_small_large']) == self.graph.edges[(package.current_position[0], package.current_position[1])]['max_road_capacity_small_large']:
#If the release of the package from the road makes it active again, we need to reflect this
self.active_edges_list_small_large.append((package.current_position[0], package.current_position[1]))
self.graph.edges[(package.current_position[0], package.current_position[1])]['packages_small_large'].remove(package)
#The current position of the package is now the index of the city at which it arrived
package.set_current_position(package.current_position[1])
else:
#The destination node is not active, so we do nothing and wait
#print "Package", package.current_position, "waiting to enter because destination is not active!", "Distance=", self.graph.edges[(package.current_position[0],package.current_position[1])]['distance']
pass
#This function increases the distance traveled by a package on a road
def travel(package):
package.set_current_position((package.current_position[0],package.current_position[1],package.current_position[2]+1))
#For each node, we send the packages from that node (if possible):
for a_node in nodes_list:
for package in self.graph.nodes[a_node]['packages']:
send_package_from_city(package)
#For each edge, we either let the packages travel, or deliver them to their destinations
for an_edge in edges_list:
for package in self.graph.edges[an_edge]['packages_small_large']:
#If the package's current position is less than the distance minus 1, just travel
if package.current_position[2] < self.graph.edges[(package.current_position[0],package.current_position[1])]['distance']-1:
travel(package)
#If the package's current position equals the distance minus 1, then we must try to deliver it to the node
else:
receive_package_from_road(package)
#If the package has reached its final destination, increase number of delivered and remove it from the node
if type(package.current_position) == type(1):
if package.destination_index == package.current_position:
self.delivered += 1
if package.current_position not in self.active_nodes_list:
#If the release of the delivered package makes the city active again, we must reflect that
self.active_nodes_list.append(package.current_position)
#Removing the package from the city
self.graph.nodes[package.current_position]['packages'].remove(package)
for package in self.graph.edges[an_edge]['packages_large_small']:
#If the package's current position is less than the distance minus 1, just travel
if package.current_position[2] < self.graph.edges[(package.current_position[1],package.current_position[0])]['distance']-1:
travel(package)
#If the package's current position equals the distance minus 1, then we must try to deliver it to the node
else:
receive_package_from_road(package)
#If the package has reached its final destination, increase number of delivered and remove it from the node
if type(package.current_position) == type(1):
if package.destination_index == package.current_position:
self.delivered += 1
if package.current_position not in self.active_nodes_list:
#If the release of the delivered package makes the city active again, we must reflect that
self.active_nodes_list.append(package.current_position)
#Removing the package from the city
self.graph.nodes[package.current_position]['packages'].remove(package)
#This function allows us to visualize the network
def observe(self):
plt.clf()
nx.draw(
self.graph, pos=self.layout, with_labels=False,
node_color = [len(self.graph.nodes[i]['packages'])/float(self.graph.nodes[i]['max_num_packages']) for i in self.graph.nodes],
edge_color = [max(0.08, len(self.graph.edges[i, j]['packages_large_small'])/float(self.graph.edges[i, j]['max_road_capacity_large_small']), len(self.graph.edges[i, j]['packages_small_large'])/float(self.graph.edges[i, j]['max_road_capacity_small_large'])) for i, j in self.graph.edges],
cmap=plt.cm.Greys, edge_cmap=plt.cm.binary, edge_vmin=0., edge_vmax=1., alpha=1., vmin=0., vmax=1.
)
labels={}
for i in range(len(self.graph.nodes)):
labels[i]=i
nx.draw_networkx_edge_labels(self.graph, self.layout, edge_labels = nx.get_edge_attributes(self.graph,'distance'), font_size = 7)
nx.draw_networkx_labels(self.graph,self.layout,labels,font_size=12, font_color = 'GREEN')
plt.title('Road Network')
plt.show()
#Defining the network and visualizing the initial state:
sim = Delivery_Network()
saturation = 0.9
sim.initialize(0,saturation)
plt.figure()
sim.observe()
#Updating the network state until all packages are delivered and visualizing the states:
while True:
if sim.get_total() == sim.get_delivered():
print "SUCCESS in", sim.get_time(), "steps"
break
sim.update()
plt.figure()
sim.observe()
#Obtaining data for decision-making:
#------------EDGES------------:
#Number of simulations used
num_of_simulations = 30
saturation = 0.9
averages = []
conf_intervals = []
#Upgrading all the edges in the list, by multiplying their respective capacities by 8
for edge_to_upgrade in [(1,5)]:
average_steps = []
for j in range(num_of_simulations):
if j==0:
#Visualize the first simulation only
sim = Delivery_Network()
sim.initialize(0,saturation)
sim.double_max_road_capacity(edge_to_upgrade[0], edge_to_upgrade[1])
sim.double_max_road_capacity(edge_to_upgrade[0], edge_to_upgrade[1])
sim.double_max_road_capacity(edge_to_upgrade[0], edge_to_upgrade[1])
plt.figure()
sim.observe()
print "edge=", edge_to_upgrade, "and j=", j
#Running the simulation
while True:
if sim.get_total()==sim.get_delivered():
print "SUCCESS in", sim.get_time(), "steps"
average_steps.append(sim.get_time())
break
sim.update()
plt.figure()
sim.observe()
else:
sim = Delivery_Network()
sim.initialize(0,saturation)
sim.double_max_road_capacity(edge_to_upgrade[0], edge_to_upgrade[1])
sim.double_max_road_capacity(edge_to_upgrade[0], edge_to_upgrade[1])
sim.double_max_road_capacity(edge_to_upgrade[0], edge_to_upgrade[1])
print "edge=", edge_to_upgrade, "and j=", j
#Running the simulation
while True:
if sim.get_total()==sim.get_delivered():
print "SUCCESS in", sim.get_time(), "steps"
average_steps.append(sim.get_time())
break
sim.update()
#Results:
print "On average:", sum(average_steps)/float(num_of_simulations), "steps are needed when we upgrade edge", edge_to_upgrade, "!"
averages.append([edge_to_upgrade, sum(average_steps)/float(num_of_simulations)])
conf_intervals.append([edge_to_upgrade, [sum(average_steps)/float(num_of_simulations) - 1.96*np.std(average_steps)/float(np.sqrt(30)), sum(average_steps)/float(num_of_simulations) + 1.96*np.std(average_steps)/float(np.sqrt(30))]])
print "Averages:"
print averages
print " "
print "Confidence intervals:"
print conf_intervals
#------------NODES------------:
#Number of simulations used
num_of_simulations = 30
saturation = 0.9
averages = []
conf_intervals = []
#Upgrading all the nodes in the list, by multiplying their respective capacities by 8
for node_to_upgrade in [3]:
average_steps = []
for j in range(num_of_simulations):
if j==0:
#Visualize the first simulation only
sim = Delivery_Network()
sim.initialize(0,saturation)
sim.double_max_num_packages(node_to_upgrade)
sim.double_max_num_packages(node_to_upgrade)
sim.double_max_num_packages(node_to_upgrade)
plt.figure()
sim.observe()
print "edge=", node_to_upgrade, "and j=", j
#Running the simulation
while True:
if sim.get_total()==sim.get_delivered():
print "SUCCESS in", sim.get_time(), "steps"
average_steps.append(sim.get_time())
break
sim.update()
plt.figure()
sim.observe()
else:
sim = Delivery_Network()
sim.initialize(0,saturation)
sim.double_max_num_packages(node_to_upgrade)
sim.double_max_num_packages(node_to_upgrade)
sim.double_max_num_packages(node_to_upgrade)
print "edge=", node_to_upgrade, "and j=", j
#Running the simulation
while True:
if sim.get_total()==sim.get_delivered():
print "SUCCESS in", sim.get_time(), "steps"
average_steps.append(sim.get_time())
break
sim.update()
#Results:
print "On average:", sum(average_steps)/float(num_of_simulations), "steps are needed when we upgrade node", node_to_upgrade, "!"
averages.append([node_to_upgrade, sum(average_steps)/float(num_of_simulations)])
conf_intervals.append([node_to_upgrade, [sum(average_steps)/float(num_of_simulations) - 1.96*np.std(average_steps)/float(np.sqrt(30)), sum(average_steps)/float(num_of_simulations) + 1.96*np.std(average_steps)/float(np.sqrt(30))]])
print "Averages:"
print averages
print " "
print "Confidence intervals:"
print conf_intervals
|
ae8017e645946884ec49cb2d72e0f55b87de9686
|
burakonal89/edu-projects
|
/pycharm_projects/HackerRank/10 Days of Statistics/1_0.py
| 1,276 | 4 | 4 |
def find_median(number_list):
"Assuming that number_list is sorted"
if len(number_list)%2 == 0:
return (number_list[len(number_list)/2]+number_list[len(number_list)/2-1])/2.0
else:
return number_list[(len(number_list)-1)/2]
def findQuantile(input_numbers):
if len(input_numbers)%2 == 0:
quantile1 = int(find_median(input_numbers[:n/2]))
quantile3 = int(find_median(input_numbers[n/2:]))
quantile2 = (input_numbers[n/2-1]+input_numbers[n/2])/2
else:
quantile1 = int(find_median(input_numbers[:n/2]))
quantile3 = int(find_median(input_numbers[n/2+1:]))
quantile2 = input_numbers[n/2]
return quantile1, quantile2, quantile3
n = int(raw_input())
input_numbers = [int(i) for i in raw_input().split(" ")]
input_numbers.sort()
if n%2 == 0:
quantile1 = int(find_median(input_numbers[:n/2]))
quantile3 = int(find_median(input_numbers[n/2:]))
quantile2 = (input_numbers[n/2-1]+input_numbers[n/2])/2
print quantile1
print quantile2
print quantile3
elif n%2 == 1:
quantile1 = int(find_median(input_numbers[:n/2]))
quantile3 = int(find_median(input_numbers[n/2+1:]))
quantile2 = input_numbers[n/2]
print quantile1
print quantile2
print quantile3
|
30deb5a82c95a6bfd098829d1f72386df351c448
|
DonghaoQiao/Python
|
/0Leetcode Solutions/0006 ZigZag Conversion.py
| 1,932 | 4.3125 | 4 |
'''
https://leetcode.com/problems/zigzag-conversion/
6. ZigZag Conversion
Medium
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
(you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
'''
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
l=len(s)
matrix=[[] for _ in range(numRows)]
i=0
while i<l:
try:
for j in range(numRows):
matrix[j].append(s[i])
i+=1
for j in range(numRows-2,0,-1):
matrix[j].append(s[i])
i += 1
except IndexError:
break
lst=[''.join(element) for element in matrix]
return ''.join(lst)
class Solution1(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows==1:
return s
step,zigzag=2*numRows-2,''
for i in range(numRows):
for j in range(i,len(s),step):
zigzag+=s[j]
if 0<i<numRows-1 and j+step-2*i<len(s):
zigzag+=s[j+step-2*i]
return zigzag
print(Solution1().convert("abcdef",3))
print(Solution1().convert("PAYPALISHIRING",3))
|
a12f705b6c35e09f4945d09462efdb36c2c85108
|
martinbaros/competitive
|
/CodeJam/2019/solution.py
| 447 | 3.953125 | 4 |
# input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Kickstart problems.
t = int(input()) # read a line with a single integer
for i in range(1, t + 1):
case = str([int(s) for s in input().split(" ")][0] )# read a list of integers, 2 in this case
print("Case #{}: {} {}".format(i, case, int(b)))
# check out .format's specification for more formatting options
#viac riadkove
|
615d95b80358c3042cc1c9a325ce4efb4c42b56b
|
vladi837/tms-21
|
/hw05/task_5_5.py
| 1,438 | 3.890625 | 4 |
''' В массиве целых чисел с количеством элементов 19 определить максимальное
число и заменить им все четные по значению элементы. [02-4.1-BL19]'''
from random import randint
maximum1 = 0
def is_even_let(_x): # Вложенная функция проверки числа х на чётность
global maximum1 # Чтение внешней переменной
if _x % 2 == 0: # Если число чётное
return maximum1 # Вернуть внешнюю переменную
else: # Иначе
return _x # Вернуть входную переменную х
numbers = [randint(1, 99) for _ in range(19)] # Генерация списка из 19 элементов со случайными числами от[1;99]
print(numbers) # Вывод списка
maximum1 = max(numbers) # Поиск макчимума в списке
print(' maximum=', maximum1) # Вывод максимума
li1 = list(map(is_even_let, numbers)) # Создать список в котором четные элементы заменены на максимум
<<<<<<< HEAD
print(li1) # Вывод списка ( для сверки изменений )
=======
print(li1) # Вывод списка ( для сверки изменений )
>>>>>>> 6a7b3c28683b32acbe46a3d9ab7df541655eb294
|
e34b01e79fb4b799d2a41d50912c95c428d64f4a
|
geekysid/Python-Projects
|
/Rock, Paper Scissor/RPS Version 1.1.py
| 2,209 | 4.40625 | 4 |
# author: Siddhant Shah
# Desc: An update to basic version of RPS. This program converts inout text to upper case and does all testing
# using upper case. This removes any ambiguity about lower and upper case
import random
print("Welcome to the Rock, Paper, Scissors Game")
user_input = input("Please choose one of the 3 options, 'Rock', 'Paper' or 'Scissor': ").upper()
print()
game_tuple = ('Rock', 'Paper', 'Scissor') # tuple which holds all possible option of game
# using randint function of class random to choose one of 3 items in tuple and converting to uppercase
random_choice = game_tuple[random.randint(0, 2)].upper()
print(f"You choose: {user_input}")
print(f"Computer choose: {random_choice}")
# creating constants. These are not mandatory but I am using them to make code look cleaner
ROCK = "rock".upper()
PAPER = "paper".upper()
SCISSOR = "Scissor".upper()
print()
# checking different conditions
if user_input == ROCK:
if random_choice == ROCK: # if both user and computer have selected 'Rock'
print("IT A DRAW!!!")
elif random_choice == PAPER: # if user have selected 'Rock' but computer has selected 'Paper'
print("LOL!! YOU LOST")
elif random_choice == SCISSOR: # if user have selected 'Rock' but computer has selected 'Scissor'
print("YAY!! YOU WIN")
elif user_input == PAPER:
if random_choice == ROCK: # if user have selected 'Paper' but computer has selected 'Rock'
print("LOL!! YOU LOST")
elif random_choice == PAPER: # if both user and computer have selected 'Paper'
print("IT A DRAW!!!")
elif random_choice == SCISSOR: # if user have selected 'Paper' but computer has selected 'Scissor'
print("YAY!! YOU WIN")
elif user_input == SCISSOR:
if random_choice == ROCK: # if user have selected 'Scissor' but computer has selected 'Rock'
print("YAY!! YOU WIN")
elif random_choice == PAPER: # if user have selected 'Scissor' but computer has selected 'Paper'
print("LOL!! YOU LOST")
elif random_choice == SCISSOR: # if both user and computer have selected 'Scissor'
print("IT A DRAW!!!")
else:
print("Please enter valid input")
|
0f8c3ca15e7a0379ce53fab5a1aa4997a951985c
|
Syzygy05/CS435-Project2
|
/thankUVertext/main.py
| 1,222 | 3.609375 | 4 |
import node
import directedGraph
import topSort
import random
def createRandomDAG(n):
dag = directedGraph.DirectedGraph()
randomNums = []
for i in range(n):
while True:
val = random.randint(0, n * 10)
if val not in randomNums:
randomNums.append(val)
dag.addNode(val)
break
else:
continue
nodes = dag.getAllNodes()
for i in range(n):
while True:
# Get 2 random nodes from the list of nodes in the graph class
first = random.choice(tuple(nodes))
second = random.choice(tuple(nodes))
# Add an edge if they are not the same node
if first != second:
dag.addDirectedEdge(first, second)
break
else:
continue
return dag
# Prints a list of nodes in a list
# Used to print the path used to traverse in the recursive and iterative approaches
def printPath(path):
for node in path:
print(node.value)
dag = createRandomDAG(5)
dag.printAllNodesWithNeighbors()
ts = topSort.TopSort()
#path = ts.Kahns(dag)
#path = ts.mDFS(dag)
#printPath(path)
|
97e46b5d680b0fe287856ff72096ae3671a2d87b
|
eebmagic/python_turtle_art
|
/pattern_spirograph/patternSpirograph.py
| 345 | 3.515625 | 4 |
import turtle
t = turtle.Turtle()
# t.speed("fastest")
angle = 45 / 2
iterations = 25
adjust_angle = 5
turts = 360 // adjust_angle
for x in range(turts):
t = turtle.Turtle()
t.speed("fastest")
t.left(x * adjust_angle)
for i in range(iterations):
t.fd(100)
t.left(i * angle)
t.hideturtle()
turtle.done()
|
2fae836dc606d29f5aa12ba1087680209983f43e
|
amineHY/video2audio
|
/video2audio.py
| 1,025 | 3.546875 | 4 |
import youtube_dl
import os
print('[Info] Simple video-to-audio converter \n')
video_url = input('Enter the youtube URL of the video or playlist: ')
print('[Info] You have entered:', video_url)
def createFolder(dirName):
try:
# Create target Directory
os.mkdir(dirName)
print("Directory " , dirName , " Created ")
return dirName
except FileExistsError:
print("Directory " , dirName , " already exists")
return dirName
if video_url is not "":
print('[Info] Conversion in progress...')
folder = createFolder('./audio/')
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': folder+'%(title)s.%(etx)s' ,
'quiet': False
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(url_list=[video_url])
print("[Info] Done!")
else:
raise ValueError ('[Error] Please enter a valid URL')
|
56c14f1a4217be9e3d260816d839151364f80e55
|
ryanmcg86/Euler_Answers
|
/053_Combinatoric_selections.py
| 1,265 | 3.609375 | 4 |
'''There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, 5C3 = 10
5C3 = 10.
In general, nCr = n! / r!(n−r)!, where r ≤ n, n! = n × (n−1) × ... × 3 × 2 × 1, and 0! = 1.
It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
How many, not necessarily distinct, values of nCr for 1 ≤ n ≤ 100, are greater than one-million?
Link: https://projecteuler.net/problem=53'''
#Imports
import time
#Build a factorial function
def fact(n):
ans = 1
for i in range(0, n):
ans *= (i + 1)
return ans
#Build an nCr function
def nCr(n, r):
return fact(n) / (fact(r) * fact(n - r))
#Build a solve function
def solve(limit):
#Define variables
start = time.time()
counter = 0
#Solve the problem
for n in range(1, 101):
for r in range(1, n + 1):
if nCr(n, r) > limit:
counter += 1
#Print the results
print 'There are ' + str(counter) + ' values of nCr that are greater'
print 'than ' + str(limit) + ' for 1 <= n <= 100.'
print 'This took ' + str(time.time() - start) + ' seconds to calculate.'
#Run the program
limit = 10**6
solve(limit)
|
c55e82849ba44d1d46fb02a772e8af1dbba1df04
|
calebpalmer/pypgbackup
|
/pypgbackup.py
| 3,921 | 3.59375 | 4 |
import argparse
import subprocess
import datetime
import os
import getpass
import tempfile
import sys
def get_dt_format():
"""
Gets the datetime format string.
Returns:
str: The datetime format string.
"""
return '%Y%m%d-%H%M%S'
def create_arg_parser():
"""
Creates an argument parser.
Returns:
The argparser.
"""
parser = argparse.ArgumentParser(description='Make postgres backups to cloud locations.')
parser.add_argument('-H', '--hostname', default='localhost', help='The hostname of the postgres server.')
parser.add_argument('-p', '--port', type=int, default=5432, help='The port of the postgres server.')
parser.add_argument('-U', '--user', help='The postgres user.', required=True)
parser.add_argument('-d', '--database', help='The postgres database to back up.', required=True)
parser.add_argument('-b2', '--b2-bucket', help='The b2 bucket to upload to.')
parser.add_argument('--b2-prefix', default='', help='The b2 bucket to upload to.')
return parser
def get_password():
"""
Gets a password either from the PGPASSWORD environment variable
or from input.
Returns:
str: The password.
"""
if 'PGPASSWORD' in os.environ:
return os.environ['PGPASSWORD']
else:
return getpass.getpass(prompt="password: ")
def create_backup(host, port, user, password, database, directory):
"""
Creates the PostgreSQL backup.
Args:
host (str): The hostname of the postgres server.
port (int): The port number of the postgres server.
user (str): The postgres username.
password (str): The postgres password.
database (str): The postgres database to backup.
directory (str): The firectory to save the file in.
Returns:
str: The path to the database export file.
"""
if 'PGPASSWORD' not in os.environ:
os.environ['PGPASSWORD'] = password
filename = '{}_{}.backup'.format(
database, datetime.datetime.utcnow().strftime(get_dt_format())
)
filepath = os.path.join(directory, filename)
cmd = ['pg_dump', '-h', host,
'-p', str(port),
'-U', user,
'-f', filepath,
'-Fc', '-Z9',
'-d', database]
completed_process = subprocess.run(' '.join(cmd), shell=True, stdout=subprocess.PIPE, stderr=sys.stdout)
assert completed_process.returncode == 0, completed_process.stdout
return filepath
def upload_to_b2_bucket(filepath, bucket_name, prefix):
"""
Upload backup to bucket.
Args:
filepath (str): The path of the file to upload.
bucket_name (str): The name of the bucket to upload to.
"""
from b2blaze import B2
# get the keys
assert 'B2_KEY_ID' in os.environ
assert 'B2_APPLICATION_KEY' in os.environ
b2 = B2()
bucket_names = list(map(lambda x: x.bucket_name, b2.buckets.all()))
assert bucket_name in bucket_names, \
'Bucket {} not in {}'.format(bucket_name, bucket_names)
bucket = b2.buckets.get(bucket_name)
if len(prefix.strip()) > 0 and prefix[:-1] != '/':
prefix = prefix.strip() + '/'
with open(filepath, 'rb') as f:
bucket.files.upload(contents=f,
file_name=prefix + os.path.basename(filepath))
def main():
parser = create_arg_parser()
args = parser.parse_args()
with tempfile.TemporaryDirectory() as tf:
filepath = create_backup(args.hostname,
args.port,
args.user,
get_password(),
args.database,
tf)
if args.b2_bucket is not None:
upload_to_b2_bucket(filepath, args.b2_bucket, args.b2_prefix)
if __name__ == '__main__':
main()
|
5c99ff057ec235421354a01771172cc87e695490
|
keolam/Project-Euler
|
/p005.py
| 508 | 3.53125 | 4 |
# This Python file uses the following encoding: utf-8
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
import functools as ft
import fractions
def lcm(a, b):
return a * b // fractions.gcd(a, b)
def find_lcm(*args):
return ft.reduce(lcm, args)
if __name__ == "__main__":
print(find_lcm(*range(1, 20)))
# prints: 232792560
|
1c02bad3c6d9d3a1e687bdf01aa3f1ac5d3160f0
|
diopch/stock_prediction
|
/stock_prediction/tradding_app.py
| 13,388 | 3.890625 | 4 |
import pandas as pd
import numpy as np
from stock_prediction.params import company_list
import pdb
from datetime import datetime, timedelta
def best_stocks(df, sell=True, eq_weight=False) :
'''This function allows us to select the best 10 stocks in our
predictions of returns for each day of the tradding experience.
We can use ut for our predictions and ask for a inequal weight ponderation
of the stocks in the portfolio, or call it for the 'True' comparaison
and ask for an equal ponderation. We can also have the best 10 stocks
to sell or buy or just to buy. '''
# the df has a 'stocks' features and one column per day of prediction
# the first column is 'stocks'
# as we need to for loop on each day and we don't want to know the number
# of days, we are going to drop 'stocks' in the column list and loop
day_pred_list = df.columns[1:]
# we create a list to store portfolio for each day
ptf_day_list = []
for days in day_pred_list :
# we select only the day we want to analyze
day_search = df[['stocks', days]].copy()
# if we work with BUY & SELL we need the absolute returns
if sell :
# we create a column with the absolute returns
day_search['abs_returns'] = day_search[days].abs()
ten_best = day_search.nlargest(10, 'abs_returns')
# we need to create the weight column depending on eq_weight
if eq_weight :
ten_best['weights'] = 0.10
else :
ten_best['weights'] = ten_best['abs_returns'] / ten_best['abs_returns'].sum()
# finally we can drop the abs_returns column
ten_best.drop(columns='abs_returns', inplace=True)
else :
ten_best = day_search.nlargest(10, days)
if eq_weight:
ten_best['weights'] = 0.10
else:
ten_best['weights'] = ten_best[days] / ten_best[days].sum()
# we have a df with the list of 10 best stocks
# their predicted returns for the day
# the weight in the portfolio
# we store it in the list
# we need to have the stocks as index
ten_best = ten_best.set_index('stocks')
ptf_day_list.append(ten_best)
return ptf_day_list
def true_returns(start_date, end_date, dict_hard_data) :
'''This function wiil allow us to have a df with all the stocks and their
respective returns for each day of the simulation
# we will also store a df with all the Cosing prices to be able to make the BUY/SELL
# in parameters we have the dates start / end of the simulation
# also the dictionary with all the inputs from yahoo API, output of workflow.data_collection'''
# we need valid dates if not errors
# in the future that would be a point of improvement but no time
# we need to know the dates gap between start date and end date because some of the stocks
# does not have the date
# so we make the search on EuroStoxx to know the gap
# we create a empty dict to store the data
dict_open_prices = {}
dict_close_prices = {}
dict_true_returns = {}
for comp in company_list :
# we select the right df in the dictionary in input
stock_df = dict_hard_data[comp]
# selection of the rows depending on dates
# because we are lazy and missing time, we must find a time period with all stocks traded
#stock_df = stock_df.iloc[stock_df.loc[stock_df['Date'] == start_date].index[0] - 1 : stock_df[stock_df['Date'] == end_date].index[0]]
stock_df = stock_df.loc[
stock_df.loc[stock_df['Date'] == start_date].index[0] - 1 :
stock_df[stock_df['Date'] == end_date].index[0]]
# we select on row before to be able to compute the return and have the price of yesterday
# of the first day to make the BUY/SELL
# we create the pct_change
stock_df['Returns_true'] = stock_df['Adj Close'].pct_change(1)
# don't forget that the first row is not part of our simulation
#**************************************************************
# for the rest of the code, all is named "CLOSE" , but making the control
# in the app trading, we cannot buy at the Close yesterday, knowing the
# close price , so we need to buy at the open price
# because no time until presentation of the project, we need to change this and
# keep the rest of the name on the code as CLOSE but it is the OPEN price
# in fact, I have more time now :) , train for tomorrow : let's try to complete the task
#**************************************************************
open_prices = stock_df[['Date', 'Open']].copy()
close_prices = stock_df[['Date', 'Close']].copy()
true_returns = stock_df[['Date', 'Returns_true']].copy()
# we want to rename the columns to be able to keep the right stock
# when merging
open_prices = open_prices.rename(columns={'Open': comp})
close_prices = close_prices.rename(columns= {'Close' : comp})
true_returns = true_returns.rename(columns={'Returns_true': comp})
# we drop the first row
# to do that we need to reset index
true_returns.reset_index(drop=True, inplace=True)
true_returns.drop(labels=0, axis='index')
# we strore in the dictionaries
dict_open_prices[comp] = open_prices
dict_close_prices[comp] = close_prices
dict_true_returns[comp] = true_returns
# now we have all the df
# we need to create a df with all days
# we merge on dates
# we retrieve the first one to be able to merge other on it
# to be sure to have all the dates in the time period for all the stocks
# we should have -1 row to be able to shift by one in case there is a day trading in
# the first df that is not for oters
# or create a first column with the dates we expect to trade during the simulation
# and merge on that and shift if there is missing value
df_open_prices = dict_open_prices[company_list[0]]
df_close_prices = dict_close_prices[company_list[0]]
df_true_returns = dict_true_returns[company_list[0]]
for comp in company_list[1:] :
df_open_prices = df_open_prices.merge(dict_open_prices[comp], how='inner', on='Date')
df_close_prices = df_close_prices.merge(dict_close_prices[comp], how='inner', on='Date')
# we do the same for the returns true
df_true_returns = df_true_returns.merge(dict_true_returns[comp], how='inner', on='Date')
# we also need to change the index and put the date as indexes
df_open_prices = df_open_prices.set_index('Date')
df_close_prices = df_close_prices.set_index('Date')
df_true_returns = df_true_returns.set_index('Date')
# now we have our 2 df
return df_open_prices, df_close_prices, df_true_returns
def portfolio(open_price, close_price, true_returns, best_true, best_pred, cash_invest, true=False) :
'''This function will use the df in inputs to compute the number of stocks we need to trade
and impact the cash '''
# we will make that simulation inside a dictionary that will help us to
# keep only one of each Date / Stock
# can call per Stocks / Date easily
#*******************************
# to improve the application, we should have to iclude the forex
# when BUY/SELL the stocks because some of them are not traded in EUR
#******************************
# we need the list of the dates we make the simulation
date_list = close_price.index.to_list()
# we must declare all the dict to be able to access the keys after and fill them
dict_dates = {x : 0 for x in date_list}
# now the dict level 1 of the stocks
# we include all stocks , cash and daily_return
dict_ext_variables = {
'cash': dict_dates.copy(),
'daily_return_pred': dict_dates.copy(),
'daily_return_true': dict_dates.copy()
}
dict_stocks = {x: dict_dates.copy() for x in company_list}
# now that e have all the dict ready, we can loop on all the days and store the results as lists
# lists : nb_stocks, return_pred, return_true, Close_price, Close_true, performance_pred, performance_true
# we need to give the amount to invest to yesterday of first day of simulation
dict_ext_variables['cash'][date_list[0]] = cash_invest
# we also need to separate the process of the best_true ptf and the best_pred_ptf
if true :
best_ten = best_true
else :
best_ten = best_pred
# noow the loop on the best_ten df in the lists generated by best_stocks function
for df in best_ten :
# we need variables to store values of the cash and preformance
amount_tot_invested = 0
perf_daily_saved = 0
perf_daily_pred = 0
# we retrieve the date of that ptf
# the df has Date column and weights columns
ptf_date = df.drop(columns='weights').columns[0]
# we need to position of the date in the date_list
position = date_list.index(ptf_date)
# we loop on the stocks in the index
for stocks in df.index.to_list() :
# the return for that stock at that date (true or pred)
rets = df.loc[stocks, ptf_date]
# here we need to know the sell / buy
if rets > 0 :
direction = 1
else :
direction = -1
# the weight we want for that stock in the ptf
weight = df.loc[stocks, 'weights']
# the amount in $ to trade
amount_to_trade = weight * dict_ext_variables['cash'][date_list[
position - 1]]
# here we need to make a condition
# because if the move between Close price day -1 and Open price of the day is higher
# than our prediction ---> our expected return is already done and we cannot make it anymore
# so we don't buy/ sell if it is the case
# the move overnight
overnight = (open_price.loc[date_list[position], stocks] / close_price.loc[date_list[position - 1], stocks]) -1
if abs(overnight) > abs(rets) :
nb_stocks = 0
# number of shares we can buy/sell with this amount
nb_stocks = amount_to_trade // open_price.loc[date_list[position], stocks]
# the real amount invested in that stock TRADED ON THE OPEN PRICE OF THE DAY
amount_traded = nb_stocks * open_price.loc[date_list[position],
stocks]
# we need to store that amount to be able to apply to the final cash position at the end of the day
amount_tot_invested += amount_traded
# we need the amount at the end of the day regarding the price close at the end of the day
amount_end_of_day = nb_stocks * close_price.loc[date_list[position], stocks]
# we find the gains (losses???) at the end of the day, for that stock
# there is a difference if we sell or buy the stock
# here we have to take in consideration the case where rets is >0 but the stock
# goes down , and contrary
# we also need the true return for that stock that day
rets_true = true_returns.loc[ptf_date, stocks]
if rets_true > 0 and rets > 0:
perform_stock = (amount_end_of_day - amount_traded)
elif rets_true < 0 and rets < 0:
perform_stock = (amount_end_of_day - amount_traded) * -1
elif rets_true > 0 and rets < 0:
perform_stock = (amount_end_of_day - amount_traded) * -1
elif rets_true < 0 and rets > 0:
perform_stock = (amount_end_of_day - amount_traded)
perf_daily_saved += perform_stock
# we need the amount we would had if the return predicted was right
# it takes in consideration the weight and the predicted return
predicted_return_amount = amount_to_trade * rets * direction
perf_daily_pred += predicted_return_amount
# we also need the true return for that stock that day
rets_true = true_returns.loc[ptf_date, stocks]
# we also need the performance during the day
day_perf = (close_price.loc[date_list[position],
stocks] / open_price.loc[
date_list[position], stocks]) - 1
# now we need to store the values in our dicts
dict_stocks[stocks][ptf_date] = [
nb_stocks, rets, rets_true, predicted_return_amount,
perform_stock, overnight, day_perf
]
# until now we made it for all the stocks in the portfolio for that day
# before going to the next day, we need to store the global values for that day
dict_ext_variables['daily_return_pred'][ptf_date] = perf_daily_pred
dict_ext_variables['daily_return_true'][ptf_date] = perf_daily_saved
dict_ext_variables['cash'][ptf_date] = dict_ext_variables['cash'][
date_list[position - 1]] + perf_daily_saved
#pdb.set_trace()
return dict_ext_variables, dict_stocks
|
5b53e5fdc0534a3e813764c607c4fb61717f59d7
|
bestchenwu/PythonStudy
|
/Unit18/ProducerConsumerTest.py
| 1,199 | 3.796875 | 4 |
import threading
from time import ctime, sleep
from random import randint
from queue import Queue
def write(queue):
# print("Producer produce start:%s" % ctime())
value = randint(1, 99)
queue.put(value)
print("Producer put value %d " % value)
# print("Producer produce end:%s" % ctime())
sleep(randint(1, 3))
def write_q(count, queue):
for i in range(count):
write(queue)
def get(queue):
# print("Consumer consume start:%s" % ctime())
value = queue.get()
print("consumer consume value %d " % value)
# print("Consumer consume end:%s" % ctime())
sleep(randint(1, 3))
def get_q(count, queue):
for i in range(count):
get(queue)
def main():
queue = Queue(30)
# todo:这里不合理的地方是创建线程的时候指定的函数必须接受一个参数列表,而不能是queue
consumer_thread = threading.Thread(target=get_q, name="consumerThread", args=(5, queue))
producer_thread = threading.Thread(target=write_q, name="producerThread", args=(5, queue))
consumer_thread.start()
producer_thread.start()
consumer_thread.join()
consumer_thread.join()
if __name__ == '__main__':
main()
|
43cba49f72330ea1ad5de3fae55c50895b97950d
|
Ash25x/PythonClass
|
/p.py
| 1,711 | 4.09375 | 4 |
# #write a function that takes an array of integers
# # and returns if it has more even numbers or more odd numbers?
#
# l =[2,4,6,8,7]
#
# def array1(l):
# countodd = 0
# counteven = 0
# for i in l:
# if i % 2 == 0:
# counteven += 1
# print(counteven)
# else:
# countodd +=1
# print(countodd)
# if counteven > countodd:
# print("even is greater")
#
# else:
# print("odd is greater")
# array1(l)
#
# #WriteaPythonprogramthatacceptsastringandcalculatethenumberofdigitsandletters
# s= "string"
# x= 0
# y= 0
# for i in s:
# if i.isdigit():
# x += 1
#
# elif i.isalpha():
# y += 1
#
# print(x)
# print(y)
#
# a= [1,5,6,7,8]
# def lisadd(a):
# count = 0
# for i in a:
# count= count + i
# print(count)
# lisadd(a)
#
# #writeaprogramthattakesanarrayofintsandreturnsanotherarraythatcontainsthesquaresofelementsfromfirstarra
# o=[2,4,6,1]
# p=[]
# for i in o:
# p.append(i**2)
# print(p)
#
# #WriteaPythonscripttocheckifagivenkeyalreadyexistsinadictionary
# d = {'h':2, 'blah':'garbage', 'arroz':'con poyo'}
# def ifindic(i):
# if i in d:
# print("ya")
# else:
# print('nah')
# ifindic('g')
# ifindic('h')
# ifindic('garbage')
#
# def printdic():
# for i in d:
# print(d)
# print(d['blah'])
# printdic()
#
# def deldic():
# print(d)
# if 'h' in d:
# del d['h']
# print(d)
# else:
# print("not in dic")
# deldic()
s= ('hello')
file1 =open('filenamez', 'a')
#x= file1.read()
file1.write(s)
file1.close
x=open('filenamez', 'a')
y=open('file2', 'r')
w=y.read()
x.write(w)
x.close()
y.close()
|
fd3ca38ba86efdd3401129f19329ed5e8578563a
|
halflogic/learn-python
|
/rps-game.py
| 2,062 | 4.375 | 4 |
# A game of rock, paper, scissors against the computer
import sys
import random
print("Welcome to Rock, Paper, Scissors game!")
win = 0
lose = 0
tie = 0
# use dictionary for the choices
choice_dict = {'r':'Rock', 'p':'Paper', 's':'Scissors'}
while True:
print("-----------------------------")
print("Score: Win=" + str(win) + " Lose=" + str(lose) + " Tie=" + str(tie))
print("-----------------------------")
print("\nSelect (r) for Rock, (p) for Paper, (s) for Scissors or (q) to quit the game.")
player_choice = input("Enter your choice: ")
if player_choice == 'q':
print("Exiting game. Thank you for playing!")
sys.exit()
elif player_choice == 'r' or player_choice == 'p' or player_choice == 's':
print("You chose: ", choice_dict[player_choice])
# Generate random choice for computer
computer_choice = random.choice(list(choice_dict.keys()))
print("Computer chose: ", choice_dict[computer_choice] )
print(">> " + choice_dict[player_choice] + " -vs- " + choice_dict[computer_choice])
# Check who wins and tally score
if player_choice == computer_choice:
tie += 1
print(">> It's a tie!")
elif player_choice == 'r' and computer_choice == 's':
win += 1
print(">> You win!")
elif player_choice == 'p' and computer_choice == 'r':
win += 1
print(">> You win!")
elif player_choice == 's' and computer_choice == 'p':
win += 1
print(">> You win!")
elif player_choice == 'r' and computer_choice == 'p':
lose += 1
print(">> You lose!")
elif player_choice == 'p' and computer_choice == 's':
lose += 1
print(">> You lose!")
elif player_choice == 's' and computer_choice == 'r':
lose += 1
print(">> You lose!")
else:
print(">> Undetermined result <<")
else:
print(">> Invalid selection! Try again.")
|
0443c4c129fb47ebea24e145131a0fd494e321bb
|
rjorth/Algorithms-and-Data-Structures
|
/LHS.py
| 340 | 3.890625 | 4 |
import collections
def findLHS(nums):
#counter counts the number of times that an element appears in the list
#you constantly confuse this with enumerate
count = collections.Counter(nums)
#store result
arr = 0
for i in count:
if i+1 in count:
arr = max(arr, count[i] + count[i+1])
return arr
print(findLHS([1,1,1,2,2,2,6]))
|
54be3853f398bf9b8e26e095a2ddc6ef4e7b9092
|
rbiswas4/utils
|
/binningutils.py
| 2,816 | 3.953125 | 4 |
#!/usr/bin/env python
import numpy as np
import math as pm
verbose = False
def nbinarray(numpyarray ,
binningcol ,
binsize ,
binmin ,
binmax ):
"""
bins a numpy array in equal bins in the variable in the column
of the array indexed by the integer binningcol.
args:
binningcol: integer, mandatory
integer indexing the column of the array holding the
variable wrt which we are binning
binsize : float, mandatory
binmins : float, mandatory
binmax : float, mandatory
returns: a numpy array of elements x corresponding to the bins. Each
element x is an array of the elements of in input numpyarray
that are assigned to the bin
example usage:
notes:
"""
#First define the bins:
numrows , numcols = np.shape(numpyarray)
numbins = int(pm.floor((binmax - binmin )/binsize))
binningcolbins = np.linspace(binmin , binmax ,numbins+1)
digitizedindex = np.digitize(numpyarray[:,binningcol],
bins = binningcolbins)
binnedarray = []
for i in range(numbins):
binnedarray.append(numpyarray[digitizedindex==i+1])
ret= np.array(binnedarray)
if verbose :
print "size of bins" , map(len, ret)
return ret
def ngetbinnedvec( nbinnedarray , col):
"""Given an array of 2d numpy arrays (ie. having
shape (numrows, numcols), returns an array of 1d
numpy arrays composed of the col th column of the
2d arrays.
example useage :
"""
numbins = len(nbinnedarray)
binnedvec = []
for i in range(numbins):
binnedvec.append(nbinnedarray[i][:,col])
return binnedvec
if __name__ == "__main__":
import sys
import numpy as np
import matplotlib.pyplot as plt
num = 10
#basic model: x is independent variable, y, z are dependent
np.random.seed = -4
x = np.random.random(size = num)
x.sort()
y = 2.0 * x
z = 0.5 * x * x + 1.5 * x + 3.0
#Set up a numpy array adding noise to y and z
a = np.zeros (shape = (num,3))
a [:,0 ] = x
a [:,1 ] = y + np.random.normal(size = num)
a [:,2 ] = z + np.random.normal(size = num)
#bin the array according to values of x which is in the col 0
#using uniform size bins from 0. to 1. of size 0.1
binnedarray = nbinarray ( a,
binningcol = 0,
binmin = 0.,
binmax = 1.0,
binsize = 0.1)
print binnedarray
print type(binnedarray)
sys.exit()
print "\n-------------------------\n"
xbinned= ngetbinnedvec (binnedarray, 0)
ybinned= ngetbinnedvec (binnedarray, 1)
#print xbinned
xavg = map (np.average , xbinned)
yavg = map (np.average , ybinned)
#xavg = map( lambda x : np.average(x ) , xbinned )
#yavg = map( lambda x : np.average(x) , ybinned)
#print map( lambda x , w : np.average(x, w), xbinned, ybinned)
plt.plot(x, y, 'k-')
plt.plot(a[:,0] , a[:,1], 'ks')
plt.plot(a[:,0], a[:,2], 'ro')
plt.plot(x,z , 'r--')
plt.plot( xavg, yavg, 'bd')
plt.show()
|
51b499e33a8ed175b89381d1786ac2daeb0399b9
|
gabriellaec/desoft-analise-exercicios
|
/backup/user_256/ch131_2020_04_01_18_25_49_144668.py
| 884 | 3.953125 | 4 |
#Fase1:
import random
dado1= random.randint(1, 10)
dado2= random.randint(1, 10)
sorteio = dado1+dado2
print("Voce tem 10 dinheiros")
dinheiro = 10
#Fase de dicas
nmr1 = int(input("Digite um numero: "))
if sorteio < nmr1:
print("Soma menor")
nmr2 = int(input("Digite outro numero: "))
if sorteio > nmr2:
print("Soma maior")
if not sorteio>nmr2 and not sorteio<nmr1:
print("Soma no meio")
#Fase de chutes
nossa = True
while nossa:
print("Voce tem {}dinheiros".format(dinheiro))
compra = int(input("Quantos chutes deseja comprar? "))
dinheiro= dinheiro - compra
while compra>0:
chute=int(input("Qual a soma? "))
compra = compra-1
if chute == sorteio:
dinheiro = dinheiro + dinheiro*5
nossa = False
if compra == 0:
nossa = False
print("Você terminou o jogo com {0} dinheiros".format(dinheiro))
|
a14454728f2a8ec6430341a2e921b38a6c4ff505
|
Gowtham-cit/Python
|
/Guvi/int-to-bin-count-of-1s.py
| 200 | 3.5625 | 4 |
def int_bin(n):
x = "{0:b}".format(n)
x = str(x)
count = 0
for i in x:
if i == '1':
count += 1
print(count)
n = int(input())
int_bin(n)
|
b9656eed835a4a701822af05c69312db01869424
|
woernerm/cucoloris
|
/cucoloris/_colorlabel.py
| 5,452 | 3.75 | 4 |
"""Defines a label that can change color.
The color shift is animated. This can be used for link-style text.
"""
from os.path import dirname as _dirname
from math import modf as _modf
from typing import Optional as _Optional
from kivy.animation import Animation as _Animation
from kivy.graphics import Color as _Color
from kivy.lang.builder import Builder as _Builder
from kivy.properties import ListProperty as _ListProperty
from kivy.properties import NumericProperty as _NumericProperty
from kivy.properties import StringProperty as _StringProperty
from kivy.uix.label import Label as _Label
_Builder.load_file(_dirname(__file__) + '\\_colorlabel.kv')
class ColorLabel(_Label):
"""Label widget that can shift its color.
The color shift is animated. This can be used for link-style text.
"""
nominal_color = _ListProperty([0,0,0,0])
"""Nominal, i.e. unmodied color of the label.
The color must be given as RGBA values, each between 0 and 1.
"""
transition = _NumericProperty()
"""Transition time in seconds.
The ColorLabel widget transitions smoothly between colors. The time
it shall take from one color state to another can be set using this
attribute.
"""
text = _StringProperty()
"""The text of the label."""
_hsv = _ListProperty()
"""Private parameter representing the current color in HSV-space."""
def __init__(self, text:_Optional[str] = None, nominal_color:_Optional[list] = None,
transition:_Optional[int] = None, **kwargs):
"""Initialization method of the class.
Args:
text: The text of the label.
nominal_color: The nominal, i.e. unmodified color of the
transition: The time it takes to transition from one color
to another.
"""
super(ColorLabel, self).__init__(**kwargs)
self.text = text if text else self.text
self.nominal_color = nominal_color if nominal_color else self.nominal_color
self.transition = transition if transition else self.transition
self.size_hint = [None, None]
self._hsv = _Color(*self.color).hsv
def on_nominal_color(self, _, color):
"""Callback for changing the color.
This callback method changes the nominal, i.e. unmodified
color of the widget.
Args:
color: The new color value.
"""
self.color = color
self._hsv = _Color(*self.color).hsv
def on__hsv(self, _, hsv):
"""Callback for animating the color modification in hsv space.
The color modification takes place in hue, saturation, value
space in order to avoid weird red color shifts moving through
several different hues instead of just the brightness (value)
component of the color.
Args:
widget: The widget the method was called from.
hsv: The new hsv value.
"""
hcolor = _Color(*self.nominal_color)
hcolor.hsv = hsv
self.color = hcolor.rgba
def modify(self, hsv):
"""Shifts the widget's color in HSV-space.
Modifies the nominal color of the widget in HSV-space (hue,
saturation and value) using a smooth color transition. The
given values are not absolute ones but differences to the
current nominal color. For example, to make a widget with name
myWidget slightly darker, one may call
```py
myWidget.modify([0, 0, -0.2])
```
to reduce the widget's value (meaning brightness) by 0.2.
The modification can be easily undone by calling the function
with zero values for all HSV-components, e.g.:
```py
myWidget.modify([0, 0, 0])
```
Args:
hsv: List of hue, saturation, and value (brightness) values
to shift the color of the widget.
"""
# Since hue is the angle on a color wheel, there is no minimum
# or maximum value. Hue values larger than one describe multiple
# revolutions around the color wheel.
targethue = _modf(_Color(*self.nominal_color).h + hsv[0])[0]
targethue = targethue if targethue > 0 else 1 - targethue
refsaturation = _Color(*self.nominal_color).s
refvalue = _Color(*self.nominal_color).v
target = [ targethue,
max(min(refsaturation + hsv[1], 1),0),
max(min(refvalue + hsv[2], 1),0)]
_Animation(_hsv = target, duration = self.transition, t='linear').start(self)
def recolor(self, color):
"""Changes the nominal color of the widget.
Changes the nominal color by smoothly transitioning to the given
color. The color to transition to is given as a list of float
values between 0 and 1 in RGBA-space, i.e. [red, green, blue,
alpha]. Unlike the modify-method, the change cannot be undone
just as easily. For that, the user needs to store the old color
in another variable and call recolor with that variable again.
Args:
rgba: The new color as a list in RGBA-space to transition
to. Each list component is a float value between 0 and 1.
"""
_Animation(nominal_color = color, duration = self.transition, t='linear').start(self)
|
07d9bb8c501270ea93a950cd7fdc9a54b01be99d
|
timkaing/spd-2-4
|
/leetcode/14.py
| 390 | 3.765625 | 4 |
# 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 "".
def longestCommonPrefix(self, strs):
if not strs:
return ""
for index, letter in enumerate(zip(*strs)):
if len(set(letter)) > 1:
return(strs[0][:index])
else:
return min(strs)
|
a96d5e960611a308638263d25c619b67112cc664
|
Toyin5/HacktoberfestAlgorithmsExercices
|
/exercicies/medium.py
| 1,386 | 3.84375 | 4 |
class Medium:
# description: paste the description here
# enter parameters: paste the enter parameters examples here
# return: paste the return expected here
def nameOfFunction(self, value1, value2):
# script here
return None
# description: Create a function to return sorted array using merge sort
# enter parameter: array = [4, 8, 6, 9, 0, -1, -20, 9, 3, 44, 6]
# return: [-20, -1, 0, 3, 4, 6, 6, 8, 9, 9, 44]
def mergeSort(self, array):
# paste your script here
return None
# description: Create a function to return next permutation of given string. i.e, rearrange string into the lexicographically next greater permutation of given string.
# If such arrangement is not possible, return its lowest possible order
# enter parameter: string = "58523"
# return: "58532"
def nextPermutation(self, string):
# paste your script here
return None
# description: Create a function that returns weather given string matchs given pattern
# in pattern, * represents it can be replaced by zero or more characters and ? represents it can be replaced by exactly one character
# enter parameter: string = "abbbbcbbc" | pattern = "ab*?b*c"
# return: true
def matchPattern(self, string, pattern):
# paste your script here
return None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.