blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8b9511302a58e785aa41a4b9d0c4b4205cad9e44 | Teanlouise/uqcs_codejam | /uqcs_pizza.py | 1,886 | 4.21875 | 4 | """
The UQCS Committee orders pizza for most of their events. Unfortunately, someone messed up and now all the orders are jumbled! The orders are stored as an array (list) comprised of strings which have a date and the number of pizzas ordered on that date. The treasurer needs the pizza orders to be sorted from the oldest order to the newest so that it can be added to the ledger easily! Help the treasurer solve this: return an array (list) where the pizza orders are sorted in ascending order (oldest first).
Input Format: Array (list) of strings, where each string is of the format date num_pizzas.
Date in each string is formatted as MM-DD-YYYY.
Constraints: Array (list) is of size , where
Output Format: Array (list) of strings, sorted with oldest orders first.
"""
import math
import os
import random
import re
import sys
from datetime import datetime
orders = ['10-28-2013 53', '05-24-2017 41', '06-06-2013 40', '10-20-2019 18', '06-15-2016 44', '02-07-2012 59']
def sort_pizza_orders(orders):
"""
Sort unorded array of strings with order date and number of pizzas.
param:
orders(arr): Strings with format 'MM-DD-YYYY ##'
return:
array: Strings in desc chronological order
"""
# Split each entry in orders into tuples
order_tuple = [tuple(map(str, i.split())) for i in orders]
# Create a dictionary with the date as key and number of pizzas as value
order_dict = dict(order_tuple)
# Convert date into 'datetime' type & sort dict using date in reverse order
ordered_data = sorted(order_dict.items(),
key = lambda x:datetime.strptime(x[0], '%m-%d-%Y'), reverse=False)
# Change dictionary back into string
sorted_orders = [' '.join(tups) for tups in ordered_data]
return(sorted_orders)
# Run sample
sample = sort_pizza_orders(orders)
mystring = '\n'.join(sample)
print(mystring)
|
cb7f8d536aef8b62705203d08ae9c3006fc98392 | gmichaeljaison/interview-questions | /probs/misc/linked_list.py | 1,201 | 4.15625 | 4 | from ds.linked_list import Node, print_linkedlist
"""
Q: Reverse a linked list
"""
def reverse(root):
rev = None
i = root
j = root.next
while j is not None:
i.next = rev
rev = i
i = j
j = i.next
i.next = rev
rev = i
return rev
def test_reverse():
a = Node(1, Node(2, Node(3, Node(4, None))))
b = reverse(a)
print_linkedlist(b)
"""
Q: Check whether a linked list is a palindrome or not
"""
def check_palindrome(root, root_rev):
if root is None:
return root_rev
rev = check_palindrome(root.next, root_rev)
if rev and rev.value == root.value:
if rev.next is None:
return True
else:
return rev.next
else:
return None
def is_palindrome(root):
return check_palindrome(root, root)
def test_is_palindrome():
a = Node(1, Node(2, Node(3, Node(2, Node(1, None)))))
print_linkedlist(a)
print(is_palindrome(a))
a = Node(1, Node(2, Node(2, Node(1, None))))
print_linkedlist(a)
print(is_palindrome(a))
a = Node(1, Node(2, Node(3, Node(3, Node(1, None)))))
print_linkedlist(a)
print(is_palindrome(a))
test_is_palindrome()
|
c5573d0511f379a71f3ca976a8b03af9a8fbadd6 | MWalega/my_projects | /cracking_the_coding_interview_algorythms/chapter_4/4.1.2.py | 770 | 3.953125 | 4 | # 4.1 Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a
# route between two nodes.
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited[v] = True
print(v, ' ')
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)
def DFS(self, v):
visited = [False] * (max(self.graph) + 1)
return print(visited)
self.DFSUtil(v, visited)
g = Graph()
edges = [(1,2),(2,3),(2,4),(3,3),(4,4)]
for edge in edges:
g.add_edge(edge[0], edge[-1])
print(g.graph)
g.DFS(2) |
c80dd808b1a5cb2c9050c04016d51b2123d606ea | x59272796/280201065 | /lab4/zeros.py | 172 | 3.921875 | 4 | a = int(input("insert a number "))
ten = 10
numOfZeros = 0
while a % ten == 0 :
numOfZeros += 1
ten *= 10
print(str(a) + " has " + str(numOfZeros) + " trailing zeros.") |
9454ff643e158110b87b7382104dadd62738a736 | infomuscle/algorithms-leetcode | /leetcode-python/27. Remove Element.py | 439 | 3.578125 | 4 | # 제출 코드 - Runtime 82.84 Memory 100
class Solution:
def removeElement(self, nums, val):
for i in range(len(nums)):
if nums[0] != val:
nums.append(nums[0])
del nums[0]
else:
del nums[0]
return len(nums)
sample1 = [3,2,2,3]
sample2 = [0,1,2,2,3,0,4,2]
sol = Solution()
print(sol.removeElement(sample1,3))
print(sol.removeElement(sample2,2)) |
30d60f5de17c3856a4961bfa23777d3994a1dcd2 | makubex01/python_lesson | /SalineConcentration/test1.py | 484 | 3.5 | 4 | #coding:utf-8
#食塩水を計算するクラス
class saline:
def __init__(self,salt,water):
self.salt = salt
self.water = water
self.calcSaline()
def calcSaline(self):
''' 食塩水を計算する '''
self.saline = self.salt + self.water
def printCount(self):
''' 結果を表示する '''
print("食塩水の重さ(g)=",self.saline)
#1
q1 = saline(salt = 8, water = 100)
q1.printCount() |
ab4c59f71b90463a38e10b125b5acb5ec8e59a9a | dzvid/aqs-sensor-node | /src/sensor_node/communication_module/message.py | 1,710 | 3.640625 | 4 | import json
from environs import Env
env = Env()
env.read_env()
class Message:
"""
A class that represents a message to be sent over DTN.
A message have following attributes:
- payload (String): A JSON string to be sent over the network;
- custody (Boolean): A boolean flag indicating if DTN custody
will be used.
By default, custody is False. Set to True to enable it for a message;
- lifetime (int): Message lifetime in seconds;
"""
def __init__(self, payload=None, custody=False, lifetime=None):
self.payload = payload
self.custody = custody
self.lifetime = lifetime
@property
def custody(self):
return self._custody
@custody.setter
def custody(self, value):
self._custody = value
@custody.getter
def custody(self):
return self._custody
@property
def lifetime(self):
return self._lifetime
@lifetime.setter
def lifetime(self, value):
if not isinstance(value, int):
raise ValueError("Lifetime must be an integer")
self._lifetime = value
@lifetime.getter
def lifetime(self):
return self._lifetime
@property
def payload(self):
return self._payload
@payload.setter
def payload(self, value):
if not self._is_json(str_json=value) or value is None:
raise ValueError("Payload must be a JSON string")
self._payload = value
@payload.getter
def payload(self):
return self._payload
def _is_json(self, str_json):
try:
json.loads(str_json)
except ValueError:
return False
return True
|
b457a77ac2e35c52957f4686890d59afce0456ea | NileshwarShukla/MLandDeepLearning | /InterquartileRange.py | 508 | 3.671875 | 4 | def median(arr):
#print arr
l= len(arr)
if l%2==1:
median=arr[l//2]
else:
median=sum(arr[l//2-1:l//2+1])/2
return median
#6
#6 12 8 10 20 16
#5 4 3 2 1 5
leng=int(input())
arr=map(int,raw_input().split(' '))
freq=map(int,raw_input().split(' '))
lis=[]
for i in range(0,leng):
lis.extend([arr[i]]*freq[i])
leng=len(lis)
lis.sort()
#print lis
q1=median(lis[:leng//2])
if leng%2==0:
q3=median(lis[leng//2:])
else:
q3=median(lis[leng//2+1:])
print round(q3-q1,1)
|
db219a6199721ad89965a911cb8ff42603d38767 | Miguelvarma/Lab22_2303 | /ejer1,5.py | 69 | 3.53125 | 4 | for i in range(5):
print ("ahora i vale",i,"y su cuadrado:",i**2) |
3885622464cc1cebb928fbffb93df98a16049aa3 | SouzaCadu/guppe | /Secao_07_Colecoes/07_38_module_collections_default_dict.py | 599 | 4.1875 | 4 | """
Módulo Collections - Default Dict
Com Default Dict, ao criar um dicionário, podemos informar um valor padrão de chave usando uma função lambda
evitando que o programa retorne um erro caso a chave não exista
"""
# Criando um dicionário
dicionario = {"instrutor": "Geek University", "curso": "Programação em Python Essencial"}
print(dicionario["instrutor"])
# print(dicionario["plataforma"]) - retorna uma KeyError
# Usando o defaultdict para evitar erros
from collections import defaultdict
dicionario1 = defaultdict(lambda: 0)
print(dicionario1["plataforma"])
print(dicionario1)
|
57cc68c9dcca47ac7298a29dfa3464b0911d75f5 | fauzihafsar/Learn-with-Tutorial | /learning start.py | 635 | 4.03125 | 4 | print('belajar python pemula')
x = 5
y = 10
print(x + y)
f = "fauzi"
h = "hafsar"
print(f + h)
print(f + " " + h)
print("'ayo pergi' kata budi")
print('ini hari jum\'at')
print("ini paragraph pertama \n ini paragraph kedua")
print("nama : \t fauzi")
c = 'babydoll'
print(c.capitalize())
b = 'babydoll'
print(b.replace('baby', 'sex'))
a = 4
b = 7
print(a + b)
print(min(a,b))
print(max(a,b))
print(max(a,b,10,15,2))
print(min(a,b,10,15,2))
print(round(9.27))
import math
print(math.pi)
print(math.cos(0))
rupiah = 5000
print('harga buku :', rupiah)
print('harga buku : ' + str(rupiah))
|
047044b4ffc585a11607028c9c60827254fdb9f9 | GabrielBrotas/Python | /modulo 3/exercicios/Ex093 - Jogador de futebol.py | 920 | 3.90625 | 4 | # Programa que leia gerencie o aproveitamento de um jogador de futebol, leia o nome do jogador e quantas partidas ele jogou.
# Depois vai ler a quantidade de gols feitas em cada partida, No final tudo isso sera mostrado em um dicionario,
# incluindo o total de gols feitos durante o campeonato
dados = {'nome': str(input('Digite o nome do jogador: ')).strip().title()}
qtd = int(input(f'Quantas partidas {dados["nome"]} jogou? '))
gols = []
for c in range(0, qtd):
gols.append(int(input(f' Quantos gols na partida {c}: ')))
dados['gols'] = gols[:]
dados['total'] = sum(gols)
print('=-'*20)
print(dados)
print('=-'*20)
for v, n in dados.items():
print(f'O campo {v} tem valor {n}')
print('=-'*20)
print(f'O jogador {dados["nome"]} jogou {len(dados["gols"])} jogos: ')
for i, v in enumerate(dados["gols"]):
print(f' =>na partida {i} fez {v} gols.')
print(f'Foi um total de {dados["total"]} gols')
|
d0a2b5b93cc6d80743c032abd6cb81df82259600 | xDannyCRx/Daniel | /IVA practice #1 lession 2.py | 147 | 3.71875 | 4 | producto=input('Producto a calcular')
precio=float(input('precio'))
IVA=precio*0.13
Total=precio+IVA
print('El IVA es',IVA)
print('EL total',Total) |
026f1e3ea70d7c3e91dae6e7df491a79b2b936a6 | VictoriqueCQ/LeetCode | /Python/845. 数组中的最长山脉.py | 617 | 3.5 | 4 | class Solution:
def longestMountain(self, A: List[int]) -> int:
n = len(A)
ans = left = 0
while left + 2 < n:
right = left + 1
if A[left] < A[left + 1]:
while right + 1 < n and A[right] < A[right + 1]:
right += 1
if right < n - 1 and A[right] > A[right + 1]:
while right + 1 < n and A[right] > A[right + 1]:
right += 1
ans = max(ans, right - left + 1)
else:
right += 1
left = right
return ans
|
57df1bdc9ce7c1da188bebb1ac50d8c8920791ed | Sandy4321/Auto-PDF-Scraper | /scripts/date_scraper.py | 1,450 | 3.625 | 4 | import datefinder
import datetime
import os
def date_scraper():
with open("scrape.txt", 'r') as file1:
text1 = file1.read()
string_with_dates = text1
matches = datefinder.find_dates(string_with_dates)
for match in matches:
print match
saving = raw_input("Would you like to save these as 'dates.txt'? Note: this will overwrite previous saves. Type 'y' for yes and 'n' for no.")
if saving == "y":
text_file1 = open("dates.txt", "w")
string_with_dates = text1
matches = datefinder.find_dates(string_with_dates)
for match in matches:
string_dates1 = (str(match))
text_file1.write(string_dates1 + '\n')
text_file1.close()
pdf_again = raw_input("Save successful! Would you like to scrape another PDF?")
if pdf_again == "y":
os.system("python pdf_scraper.py")
exit(0)
if pdf_again == "n":
print "Bye!"
exit(0)
else:
print "Please enter a valid input."
if saving == "n":
pdf_again = raw_input("Would you like to scrape another PDF?")
if pdf_again == "y":
os.system("python pdf_scraper.py")
exit(0)
if pdf_again == "n":
print "Bye!"
exit(0)
else:
print "Please enter a valid input."
else:
print "Please enter a valid input."
date_scraper()
|
808a876017b1c7fca265d5bf8610f89105077a4a | surajshrestha-0/python-Basic-II | /Question5.py | 905 | 4.75 | 5 | """
Create a tuple with your first name, last name, and age.
Create a list, people, and append your tuple to it.
Make more tuples with the corresponding information from your friends and append them to the list.
Sort the list.
When you learn about sort method, you can use the key parameter to sort by
any field in the tuple, first name, last name, or age.
"""
name_tuple = ('Suraj', 'Shrestha', 22)
people = []
# appending name_tuple to empty list
people.append(name_tuple)
print(people)
# appending information from friends
people.append(('Ram', 'Shahi', 20))
people.append(('Shyam', 'Chhetri', 19))
people.append(('Binod', 'Dangol', 24))
people.append(('Krishna', 'Shakya', 24))
# sorted list based on first name
print(sorted(people, key=lambda x: x[0]))
# sorted list based on last name
print(sorted(people, key=lambda x: x[1]))
# sorted list based on age
print(sorted(people, key=lambda x: x[2]))
|
22e5057a4241b98b0b3420c7f12f36392ca2e71d | ziggyt/SofiaTenta2 | /Tenta.py | 2,383 | 3.78125 | 4 | # Skriv en funktion upprepa(s,n) som skriver ut strängen s på skärmen n gånger, en gång per rad
def upprepa(s,n):
# i kan du döpa till vad du vill, det är en "varvräknare" som börjar på 0. in range betyder för "i intervallet"
"""En funktion som upprepar strängen s för ett antal n gånger.""" #Detta är en docstring
for i in range(0, n):
print(s)
upprepa("Hej", 5)
# 2.Dokumentera funktionen upprepa(s,n)ovan med hjälp av en lämplig docstring
# skriv 3 citattecken följt av en beskrivning och stäng med 3 citatteckken
print (upprepa.__doc__)
#3.Gör ett dialogskript som ber användaren skriva in sin ålder i år och sedan skriver ut åldern i dagar på skärmen.
# AVKOMMENTERA DENNA FÖR ATT DEN SKA FRÅGA OM ÅLDER (TA BORT # FRÅN RADEN NEDAN)
# ålder = input("Skriv din ålder i år : ")
# inputen blev en sträng och du kan inte ta en sträng gånger ett tal så du får omvandla med int(detduvillomvandla)
#print(int(ålder)*365)
# Skriv en funktion räkna(symb,s) som returnerar antalet gånger som symbolen symb förekommer i strängen s.
fraser = ["hejsan", "svejsan", "tja"]
for hälsningar in (fraser):
print(hälsningar)
def räkna(symb,s):
counter = 0
for letter in (s):
if letter == symb:
counter+=1
return counter
print(räkna("s", "sofias snurr"))
#Skriv en funktion fib(n)som returnerar tal nummern i Fibonaccis talföljd 0,1,1,2,3,5,8,13,... där nästa tal fås genom att summera de båda föregående talen
# 5 8 13 21 34
def F(n):
if n == 0: return 0
elif n == 1: return 1
else: return F(n-1)+F(n-2)
############################
## bokstavligt talat en ordlista (dictionary)
ordlista = {
"Ost" : "Cheese",
"Hund" : "Dog",
"Swag" : "Idiot"
}
##för att hämta ord använd funktionen "get" som alla dictionarys har
## hämtar motsvarande ord i ordlistan
print(ordlista.get("Ost"))
print(ordlista)
print("Nu har vi ändrat på den") #genom att "poppa" så tar vi bort det översta i listan, alltså har vi nu ändrat på dictionaryn
ordlista.pop("Ost") #vi behöver inte tilldela den igen genom att ta ordlista = ordlista.pop("Ost)
print(ordlista)
vårsträng = "en mening"
vårsträng.capitalize()
print (vårsträng)
## man kan alltså inte ändra direkt på strängen, du måste tilldela den igen
vårsträng = vårsträng.capitalize()
|
e5337163fbff94678da65494f037c9d9edca2dc3 | RenatoMartinsXrd/UriOnlineJudge-Solutions | /Python/A_NivelIniciante/Exercicio_2863.py | 410 | 3.640625 | 4 | contador = 0
menor = 0
anterior = 0
numeroTeste = int(input())
while True:
try:
if contador<numeroTeste:
contador = contador + 1
atual = float(input())
menor = atual if atual<anterior else menor
anterior = atual
else:
contador = 0
print(menor)
numeroTeste = int(input())
except EOFError:
break
|
f4a61c4a96bf44dbd591cffe48e6d18f7b881503 | srfunksensei/think-python | /exercise6/exercise6.7.py | 321 | 4.375 | 4 | def is_power(a, b):
"""A number, a, is a power of b if it is divisible by b and a/b is a power of b."""
if b <= 0:
return False
if a % b == 0:
if a == b:
return True
else:
return is_power(a/b, b)
return False
print(is_power(29, 3))
print(is_power(8, 2))
|
fe71037266e614af5986538bf632863346408380 | qianjing2020/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 800 | 4.21875 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
# base case no th in word
search = 'th'
len1 = len(search)
len2 = len(word)
# special case: word = []
if len2 == 0:
return 0
# base case: word has less letter than th:
if len2 < len1:
return 0
# recursve case, start from first len1 in word
# if search match first two character, add 1
if search == word[0:len1]:
return 1 + count_th(word[1:])
# otherwise, search the right by jump to the next character
else:
return count_th(word[1:])
|
59b509ca2f287c9e7fa4afca7bc1553f0fdd74ad | zhujixiang1997/6969 | /7月11日/练习03.py | 116 | 3.671875 | 4 | a=float(input('请输入:'))
b=float(input('请输入:'))
if a%b==0 or a+b>1000:
print(a)
else:
print(b) |
8062f3919d117c7b39f3da5f8e3fcf16057c96a1 | crazykuma/leetcode | /python3/0011.py | 762 | 3.65625 | 4 | from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
# 双指针解法
maxpool = float("-inf")
i = 0
j = len(height)-1
while i < j:
# 矩形公式,长=(j-i),宽=最短边的长
poolsize = (j-i)*min(height[i], height[j])
maxpool = max(maxpool, poolsize)
if height[i] < height[j]:
# 因为每次长都会缩减1,那么要让水变多
# 关键在于让最短边更长,增加的面积=(j-i-1)*(height1-height2)
i += 1
else:
j -= 1
return maxpool
if __name__ == "__main__":
s = Solution()
print(s.maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]))
|
9d014a9b9c2322add9d8bc980946fb9a0f876c5d | Sushmita-08june/cat | /Mean_Meadian_Mode.py | 948 | 4.03125 | 4 | #Finding mean of array (average of array numbers)
n_num = [2, 5, 6, 7, 8]
n = len(n_num)
meanofn_num = sum(n_num) / n
print(meanofn_num)
#or
from statistics import mean
n_num = [2, 5, 6, 7, 8]
print(mean(n_num))
#Median of array (middle number after arranging small value to bigger value from left to right)
A = [4, -4,-2,-1, 0, 5, 8]
A.sort()
n = len(A)
if n % 2 == 0:
median1 = A[n//2]
median2 = A[n//2 -1]
median = (median1 + median2) / 2
else :
median = A[n//2]
print('median of A is', median)
#or
from statistics import median , median_low, median_high
A = [1 , 2 , 3 , 4 , 5, 6]
print('Median of data-set A is %s ' % (median(A)))
print('Median low is % s' % (median_low(A)))
print('Median high is % s' % (median_high(A)))
#Mode of the array
from statistics import mode, multimode
B = [1, 2, 5, 1, 1, 3, 2, 2,2, 3]
C = ('aabbbbbccdddddfffffg')
print(mode(B))
print(multimode(C))
|
c7969c041d3f61292f3440be5c5ff63c85a6a0b7 | mahatmaWM/leetcode | /leetcode/editor/cn/329.矩阵中的最长递增路径.py | 1,803 | 3.671875 | 4 | #
# @lc app=leetcode.cn id=329 lang=python3
#
# [329] 矩阵中的最长递增路径
#
# https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix/description/
#
# algorithms
# Hard (40.91%)
# Likes: 193
# Dislikes: 0
# Total Accepted: 14.6K
# Total Submissions: 35.6K
# Testcase Example: '[[9,9,4],[6,6,8],[2,1,1]]'
#
# 给定一个整数矩阵,找出最长递增路径的长度。
#
# 对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
#
# 示例 1:
#
# 输入: nums =
# [
# [9,9,4],
# [6,6,8],
# [2,1,1]
# ]
# 输出: 4
# 解释: 最长递增路径为 [1, 2, 6, 9]。
#
# 示例 2:
#
# 输入: nums =
# [
# [3,4,5],
# [3,2,6],
# [2,2,1]
# ]
# 输出: 4
# 解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。
#
#
#
# @lc code=start
class Solution:
# 思路:dfs,memo[i][j]记录从i j节点能走的最长路径。
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
if not matrix or not matrix[0]: return 0
row = len(matrix)
col = len(matrix[0])
memo = [[0] * col for _ in range(row)]
def dfs(i, j):
nonlocal memo
if memo[i][j] != 0: return memo[i][j]
res = 1
for x, y in [[-1, 0], [1, 0], [0, 1], [0, -1]]:
tmp_i = x + i
tmp_j = y + j
if 0 <= tmp_i < row and 0 <= tmp_j < col and matrix[tmp_i][tmp_j] > matrix[i][j]:
res = max(res, 1 + dfs(tmp_i, tmp_j))
memo[i][j] = max(res, memo[i][j])
return memo[i][j]
return max(dfs(i, j) for i in range(row) for j in range(col))
# @lc code=end
|
0d5f02549551ff184d241f13eceec310fd41cb75 | cristyferbrunoc/coursera | /SetimaSemana/Primario/LarguraAltura.py | 186 | 3.984375 | 4 | largura = int(input('Digite a Largura: '))
altura = int(input('Digite a Altura: '))
for linha in range(altura):
for coluna in range(largura):
print('#', end="")
print()
|
6ddd48c1bca2eb2a73e6d9584a911635b9df9d13 | rafaelperazzo/programacao-web | /moodledata/vpl_data/148/usersdata/276/86438/submittedfiles/testes.py | 195 | 3.859375 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
dolares = float(input('Digite o valor de dolares: '))
cotacao = float(input('Digite o valor de ano cotacao: '))
reais = dolares*cotacao
print (reais) |
d285e63d111e775be956f45814ea13f1cb16ff62 | Tele-Pet/informaticsPython | /Homework/Week 2/Assignment2.3_v1.py | 591 | 4.375 | 4 | # 2.3 Write a program to prompt the user for hours and rate per hour using
# raw_input to compute gross pay. Use 35 hours and a rate of 2.75 per hour to
# test the program (the pay should be 96.25). You should use raw_input to read
# a string and float() to convert the string to a number. Do not worry about
# error checking or bad user data.
# Ask user for hours and convert to float
hours = float(raw_input('How many hours? '))
# Ask user for rate and convert to float
rate = float(raw_input('What is the rate? '))
# Compute pay
pay = hours * rate
stringPay = str(pay)
print stringPay
|
2bcb35cb6ac57cbd31225abdc1dd2eafe71e08c5 | k0syan/Kattis | /tri.py | 799 | 3.6875 | 4 | if __name__ == "__main__":
tmp = input().split()
x, y, z = int(tmp[0]), int(tmp[1]), int(tmp[2])
if x == y / z:
s = str(x) + "=" + str(y) + "/" + str(z)
print(s)
elif x == y * z:
s = str(x) + "=" + str(y) + "*" + str(z)
print(s)
elif x == y + z:
s = str(x) + "=" + str(y) + "+" + str(z)
print(s)
elif x == y - z:
s = str(x) + "=" + str(y) + "-" + str(z)
print(s)
elif x * y == z:
s = str(x) + "*" + str(y) + "=" + str(z)
print(s)
elif x / y == z:
s = str(x) + "/" + str(y) + "=" + str(z)
print(s)
elif x + y == z:
s = str(x) + "+" + str(y) + "=" + str(z)
print(s)
elif x - y == z:
s = str(x) + "-" + str(y) + "=" + str(z)
print(s)
|
3128fe50feea5322083f0f98f76fd26a96a150bc | Aqdas/Sample | /python-course/bool_check_exercise.py | 221 | 4.15625 | 4 | my_age = 32
user_age = int (input ("Please enter your age: "))
if (user_age > my_age):
print ("You are older than you")
elif (user_age == my_age):
print ("We are age fellows")
else:
print ("You are younger than me") |
e7966abf6918b4c0321fc94c947b97ab407c86d5 | brunofonsousa/python | /cursoemvideo/desafios/Desafio034.py | 480 | 3.8125 | 4 | '''
Escreva um programa que pergunte o salário de um funcionário e calcule o
valor do seu aumento. Para salários superiores a R$1250,00, calcule um
aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%.
'''
salario = float(input('Digite o salário do funcionário: '))
if salario > 1250:
novosal = salario + salario / 100 * 10
else:
novosal = salario + salario / 100 * 15
print('Quem ganhava R$ {:.2f} passa a ganhar R$ {:.2f}'.format(salario, novosal))
|
66d914d8a7df1d436a0762db8f170163a8a2e378 | hackergong/Python-TrainingCourseLearning | /day008/6-析构函数/析构函数.py | 1,089 | 4.21875 | 4 |
'''
析构函数:__del__() #释放对象是自动调用
'''
class Person(object):
def run(self):
print("run")
def eat(self,food):
print("I have eat "+food)
# 默认存在,但不显示存在
def say(self):#self代表类的实例
#下面方法中self代表per1对象
print("Hello! my name is %s,I am %d years old" % (self.name,self.age))#
#self不是关键字,其他标识符也可以,但是统一用self
def play(self):
print("play"+self.name)
def __init__(self,name,age,height,weight):
#定义属性
self.name = name
self.height = height
self.weight = weight
self.age = age
def __del__(self):
print("这里是析构函数")
per = Person("Tom",20,10,40)
#当程序结束,则执行__del__
#释放对象
del per
#对象释放以后不可再访问
# print(per.age)
#在函数里定义的对象,会在函数结束时自动释放,
# 这样可以用来减少内存空间的浪费
def func():
per2 = Person("aa",1,1,1)
func()
while 1:
pass
|
71869dbfcfd836b0c79a6c2c67e0a68806100ff4 | sebasvj12/CodigoComentado | /main.py | 1,638 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 13 10:28:40 2019
@author: (╯°□°)╯︵ ┻━┻
"""
import ArreglarCSV as ac # Importa el codigo ArreglarCSV y le asigna el nombre ac
import FiabilidadCronbach as fc # Importa el codigo FiabilidadCronbach y le asigna el nombre fc
class Main: # Inicio clase Main
def __init__(self): # Clase Init
self.alfaCronbach = 0 # Se instancia alfaCronbach
def seleccion(self, numero): # Funcion selección, se envía parámetro numero
if numero == 1: # Inicio de sentencia condicional if
ac.ArreglarCSV() # Si es 1 el objeto ac inicia la función ArreglarCSV
elif numero == 2: # Opcion 2 del codicional
fc.FiablidadCronbach() # Si es 2 el objeto fc inicia la función resultado()
self.alfaCronbach = fc.FiablidadCronbach().resultado()
print(self.alfaCronbach)
# Fin funcion selección
if __name__ == "__main__": # Condicional iniciado
print("John Sebastian Martinez Zabala")
print("Universidad Distrital Francisco Jose de Caldas")
opcion = 0
while opcion >= 0: # Mientras la opción sea 0 o mayor permanece en el ciclo
Main()
print('Para crear CSV escriba 1:')
print('Para calcular alfa de crombach:')
print('Para salir ponga 0:')
opcion = int(input('selecciona una opción\n')) # Recibe la opcion ingresada como entero
opcion = int(opcion)
Main().seleccion(opcion) # Inicia funcion seleccion de acuerdo a opcion seleccionada
if (opcion == 0):
opcion = -1 # Sale del ciclo while
|
015ca15767028e0e19f4defa7bb1b55a532e9368 | UmuhireAnuarithe/Login | /test.py | 920 | 3.5 | 4 | import unittest
from sigin import User
class testing (unittest.TestCase):
def setUp(self):
self.newuser= User("Claudine","111")
def test_init(self):
self.assertEqual(self.newuser.username,"Claudine")
self.assertEqual(self.newuser.password,"111")
def saving (self):
self.newuser.saving()
self.assertEqual(len(User.user_list),1)
def test_delete(self):
User.user_list.remove(self)
# def test_user_exists(self):
self.newuser.saving()
test_user = User("claudine","111")
test_user.saving()
self.newuser.delete()
self.assertTrue(len(User.user_list),1)
def test_display(self):
self.newuser.saving()
test_user = User("claudine","111")
test_user.saving()
self.assertTrue(len(User.user_list),2)
if __name__ == '__main__':
unittest.main()
|
6b549b28dd85bd476b40f56439aaf7553176475b | forrestjan/Labos-MCT-19-20 | /2019-prog-labooefeningen-forrestjan/week2/oefening12.py | 883 | 3.640625 | 4 | def vertaal_maandnummer_naar_str(maandnummer):
if maandnummer == 1 :
return "januarie"
elif maandnummer == 2 :
return "februarie"
elif maandnummer == 3 :
return "maart"
elif maandnummer == 4 :
return "april"
elif maandnummer == 5 :
return "mei"
elif maandnummer == 6 :
return "juni"
elif maandnummer == 7 :
return "juli"
elif maandnummer == 8 :
return "augustus"
elif maandnummer == 9 :
return "september"
elif maandnummer == 10 :
return "oktober"
elif maandnummer == 11 :
return "november"
elif maandnummer == 12 :
return "december"
else:
return print("ongeldige maand")
maandnummer = int(input("geef een maandnummer op > "))
print(f"de overeenkomende maand van {maandnummer} is {vertaal_maandnummer_naar_str(maandnummer)}") |
038939fa48984f790c9b58997cc936be054824dd | tippitytapp/Graphs | /projects/DONE_social/utils.py | 4,069 | 3.796875 | 4 | class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
class Stack():
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
def pop(self):
if self.size() > 0:
return self.stack.pop()
else:
return None
def size(self):
return len(self.stack)
class Graph:
def __init__(self):
self.vertices = {}
self.visited = set()
self.path = []
def add_vertex(self, vertex_id):
self.vertices[vertex_id] = set()
def add_edge(self, fromV, toV):
if fromV in self.vertices and toV in self.vertices:
self.vertices[fromV].add(toV)
else:
raise IndexError('vertex (vertices) do not exist in graph, add to graph first')
def get_neighbors(self, vertex_id):
return self.vertices[vertex_id]
def bft(self, starting_vertex):
queue = Queue()
visited = set()
queue.enqueue(starting_vertex)
while queue.size() > 0:
vertex = queue.dequeue()
if vertex not in visited:
visited.add(vertex)
print(vertex)
for next_vertex in self.get_neighbors(vertex):
queue.enqueue(next_vertex)
def dft(self, starting_vertex):
stack = Stack()
visited = set()
stack.push(starting_vertex)
while stack.size() > 0:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
print(vertex)
for next_vertex in self.get_neighbors(vertex):
stack.push(next_vertex)
def dft_recursive(self, starting_vertex):
if starting_vertex not in self.visited:
self.visited.add(starting_vertex)
print(starting_vertex)
for next_v in self.get_neighbors(starting_vertex):
self.dft_recursive(next_v)
def bfs(self, starting_vertex, destination_vertex):
queue = [[starting_vertex]]
visited = []
if starting_vertex == destination_vertex:
return queue
while queue:
path=queue.pop(0)
vertex = path[-1]
if vertex not in visited:
for next_v in self.get_neighbors(vertex):
new_path = list(path)
new_path.append(next_v)
queue.append(new_path)
if next_v == destination_vertex:
return new_path
visited.append(vertex)
return
def dfs(self, starting_vertex, destination_vertex):
stack = [[starting_vertex]]
visited = []
if starting_vertex == destination_vertex:
return stack
while stack:
path = stack.pop(0)
vertex = path[-1]
if vertex not in visited:
for next_v in self.get_neighbors(vertex):
new_path = list(path)
new_path.append(next_v)
stack.insert(0, new_path)
if next_v == destination_vertex:
return new_path
visited.append(vertex)
return
def dfs_recursive(self, starting_vertex, destination_vertex, visited = None, path=[]):
if visited is None:
visited = set()
visited.add(starting_vertex)
path = path + [starting_vertex]
if starting_vertex == destination_vertex:
return path
for next_v in self.get_neighbors(starting_vertex):
if next_v not in visited:
new_path = self.dfs_recursive(next_v, destination_vertex, visited, path)
if new_path:
return new_path
return None
|
96a0dd464c1dc31bf74cb13a2638f62163777d62 | TakeruNishimi/Kadai-B | /circle.py | 677 | 4.15625 | 4 | class Circle:
def __init__(self,radius):
self.radius = radius
def area(self):
return self.radius ** 2 * 3.14
def perimeter(self):
return self.radius * 2 *3.14
def main():
circle1 = Circle(radius=1)
print(f'半径が{circle1.radius}cmの円の面積は{circle1.area()}cm^2です。')
print(f'半径が{circle1.radius}cmの円の円周は{circle1.perimeter()}cmです。')
circle3 = Circle(radius=3)
print(f'半径が{circle3.radius}cmの円の面積は{circle3.area()}cm^2です。')
print(f'半径が{circle3.radius}cmの円の円周は{circle3.perimeter()}cmです。')
if __name__ == '__main__':
main()
|
6c337474b854ad4936246933c996e73428744259 | yang-f/algorithm | /rb_tree.py | 6,272 | 3.625 | 4 | class RBTree:
def __init__(self):
self.nil = RBTreeNode(0)
self.root = self.nil
class RBTreeNode:
def __init__(self, x):
self.key = x
self.left = None
self.right = None
self.parent = None
self.color = 'black'
class Solution:
def InorderTreeWalk(self, x):
if x != None:
self.InorderTreeWalk(x.left)
if x.key != 0:
print 'key:', x.key, 'parent:', x.parent.key, 'color:', x.color
self.InorderTreeWalk(x.right)
def LeftRotate(self, T, x):
y = x.right
x.right = y.left
if y.left != T.nil:
y.left.parent = x
y.parent = x.parent
if x.parent == T.nil:
T.root = y
elif x == x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
def RightRotate(self, T, x):
y = x.left
x.left = y.right
if y.right != T.nil:
y.right.parent = x
y.parent = x.parent
if x.parent == T.nil:
T.root = y
elif x == x.parent.right:
x.parent.right = y
else:
x.parent.left = y
y.right = x
x.parent = y
def RBInsert(self, T, z):
# init z
z.left = T.nil
z.right = T.nil
z.parent = T.nil
y = T.nil
x = T.root
while x != T.nil:
y = x
if z.key < x.key:
x = x.left
else:
x = x.right
z.parent = y
if y == T.nil:
T.root = z
elif z.key < y.key:
y.left = z
else:
y.right = z
z.left = T.nil
z.right = T.nil
z.color = 'red'
self.RBInsertFixup(T,z)
def RBInsertFixup(self, T, z):
while z.parent.color == 'red':
if z.parent == z.parent.parent.left:
y = z.parent.parent.right
if y.color == 'red':
z.parent.color = 'black'
y.color = 'black'
z.parent.parent.color = 'red'
z = z.parent.parent
else:
if z == z.parent.right:
z = z.parent
self.LeftRotate(T, z)
z.parent.color = 'black'
z.parent.parent.color = 'red'
self.RightRotate(T,z.parent.parent)
else:
y = z.parent.parent.left
if y.color == 'red':
z.parent.color = 'black'
y.color = 'black'
z.parent.parent.color = 'red'
z = z.parent.parent
else:
if z == z.parent.left:
z = z.parent
self.RightRotate(T, z)
z.parent.color = 'black'
z.parent.parent.color = 'red'
self.LeftRotate(T, z.parent.parent)
T.root.color = 'black'
def RBTransplant(self, T, u, v):
if u.parent == T.nil:
T.root = v
elif u == u.parent.left:
u.parent.left = v
else:
u.parent.right = v
v.parent = u.parent
def RBDelete(self, T, z):
y = z
y_original_color = y.color
if z.left == T.nil:
x = z.right
self.RBTransplant(T, z, z.right)
elif z.right == T.nil:
x = z.left
self.RBTransplant(T, z, z.left)
else:
y = self.TreeMinimum(z.right)
y_original_color = y.color
x = y.right
if y.parent == z:
x.parent = y
else:
self.RBTransplant(T, y, y.right)
y.right = z.right
y.right.parent = y
self.RBTransplant(T, z, y)
y.left = z.left
y.left.parent = y
y.color = z.color
if y_original_color == 'black':
self.RBDeleteFixup(T, x)
def RBDeleteFixup(self, T, x):
while x != T.root and x.color == 'black':
if x == x.parent.left:
w = x.parent.right
if w.color == 'red':
w.color = 'black'
x.parent.color = 'red'
self.LeftRotate(T, x.parent)
w = x.parent.right
if w.left.color == 'black' and w.right.color == 'black':
w.color = 'red'
x = x.parent
else:
if w.right.color == 'black':
w.left.color = 'black'
w.color = 'red'
self.RightRotate(T, w)
w = x.parent.right
w.color = x.parent.color
x.parent.color = 'black'
w.right.color = 'black'
self.LeftRotate(T, x.parent)
x = T.root
else:
w = x.parent.left
if w.color == 'red':
w.color = 'black'
x.parent.color = 'red'
self.RightRotate(T, x.parent)
w = x.parent.left
if w.right.color == 'black' and w.left.color == 'black':
w.color = 'red'
x = x.parent
else:
if w.left.color == 'black':
w.right.color = 'black'
w.color = 'red'
self.LeftRotate(T, w)
w = x.parent.left
w.color = x.parent.color
x.parent.color = 'black'
w.left.color = 'black'
self.RightRotate(T, x.parent)
x = T.root
x.color = 'black'
def TreeMinimum(self, x):
while x.left != T.nil:
x = x.left
return x
nodes = [11,2,14,1,7,15,5,8,4]
T = RBTree()
s = Solution()
for node in nodes:
s.RBInsert(T,RBTreeNode(node))
s.InorderTreeWalk(T.root)
s.RBDelete(T,T.root)
s.InorderTreeWalk(T.root) |
02de1eb2452f1815aad5a722f1e996f647a54c00 | indu15cs009/python | /words.py | 265 | 4.28125 | 4 | while True:
print("enter 'x' for exit");
string=input("enter any string\n")
if string=='x':
break
else:
word_length=len(string.split())
print("number of words\n")
print(word_length)
|
37c295271dfcd7c580ad318d1ef7b86d6f151d9a | songdanlee/python_code_basic | /leecode/sort/冒泡排序.py | 2,431 | 3.75 | 4 | """
冒泡排序:让子序列中的最大元素不断沉底,达到排序的目的。
冒泡排序一共经过N-1次遍历,其中第i次遍历前N-i个元素(第i+1到N个元素已经排序完毕),将第i大的元素移动到N-i的位置
"""
# lists = [2, 4, 1, 3, 0, 100, 23, 60]
#
# for i in range(len(lists) - 1):
# for j in range(0, len(lists) - i - 1):
# lists[j], lists[j + 1] = min(lists[j], lists[j + 1]), max(lists[j], lists[j + 1])
#
# # 优化
# # 如果进行某一趟排序时并没有进行数据交换,则说明所有数据已经有序,可立即结束排序,避免不必要的比较过程
#
# for i in range(len(lists) - 1):
# flag = False
# for j in range(len(lists) - 1 ,i,-1):
# if lists[j] < lists[j - 1]:
# flag = True
# lists[j],lists[j-1] = lists[j-1],lists[j]
# if not flag:
# break
#
# print(lists)
# 选择排序,每次选择一个最小的放在当前未排序序列的首位
lists = [2, 4, 1, 3, 0, 100, 23, 60]
def selection_sort(li):
for i in range(len(li)):
index = li.index(min(li[i:]))
li[i], li[index] = li[index], li[i]
print(li)
# selection_sort(lists)
# arr = [1, 12, 2, 11, 13, 5, 6, 18, 4, 9, -5, 3, 11]
# def insertionSort(arr):
# # 从要排序的列表第二个元素开始比较
# for i in range(1,len(arr)):
# j = i
# # 从大到小比较,直到比较到第一个元素
# while j > 0:
# if arr[j] < arr[j-1]:
# arr[j-1],arr[j] = arr[j],arr[j-1]
# j -= 1
# return arr
# print(insertionSort(arr))
# 通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
# arr = [1, 12, 2, 11, 13, 5, 6, 18, 4, 9, -5, 3, 11]
#
# def insertsort(arr):
# for i in range(1, len(arr)):
# j = i
# while j > 0:
# if arr[j] < arr[j - 1]:
# arr[j], arr[j - 1] = arr[j - 1], arr[j]
# j -= 1
# return arr
#
#
# print(insertsort(arr))
arrx = [1, 12, 2, 11, 13, 5, 6, 18, 4, 2,9, -5, 3, 11]
def quick_sort(arr):
if len(arr) < 0:
return arr
else:
pivot = arr[0]
small_arr = [i for i in arr[1:] if i < pivot]
big_arr = [i for i in arr[1:] if i >= pivot]
return quick_sort(small_arr) + [pivot] + quick_sort(big_arr)
print(quick_sort(arrx))
|
bbbf9e3a115e89bac056cfcb345edb5a1a380f65 | Aurora-yuan/Leetcode_Python3 | /443 压缩字符串/443 压缩字符串.py | 1,750 | 3.703125 | 4 | #label: string difficulty: easy
"""
思路一:
1.首先构建一个字符串用于存放字符和其重复的次数
2.遍历字符串,碰到连续的字符计算其连续次数,如果连续相同字符的个数大于1则还需要把字符串的次数统计减进去
3.最后把构建好的char_str,list一下并顺序用char_str中的字符改变chars对应位置的字符并返回char_str的长度
"""
class Solution:
def compress(self, chars: List[str]) -> int:
string = ""
count = 1
c = len(chars)
if c == 1:
return 1
for i in range(1,c):
if chars[i] == chars[i-1]:
count += 1
else:
if count > 1:
string += chars[i-1] + str(count)
else:
string += chars[i-1]
count = 1
if count > 1:
string += chars[i]+str(count)
else:
string += chars[i]
string = list(string)
chars[::]=string[::] #存回本地
return len(chars)
“”“
思路二:
从后向前遍历,这样在压缩的时候就不用更新索引
”“”
class Solution:
def compress(self, chars: List[str]) -> int:
count = 1
length = len(chars)
for index in range(length-1, -1, -1):
if index > 0 and chars[index] == chars[index-1]:
count += 1
else:
end = index + count
if count == 1:
chars[index:end] = [chars[index]]
else:
chars[index:end] = [chars[index]] + list(str(count))
count = 1
return len(chars)
|
aa84e2ca86bd6ece758860801402ae335fc621be | OmarJabri7/UofG_Robotics_TDP | /Robots/robot_control.py | 481 | 3.734375 | 4 | from abc import ABC, abstractmethod
class Robot(ABC):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def get_action(self, goal):
"""
Generate action based on the goal, state etc.
:param goal:
:return:
"""
pass
@abstractmethod
def accrue_sensors_data(self):
"""
Get information from robot/model an convert it to the robot state
:return:
"""
pass
|
4e72ba327947d95ed32b707594931192efae163a | mazsoltani/Python_Assignment3 | /Practice2_14000515_Non-Repetitive.py | 353 | 3.6875 | 4 | import random
lenght_of_number = int(input("Please Enter Lenght of List= "))
list1= []
for i in range(0,lenght_of_number):
number = random.randint(1,lenght_of_number)
list1.append(number)
#list1.append(number
# Mylist_none_repeat = list(dict.fromkeys(my_list))
print(list1)
finalData = list(set(list1))
print(finalData)
|
2275cbb49916ec2cb311765688977a74064e92ca | coconutragdoll/PythonStudy | /scoregrade.py | 509 | 4.15625 | 4 | #!/usr/bin/env python
print 'Welcome to the grade conversion tool!'
while True:
score = int(raw_input("Enter 999 to exit. Please enter score-->"))
if score == 999:
print 'Have a nice day!'
break
elif score > 100:
print 'Invalid score'
elif score < 0:
print 'Invalid score'
elif score>=90:
print "Grade A"
elif score>=80:
print 'Grade B'
elif score>=70:
print 'Grade C'
elif score>=60:
print 'Grade D'
else:
print 'Grade E'
else:
print 'shouldnot see this'
|
df6a1abb0718118667bb8532b24f14df18527fcb | MMyungji/Algorithm-solving | /programmers/stack_queue/priority.py | 964 | 3.71875 | 4 | def solution(priorities, location):
answer = 0
p = [(v,i) for i,v in enumerate(priorities)]
m = max(priorities)
#print("max: ", m)
while True:
#print(p)
pi = p.pop(0)
#print(pi)
#print(pi[0])
#최대값과 같으면 프린트 출력!
if m == pi[0]:
#출력하므로 answer번째 출력 +1
answer += 1
#출력한 값 제외, 다시 max값 구하기
priorities.pop(0)
m = max(priorities)
#최대값의 인덱스가 내가 요청한 인덱스값과 같음 break!
if location == pi[1]:
break
#최대값보다 작으면
else:
#pop()한 것 맨 마지막에 배치
p.append(pi)
priorities.append(priorities.pop(0))
return answer
p1 = [2, 1, 3, 2]
l1 = 2
print(solution(p1, l1))
p2 = [1, 1, 9, 1, 1, 1]
l2 = 0
print(solution(p2, l2))
|
96e2275a2880379cb3cf57275c5d6e4388ad1ed0 | quangdbui9999/CS-171 | /FinalExam-Python-CS171/Final Exam/20.driving_cost.py | 871 | 4.1875 | 4 |
def driving_cost(number_of_gallons, miles_per_gallon, dollars_per_gallon):
cost = number_of_gallons * (dollars_per_gallon / miles_per_gallon)
return cost
def readFloat(question):
valid = False
while not valid:
try:
x = input(question)
x = float(x)
if(x > 0):
return x
except ValueError as e:
print('Not an float number. Try again.')
gallons = readFloat("Enter a number of gallons in tank: ")
fuel_efficiency = readFloat("Enter the fuel efficiency in miles per gallon: ")
price_per_gallons = readFloat("Enter the price of gas per gallon: ")
print("The cost per 100 miles is: %0.2f." %driving_cost(100, fuel_efficiency, price_per_gallons))
print("The car can go %0.2f miles with amount of gas is %0.2f." %(driving_cost(gallons, fuel_efficiency, price_per_gallons), gallons)) |
cf5a2edb6528ab7124e290ecff143ae98ba9049f | RianRBPS/PythonMundos | /Aulas/Mundo03 - Aulas/Aula16.py | 1,110 | 3.96875 | 4 | #Tuplas são imutáveis
#lanche = (Tupla) [Lista] {Dicionário}
lanche = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim')
print(lanche)
print(lanche[0])
print(lanche[3])
print(lanche[-1])
print(lanche[1:3])
print(lanche[2:])
print(lanche[:2])
print(lanche[-2:])
print(len(lanche))
lanche2 = ('Hambúrguer', 'Suco', 'Pizza', 'Pudim', 'Batata Frita')
print(sorted(lanche2)) #Em ordem
for comida in lanche: #Não tem como mostrar posição
print(f'Eu vou comer {comida}')
for cont in range(0, len(lanche2)):
print(f'Eu vou comer {lanche2[cont]} na posição {cont}')
for pos, comida in enumerate(lanche2): #Posição enumerada
print(f'Eu vou comer {comida} na posição {pos}')
print('Comi pra caramba!')
a = (2, 5, 4)
b = (5, 8, 1, 2)
c = a + b #Ordem dos fatores altera o resultado
d = b + a
print(len(c))
print(d)
print(c)
print(c.count(9)) # Quantas vezes o 9 apareceu
print(c.index(8)) # Em que posição está o 8
print(c.index(5, 1))# Primeiro 5 a partir da posição 1
pessoa = ('Gustavo', 39, 'M', 99.88) # Em java não pode misturar tipos diferentes nas tuplas
del(pessoa) #Deleta a tupla
|
17b14fefdc9b957d04d8cc6f68c76d364700975c | pedrobriton/calculadora-basica-em-python | /calculadora.py | 1,860 | 3.515625 | 4 | from flask import Flask, render_template, request
#########################################
### LOGICA PARA CALCULADORA BASICA ###
### OPERAÇÕES BÁSICAS ###
### SOMAR ###
### SUBTRAIR ###
### MULTIPLICAR ###
### DIVIDIR ###
#########################################
# develope by Pedro Brito #
#########################################
# instanciando a variavel app que sera referencia ao flask
app = Flask(__name__)
# rotas
@app.route('/')
def main():
return render_template('index.html')
@app.route('/send', methods=['POST'])
def send(sum=sum):
if request.method == 'POST':
num1 = request.form['num1']
num2 = request.form['num2']
operation = request.form['operation']
if operation == 'add':
try:
sum = float(num1) + float(num2)
return render_template('index.html', sum=sum)
except Exception:
return "Ocorreu um erro, retorne para pagina inicial"
elif operation == 'subtract':
sum = float(num1) - float(num2)
return render_template('index.html', sum=sum)
elif operation == 'multiply':
sum = float(num1) * float(num2)
return render_template('index.html', sum=sum)
elif operation == 'divide':
sum = float(num1) / float(num2)
return render_template('index.html', sum=sum)
else:
return render_template('index.html')
# falta implementar excessoes para tratar alguns possiveis erros, e melhorar
# o front
# incia o app, no modo de debug
if __name__ == '__main__':
app.debug = True
app.run()
|
bf1fa434f91d008983c4dbc3a36ccf21311204d6 | vreddy2018/problemset0 | /ps0-testcases.py | 4,279 | 4.40625 | 4 | import ps0
#0
print("Odd even examples:")
number = 5
if ps0.odd_even(number):
print("{} is even.".format(number))
else:
print("{} is odd.".format(number))
number = 0
if ps0.odd_even(number):
print("{} is even.".format(number))
else:
print("{} is odd.".format(number))
number = 1
if ps0.odd_even(number):
print("{} is even.".format(number))
else:
print("{} is odd.".format(number))
number = 22
if ps0.odd_even(number):
print("{} is even.".format(number))
else:
print("{} is odd.".format(number))
#1
print("\nDigit counting examples:")
number = 4
print("There is/are {} digit(s) in {}.".format(ps0.digits(number),number))
number = 123
print("There is/are {} digit(s) in {}.".format(ps0.digits(number),number))
number = 36
print("There is/are {} digit(s) in {}.".format(ps0.digits(number),number))
number = 0
print("There is/are {} digit(s) in {}.".format(ps0.digits(number),number))
number = 14223
print("There is/are {} digit(s) in {}.".format(ps0.digits(number),number))
#2
print("\nSum of digits examples:")
number = 4
print("The sum of the digits in {} is {}.".format(number, ps0.sum_digits(number)))
number = 57
print("The sum of the digits in {} is {}.".format(number, ps0.sum_digits(number)))
number = 0
print("The sum of the digits in {} is {}.".format(number, ps0.sum_digits(number)))
number = 902384
print("The sum of the digits in {} is {}.".format(number, ps0.sum_digits(number)))
#3
print("\nSum of integers less than number examples:")
number = 20
print("The sum of the integers less than {} is {}.".format(number, ps0.sum_less_int(number)))
number = 312
print("The sum of the integers less than {} is {}.".format(number, ps0.sum_less_int(number)))
number = 1
print("The sum of the integers less than {} is {}.".format(number, ps0.sum_less_int(number)))
number = 0
print("The sum of the integers less than {} is {}.".format(number, ps0.sum_less_int(number)))
#4
print("\nFactorial examples:")
number = 5
print("{} factorial is {}.".format(number,ps0.factorial(number)))
number = 0
print("{} factorial is {}.".format(number,ps0.factorial(number)))
number = 1
print("{} factorial is {}.".format(number,ps0.factorial(number)))
number = 11
print("{} factorial is {}.".format(number,ps0.factorial(number)))
#5
print("\nChecking factor examples:")
factor =2
if ps0.factor(number, factor):
print("{} is a factor of {}.".format(factor, number))
else:
print("{} is not factor of {}.".format(factor, number))
number = 15
factor = 5
if ps0.factor(number, factor):
print("{} is a factor of {}.".format(factor, number))
else:
print("{} is not a factor of {}.".format(factor, number))
#6
print("\nPrime checking examples:")
if ps0.prime(number):
print("{} is not prime.".format(number))
else:
print("{} is prime.".format(number))
number = 1
if ps0.prime(number):
print("{} is not prime.".format(number))
else:
print("{} is prime.".format(number))
number = 35
if ps0.prime(number):
print("{} is not prime.".format(number))
else:
print("{} is prime.".format(number))
number = 11
if ps0.prime(number):
print("{} is not prime.".format(number))
else:
print("{} is prime.".format(number))
#7
print("\nPerfect numbers examples:")
if ps0.is_perfect(number):
print("{} is perfect.".format(number))
else:
print("{} is not perfect.".format(number))
number = 0
if ps0.is_perfect(number):
print("{} is perfect.".format(number))
else:
print("{} is not perfect.".format(number))
number = 28
if ps0.is_perfect(number):
print("{} is perfect.".format(number))
else:
print("{} is not perfect.".format(number))
number = 1
if ps0.is_perfect(number):
print("{} is perfect.".format(number))
else:
print("{} is not perfect.".format(number))
#8
print("\nSum of digits as a factor examples:")
if ps0.sum_factor(number):
print("The sum of the digits in {} is a factor".format(number))
else:
print("The sum of the digits in {} is not a factor".format(number))
number = 22
if ps0.sum_factor(number):
print("The sum of the digits in {} is a factor".format(number))
else:
print("The sum of the digits in {} is not a factor".format(number))
number = 12
if ps0.sum_factor(number):
print("The sum of the digits in {} is a factor".format(number))
else:
print("The sum of the digits in {} is not a factor".format(number))
|
e83c53ee3ed427db670120e1f83ce2d602dfb4c1 | borislavstoychev/Soft_Uni | /soft_uni_fundamentals/Data Types and Variables/exercises/07_water_overflow.py | 214 | 3.75 | 4 | n = int(input())
total = 0
for i in range(n):
quantity = int(input())
total += quantity
if total > 255:
total -= quantity
print("Insufficient capacity!")
print(total)
|
8d8d39045b3dfdaf7b61456eb374658905a9be6f | tjgran01/cfilemanual | /cfilemanual/scripts/python/pan_qualtrics.py | 13,508 | 3.671875 | 4 | import pandas as pd
import os
import getpass
import csv
import sys
import get_qualtrics
from inputmanager import InputManager
def clean_getaway():
"""Displays a prompt to the user and then exits the program.
Args:
None
Returns:
None"""
print("Something has gone wrong - either your survey questions are not"
" evenly spaced throughout your study, or some other error has "
" taken place that will make parsing automatically difficult."
" The program is now closing.")
sys.exit()
def get_cleaned_df(col_to_drop, marking=False):
"""Strips the qualtrics survey off all the columns and rows not needed
to generate conditions files.
Args:
col_to_drop(list): List of string column heading that can be removed
from the df.
Returns:
df: df with the unneeded columns dropped."""
file_name = str(os.listdir(f"{os.getcwd()}/MyQualtricsDownload/"))[2:-2]
df = pd.read_csv(f"{os.getcwd()}/MyQualtricsDownload/{file_name}")
#cleaning
df.drop(col_to_drop, axis=1, inplace=True)
headcol = df.iloc[0]
df.columns = headcol
df.drop(1, axis=0, inplace=True)
if marking:
# Strip off pre-lims:
num_prelim_qs = get_prelim_qs(df)
cols_to_remove = headcol[:num_prelim_qs]
df.drop(cols_to_remove, axis=1, inplace=True)
return df
def get_slice_strings(df):
"""Tries to locate the strings (question text) that the program needs in
order to properly parse the qualtrics survey data.
Args:
df: a DataFrame of the qualtrics data export.
Returns:
first_q(str): The first question in the survey.
slice_prompt: The first question in the repeated survey that the
participant is given after completing an experimental task."""
first_q = find_first_q(df)
if not first_q:
print("First question not able to be located, using default.")
first_q = "(For Experimenter) Please Enter Participant ID."
slice_prompt = find_slice_prompt(df)
if not slice_prompt:
print("slice_prompt not able to be located, using default.")
slice_prompt = ("(For Experimenter) Please select the corresponding"
" task number referring to the task the particip...")
return (first_q, slice_prompt)
def find_first_q(df):
"""Asks the user if the first question left over in the cleaned df is the
first question of their survey. It also informs that user that the first
question should be in the question asking for the participant's ID.
Args:
df: a (cleaned) DataFrame of the qualtrics data export.
Returns: None"""
try:
first_q = df.iloc[0][0]
except:
return None
ans = InputManager.get_yes_or_no("\033[1m CHECKING FIRST QUESTION:"
f"\n\n'{first_q}'\033[0m\n\n"
"is the above the first survey question "
"in your survey?: (Y/n) \n\n"
"\033[1mNOTE:\033[0m This question should "
"be asking for the experimenter to enter "
"the participant's ID number.")
if ans:
return first_q
else:
clean_getaway()
def get_slice_prompt_index(df):
"""Calls a series of functions that ask for user input in order to determine
what question is the first in the series of questions given to a participant
after each task is completed.
Args:
df: A cleaned DataFrame of the Qualtrics export.
Returns:
num_of_tasks(int): The number of surveys the participant completed.
task_amount(int): The number of questions in each survey.
num_prelim_qs(int): The number of questions before the experiment began.
"""
total_q = len(df.iloc[0])
num_prelim_qs = get_prelim_qs(df)
num_sur_q = total_q - num_prelim_qs
task_amount = ask_user_task_amount(df, num_sur_q)
num_of_tasks = num_sur_q / task_amount
if num_of_tasks.is_integer():
int(num_of_tasks)
return (num_of_tasks, task_amount, num_prelim_qs)
clean_getaway()
def get_prelim_qs(df):
"""Asks the user to input the amount of questions in the survey that do not
correspond to survey questions given to the participant (preliminary
questions).
Args:
df: A cleaned DataFrame of the Qualtrics export.
Returns:
num_prelim_qs(int): The number of questions before the experiment began.
"""
num_prelim_qs = InputManager.get_numerical_input("How many preliminary "
"questions were asked "
"before the experiment "
"began?: ", 9)
return num_prelim_qs
def ask_user_task_amount(df, num_sur_q):
"""Asks for user input to determine how many surveys were given to the
participant in the study.
Args:
df: A cleaned DataFrame of the Qualtrics export.
num_sur_q(int): Total number of questions asked in surveys.
Returns:
task_amount(int): The number of questions in each survey.
"""
poten_task_amts = [x for x in range(2, 30) if num_sur_q % x == 0]
if len(poten_task_amts) > 1:
print(f"Judging by the numbers, it looks like there are multiple ways"
" in which these questions could be broken up. Please answer the"
" question(s) below to continue to attempt to parse the data.\n")
for poten_task_amt in poten_task_amts:
ans = InputManager.get_yes_or_no(f"Where there {poten_task_amt} "
"total tasks in your study?")
if ans:
task_amount = poten_task_amt
return task_amount
break
elif len(poten_task_amts) == 1:
ans = InputManager.get_yes_or_no(f"There were {poten_task_amts} in your"
" study? (Y/n): ")
if not ans:
clean_getaway()
task_amount = poten_task_amts[0]
return task_amount
else:
clean_getaway()
def find_slice_prompt(df):
"""Finds the string value that the script will use to slice the survey data
up by - the first question asked in the beginning of each survey.
Args:
df: A cleaned DataFrame from the Qualtrics export.
Returns:
slice_prompt(str): The string value of the first survey question in each
survey."""
questions_list = df.iloc[0].tolist()
num_of_q_per_task, num_of_tasks, num_prelim_qs = get_slice_prompt_index(df)
print(f"There were {int(num_of_q_per_task)} questions per task.")
print(f"There were {num_of_tasks} tasks total")
print(f"The first {num_prelim_qs} were preliminary questions.")
slice_prompt = questions_list[num_prelim_qs]
ans = InputManager.get_yes_or_no("\033[1m CHECKING FIRST SURVEY QUESTION:"
f"\n\n'{slice_prompt}'\033[0m\n\n"
"is the above the first survey question "
"in your survey?: (Y/n) \n\n"
"\033[1mNOTE:\033[0m This question should "
"be asking for the experimenter to enter "
"the task the participant just completed.")
if not ans:
clean_getaway()
return slice_prompt
def check_if_download():
"""Checks to see if the Qualtrics Download is in the current directory. Runs
get_qualtrics.py the directory is not found.
Args:
None
Returns:
None"""
if not os.path.exists(f"{os.getcwd()}/MyQualtricsDownload/"):
apiToken = get_qualtrics.get_api_token()
surveyId = get_qualtrics.get_survey_id(apiToken)
get_qualtrics.main(surveyId, apiToken)
def leave_any_out(df):
"""Asks the user if there is any section of the survey they would like
to leave out of the parsing process.
Args:
df: A cleaned Qualtrics survey export.
Returns:
df: A cleaned Qualtrics export with the proper columns removed."""
ans = InputManager.get_yes_or_no("Are there any columns you not like to"
" include in the conditions files? (Y/n):")
if ans:
first_prompt = input("Please enter the first prompt for the section "
"you wish to remove: ")
how_many_after = int(input("How many columns do you wish to remove "
" after the first prompt?: "))
headings_list = df.iloc[0].tolist()
first_indx = headings_list.index(first_prompt)
cols_to_remove = headings_list[first_indx:first_indx + how_many_after]
df.drop(cols_to_remove, axis=1, inplace=True)
return df
def get_q_measures(num_questions):
"""Prompts the user in input the operational conditionals value titles for
all of the questions in their survey. These value titles will serve as row
headings in the conditions files.
Args:
num_questions(int): Number of questions administered in a survey given
the the participant after each task.
Returns:
q_measures(list): A list of the row headings for the completed
conditions file."""
keyword_measures = {"tlx": ["", "onset", "duration", "stim", "tlx",
"tlx_mental", "tlx_physical",
"tlx_temporal", "tlx_performance",
"tlx_effort", "tlx_frustration"],
"mrq": ["", "onset", "duration", "stim", "mrq"],
}
q_measures = []
for x in range(0, num_questions + 1):
if x == 0:
q_measures.append("")
elif x == 1:
q_measures.append("stim")
else:
prompt = (f"Please enter the measurement name for"
f" question {x + 1} in the survey.")
measure = InputManager.get_variable_name(prompt)
q_measures.append(measure)
if measure in keyword_measures:
return keyword_measures[measure]
elif measure == "default":
return [f"measure {x}" for x in range(0, num_questions + 1)]
return q_measures
def make_c_files(par_id, csv_data, q_measures,
sensor_type="fNIRS", session_num="1"):
"""Creates a .csv file, called a conditions file and exports it to a
subdirectory in the directory in which this script is run.
Args:
par_id(str): The participant's ID in the study.
csv_data(list): The survey data gathered from the qualtrics export for
the corresponding participant.
q_measures(list): The row headings for the exported .csv file.
sensor_type(str): Sensor for which the conditions file is being made.
Used in the naming of the conditions file.
session_num(str): The session number for which the file is being made.
Used in the naming of the conditions file.
Returns:
None"""
exper_id = par_id[:2]
csv_data = zip(*csv_data)
csv_data = [list(x) for x in csv_data]
# inserts blank rows for onset and duration
csv_data.insert(1, [])
csv_data.insert(1, [])
if not os.path.exists(f"./experiment_{exper_id}_cfiles/"):
os.mkdir(f"./experiment_{exper_id}_cfiles/")
file_name = (f"./experiment_{exper_id}_cfiles/{par_id}"
f"_{sensor_type}_conditions_s{session_num}.csv")
with open(file_name, "w") as out_csv:
writer = csv.writer(out_csv, delimiter=",")
for i, row in enumerate(csv_data):
if i == 0:
total_col = len(row)
row.insert(0, q_measures[i])
if q_measures[i] == "onset" or q_measures[i] == "duration":
for x in range(total_col):
row.append("")
writer.writerow(row)
def get_slice_points(indexer_list, slice_prompt):
"""Scans across the indexer list to determine where tasks begin and end in
a Qualtrics export .csv file.
Args:
indexer_list(list): A list of the question headings row in the Qualtrics
.csv export file.
slice_prompt(str): The first question given to a participant after they
complete each task.
Returns:
slice_points(list): A list of the index values in the .csv where the
first question in the after task survey begins."""
# Scans question text to determine where stim is entered by experimentor.
slice_points = []
for i, row in enumerate(indexer_list):
if row == slice_prompt:
slice_points.append(i)
return(slice_points)
def count_survey_questions(slice_points):
"""Calculates the amount of questions between each task.
Args:
slice_points(list): A list of the index values in the .csv where the
first question of the after task survey begins.
Returns:
num_questions[1:](int): The amount of questions in a survey."""
num_questions = []
for i, slice_point in enumerate(slice_points):
if i == 0:
x = 0
y = slice_point
question_num = abs((x - y))
num_questions.append(question_num)
x = slice_point
return num_questions[1:]
def check_num_questions(num_questions):
"""Determines whether or the the amount of questions in a survey is > 1
Args:
num_questions(int): The amount of questions in a survey.
Returns:
Bool: True is num_questions > 1."""
return len(set(num_questions)) <= 1
def main(col_to_drop):
check_if_download()
df = get_cleaned_df(col_to_drop)
df = leave_any_out(df)
first_q, slice_prompt = get_slice_strings(df)
par_ids = df[first_q].tolist()
num_participants = len(par_ids)
# sets participant id as index of df.
df.set_index(first_q, inplace=True)
indexer_list = df.loc[first_q].tolist()
slice_points = get_slice_points(indexer_list, slice_prompt)
num_questions = count_survey_questions(slice_points)
questions_equal = check_num_questions(num_questions)
if questions_equal:
survey_length = num_questions[0]
q_measures = get_q_measures(survey_length)
else:
clean_getaway()
for index, row in df.iterrows():
if index.isnumeric():
par_id = index
list_row = row.tolist()
head_cir = list_row.pop(0)
list_row.pop(0) # remove first mark
if len(list_row) % survey_length != 0:
clean_getaway()
task_num = int(len(list_row) / survey_length)
csv_data = []
for x in range(0, task_num):
start_cell = (survey_length * x)
end_cell = (start_cell + 8)
task_answers = list_row[start_cell:end_cell]
task_answers.insert(0, f"Task{x + 1}")
csv_data.append(task_answers)
make_c_files(par_id, csv_data, q_measures)
if __name__ == "__main__":
# cols not needed in qualtrics export.
col_to_drop = ["ResponseID", "ResponseSet", "IPAddress", "StartDate",
"EndDate", "RecipientLastName", "RecipientFirstName",
"RecipientEmail", "ExternalDataReference", "Finished",
"Status", "LocationLatitude", "LocationLongitude",
"LocationAccuracy"]
main(col_to_drop)
|
7cf2375e9ad40d2e5ddc4a5470acd93ba783575c | Luke-zhang-04/Graphing-Calculator-Toolbox | /main.py | 763 | 4.15625 | 4 | from GraphingCalculatorToolbox import graphingCalculator
graph = graphingCalculator(int(input("Please enter Screen Size: "))) #user inputs screen size
graph.draw_axes(int(input("Please enter xMin: ")),int(input("Please enter xMax: ")),int(input("Please enter yMin: ")),int(input("Please enter increment for x: ")),int(input("Please enter increment for y: "))) #User draws up a grid
TOV = graph.makeTableofValues (int(input("Please enter number of points: ")), input("Enter equation: y=")) #Using given data, user enters desired number of points and an equation (in the function)
#graph.plotPoints(TOV[0], TOV[1]) #makeTableofValues returns a tuple of a list of x values and a list of y values
graph.plotPoints()
graph.screen.update()
graph.screen.mainloop()
|
07110f2edec20c2c1301f730786dbc2ab4ad7fb9 | travisjungroth/algo-drills | /algorithms/selection_sort_iter.py | 709 | 3.953125 | 4 | """
ID: 556c4a0f-f488-4a6b-99b4-4d09e006be23
Grokking Algorithms, Page 32
Python Algorithms, Page 75
This implementation is different than the ones in the referenced books, which are different from each other.
It uses methods and functions that do iteration versus for-loops. Just remember it's still O(n^2).
"""
from collections.abc import MutableSequence
from src.typehints import T
def selection_sort_iter(seq: MutableSequence[T]) -> None:
"""Use selection sort iteratively on a list in-place."""
for i, val in enumerate(seq):
min_val = min(seq[i:])
min_val_i = seq.index(min_val, i) # First index of min_val at or after i
seq[i] = min_val
seq[min_val_i] = val
|
f2a413bd0c6994de4867b993c8c8245c7257b191 | antondelchev/Python-Fundamentals | /Functions - Exercise/05. Palindrome Integers.py | 536 | 3.9375 | 4 | def check_for_palindrome_num(list_of_nums):
nums_list = str(list_of_nums).split(", ")
for i in range(len(nums_list)):
if i < len(nums_list) - 1:
if nums_list[i] == nums_list[i][::-1]:
print("True")
else:
print("False")
elif i == len(nums_list) - 1:
if nums_list[i] == nums_list[i][::-1]:
return "True"
else:
return "False"
list_of_numbers = input()
print(check_for_palindrome_num(list_of_numbers))
|
b10ece79011e34e73ec97c52843598507938479c | wellqin/USTC | /DesignPatterns/structural/filter/filter_chain.py | 4,109 | 3.53125 | 4 | # -*- coding:utf-8 -*-
import abc
from typing import List
"""
拦截过滤器模式(Intercepting Filter Pattern)用于对应用程序的请求或响应做一些预处理/后处理。
定义过滤器,并在把请求传给实际目标应用程序之前应用在请求上。过滤器可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序。
以下是这种设计模式的实体。
"""
class AbstractFilter(abc.ABC):
@abc.abstractmethod
def execute(self, request: List[str]): ...
class AuthenticationFilter(AbstractFilter):
def execute(self, request: List[str]):
print(f"Authenticating request: {request}")
return [r for r in request if r == "Authentication"]
class DebugFilter(AbstractFilter):
def execute(self, request: List[str]):
print(f"DebugFilter request: {request}")
return [r for r in request if r == "Debug"]
class Target:
"""Target 对象是请求处理程序"""
@staticmethod
def execute(request: List[str]):
print(f"Target Executing request: {request}")
return request + ["Target"]
class FilterChain:
"""过滤器链带有多个过滤器,并在 Target 上按照定义的顺序执行这些过滤器。"""
def __init__(self, builder=None):
self.filters = []
self.filter_chain_builder = getattr(builder, "chain", [])
self.target = None
class FilterChainBuilder:
def __init__(self):
self.chain = []
def add_filter(self, fi: AbstractFilter):
self.chain.append(fi)
return self
def build(self):
return FilterChain(self)
def add_filter(self, fi: AbstractFilter):
self.filters.append(fi)
def extend_filter(self, fi_chain: List[AbstractFilter]):
self.filters.extend(fi_chain)
def build_filter(self, fi: AbstractFilter):
self.filters = self.FilterChainBuilder().add_filter(fi).build().filter_chain_builder
def execute(self, request: str):
# 1、处理前,过滤器可以做认证/授权/记录日志,或者跟踪请求,然后把请求传给相应的处理程序
# test2有而test1没有的元素: list(set(test2).difference(set(test1)))
for fi in self.filters:
request = list(set(request).difference(set(fi.execute(request))))
# 2、真正去处理逻辑
return self.target.execute(request)
def set_target(self, target: Target):
self.target = target
class FilterManager:
def __init__(self, target: Target):
self.filter_chain = FilterChain()
self.filter_chain.set_target(target)
def set_filter(self, fi: AbstractFilter):
self.filter_chain.add_filter(fi)
def set_filter_chain(self, fi_chain: List[AbstractFilter]):
self.filter_chain.extend_filter(fi_chain)
def set_build_filter(self, fi: AbstractFilter):
self.filter_chain.build_filter(fi)
def filter_request(self, request: str):
return self.filter_chain.execute(request)
class Client:
def __init__(self):
self.filter_manager = None
def set_filter_manager(self, fi_manager: FilterManager):
self.filter_manager = fi_manager
def send_request(self, request: List[str]):
return self.filter_manager.filter_request(request)
if __name__ == "__main__":
filter_manager = FilterManager(Target())
# 1、过滤器链: 也可以使用建造者模式创建
filter_manager.set_build_filter(AuthenticationFilter())
# 2、一口气加载全部过滤器接口子类, __subclasses__这个方法返回的是这个类的子类的集合
# sub_class_list = AbstractFilter.__subclasses__()
# filter_manager.set_filter_chain([sub() for sub in sub_class_list])
# 3、依次加入每个过滤器接口子类
# filter_manager.set_filter(AuthenticationFilter())
# filter_manager.set_filter(DebugFilter())
client = Client()
client.set_filter_manager(filter_manager)
res = client.send_request(["HOME", "hello", "Authentication", "Debug"])
print(res)
|
a9f03735834a038e0e7e75caa4625dd6308895fa | amararora07/CodeFights | /factorSum.py | 259 | 3.703125 | 4 | def factorSum(n):
def sumFact(n):
t=2
tot=0
while n>1:
while n%t==0:
tot+=t
n/=t
t+=1
return tot
while n!=sumFact(n):
n=sumFact(n)
return n
|
7eccc3d420579ed4fb869bde677ca2ac6e9d2150 | adammartin2019/ChallengeCode | /AddTwoNumbers.py | 4,948 | 3.9375 | 4 | """
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order, and each of their nodes contains a single digit.
Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
Constraints:
The number of nodes in each linked list is in the range [1, 100].
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros.
"""
#This solution ignores the linked list aspect, not correct for the given problem
l1 = [2,4,3]
l2 = [5,6,4]
L1 = [0]
L2 = [0]
LIST1 = [9,9,9,9,9,9,9]
LIST2 = [9,9,9,9]
def addTwoNumbers(l1, l2):
L1r = []
L2r = []
for i in reversed(l1):
L1r.append(i)
for j in reversed(l2):
L2r.append(j)
num1 = int(''.join(map(str,L1r)))
num2 = int(''.join(map(str,L2r)))
addNum = num1 + num2
finalNumList = [int(i) for i in reversed(str(addNum))]
print(finalNumList)
return finalNumList
addTwoNumbers(l1,l2)
addTwoNumbers(L1,L2)
addTwoNumbers(LIST1,LIST2)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class LinkedList:
def __init__(self):
self.headval = None
def listPrint(self):
printVal = self.headval
while printVal is not None:
print(printVal.dataval)
printVal = printVal.nextval
L1 = LinkedList()
L2 = LinkedList()
#generate list 1
L1.headval = Node(2)
l1n2 = Node(4)
l1n3 = Node(3)
L1.headval.nextval = l1n2
l1n2.nextval = l1n3
#generate list 2
L2.headval = Node(5)
l2n2 = Node(6)
l2n3 = Node(4)
L2.headval.nextval = l2n2
l2n2.nextval = l2n3
def addTwoNumbers(l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
result = Node(0)
result_tail = result
carry = 0
while l1 or l2 or carry:
val1 = (l1.dataval if l1 else 0)
val2 = (l2.dataval if l2 else 0)
carry, out = divmod(val1+val2 + carry, 10)
result_tail.nextval = Node(out)
result_tail = result_tail.nextval
l1 = (l1.nextval if l1 else None)
l2 = (l2.nextval if l2 else None)
return result.nextval
addTwoNumbers(L1.headval, L2.headval)
"""
Intuition
Keep track of the carry using a variable and simulate digits-by-digits sum starting from the head of list,
which contains the least-significant digit.
Algorithm
Just like how you would sum two numbers on a piece of paper, we begin by summing the least-significant digits,
which is the head of l1l1l1 and l2l2l2. Since each digit is in the range of 0…90 \ldots 90…9, summing two digits
may "overflow". For example 5+7=125 + 7 = 125+7=12. In this case, we set the current digit to 222 and bring over
the carry=1carry = 1carry=1 to the next iteration. carrycarrycarry must be either 000 or 111 because the largest
possible sum of two digits (including the carry) is 9+9+1=199 + 9 + 1 = 199+9+1=19.
The pseudocode is as following:
Initialize current node to dummy head of the returning list.
Initialize carry to 000.
Initialize ppp and qqq to head of l1l1l1 and l2l2l2 respectively.
Loop through lists l1l1l1 and l2l2l2 until you reach both ends.
Set xxx to node ppp's value. If ppp has reached the end of l1l1l1, set to 000.
Set yyy to node qqq's value. If qqq has reached the end of l2l2l2, set to 000.
Set sum=x+y+carrysum = x + y + carrysum=x+y+carry.
Update carry=sum/10carry = sum / 10carry=sum/10.
Create a new node with the digit value of (sum mod 10)(sum \bmod 10)(summod10) and set it to current node's next,
then advance current node to next.
Advance both ppp and qqq.
Check if carry=1carry = 1carry=1, if so append a new node with digit 111 to the returning list.
Return dummy head's next node.
Note that we use a dummy head to simplify the code. Without a dummy head, you would have to write extra conditional statements
to initialize the head's value.
Complexity Analysis
Time complexity : O(max(m,n))O(\max(m, n))O(max(m,n)). Assume that mmm and nnn represents the length of l1l1l1 and l2l2l2
respectively, the algorithm above iterates at most max(m,n)\max(m, n)max(m,n) times.
Space complexity : O(max(m,n))O(\max(m, n))O(max(m,n)). The length of the new list is at most
max(m,n)+1\max(m,n) + 1max(m,n)+1.
"""
|
c67eec753425f2dc74b6ab9e953ab72ce90ef650 | KunwarBisht/Python-Assignment-L1 | /3_solution.py | 451 | 3.6875 | 4 | '''Question
Write a program to receive a string from keybord and check if the string has two 'e' in the characters.
If yes return True else False.
'''
def check_char(char):
count=0
if len(char) < 2:
print("False")
return
else:
for i in string:
if i =='e':
count +=1
if count==2:
print("True")
else:
print("False")
string=input("Enter the String : ")
check_char(string)
|
90be04137f4df8ee6c4d1b9660a9d1ce5182b29b | Anewnoob/Leetcode | /mirrorTree.py | 828 | 4 | 4 | #请完成一个函数,输入一个二叉树,该函数输出它的镜像。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
# #dfs
# if root is None: return None
# root.left,root.right = self.mirrorTree(root.right),self.mirrorTree(root.left)
# return root
#bfd
if root is None: return root
stack = collections.deque([root])
while stack:
node = stack.popleft()
if node.left is not None: stack.append(node.left)
if node.right is not None: stack.append(node.right)
node.left,node.right = node.right,node.left
return root
|
d1127315043247fe653761ae60486e97d41286e6 | KamalovRuslan/LeetCode | /RussianDoll1.py | 1,998 | 3.71875 | 4 | class Doll(object):
def __init__(self, envelop):
self.w = envelop[0]
self.h = envelop[1]
def __lt__(self, other):
return self.w < other.w and self.h < other.h
def __gt__(self, other):
return return self.w > other.w and self.h > other.h
class DollNode(object):
def __init__(self, doll):
self.doll = doll
self.next = None
class DollList(object):
def __init__(self):
self.root = None
self.len = 0
def insert(self, envelop):
if self.root is None:
self.root = DollNode(Doll(envelop))
else:
doll = Doll(envelop)
self._insert(root, root.next, doll)
def _insert(self, prev_node, node, doll):
if node is None:
node = DollNode(doll)
self.len += 1
return
elif node.doll > doll:
self._insert(node, node.next, doll)
elif node.doll < doll:
_doll = node.doll
node.doll = doll
tmp_node = DollNode(_doll)
tmp_node.next = node.next
node.next = tmp_node
self.len += 1
return
else:
raise ValueError
return
def __len__(self):
return self.len
def get_max_doll(dolls):
return max([len(doll) for doll in dolls])
class Solution(object):
@classmethod
def maxEnvelopes(self, envelopes):
"""
:type envelopes: List[List[int]]
:rtype: int
"""
dolls = [DollList()]
for envelop in envelopes:
not_put = True
for doll in dolls:
try:
doll.insert(envelop)
except ValueError:
not_put = True
if not_put:
dolls.append(DollList().insert(envelop))
return get_max_doll(dolls)
if __name__ == "__main__":
inp = input()
envelopes = eval(inp)
print(Solution.maxEnvelopes(envelopes))
|
8ec532f09587509d8c2caa29a198dead6032bcf4 | Hadayo/MC-Portfolio-Evaluation | /portopt/market.py | 7,424 | 3.859375 | 4 | """
Defines the MarketSimulator class and some MaketModels like the constant
market model.
"""
import numpy as np
from .expand_array import ExpandArray
class ConstantMarketModel(object):
"""Defines the underlying variables of a constant market.
The class has two modes of operation: online or batch.
1. online mode:
Works through the `step` function. Each call to the function updates
the tracked parameters and returns them to the caller.
2. batch mode:
Works with the function `sample_path` which receives the time horizon in
advance. One call to the function returns all the tracked parameters
and their paths over time.
Working in batch mode increases performance by 2 orders of magnitude.
Parameters
----------
dt : float
The time difference between each two points (in years).
stock_mean : float
The stock mean rate of return (in 1/years).
stock_volatility : float
The stock volatility (in 1/sqrt(years)).
ir : float
The money market account interest rate.
Attributes
----------
num_params : int
The number of parameters the model tracks.
dt
stock_mean
stock_volatility
ir
"""
def __init__(self, dt, stock_mean, stock_volatility, ir):
self.dt = dt
self.stock_mean = stock_mean
self.stock_volatility = stock_volatility
self.ir = ir
self.num_params = 3
def reset(self):
pass # here for consistency reasons
def step(self):
return self.stock_mean, self.stock_volatility, self.ir
def sample_path(self, T_horizon):
"""Simulate the parameters over a path with length T_horizon.
Since the market model describes a constant market, this equals
duplicating the inital values through time.
Parameters
----------
T_horizon : float
The time horizon (in years).
Returns
-------
ndarray
A [num_params x (T/dt - 1)] matrix where each row represents a path for
one of the tracked parameters.
"""
num_points = int(T_horizon / self.dt) - 1
params = np.array([self.stock_mean, self.stock_volatility, self.ir]).reshape(-1, 1)
return np.ones((self.num_params, num_points)) * params
class MarketSimulator(object):
"""The MarketSimulator can simulates a market with a stock and a money
market account under a given market model.
The stock prices is progressed according to the Generalized Geometric
Brownian Motion SDE:
dS_t = S_t * (mu_t*dt + sigma_t*dW_t)
where:
S - the price of the stock
mu - the instantaneous mean rate of return
sigma - instantaneous volatility
W - a Brownian motion
The money market price is progressed according to the continous compounding
formula:
dM_t = M_t*r_t*dt
where:
M - the money market price
r - the instantaneous interest rate
The class has two modes of operation: online or batch.
1. online mode:
Works with the `step` function. Each call to the function updates
the stock prices and returns them and the interest rate to the caller.
2. batch mode:
Works with the function `sample_path` which receives the time horizon in
advance. One call to the function returns all the stock prices and
their paths over time.
Working in batch mode increases performance by 2 orders of magnitude.
Parameters
----------
market_model : MarketModel
The model that describes the dynamics of the mean rate of return
for the stock, the volatility of the stock and the interest rate.
dt : float
The time difference between two points (in years).
Attributes
----------
num_assets : int
The number of assets simulated.
prices : ExpandArray
An expandable array for tracking the prices over time.
dt
market_model
"""
def __init__(self, market_model, dt):
self.dt = dt
self.num_assets = 2 # including the money market account
self.market_model = market_model
self.reset()
def reset(self):
self.market_model.reset()
self.prices = ExpandArray(self.num_assets)
self.prices.append_col([1, 1])
def step(self):
"""Performs one step of updates to the stock price and money market
accound price.
The money market accound follows a simple compound
interest dynamics. The stock follows a generalized geometric Brownian
motion with the parameters supplied by the market model.
Returns
-------
information : list
The current stock price, money market account price, and interest
rate. This information is assumed to be available to the trader.
secret_information : list
The current stock volatility and stock mean rate of return. This
information is used for debugging and is not assumed to be
available to the trader.
"""
stock_mean, stock_volatility, ir = self.market_model.step()
money_market_price, stock_price = self.prices.last_col()
delta_stock = stock_price * (stock_mean * self.dt
+ stock_volatility * np.sqrt(self.dt) * np.random.randn())
new_stock_price = stock_price + delta_stock
new_money_market_price = money_market_price * (1 + ir * self.dt)
information = [new_money_market_price, new_stock_price, ir]
secret_information = [stock_mean, stock_volatility]
self.prices.append_col([new_money_market_price, new_stock_price])
return information, secret_information
def sample_path(self, T_horizon):
"""Computs a path for the prices of the stock and the money market
account. This is the batch version of the `step` function that runs
faster.
Parameters
----------
T_horizon : float
The time horizon to be simulated (in years).
Returns
-------
information : ndarray
A 3 by T_horizon/dt array containing the prices of the stock,
the money market account and the interest rates for the given
horizon.
secret_information : ndarray
A 2 by T_horizon/dt array containing the market parameters path
over the given horizon (stock mean and volatility).
"""
num_points = int(T_horizon / self.dt) - 1
market_params = self.market_model.sample_path(T_horizon)
stock_means = market_params[0]
stock_volatilities = market_params[1]
irs = market_params[2]
brownian_motion = np.random.randn(num_points)
stock_multipliers = (1 + stock_means * self.dt
+ stock_volatilities * np.sqrt(self.dt) * brownian_motion)
stock_prices = np.hstack(([1], np.cumprod(stock_multipliers)))
money_market_prices = np.hstack(([1], np.exp(self.dt * np.cumsum(irs))))
irs_long = np.insert(irs, 0, irs[0])
information = np.vstack([money_market_prices, stock_prices, irs_long])
secret_information = market_params[:2]
return information, secret_information
def get_prices(self):
return self.prices.as_array()
|
b97a318f832d6ec4c9529715cd260fd42a5d8b51 | Camiloasc1/AlgorithmsUNAL | /Udacity/7/8Favor.py | 4,144 | 3.71875 | 4 | # Finding a Favor v2
#
# Each edge (u,v) in a social network has a weight p(u,v) that
# represents the probability that u would do a favor for v if asked.
# Note that p(v,u) != p(u,v), in general.
#
# Write a function that finds the right sequence of friends to maximize
# the probability that v1 will do a favor for v2.
#
#
# Provided are two standard versions of dijkstra's algorithm that were
# discussed in class. One uses a list and another uses a heap.
#
# You should manipulate the input graph, G, so that it works using
# the given implementations. Based on G, you should decide which
# version (heap or list) you should use.
#
# code for heap can be found in the instructors comments below
from operator import itemgetter
import math
from heap import *
def maximize_probability_of_favor(G, v1, v2):
# your code here
# call either the heap or list version of dijkstra
# and return the path from `v1` to `v2`
# along with the probability that v1 will do a favor
# for v2
V = len(G)
E = 0
Glog = {}
for n in G:
E += len(G[n])
Glog[n] = {}
for m in G[n]:
Glog[n][m] = -math.log(G[n][m]) # if n < 1 --> log(n) < 0
if (V + E) * math.log(V) <= V ** 2:
dist = dijkstra_heap(Glog, v1)
else:
dist = dijkstra_list(Glog, v1)
if v2 not in dist:
return None, 0
return ParentRoute(dist, v1, v2), math.exp(-dist[v2][0])
def ParentRoute(parent, n1, n2):
if n1 not in parent or n2 not in parent:
return None
if n1 == n2:
return []
route = [n2]
while n1 != n2:
n2 = parent[n2][1]
if n2 == None: # Not connected
return None
route.insert(0, n2)
return route
#
# version of dijkstra implemented using a heap
#
# returns a dictionary mapping a node to the distance
# to that node and the parent
#
# Do not modify this code
#
def dijkstra_heap(G, a):
# Distance to the input node is zero, and it has
# no parent
first_entry = (0, a, None)
heap = [first_entry]
# location keeps track of items in the heap
# so that we can update their value later
location = {first_entry:0}
dist_so_far = {a:first_entry}
final_dist = {}
while len(dist_so_far) > 0:
dist, node, parent = heappopmin(heap, location)
# lock it down!
final_dist[node] = (dist, parent)
del dist_so_far[node]
for x in G[node]:
if x in final_dist:
continue
new_dist = G[node][x] + final_dist[node][0]
new_entry = (new_dist, x, node)
if x not in dist_so_far:
# add to the heap
insert_heap(heap, new_entry, location)
dist_so_far[x] = new_entry
elif new_entry < dist_so_far[x]:
# update heap
decrease_val(heap, location, dist_so_far[x], new_entry)
dist_so_far[x] = new_entry
return final_dist
#
# version of dijkstra implemented using a list
#
# returns a dictionary mapping a node to the distance
# to that node and the parent
#
# Do not modify this code
#
def dijkstra_list(G, a):
dist_so_far = {a:(0, None)} # keep track of the parent node
final_dist = {}
while len(final_dist) < len(G):
node, entry = min(dist_so_far.items(), key = itemgetter(1))
# lock it down!
final_dist[node] = entry
del dist_so_far[node]
for x in G[node]:
if x in final_dist:
continue
new_dist = G[node][x] + final_dist[node][0]
new_entry = (new_dist, node)
if x not in dist_so_far:
dist_so_far[x] = new_entry
elif new_entry < dist_so_far[x]:
dist_so_far[x] = new_entry
return final_dist
##########
#
# Test
def test():
G = {'a':{'b':.9, 'e':.5},
'b':{'c':.9},
'c':{'d':.01},
'd':{},
'e':{'f':.5},
'f':{'d':.5}}
path, prob = maximize_probability_of_favor(G, 'a', 'd')
assert path == ['a', 'e', 'f', 'd']
assert abs(prob - .5 * .5 * .5) < 0.001
test()
|
aa5199492ffd6cefc033171ad95b61fb5d4daf6a | AliAldobyan/age-calculator | /age_calculator.py | 724 | 4.25 | 4 | from datetime import datetime
def check_birthdate(year, month, day):
# write code here
birthdate = datetime(year, month, day)
today = datetime.now()
if today > birthdate:
return True
else:
return False
def calculate_age(year, month, day):
# write code here
age = datetime.now() - datetime(year, month, day)
age_in_years = age.days/365
print("You are %d years old" % (age_in_years))
def main():
# write main code here
year = int(input("Enter year of birth: "))
month = int(input("Enter month of birth: "))
day = int(input("Enter day of birth: "))
if check_birthdate(year, month, day):
calculate_age(year, month, day)
else:
print("The birthdate is invalid")
if __name__ == '__main__':
main()
|
e5df0c7ad4b7ac068efa92a95317a66b19b23252 | adharris/euler | /problems/problems_000_099/problems_050_059/problem_059.py | 2,621 | 3.6875 | 4 |
import click
from itertools import permutations
from pathlib import Path
@click.command('59')
@click.option('--verbose', '-v', count=True)
def problem_059(verbose):
"""XOR decryption.
Each character on a computer is assigned a unique code and the preferred
standard is ASCII (American Standard Code for Information Interchange).
For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to
ASCII, then XOR each byte with a given value, taken from a secret key. The
advantage with the XOR function is that using the same encryption key on
the cipher text, restores the plain text; for example, 65 XOR 42 = 107,
then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text
message, and the key is made up of random bytes. The user would keep the
encrypted message and the encryption key in different locations, and
without both "halves", it is impossible to decrypt the message.
Unfortunately, this method is impractical for most users, so the modified
method is to use a password as a key. If the password is shorter than the
message, which is likely, the key is repeated cyclically throughout the
message. The balance for this method is using a sufficiently long password
key for security, but short enough to be memorable.
Your task has been made easy, as the encryption key consists of three
lower case characters. Using
[cipher.txt](project/resources/p059_cipher.txt) (right click and 'Save
Link/Target As...'), a file containing the encrypted ASCII codes, and the
knowledge that the plain text must contain common English words, decrypt
the message and find the sum of the ASCII values in the original text.
"""
letters = 'abcdefghijklmnopqrstuvwxyz'
ordinals = [ord(l) for l in letters]
keys = permutations(ordinals, 3)
code = get_encrypted()
for key in keys:
decoded = "".join(decrypt(code, key))
words = decoded.split(' ')
if len(words) > 50 and 'the' in decoded and 'and' in decoded:
click.echo("{} ({}): {}".format(
"".join(chr(k) for k in key),
sum(ord(l) for l in decoded),
"".join(decoded)))
def decrypt(numbers, key):
return [chr(n ^ key[i % 3]) for i, n in enumerate(numbers)]
def get_encrypted():
with Path('.', 'files', 'cipher.txt').open('r') as f:
numbers = f.read()
return [int(i) for i in numbers.strip().split(',')]
|
36b38430fdc8e878263ceb3589b2e3be86141546 | Abu-Sayad-Hussain/visual-studio-projects | /projectDeadline.py | 726 | 4.25 | 4 | import datetime
#initiaize variables
strDeadLn = ""
nmbrOfDays = 0
nmbrOfWks = 0
nmbrOfrDays = 0
#Get today's date
currentDate = datetime.date.today()
#ask user to enter project deadline
strDeadLn = input("Enter project deadline (dd/mm/yyyy)")
deadLine = datetime.datetime.strptime(strDeadLn, "%d/%m/%Y").date()
#Calculaate difference between project deadline and today's date
nmbrOfDays = deadLine - currentDate
#Calculate number of week remaining
nmbrOfWks = nmbrOfDays.days / 7
#Calculate the remain days
nmbrOfrDays = nmbrOfDays.days % 7
#Print the value to the user
print("You have %d" %nmbrOfWks + " weeks and %d" %nmbrOfrDays + " days remaining to submit your project") |
9617bc0d0671da6b47307619ee555765a1587e88 | mscott99/Concentrated-Sports | /Sport_density.py | 1,254 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 28 12:09:13 2018
Script to extract the number of sport places for a list of sports in a given
radius around a specific latitude/longitude. Extract the information
by querying the sport places API
@author: AI team
"""
import json
import requests
class sport_density():
def __init__(self, lat, lon, list_of_sports, radius=1):
self.lat = lat
self.lon = lon
self.list_of_sports = list_of_sports
def number_of_sport_places(self, radius=50):
self.radius = radius
#We will extract the number of sport places in a dictionary
self.number_sport_places = {}
#Query the sport places API
for i in self.list_of_sports:
try:
url = 'https://sportplaces-api.herokuapp.com/api/v1/places?origin={},{}&radius={}&sports={}'.format(self.lon,self.lat, self.radius, int(i))
response = requests.get(url)
data = json.loads(response.text)
self.number_sport_places[i] = len(data['features'])
except:
print('Could not find number of locations for sport {}'.format(int(i)))
self.number_sport_places[i] = 0
|
cc4072a7656af90f0db374f81db35f0c90e08adc | Fernandarangel23/Activities | /Week 3/Activities/Activity3_DownToInput.py | 540 | 4.25 | 4 | # Collects the user's and neighbors
myname = input("What is your name? ")
neighbor = input("What is your neighbor's name?")
# Collects the user's input for the prompt "How old are you?" and converts the string to an integer.
months = int(input("How many months you have been coding?"))
nighbormonths = int(input("How many months your neighbor has been coding?"))
totalmonths = months + nighbormonths
# print names and total of age
print(myname + " and " + neighbor + " have been coding for " + str(totalmonths) + " months.")
|
a2dd34849f45da1d3a1441e38913250bc2be5b2e | NARESHSWAMI199/python | /python/dictnary/pop_items.py | 315 | 3.78125 | 4 | names= {
"name1" : "naresh",
"name2" : "manish",
"name3" : {"name" : "naresh" , "surname" : "swami" }
}
# add item
# names["name4"] = "rocky"
# pop item
# print(names.pop("name3")) # must write one key item in
# popitem
# print(names.popitem()) # this will return a tuple
# print(names)
|
90fb683612776bb6a40b07171bf66d483a2b3413 | agkozik/CleanPython | /functions/callable_object.py | 310 | 3.953125 | 4 | class Adder:
def __init__(self, number):
self.number = number
def __call__(self, x):
return self.number + x
adder = Adder(3)
print(adder(10))
print(Adder(1)(2))
# проверка, является ли объект или функция вызываемыми
print(callable(adder)) |
f7c43015a85da581a1cc90721de2c7b21d36fa06 | Chotom/OOP-WorldSimulation-Python | /OOP_WorldSim.py | 4,246 | 3.609375 | 4 | from tkinter import *
from World import World
class MainWindow(object):
def __init__(self):
self.__mainWindow = Tk()
self.__mainWindow.resizable(False, False)
self.__mainWindow.title("Tomasz Czochanski")
# Set Board (0, 0)
self.__boardWindow = LabelFrame(self.__mainWindow, text="Board")
self.__boardWindow.grid(row=0, column=0, columnspan=10, rowspan=10)
self.__worldView = Canvas(self.__boardWindow, height=600, width=600, border=1, bg="white")
self.__worldView.grid(row=0, column=0)
# Set Size area (0, 1)
self.__setSizeWindow = LabelFrame(self.__mainWindow, text="Change size:")
self.__setSizeWindow.grid(row=0, column=10, columnspan=6)
self.__xSizeSpinner = Spinbox(self.__setSizeWindow, from_=2, to=50, width=20)
self.__xSizeSpinner.grid(row=0, column=0)
self.__ySizeSpinner = Spinbox(self.__setSizeWindow, from_=2, to=50, width=20)
self.__ySizeSpinner.grid(row=0, column=1)
self.__setWorldSizeButton = Button(self.__setSizeWindow, text="Set world size", width=21, command=self.__changeSize)
self.__setWorldSizeButton.grid(row=0, column=3)
# Set addOrg area (1, 1)
self.__addOrgWindow = LabelFrame(self.__mainWindow, text="Add Organism:")
self.__addOrgWindow.grid(row=1, column=11, columnspan=6)
self.__addOrgText = Label(self.__addOrgWindow, text="Click left button on board to add chosen organism", width=60)
self.__addOrgText.grid(row=0, column=0, columnspan=6)
self.__organismToChoose = StringVar(self.__addOrgWindow, "Antelope")
organisms = ("Antelope", "Fox", "Sheep", "CyberSheep", "Turtle", "Wolf", "Dandelion", "DeadlyNightshade", "Grass", "Guarana", "SosnowskyHogweed")
self.__organismChooser = OptionMenu(self.__addOrgWindow, self.__organismToChoose, *organisms)
self.__organismChooser.grid(row=1, column=0, columnspan=6, rowspan=1)
# Set TextBox (2, 1)
self.__textBoxWindow = LabelFrame(self.__mainWindow, text="Actions:")
self.__textBoxWindow.grid(row=2, column=11, columnspan=6)
self.__labelText = StringVar()
self.__labelText.set("Arrows - move as Human\nR - special ability\nClick tile to add selected organism\nPress New Turn to start\n")
self.__messagesOutput = Label(self.__textBoxWindow, textvariable=self.__labelText, height=22, width=60, bg="white", fg="black", relief=GROOVE)
self.__messagesOutput.grid(row=0, column=0)
# Add world
self.__world = World.World(self.__worldView, 10, 10, self.__labelText)
# Set Buttons (3, 1)
self.__saveWorldButton = Button(self.__mainWindow, text="Save", width=29, height=4, command=self.__world.saveToFile)
self.__saveWorldButton.grid(row=3, column=10, columnspan=3, rowspan=1)
self.__loadWorldButton = Button(self.__mainWindow, text="Load", width=29, height=4, command=self.__world.loadFile)
self.__loadWorldButton.grid(row=3, column=13, columnspan=3, rowspan=1)
self.__newTurnButton = Button(self.__mainWindow, text="New Turn", width=60, height=4, command=self.__world.setNextTurn)
self.__newTurnButton.grid(row=4, column=10, columnspan=6, rowspan=1)
# Key binds for events
self.__worldView.bind("<Left>", lambda e: self.__world.setHumanZn("w"))
self.__worldView.bind("<Up>", lambda e: self.__world.setHumanZn("a"))
self.__worldView.bind("<Right>", lambda e: self.__world.setHumanZn("s"))
self.__worldView.bind("<Down>", lambda e: self.__world.setHumanZn("d"))
self.__worldView.bind("r", lambda e: self.__world.setHumanZn("r"))
self.__worldView.bind("<Button-1>", self.__addOrganismOnClick)
self.__worldView.focus_set()
self.__world.drawWorld()
self.__mainWindow.mainloop()
def __changeSize(self):
self.__world.changeSize(int(self.__xSizeSpinner.get()), int(self.__ySizeSpinner.get()))
self.__worldView.focus_set()
def __addOrganismOnClick(self, event):
self.__world.addOnClick(self.__organismToChoose.get(), event.x, event.y)
self.__worldView.focus_set()
window = MainWindow() |
21948fc6f51e2aa1faf2dcc9576e42f3571d1303 | CameronHunt5812/Python-Project1 | /python_prject.py | 7,991 | 4 | 4 | f = open("C:\Users\S581267\Documents\GitHub\Python-Project1\wordsearch3","r")
#Find the height, width and how many words to look for in the file.
height = int(f.readline())
width = int(f.readline())
numOfWords = int(f.readline())
#make a list of lists filled with 0 to fill with the letters from the word search
position = [[0 for x in range(width)]for y in range(height)]
#look at each position in the list and replace the 0 with the correct letter from the word search
for y in range (height):
#store line of charitors in a string to pull each sequentially
tempLine = f.readline()
for x in range (width):
#pull reach charitor and incert it into the list
temp = tempLine[x]
position[y][x] = temp
print position
#make a list of the words that you are looking for
lookFor = [f.readline() for w in range(numOfWords)]
print lookFor
found = [0 for f in range (numOfWords)]
def search(placesToCheck,position,y,x,):
Direct = -1
#get the values forom the list to see which adjacent places you can check
#cykle through the list keeping track of whare you are in it with Direct
#the position in the list represents the direction that the word is pointing
for di in (placesToCheck):
Direct = Direct + 1
if di == 1:
if Direct == 0:
for char in range (len(lookFor[word]) - 1):
if y-char != -1 and x-char != -1:
letter = lookFor[word][char]
if letter == position[y-char][x-char]:
if char == len(lookFor[word])-2:
found[word] = 1
#print the cordanits, the direction and the word you found
print str(x+1) + "," + str(y+1) + " Direction: Up and leaft, " + lookFor[word]
placesToCheck[Direct] = 0
else:
break
else:
break
if Direct == 1:
for char in range (len(lookFor[word]) - 1):
if y-char != -1:
letter = lookFor[word][char]
if letter == position[y-char][x]:
if char == len(lookFor[word])-2:
found[word] = 1
print str(x+1) + "," + str(y+1) + " Direction: Up, " + lookFor[word]
placesToCheck[Direct] = 0
else:
break
else:
break
if Direct == 2:
for char in range (len(lookFor[word]) - 1):
if y-char != -1 and x+char != width:
letter = lookFor[word][char]
if letter == position[y-char][x+char]:
if char == len(lookFor[word])-2:
found[word] = 1
print str(x+1) + "," + str(y+1) + " Direction: Up and Right, " + lookFor[word]
placesToCheck[Direct] = 0
else:
break
else:
break
if Direct == 3:
for char in range (len(lookFor[word]) - 1):
if x-char != -1:
letter = lookFor[word][char]
if letter == position[y][x-char]:
if char == len(lookFor[word])-2:
found[word] = 1
print str(x+1) + "," + str(y+1) + " Direction: Leaft, " + lookFor[word]
placesToCheck[Direct] = 0
else:
break
else:
break
if Direct == 4:
for char in range (len(lookFor[word]) - 1):
if x+char != width:
letter = lookFor[word][char]
if letter == position[y][x+char]:
if char == len(lookFor[word])-2:
found[word] = 1
print str(x+1) + "," + str(y+1) + " Direction: Right, " + lookFor[word]
placesToCheck[Direct] = 0
else:
break
else:
break
if Direct == 5:
for char in range (len(lookFor[word]) - 1):
if y+char != height and x-char != -1:
letter = lookFor[word][char]
if letter == position[y+char][x-char]:
if char == len(lookFor[word])-2:
found[word] = 1
print str(x+1) + "," + str(y+1) + " Direction: Doun and Leaft, " + lookFor[word]
placesToCheck[Direct] = 0
else:
break
else:
break
if Direct == 6:
for char in range (len(lookFor[word]) - 1):
if y+char != height:
letter = lookFor[word][char]
if letter == position[y+char][x]:
if char == len(lookFor[word])-2:
found[word] = 1
print str(x+1) + "," + str(y+1) + " Direction: Doun, " + lookFor[word]
placesToCheck[Direct] = 0
else:
break
else:
break
if Direct == 7:
for char in range (len(lookFor[word]) - 1):
if y+char != height and x+char != width:
letter = lookFor[word][char]
if letter == position[y+char][x+char]:
if char == len(lookFor[word])-2:
found[word] = 1
print str(x+1) + "," + str(y+1) + " Direction: Doun and Right, " + lookFor[word]
placesToCheck[Direct] = 0
else:
break
else:
break
for y in range (height):
for x in range (width):
for word in range (len(lookFor)):
if position[y][x] == lookFor[word][0] and found[word] == False:
placesToCheck = []
# make a list that represents the directions you can check relitive to
# the curent position in the wordsearch so you do not try to check owtside of the list
# when following a word you have found
if y == 0 and x == 0:
#the position in the list represents each of the directions
#upLeaft,up,upRight,Leaft,Right,DounRight,Doun,DounRight
placesToCheck = [0,0,0,0,1,0,1,1]
elif y == 0 and x == width-1:
placesToCheck = [0,0,0,1,0,1,1,0]
elif y == height-1 and x == 0:
placesToCheck = [0,1,1,0,1,0,0,0]
elif y == height-1 and x == width-1:
placesToCheck = [1,1,0,1,0,0,0,0]
elif y == 0:
placesToCheck = [0,0,0,1,1,1,1,1]
elif y == height-1:
placesToCheck = [1,1,1,1,1,0,0,0]
elif x == 0:
placesToCheck = [0,1,1,0,1,0,1,1]
elif x == width-1:
placesToCheck = [1,1,0,1,0,1,1,0]
else:
placesToCheck = [1,1,1,1,1,1,1,1]
direction = search(placesToCheck,position,y,x) |
9067e5b101d88f2701ec2dc978baaf5d51857dce | ThomasEA/MachineLearningAVA | /Dataset/Algoritmos/random.py | 359 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 15 20:13:44 2017
@author: Everton
"""
import numpy as np
def randrange(n, vmin, vmax):
'''
Helper function to make an array of random numbers having shape (n, )
with each number distributed Uniform(vmin, vmax).
'''
return (vmax - vmin)*np.random.rand(n) + vmin
array = randrange(40, 0, 1)
|
5721dcb7b1c21f47902c86b0ac13b7b7a7b32a3d | avin-sharma/GEDCOM | /marriage_checkers.py | 9,512 | 3.765625 | 4 | from datetime import datetime
def bigamy(individuals, families, tag_positions):
"""
User Story 11
Marriage should not occur during marriage to another spouse.
returns: a list of warning strings.
"""
warnings = []
# Find of someone is married once
# Then check if they dont have any other active marriage(married before today).
# Ignore active marriages with dead(death before today) spouses.
for indi_id in individuals:
individual = individuals[indi_id]
count = 0
if individual.spouse:
for fam_id in individual.spouse:
if is_married(individuals, families, fam_id):
count += 1
if count > 1:
num = tag_positions[indi_id]['FAMS']
warnings.append(f'ANOMALY: INDIVIDUAL: US11, line {num}, {individual.name} has more than 1 active marriages!')
return warnings
def is_married(individuals, families, family_id):
"""
Checks if the spouses of a given family are presently married.
They are not married if divorce date is present and is before today
and if one of the spouses is not alive.
returns: a boolean
"""
family = families[family_id]
divorce_date = family.divorced
if divorce_date and divorce_date < datetime.now():
return False
if not family.hid or not family.wid:
return False
# if one of the partners has passed away, they are not married.
if not is_alive(individuals, family.hid) or not is_alive(individuals, family.wid):
return False
return True
def is_alive(individuals, individual_id):
"""
Checks if the individual with the given id is alive.
"""
return individuals[individual_id].alive
def first_cousins_married(individuals, families, tag_positions):
"""
User Story 19
Searches and warns if first cousins are married
in the given families and individuals.
returns: a list of warning strings
"""
warnings = []
for fam_id in families:
family = families[fam_id]
parents_child_at = set()
if not family.hid or not family.wid:
continue
husband = individuals[family.hid]
wife = individuals[family.wid]
h_parents = get_parents(individuals, families, family.hid)
w_parents = get_parents(individuals, families, family.wid)
# add parents family where they are child to the variable
h_parents_famc = get_parents_famc(individuals, families, family.hid)
w_parents_famc = get_parents_famc(individuals, families, family.wid)
if h_parents_famc.intersection(w_parents_famc) and not h_parents.intersection(w_parents):
num = tag_positions[fam_id]['HUSB'] | tag_positions[fam_id]['WIFE'] | tag_positions[family.hid]['FAMS'] | tag_positions[family.wid]['FAMS']
warnings.append(f'ANOMALY: FAMILY: US19, line {num} {husband.name} is married to his first cousin {wife.name}!')
return warnings
def get_parents_famc(individuals, families, indi_id):
"""
Find family id of both the parents of the given person.
"""
if not indi_id:
return set()
individual = individuals[indi_id]
parents_famc = set()
if not individual.child:
return set()
for famc in individual.child:
family = families[famc]
if family.hid and individuals[family.hid].child:
father = individuals[family.hid]
parents_famc.update(father.child)
if family.wid and individuals[family.wid].child:
mother = individuals[family.wid]
parents_famc.update(mother.child)
return parents_famc
def get_parents(individuals, families, indi_id):
"""
Find parents of the given person.
"""
if not indi_id:
return set()
individual = individuals[indi_id]
parents = set()
if not individual.child:
return set()
for famc in individual.child:
family = families[famc]
if family.hid:
parents.add(family.hid)
if family.wid:
parents.add(family.wid)
return parents
def check_sibling_counts(individuals, families, tag_positions):
"""
User Story 15
There should be fewer than 15 siblings in a family.
returns: a list of warning strings.
"""
warnings = []
for fam_id in families:
family = families[fam_id]
if family.children and len(family.children) >= 15:
num = tag_positions[fam_id]['CHIL']
for child_id in family.children:
num.update(tag_positions[child_id]['FAMC'])
warnings.append(f'ANOMALY: FAMILY: US15, line {sorted(num)} Family {fam_id} has more than 14 siblings!')
return warnings
def check_marriage_aunts_uncles(individuals, families, tag_positions):
"""
User Story 20
Aunts and uncles should not marry their nieces or nephews.
returns: a list of warning strings.
"""
warnings = []
for indi_id in individuals:
individual = individuals[indi_id]
if not individual.spouse:
continue
parents = get_parents(individuals, families, indi_id)
aunts_uncles = set()
for fam_id in get_parents_famc(individuals, families, indi_id):
aunts_uncles.update(families[fam_id].children)
aunts_uncles = aunts_uncles - parents
for person_id in aunts_uncles:
if (individuals[person_id].spouse).intersection(individual.spouse):
num = tag_positions[indi_id]['FAMS']
warnings.append(f'ANOMALY: FAMILY: US20, line{num} {individual.name} married to their uncle or aunt.')
return warnings
def marriage_before_divorce(individuals, families, tag_positions):
"""
User Story 04
Marriage should be before divorce.
"""
warnings = []
for fam_id in families:
family = families[fam_id]
if family.married and family.divorced:
if family.married > family.divorced:
num = tag_positions[fam_id]['MARR'] | tag_positions[fam_id]['DIV']
warnings.append(f'ANOMALY: FAMILY: US04, line{num}, Divorced before marriage in family {fam_id}.')
return warnings
def marriage_before_death(individuals, families, tag_positions):
"""
User Story 05
Marriage should be before death.
"""
warnings = []
for indi_id in individuals:
individual = individuals[indi_id]
if not individual.spouse or not individual.death:
continue
for fam_spouse_id in individual.spouse:
if families[fam_spouse_id].married and families[fam_spouse_id].married > individual.death:
num = tag_positions[indi_id]['DEAT'] | tag_positions[fam_spouse_id]['MARR']
warnings.append(f'ANOMALY: INDIVIDUAL: US05, line {num}, {individual.name} was married after their death.')
return warnings
def divorce_before_death(individuals, families, tag_positions):
"""
User Story 06
Divorce should be before death.
"""
warnings = []
for indi_id in individuals:
individual = individuals[indi_id]
if not individual.spouse or not individual.death:
continue
for fam_spouse_id in individual.spouse:
if families[fam_spouse_id].divorced and families[fam_spouse_id].divorced > individual.death:
num = tag_positions[indi_id]['DEAT'] | tag_positions[fam_spouse_id]['DIV']
warnings.append(f'ANOMALY: INDIVIDUAL: US06, line {num}, {individual.name} was divorced after their death.')
return warnings
def marriages_to_children(individuals, families, tag_positions):
"""
User Story 17
No marriages to children.
Returns a list of string warnings.
"""
warnings = []
for indi_id in individuals:
individual = individuals[indi_id]
spouses = set()
children = set()
if individual.spouse:
for spouse in individual.spouse:
family = families[spouse]
children |= family.children
if individual.id == family.hid:
spouses.add(family.wid)
else:
spouses.add(family.hid)
child_spouse = spouses.intersection(children)
if child_spouse:
child_spouse = ' '.join(child_spouse)
num = tag_positions[indi_id]['FAMS']
warnings.append(f'ANOMALY: FAMILY: US17, line {num}, {individual.name} is married to their child(ren) {child_spouse}!')
return warnings
def marriages_to_siblings(individuals, families, tag_positions):
"""
User Story 18
No marriages to children.
Returns a list of string warnings.
"""
warnings = []
for fam_id in families:
family = families[fam_id]
if not family.hid or not family.wid:
continue
husband = individuals[family.hid]
wife = individuals[family.wid]
for famc in husband.child:
if famc in wife.child:
num = tag_positions[family.hid]['FAMS'] | tag_positions[family.wid]['FAMS']
warnings.append(f'ANOMALY: FAMILY: US18, line {num}, {husband.name} and {wife.name} are siblings and married to each other!')
return warnings |
3a0e42bfce533825473d8dd2c3b179a5b1903387 | bethewind/pylite | /tests/misc/scope.py | 186 | 3.96875 | 4 | for i in range(3):
print i
def f():
print i
f()
class Animal:
count = 123
def __init__(self):
print self.count
print Animal.count
animal = Animal()
|
4ccba281294de225ce84ad232f62389571f7599e | quinn-n/Math | /factorEquationDev/1st_round/factorEquation.py | 3,356 | 4.15625 | 4 | #!/usr/bin/env python3
from sys import argv
maxLcm = 1000
#import math
chars = "abcdefghijklmnopqrstuvwxyz"
nums = range(10)
operators = "+-*/"
if len(argv) < 2:*
print("Usage: "+argv[0]+" <equation>")
print("Factors an equation. Hopefully. That's the plan anyways.")
exit()
def getType(char):
for c in chars:
if char == c:
return "var"
for num in nums:
if int(char) == num:
return "num"
if char == "(":
return "("
elif char == ")":
return ")"
elif char == "^":
return "^"
elif char == ".":
return "."
for op in operators:
if char == op:
return "operator"
def getNumAtPos(equation, pos): #gets the number after a position. Useful for finding the number after an operation (eg. ^, +, /)
strNum = ""
startPos = pos
elementType = getType(equation[pos])
while elementType == "num" or elementType == ".":
strNum += equation[pos]
return float(strNum), pos - startPos
def hasVar(term,num): #return true if said term has a variable.
if term["vars"][num] == "":
return True
else:
return False
def isInt(num):
if num % 1 == 0:
return True
else:
return False
def isIn(string, char):
strLen = len(string)
for i in range(strLen):
if string[i] == char:
return True
return False
def getLcm(terms): #get the lowest common multiple
numTerms = len(terms)
lcm = 0
for multiple in range(maxLcm,0,-1):
works = True
for termNum in range(numTerms):
for currentNum in range(termNums[0]["nums"]):
if not isInt(terms[termNum]["nums"][currentNum] / multiple):
works = False
if works:
return multiple
def commonFactor(terms,termNum):
numNums = len(terms[termNum]["nums"])
termMultipliers = []
i = 0
while i < numNums:
while n < numNums:
if n != i:
if terms[termNum]["vars"][i]
terms = []
currentBracket = 0
currentNum = 0
rawEquation = argv[1:]
template = {"nums":[],"vars":[],"powers":[],"operators":[]}
equationLen = len(rawEquation)
equationNum = 0
while equationNum < equationLen:
element = rawEquation[equationLen]
elementType = getType(element)
if elementType == "(": #setup terms with a new template & defaults.
terms.append(template)
currentNum = 0
terms[equationNum]["nums"][currentNum] = 1
terms[equationNum]["powers"][currentNum] = 1
terms[equationNum]["vars"][currentNum] = ""
terms[equationNum]["operators"][currentNum] = "+"
elif elementType == ")":
currentBracket += 1
elif elementType == "^":
power, numsSkipped = getNumAtPos(rawEquation, equationNum + 1)
terms[currentBracket]["powers"][currentNum] = power
equationNum += numsSkipped + 1
elif elementType == "var":
terms[currentBracket]["vars"][currentNum] += element
elif elementType == "operator":
terms[currentBracket]["operators"][currentNum] = element
currentNum += 1
elif elementType == "num":
if terms[currentBracket]["nums"][currentNum] == 1:
terms[currentBracket]["nums"][currentNum] = getNumAtPos(rawEquation, equationNum)
equationNum += 1
|
6579311fb8fffd4bd1329d1d74b12772c0f3d0aa | TimothyErcia/DailySolution | /SolutionDay9.py | 1,611 | 4.125 | 4 | """
This problem was asked by Microsoft.
Let's represent an integer in a linked list format by having each node represent a digit in the number.
The nodes make up the number in reversed order.
For example, the following linked list:
1 -> 2 -> 3 -> 4 -> 5
is the number 54321.
"""
import numpy as np
class Node:
def __init__(self, dataVal = None):
self.dataVal = dataVal
self.nextval = None
class LList:
def __init__(self):
self.headNode = Node()
def append_data(self, data):
new_node = Node(data)
current = self.headNode
while current.nextval is not None:
current = current.nextval
current.nextval = new_node
def length_list(self):
current = self.headNode
total = 0
while current.nextval is not None:
total+=1
current = current.nextval
return total
def printList(self):
elements = []
current_node = self.headNode
while current_node.nextval is not None:
current_node = current_node.nextval
elements.append(current_node.dataVal)
return elements
llist = LList()
llist.append_data(1)
llist.append_data(2)
llist.append_data(3)
llist.append_data(4)
llist.append_data(5)
def reverse_list(data):
pp = []
k = 0
while k != data.length_list():
pp.append(data.printList()[k])
k+=1
j = maxPP = len(pp)
i = 0
revList = []
while i != maxPP:
revList.append(pp[j-1])
i+=1
j-=1
return revList
print(reverse_list(llist))
|
71942595cc9b16ad4ef05c240075b7e9cfe0c469 | MikaIce/MacPyGame | /personnage.py | 2,055 | 3.90625 | 4 | #!/usr/bin/python3.8
# -*-coding:utf-8 -
"""
The class personnage manages the movement of our heroe
"""
from constantes import SPRITE_SIZE, NB_SPRITE
class Heroe():
"""
The class Heroe has x and y positions
(pixel and real) as an attribute.
It takes the labyrinth as a parameter
in order to recover the structure.
"""
def __init__(self, labyrinth):
""" Position in pixel: """
self.high = 0
self.low = 0
""" Position in square: """
self.sprite_x = 0
self.sprite_y = 0
#Labyrinth
self.labyrinth = labyrinth
def move(self, direction):
""" Move to the right """
if direction == "right":
if self.sprite_x < NB_SPRITE -1:
if self.labyrinth.grid[self.sprite_y][self.sprite_x+1] != "w":
self.sprite_x += 1
#Position in pixel:
self.high = self.sprite_x * SPRITE_SIZE
#Move to the left
if direction == "left":
if self.sprite_x > 0:
if self.labyrinth.grid[self.sprite_y][self.sprite_x-1] != "w":
#move of one sprite
self.sprite_x -= 1
#Position in pixel:
self.high = self.sprite_x * SPRITE_SIZE
#Move to the bottom
if direction == "bottom":
if self.sprite_y < NB_SPRITE-1:
if self.labyrinth.grid[self.sprite_y+1][self.sprite_x] != "w":
#move on one sprite
self.sprite_y += 1
#Position in pixel:
self.low = self.sprite_y * SPRITE_SIZE
#Move to the top
if direction == "up":
if self.sprite_y > 0: #to avoid go out of the screen
if self.labyrinth.grid[self.sprite_y-1][self.sprite_x] != "w":
#move on one sprite
self.sprite_y -= 1
#Position in pixel:
self.low = self.sprite_y * SPRITE_SIZE
|
0fc7477f2317f9213e8aafcd2d477fab9af2ce01 | hirata-ai/Laplacian_bootstrap | /script/count_ngram.py | 429 | 3.828125 | 4 | #!/usr/bin/python
# -*-coding:utf-8-*-
import sys
from collections import defaultdict
def count_ngram(input_file):
ngram_dic = defaultdict(int)
for line in open(input_file):
line = line.strip()
ngram_dic[line] += 1
for ngram, number in sorted(ngram_dic.items(), key=lambda x:x[1], reverse=True):
print "{}\t{}".format(ngram, number)
if __name__ == "__main__":
count_ngram(sys.argv[1])
|
2b4e595f79ba59a4c5390bf22470f3eb5ee4883d | Neelmaurya/Assignment | /Python Practice Prog/Multiple_Inheritance.py | 772 | 4.15625 | 4 | """
In Multiple inheritance the child inherits more then 1 parent class.
"""
class Parent1:
def assign_string_one(self, str1):
self.str1 = str1
def show_string_one(self):
return self.str1
class Parent2:
def assign_string_two(self, str2):
self.str2 = str2
def show_string_two(self):
return self.str2
class Child(Parent1, Parent2):
def assign_string_three(self, str3):
self.str3 = str3
def show_string_three(self):
return self.str3
my_Child = Child()
my_Child.assign_string_one("I am String of Parent1 ")
my_Child.assign_string_two("I am String of Parent2 ")
my_Child.assign_string_three("I am String of Child")
my_Child.show_string_one()
my_Child.show_string_two()
my_Child.show_string_three() |
ba58193c449ef438465d34ef98edd89ae8fca356 | bharatmazire/Python | /Programs/Advance/Turtle/ModifiedCircleSpiral1.py | 178 | 3.71875 | 4 | import turtle
colors = ['red', 'blue', 'yellow', 'pink']
t = turtle.Pen()
turtle.bgcolor('black')
for x in range(100):
t.color(colors[x%len(colors)])
t.circle(x)
t.left(91)
|
2bf4ecbc377dad7c080db435d289292ff5ddc882 | estefanomoreira/curso-python | /modulo-01/aula02/aula02-conversao.py | 287 | 3.609375 | 4 | v1Str = "5"
v2Str = "6"
totStr = v1Str + v2Str
print(totStr)
v1 = int(v1Str)
v2 = int(v2Str)
tot = v1 + v2
print(tot)
v1FltStr = "4.5"
v2FltStr = "5.5"
totFltStr = v1FltStr + v2FltStr
print(totFltStr)
vFlt1 = float(v1FltStr)
vFlt2 = float(v2FltStr)
totFlt =vFlt1 + vFlt2
print(totFlt) |
1f49fe95301ce7b77e56b087d94acb5eb94bf7e9 | toroleyson/data-prework | /1.-Python/2.-Duel-of-Sorcerers/Problem 2 - Arnoldo Leyson.py | 1,188 | 3.6875 | 4 | Python 3.6.8 (v3.6.8:3c6b436a57, Dec 24 2018, 02:04:31)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> gandalf = [10, 11, 13, 30, 22, 11, 10, 33, 22, 22]
>>> saruman = [23, 66, 12, 43, 12, 10, 44, 23, 12, 17]
>>>
>>> spells = 0
>>> if (len(gandalf) == len(saruman)):
print ("Duel of socerers:")
spells = len(gandalf)
else:
"Sorcerers don't have the same number of spells"
Duel of socerers:
>>> gandalf_wins = 0
>>> saruman_wins = 0
>>> ties = 0
>>>
>>> for i in range (0,spells):
if gandalf[i] > saruman[i]:
gandalf_wins = gandalf_wins + 1
elif saruman[i] > gandalf[i]:
saruman_wins = saruman_wins + 1
else:
ties = ties + 1
>>> print ("Gandalf wins:", gandalf_wins)
Gandalf wins: 6
>>> print ("Saruman wins:", saruman_wins)
Saruman wins: 4
>>> print ("Ties:", ties)
Ties: 0
>>> if gandalf_wins > saruman_wins:
print ("Result of the duel: Gandalf wins")
elif saruman_wins > gandalf_wins:
print ("Result of the duel: Saruman wins")
else:
print ("Result of the duel: Tie")
Result of the duel: Gandalf wins
>>>
|
b5ed78144468806fc1cfd6fb5bd1b63a7afad66e | liadbiz/Leetcode-Solutions | /src/python/greedy_algorithm/dota2_senate.py | 4,412 | 3.796875 | 4 | """
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the senate
wants to make a decision about a change in the Dota2 game. The voting for this
change is a round-based procedure. In each round, each senator can exercise one of the two rights:
Ban one senator's right:
A senator can make another senator lose all his rights in this and all the
following rounds.
Announce the victory:
If this senator found the senators who still have rights to vote are all from
the same party, he can announce the victory and make the decision about the
change in the game.
Given a string representing each senator's party belonging. The character 'R'
and 'D' represent the Radiant party and the Dire party respectively. Then if
there are n senators, the size of the given string will be n.
The round-based procedure starts from the first senator to the last senator in
the given order. This procedure will last until the end of voting. All the
senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his
own party, you need to predict which party will finally announce the victory and make the change in the Dota2 game. The output should be Radiant or Dire.
Example 1:
Input: "RD"
Output: "Radiant"
Explanation: The first senator comes from Radiant and he can just ban the next
senator's right in the round 1.
And the second senator can't exercise any rights any more since his right has
been banned.
And in the round 2, the first senator can just announce the victory since he
is the only guy in the senate who can vote.
Example 2:
Input: "RDD"
Output: "Dire"
Explanation:
The first senator comes from Radiant and he can just ban the next senator's right in the round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And the third senator comes from Dire and he can ban the first senator's right in the round 1.
And in the round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
Note:
The length of the given string will in the range [1, 10,000].
"""
class Solution:
# 思路:
# 对于每一次投票过程(round),遍历senate,维护一个变量dn,表示需要被ban吊的
# 字母的数量,对于每一个被遍历到的字母,如果需要被ban掉,那么就ban掉它,dn-1.
# 知道某一投票过程没有ban掉一个字母,说明投票结束。
# 第一个函数是我的实现,第二个函数是简化实现,思路是一致的。
def predictPartyVictory(self, senate):
"""
:type senate: str
:rtype: str
"""
ban = [0 for i in range(len(senate))]
dn = 0
crt = ''
flag = True
while flag:
i = 0
flag = False
while i < len(senate):
if not ban[i]:
if dn == 0:
crt = senate[i]
dn += 1
elif crt == senate[i]:
dn += 1
elif crt != senate[i]:
flag = True
ban[i] = 1
dn -=1
i += 1
return ['Radiant' if senate[i] == 'R' else 'Dire' for i in range(len(ban)) if ban[i] == 0][0]
# for i in range(len(ban)):
# if ban[i] == 0:
# return 'Radiant' if senate[i] == 'R' else 'Dire'
def predictPartyVictory2(self, senate):
"""
:type senate: str
:rtype: str
"""
delta = 0
while len(set(senate)) > 1:
nsenate = ''
for s in senate:
if s == 'R':
if delta >= 0: nsenate += 'R'
delta += 1
else:
if delta <= 0: nsenate += 'D'
delta -= 1
senate = nsenate
return {'D' : 'Dire', 'R' : 'Radiant'}[senate[0]]
if __name__ == '__main__':
senate1 = "RD"
senate2 = "RDD"
senate3 = "DDRRR"
senate4 = "RRR"
print(Solution().predictPartyVictory(senate1))
print(Solution().predictPartyVictory(senate2))
print(Solution().predictPartyVictory(senate3))
print(Solution().predictPartyVictory(senate4))
|
5fc1e3c62949d8486e2fa0fc872fa2231e3abb2b | MaiadeOlive/Curso-Python3 | /desafios-2mundo-36-71/D055 ANALISE DE PESO.py | 628 | 3.921875 | 4 | maior = 0
menor = 0
for c in range(1, 6):
peso = float(input('Digite o {}º peso '.format(c)))
if c == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
if peso < menor:
menor = peso
print('O menor peso digitado é {}kg.'.format(menor))
print('O maior peso digitado é {}kg.'.format(maior))
#menorpeso = float(peso < c)
# maiorpeso = float(peso > c)
#if peso > c:
# print('O maior peso inserido foi {}'.format(maiorpeso))
#elif c > peso:
# print('O menor peso inserido é {} '.format(menorpeso))
|
b5f238ddd157a8074309c93ad3bb266223b1e550 | garethdmm/experiments | /ruin/ruin.py | 5,271 | 3.90625 | 4 | """
A simple simulation of risk-taking in a domain where risk premiums come with a
proportional chance of ruin. Based on the real world challenge of trading firms choosing
cryptocurrency exchanges to trade on.
We have a set of traders, T, and a set of exchanges E. Traders are given N 'bets' to
represent trading capital, and allocate these between between exchanges. Traders may
allocate multiple (or all) bets on a single exchange. Exchanges give returns at each
step of the simulation, and each exchange has unique return characteristics determined
by a single parameter 'z'. At a low z, exchanges give high returns, but there is also a
high chance that they will "explode" with a complete loss of funds to their traders. As
z increases, both ruin risk and the excess returns decrease exponentially.
"""
from collections import defaultdict
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import colormaps
NEGATIVE_INFINITY = -10000
NUM_STEPS = 2600
NUM_EXCHANGES = 8
BETS_PER_TRADER = 2
BET_SIZE = 1.0 / BETS_PER_TRADER
NUM_TRADERS = NUM_EXCHANGES * BETS_PER_TRADER
MAX_RISK = 30 # The riskiest exchange has a 1 in (MAX_RISK ^ RUIN_DECAY) ruin risk.
RUIN_DECAY = 2 # Exponent by which ruin risk decreases as z increases.
PREMIUM_DECAY = 2.6 # Exponent by which the risk premium decreases as z increases.
MAX_PREMIUM = 0.0009 # Maximum risk premium.
# Default return characteristics for each tick.
RETURN_MEAN = 0
RETURN_STD = 0.007
class Exchange(object):
def __init__(self, z):
self.z = z
self.traders = [] # Trader to notify of a new payoff.
self.is_dead = False
rank = (float(self.z) - MAX_RISK) / (NUM_EXCHANGES - 1)
scale = (1 - rank) ** PREMIUM_DECAY
self.premium = scale * MAX_PREMIUM
def register_trader(self, t):
self.traders.append(t)
def tick(self, tick_num):
if self.is_dead:
payoff = 0.0
elif np.random.randint(0, self.z ** RUIN_DECAY) == 0:
payoff = NEGATIVE_INFINITY
self.is_dead = True
else:
payoff = np.random.normal(
RETURN_MEAN + self.premium,
RETURN_STD,
)
for t in self.traders:
t.receive_payoff(self.z, payoff, tick_num)
class Trader(object):
def __init__(self, trader_id, exchanges):
self.trader_id = trader_id
self.exchanges = exchanges
self.account_balance = defaultdict(lambda: 0.0)
self.account_series = defaultdict(lambda: np.array([]))
self.tick = 0
for e in self.exchanges:
self.account_balance[e.z] += BET_SIZE
for z, initial_balance in self.account_balance.items():
self.account_series[z] = np.array(initial_balance)
for e in self.exchanges:
e.register_trader(self)
def receive_payoff(self, z, payoff, tick):
if tick > self.tick:
self.record_balances(self.tick)
self.tick = tick
self.account_balance[z] += payoff
def record_balances(self, tick):
for z in set([e.z for e in self.exchanges]):
if self.account_balance[z] < 0:
self.account_balance[z] = 0.0
self.account_series[z] = np.append(
self.account_series[z],
[self.account_balance[z]],
)
@property
def returns(self):
return sum([v for k,v in self.account_series.items()])
def contiguous_sublists_size_n(l, n):
return [l[i: i + n] for i in range(0, len(l) - (n - 1))]
def add_colorbar(colormap):
sm = plt.cm.ScalarMappable(cmap=colormap, norm=plt.Normalize(vmin=0, vmax=1))
sm._A = []
cb = plt.colorbar(sm)
#cb.ax.set_yticks([0, 0.5, 1])
#cb.ax.set_yticklabels(['-1', '0', '1'])
cb.set_ticks([0, 1])
cb.set_ticklabels(['High', 'Low'])
cb.set_label('Risk', fontsize=15, rotation=0)
def plot_all_returns(traders):
pd.options.display.mpl_style = 'default'
df = pd.DataFrame([t.returns for t in traders]).transpose()
df.plot(linewidth=5, colormap=colormaps.plasma, figsize=(12, 6))
plt.legend().remove()
add_colorbar(colormaps.plasma)
pretty_plot()
def pretty_plot():
plt.yticks([1])
plt.xticks([])
plt.xlabel('Time', fontsize=15, labelpad=20)
plt.ylabel('Returns', fontsize=15, position=(0, 0.5), labelpad=30, rotation=0)
def generate_exchanges():
return [Exchange(z + MAX_RISK) for z in range(0, NUM_EXCHANGES)]
def generate_traders(exchanges):
exchanges_perm = []
for e in exchanges:
for i in range(BETS_PER_TRADER):
exchanges_perm.append(e)
exchange_sets = contiguous_sublists_size_n(exchanges_perm, BETS_PER_TRADER)
traders = [Trader(i, exchange_sets[i]) for i in range(len(exchange_sets))]
return traders
def run_simulation(exchanges, steps):
for i in range(0, steps):
for exchange in exchanges:
exchange.tick(i)
return exchanges
def main():
exchanges = generate_exchanges()
traders = generate_traders(exchanges)
run_simulation(exchanges, NUM_STEPS)
plot_all_returns(traders)
return traders, exchanges
if __name__ == '__main__':
main()
|
a63e304721d90cc3feeef2645dc0e086165f8612 | HelloYeew/helloyeew-lab-computer-programming-i | /Electric Appliance Store.py | 833 | 3.8125 | 4 | # Enter the number of TVs: 1
# Enter the number of DVD players: 0
# Enter the number of audio systems: 1
# The total amount is 9000.00 baht.
# Please pay 9000.00 baht. Thank you very much.
# The store offers 20% discount to the customer who purchases at least 20000 bahts.
tv = int(input("Enter the number of TVs: "))
dvd = int(input("Enter the number of DVD players: "))
audio = int(input("Enter the number of audio systems: "))
total = (tv*6000)+(dvd*1500)+(audio*3000)
if total>20000:
print(f"The total amount is {total:.2f} baht.")
discount=total*0.2
print(f"You got a discount of {discount:.2f} baht.")
total = total-discount
print(f"Please pay {total:.2f} baht. Thank you very much.")
else :
print(f"The total amount is {total:.2f} baht.")
print(f"Please pay {total:.2f} baht. Thank you very much.") |
4a292838e123aacdffbf1498cfbc6579e8e06ad8 | arnaumas/mknn_homology | /mknn/homology_dict.py | 1,169 | 3.609375 | 4 | class HomDict(dict):
def __init__(self, *args, **kwargs):
self.aux_dict = {}
self.update(*args, **kwargs)
def __setitem__(self, item, value):
if item not in self:
# We are adding a new key to the dictionary
super().__setitem__(item, value)
if value not in self.aux_dict:
# We are setting a new value
self.aux_dict[value] = [item]
else:
# There already exist keys with this value
self.aux_dict[value] += [item]
else:
# The key was already in the dictionary
old_value = self[item]
if value not in self.aux_dict:
# We are setting a new value
self.aux_dict[value] = []
# Update all the other keys that contained the old value
for key in self.aux_dict[old_value]:
self.aux_dict[value].append(key)
super().__setitem__(key, value)
del self.aux_dict[old_value]
def update(self, *args, **kwargs):
for k , v in dict(*args, **kwargs).items():
self[k] = v
|
9f04f5a4f5617fe61474ad8603ac40e1d36dd56c | utkpython/utkpython.github.io | /session5/text_twist.py | 1,502 | 3.53125 | 4 | #!/usr/bin/env python
from itertools import permutations
f = open("dict.txt")
i = 1
l = list()
for line in f:
stripped = line.rstrip("\r\n\t").lower()
if ('\'' in stripped or len(stripped) not in range(1,7)):
continue
else:
l.append(stripped)
#print "Adding item " + str(i)
i += 1
print "Done, processed " + str(i-1) + " items."
f.close()
l.sort()
while True:
i = raw_input("Search for: ")
if (i.lower() == "exit" or i.lower() == "quit"):
break
if (len(i) > 6):
print "Length must be equal to or less than 6."
continue
perms = []
for m in range(1,len(i)+1):
perm = [''.join(p) for p in permutations(i,m)]
perms = perms + perm
perms = list(set(perms))
perms.sort(key=len)
unique = []
for p in perms:
if (nsearch(p, l)) and p not in unique:
print "Possilbe string: " + p
unique.append(p)
while True:
i = raw_input("Search for: ")
if (i.lower() == "exit" or i.lower() == "quit"):
break
if (len(i) > 6):
print "Length must be equal to or less than 6."
continue
perms = []
for m in range(1,len(i)+1):
perm = [''.join(p) for p in permutations(i,m)]
perms = perms + perm
perms = list(set(perms))
perms.sort(key=len)
unique = []
for p in perms:
if (bisearch(p, l)) and p not in unique:
print "Possilbe string: " + p
unique.append(p)
|
80ba77499ae09314a6dac38e30c068e1cf6b2c7a | maumneto/exercicio-python | /codigos-aula/cod2.py | 167 | 3.75 | 4 | nota_1 = float(input('Digite a primeira nota: '))
nota_2 = float(input('Digite a segunda nota: '))
media = (nota_1 + nota_2)/2
print('A média do aluno é: ', media) |
d31d572f518b565fd583f7176f9d54bfe7b9feae | noozip2241993/homework7 | /task1.py | 1,012 | 3.671875 | 4 | import random
import statistics
from collections import Counter
#set a ramdom seed generator
random.seed(2020)
#set number of integers
integers = 20
random_number= [random.randrange(100,121) for _ in range(integers)]
sort_random_number = sorted(random_number)
print(sort_random_number)
count_numbers = len(sort_random_number)//2
Median = (sort_random_number[count_numbers - 1] + sort_random_number[count_numbers])/2
print(f'Mannually Median is {Median}')
test_median = statistics.median(random_number)
print(f'Statistics module Median is {test_median}')
#set a unique list
unique_list = set(sort_random_number)
data = Counter(sort_random_number)
print(data)
get_mode = dict(data)
mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]
print(f'Mannually Mode is {mode}')
test_mode = statistics.mode(random_number)
print(f'Statistics module Mode is {test_mode}')
list_all_mode = [k for k, v in get_mode.items() if v >= 2]
print(f'Two or more number have the same frequency:\n{list_all_mode}') |
6071a1f0b6e5556fecab8fa101668490527a65f4 | returnpie/data-structures | /hash-table/dictionary-in-python.py | 284 | 3.90625 | 4 | d = {'name': 'Kevin', 'age': 34, 'gender': 'male'}
print(d.keys())
print(d.values())
print(d['name'])
print(d['age'])
print(d['gender'])
print('---------')
for key, value in d.items():
print(key, value)
d.clear()
print(d.keys())
print(d.values())
# delete dictionary
# del d |
b914457c664fe0100a16c2fbe64534eadf779636 | rifqirosyidi/python-simple-kabisat | /main-file.py | 407 | 3.5 | 4 |
list_jumlah_bulan = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def kabisat(tahun):
return tahun % 4 == 0 and (tahun % 100 != 0 or tahun % 400 == 0)
def hari_di_bulan(tahun, bulan):
if not 1 <= bulan <= 12:
return "Bulan Tidak Valid"
if bulan == 2 and kabisat(tahun) == True:
return 29
return list_jumlah_bulan[bulan]
# print hari_di_bulan(tahun, bulan)
print(hari_di_bulan(1998,2)) |
8c6dcfbd25a9a3d27ba19c0d0ccc0a13bb4dbf39 | jaqxues/AL_Info | /Cours_1ere/Chapter2/Ex2_1.py | 2,004 | 3.828125 | 4 | from profile import run
from time import perf_counter
from timeit import timeit
from math import sqrt
def fib_it(n):
"""
Time Complexity: range(n) -> O(n)
"""
x, y = 0, 1
for _ in range(n):
x, y = y, x + y
return x
def fib_rec(n):
"""
Time Complexity: O(2**n)
"""
if n < 2:
return n
return fib_rec(n - 1) + fib_rec(n - 2)
def fib_dir(n):
"""
Time Complexity: O(1)
"""
phi = (1 + sqrt(5)) / 2
psi = (1 - sqrt(5)) / 2 # - 1 / phi
return round((1 / sqrt(5)) * (phi ** n - psi ** n))
if __name__ == '__main__':
print("Testing Fibonacci Numbers")
for i in range(20):
f = fib_it(i)
assert f == fib_rec(i) == fib_dir(i), "Values not matching"
print(f'{i:5} - {f:5}')
'''
Mechanisms for measuring time accurately in Python:
* Using the time Library (not recommended)
* time.time: Unsuitable for accurate measuring (in given cases only precision of 1 second as stated in the docs)
* time.perf_counter (time.process_time): Allows measuring Time deltas more accurately.
* timeit.timeit: Executes a given statement n times and returns the average value of time per single execution.
* profile.run: Profiles the method and shows a more in-depth analysis.
It is generally not recommended to use time for measuring statements and functions in Python. Use timeit or profile.
'''
start = perf_counter()
for _ in range(10):
fib_rec(30)
print('Measuring with time (recursive):', perf_counter() - start)
print()
print("Measuring with timeit")
print("* Iterative:", timeit('fib_it(30)', 'from __main__ import fib_it', number=10))
print("* Recursive:", timeit('fib_rec(30)', 'from __main__ import fib_rec', number=10))
print()
print("Measuring iterative and recursive implementations with profile.run")
print("* Iterative")
run('fib_it(30)')
print("* Recursive")
run('fib_rec(30)')
|
555d299cc324d05a8297ea9edd5ea418af9c89ca | dougfunny1983/Hello_Word_Python3 | /ex059.py | 1,594 | 4.15625 | 4 | print('''#############################
##Criando um Menu de Opções##
#############################''')
print('→←'*30)
maior = menor = 0
while True:
n1 = int(input('Digite o primeiro numero → '))
n2 = int(input('Digite o segundo numero → '))
opcao =int(input('Escolha um opção parar:\n'
'# 1 para Adição\n'
'# 2 para subtração\n'
'# 3 para divisao\n'
'# 4 para multiplicacao\n'
'# 5 para maior número\n'
'# 6 para menor numero\n'
'# 7 para novos números\n'
'# 0 para sair → '))
if n1 > n2:
maior = n1
menor = n2
else:
maior = n2
menor = n1
print(f'Voce escolheu a opção: {opcao}')
if opcao >= 0 and opcao < 8:
if opcao == 1:
print(f'{n1} + {n2} = {n1+n2}')
elif opcao == 2:
print(f'{n1} - {n2} = {n1-n2}')
elif opcao == 3:
print(f'{n1} ÷ {n2} = {n1/n2}')
elif opcao == 4:
print(f'{n1} X {n2} = {n1*n2}')
elif opcao == 5:
print(f'entre o {n1} e o {n2} o maior é {maior}')
elif opcao == 6:
print(f'Entre o {n1} e o {n2} o menor é {menor}')
elif opcao == 7:
print('Escolha novos numeros.')
elif opcao == 0:
print('Finalizando o programa')
print('Volte sempre!!!')
break
else:
print('Opção incorreta. Escolha entre 0 e 7')
print('→←'*30)
|
5136f2fbab3a129347874b367e5f9d4d3d6a2ece | AmalKrishna94/my_code | /Python_programs/swapping.py | 203 | 4.0625 | 4 | number1 = int(input("Enter num1: "))
number2 = int(input("Enter num2: "))
temp = number1
number1 = number2
number2 = temp
print("The swapped numbers are num1: {0}, num2: {1}".format(number1, number2))
|
f5908325b787e43baa0f4cd085ce299042905e65 | AnetaStoycheva/Programming0_HackBulgaria | /Week 9/sort_non_mutating.py | 1,275 | 3.921875 | 4 | # a --> selection_sort --> b (не го мутира, а връща нов списък)
# [0, 5, 7, 8, -2, -3] --> [-3, -2, 0, 5, 7, 8]
def diff(list1, list2):
result = []
for a in list1:
if a not in list2:
result.append(a)
return result
print(diff([0, 1, 3, 5], [0, 1])) # връща разликата - [3, 5]
# взима индекса на най-малкия елемент, неизползван досега
def min_index_without_used(list_numbers, from_index): # items, used
unused_indexes = diff(range(0, len(list_numbers)), from_index)
min_index = unused_indexes[0]
for index in unused_indexes:
if list_numbers[index] < list_numbers[min_index]:
min_index = index
return min_index
# for index in range(from_index, len(list_numbers)):
# if list_numbers[index] < list_numbers[min_index]:
# min_index = index
# return min_index
def selection_sort(a_list):
result = []
used_indexes = []
while len(result) != len(a_list):
min_index = min_index_without_used(a_list, used_indexes)
used_indexes.append(min_index)
result.append(a_list[min_index])
return result
print(selection_sort([1, 4, 7, -9, 7, 4, -100, -3]))
|
c34c836d35f88fe96603235a4120fe2b5787884d | MrFey/deneigement_montreal | /Demo/scripts/fleury.py | 2,973 | 4.09375 | 4 | #! /usr/bin/env python3
#-- all rights: @fey --#
#-- py-version: 3.* --#
from copy import copy
'''
is_connected - Checks if a graph in the form of a dictionary is
connected or not, using Breadth-First Search Algorithm (BFS)
'''
def is_connected(G):
start_node = list(G)[0]
color = {v: 'white' for v in G}
color[start_node] = 'gray'
S = [start_node]
while len(S) != 0:
u = S.pop()
for v in G[u]:
if color[v] == 'white':
color[v] = 'gray'
S.append(v)
color[u] = 'black'
return list(color.values()).count('black') == len(G)
'''
odd_degree_nodes - returns a list of all G odd degrees nodes
'''
def odd_degree_nodes(G):
odd_degree_nodes = []
for u in G:
if len(G[u]) % 2 != 0:
odd_degree_nodes.append(u)
return odd_degree_nodes
'''
from_dict - return a list of tuples links from a graph G in a
dictionary format
'''
def from_dict(G):
links = []
for u in G:
for v in G[u]:
links.append((u,v))
return links
'''
fleury(G) - return eulerian trail from graph G or a
string 'Not Eulerian Graph' if it's not possible to trail a path
'''
def fleury(G):
'''
checks if G has eulerian cycle or trail
'''
odn = odd_degree_nodes(G)
#print(odn)
if len(odn) > 2 or len(odn) == 1:
return 'Not Eulerian Graph'
else:
g = copy(G)
trail = []
if len(odn) == 2:
u = odn[0]
else:
u = list(g)[0]
# - - -
init = len(from_dict(g)) + 0.0
old_pourcentage = -1
# - - -
while len(from_dict(g)) > 0:
# - - - - Affichage du % - - - - -
pourcentage = round((init - len(from_dict(g)) )*100.0/init, 1)
if pourcentage > old_pourcentage:
len_to_clear = len(str(old_pourcentage))+1
clear = '\x08' * (len_to_clear + 2)
old_pourcentage = pourcentage
print(clear,end="")
print("\r[*] Compute Eulerian path:", pourcentage, "%", end='', flush=True)
print(clear,end="")
# - - - - - - - - - - - - - - - - -
current_vertex = u
for u in g[current_vertex]:
g[current_vertex].remove(u)
g[u].remove(current_vertex)
bridge = not is_connected(g)
if bridge:
g[current_vertex].append(u)
g[u].append(current_vertex)
else:
break
if bridge:
g[current_vertex].remove(u)
g[u].remove(current_vertex)
g.pop(current_vertex)
trail.append((current_vertex, u))
print("\r[*] Compute Eulerian path:", "100", "%", end='', flush=True)
print("\n[+] Euleriand Path Found !")
return trail
|
1688ca90650cb2375b5850087f0ec41cbdf1b3b4 | priyaSNHU/Practice-Questions | /Searching and sorting/searching/binary_search.py | 862 | 4.1875 | 4 | from bubble_sort import bubble
def bin_search(a_list, item):
first = 0
last = len(a_list) - 1
found = False
while first <= last and not found:
mid_point = (first+last)//2
if (a_list[mid_point] == item):
found = True
print('The element is found at %d', mid_point)
else:
if (item < a_list[mid_point] ):
last = mid_point-1
else:
first = mid_point+1
return found
def main():
a_list = []
num = int(input('Enter the number of elements: '))
for i in range(0,num):
num_item = input('enter the elements in the array: ')
a_list.append(num_item)
bubble(a_list)
print(a_list)
search_element = input('enter the element you want to search for: ')
bin_search(a_list , search_element)
main()
|
ead684bfbf858b344ce9c9392061c9e252ed7407 | erkyrath/remglk | /jsonvalidate.py | 459 | 3.625 | 4 | #!/usr/bin/env python3
# Read a stream of JSON from stdin. Display each one as it is read.
# If a syntax error occurs, it won't actually be detected; the output
# will just freeze up.
import sys
import json
dec = json.JSONDecoder()
dat = ''
while True:
ln = sys.stdin.readline()
if (not ln):
break
dat = dat + ln
try:
(obj, pos) = dec.raw_decode(dat)
dat = dat[ pos : ]
print(obj)
except:
pass
|
3869595bb92e83554bdecc7fc45ee1dda41ce6b9 | thevictormaina/news-app | /tests/test_article.py | 1,270 | 3.765625 | 4 | import unittest
from app.models import Article
class TestArticle(unittest.TestCase):
"""
Tests for Article class
Args:
unittest.TestCase: This class inherits from unittests
"""
def setUp(self):
"""
Runs before each test
"""
self.new_article = Article(source_id="bbc-news", source_name="BBC News", author="Mariella Moon", title="'One day everyone will use China's digital currency'", description="China plans a digital version of its currency, which some say could become a big global payment system.", url="https://www.bbc.co.uk/news/business-54261382", url_to_image="https://ichef.bbci.co.uk/news/1024/branded_news/C414/production/_114569105_chandler.racks.jpg", published_at="2020-09-24T23:16:08Z")
def tearDown(self):
"""
Runs after each test
"""
def test_init(self):
"""
Test case to check if article object is properly initialized
"""
self.assertIsInstance(self.new_article, Article
)
def test_format_time(self):
"""
Test case to check if date is being formatted correctly
"""
date_time = self.new_article.format_time()
self.assertEqual(date_time, "23:16 Sept 24, 2020")
|
0a01510f15a9487bd1a9a47f7fbf274f2369ecd1 | fujihiraryo/aizu-online-judge | /GRL/05A_DiameterOfTree.py | 662 | 3.703125 | 4 | import heapq
INF = 1 << 30
def dijkstra(graph, start):
dist = [INF] * len(graph)
dist[start] = 0
heap = [(0, start)]
heapq.heapify(heap)
while heap:
_, x = heapq.heappop(heap)
for y in graph[x]:
if dist[y] > dist[x] + graph[x][y]:
dist[y] = dist[x] + graph[x][y]
heapq.heappush(heap, (dist[y], y))
return dist
n = int(input())
graph = [{} for _ in range(n)]
for _ in range(n - 1):
x, y, w = map(int, input().split())
graph[x][y] = w
graph[y][x] = w
dist_from_0 = dijkstra(graph, 0)
x = max(range(n), key=lambda x: dist_from_0[x])
print(max(dijkstra(graph, x)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.