blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8a25b07e40fb6859fdbd7d6e26f3a36fe95b7087 | waithope/leetcode-jianzhioffer | /剑指offer/17-打印从1到最大的n位数.py | 2,319 | 3.90625 | 4 | # -*- coding:utf-8 -*-
'''
打印从1到最大的n位数
==========================
输入数字n,按顺序打印从1到最大的n位十进制数。比如输入3,则打印出1、2、3
一直到最大的3位数999
'''
def print1ToMaxOfNDigits(n):
'''
提示:由于没有规定n的范围,当输入的n非常大的时候,可能会出现溢出的情况,
也就是说我们要考虑大数问题。
'''
def incrementBy1(nums):
isOverflow = False
carry = 1
for i in range(len(nums)-1, -1, -1):
res = nums[i] + carry
carry = res // 10
nums[i] = res % 10
if i == 0 and carry:
isOverflow = True
return isOverflow
def printNumber(nums):
isBeginningZero = True
res = ''
for i in range(len(nums)):
if nums[i] != 0 and isBeginningZero:
isBeginningZero = False
if not isBeginningZero:
res += str(nums[i])
if res:
print(res)
if not isinstance(n, int) or n <= 0:
return
nums = [0] * n
while not incrementBy1(nums):
printNumber(nums)
def print1ToMaxOfNDigits_Recursively(n):
'''
提示:把n位数看成是一个全排列问题,每一位的数值范围都是从0~9递增,用递归可使代码更简洁
'''
def printNumber(nums):
isBeginningZero = True
res = ''
for i in range(len(nums)):
if nums[i] != 0 and isBeginningZero:
isBeginningZero = False
if not isBeginningZero:
res += str(nums[i])
if res:
print(res)
def digitsPermutation(nums, index):
if index == len(nums):
printNumber(nums)
return
for i in range(10):
nums[index] = i
digitsPermutation(nums, index+1)
if not isinstance(n, int) or n <= 0:
return
nums = [0] * n
digitsPermutation(nums, 0)
if __name__ == '__main__':
# testing for normal version
print1ToMaxOfNDigits(0)
print1ToMaxOfNDigits(1)
print1ToMaxOfNDigits(2)
# testing for recursive version
print1ToMaxOfNDigits_Recursively(0)
print1ToMaxOfNDigits_Recursively(1)
print1ToMaxOfNDigits_Recursively(2)
|
d37300a9674231ae93cd74607fb136059bcc9ac0 | leodengyx/LeoAlgmExercise | /DataStructure/Queue/linked_queue.py | 2,314 | 4.28125 | 4 | class Node(object):
'''
Defines a class for Queue Node
'''
def __init__(self, value=None):
self.value = value
self.next = None
def __repr__(self):
#return "{value: %s, next: '%s'}" % (self.value, self.next)
return str(self.value)
def __str__(self):
return str(self.value)
class Queue(object):
'''
Defines a class for Queue which acts as a container for nodes that are
inserted and removed according FIFO
'''
def __init__(self):
self.front = None
self.back = None
def isEmpty(self):
return (self.front is None) and (self.back is None)
def enqueue(self, value):
node = Node(value)
if self.back:
self.back.next = node
self.back = node
if self.front is None:
self.front = node
def dequeue(self):
if self.front:
value = self.front.value
self.front = self.front.next
if self.front is None:
self.back = None
return value
else:
raise Exception("Queue is empty")
def size(self):
node = self.front
if node:
num_nodes = 1
else:
return 0
node = node.next
while node:
num_nodes += 1
node = node.next
return num_nodes
def peak(self):
if self.front:
return self.front.value
else:
return None
def __repr__(self):
items = list()
node = self.front
while node:
items.append(node)
node = node.next
return "<front>%s<back>" % repr(items)
def __str__(self):
items = list()
node = self.front
while node:
items.append(node)
node = node.next
return "<front>%s<back>" % str(items)
def main():
queue = Queue()
queue.enqueue(1)
print(str(queue))
queue.enqueue(2)
print(str(queue))
queue.enqueue(3)
print(str(queue))
print(queue.size())
print(queue.peak())
print(queue.dequeue())
print(str(queue))
print(queue.peak())
if __name__ == "__main__":
main()
def main():
queue = Queue()
queue.enqueue(1)
if __name__ == "__main__":
main()
|
2086a97245aaa323671d6c587d3f1be6993558f8 | shasha9/30-days-of-code-hackerrank | /Day_22_Binary_Search_Trees.py | 671 | 4.21875 | 4 | #Task
#The height of a binary search tree is the number of edges between the tree's root and its furthest leaf.
#You are given a pointer,root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of the binary search tree.
def getHeight(self,root):
if root.left==None and root.right==None:
return(0)
else:
hLeft = 0
hRight = 0
if root.left:
hLeft = self.getHeight(root.left) + 1
if root.right:
hRight = self.getHeight(root.right) + 1
return(max(hLeft, hRight))
|
17f5b1773906e9bdb0e1dc5d745092037a4e15f8 | nrndll/roguelike_tutorial | /action.py | 1,136 | 3.5 | 4 | class Action:
def perform(self, engine, entity):
# do this within the engine, entity performs the action
# this raises an error and so Action must be overridden by one of the subclasses
raise NotImplementedError()
# action when escape is pressed, exits program
class EscapeAction(Action):
def perform(self, engine, entity):
raise SystemExit()
# movement will take positional arguements, dx and dy, to handle player movement based on key inputs.
class MovementAction(Action):
def __init__(self, dx: int, dy: int):
super().__init__()
self.dx = dx
self.dy = dy
def perform(self, engine, entity):
dest_x = entity.x + self.dx
dest_y = entity.y + self.dy
# don't move if movement will be out of bounds of game map
if not engine.game_map.in_bounds(dest_x, dest_y):
return
# don't move if the destination tile is not walkable, i.e. a floor tile
if not engine.game_map.tiles["walkable"][dest_x, dest_y]:
return
entity.move(self.dx, self.dy)
|
2df07640c4586f83b7d5e1bc72bc69dc03b9f476 | ThisIsJorgeLima/DS-Unit-3-Sprint-2-SQL-and-Databases | /module4-acid-and-database-scalability-tradeoffs/practice_on_titanic (1).py | 2,132 | 3.609375 | 4 | import pandas as pd
import numpy as np
import sqlite3
import psycopg2
!pip install psycopg2-binary
df = pd.read_csv('https://raw.githubusercontent.com/EvidenceN/DS-Unit-3-Sprint-2-SQL-and-Databases/master/module2-sql-for-analysis/titanic.csv')
df.head()
# In case we have issues with spaces and /:
df.columns = df.columns.str.replace(' ', '_')
df.columns = df.columns.str.replace('/', '_')
# Lets get rid of the ' in some of the names
df.Name = df.Name.str.replace("'", " ")
# The longest name in Name column for table creation:
df.Name.map(lambda x: len(x)).max()
sq_conn = sqlite3.connect('titanic.sqlite3')
sq_curs = sq_conn.cursor()
#Database elephantSQL acct. info:
#Our Connection object :
pg_conn = psycopg2.connect(dbname=dbname, user = user, password=password, host=host)
pg_curs = pg_conn.cursor()
# Create en# type for Sex
query1 = "CREATE TYPE gender AS ENUM ('male', 'female');"
pg_curs.execute(query1)
# Remember when creating your table add in
# PRIMARY KEY on first insert.
#Create insert_titanic table:
create_insert_titanic = """
CREATE TABLE insert_titanic (
Passenger_ID SERIAL PRIMARY KEY,
Survived INT,
Pclass INT,
Name VARCHAR(85),
Sex gender,
Age FLOAT,
Siblings_Spouses_Aboard INT,
Parents_Children_Aboard INT,
Fare FLOAT
);
"""
# Lets now exexute this:
pg_curs.execute(create_insert_titanic)
passengers = sq_curs.execute('SELECT * from insert_titanic;').fetchall()
# Lets work on our for loop now and insert our data from sqlite3
# into our postgres table:
for passenger in passengers:
insert_passenger = """
INSERT INTO insert_titanic
(Survived, Pclass, Name, Sex, Age, Siblings_Spouses_Aboard,
Parents_Children_Aboard, Fare)
VALUES """ + str(passenger[1:]) + ";"
pg_curs.execute(insert_passenger)
pg_curs.execute('SELECT * from insert_titanic;')
pg_curs.fetchall()
# Make sure rows match between 2 tables:
pg_passengers = pg_curs.fetchall()
for passenger, pg_passenger in zip(passengers, pg_passengers):
assert passengers == pg_character
# Close connections and commit changes:
pg_curs.close()
pg_conn.commit()
sq_curs.close()
sq_conn.commit()
|
66a28b65bab0ef1f85625288b7e04a37be036771 | JohnBrown19/TTS_Notes | /DS/Day 5/Hackerrank exercises Day 5.py | 898 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 11:13:25 2020
@author: Jbrown
"""
#Exercise 1
from itertools import product
X = list(map(int, input().split()))
Y = list(map(int, input().split()))
XCrossY = product(X, Y)
print(*XCrossY)
#Exercise 2
from itertools import permutations
def Permutations(str, num):
text = list(permutations(str, num))
text.sort()
for i in text:
print(''.join(i))
if __name__ == "__main__":
str, num = input().split(' ')
Permutations(str, int(num))
#Exercise 3
from itertools import combinations_with_replacement as cwr
word, num = input().split(' ')
num = int(num)
text = list(cwr(word, num))
combinations = []
for combs in text:
result = ""
combs = sorted(combs)
for i in combs:
result += i
combinations.append(result)
combinations.sort()
for combs in combinations:
print(combs)
|
a7241f4b617ab69e21b4a12fed29392376c4fdf2 | Viola8/Python-Exercises | /dct4.py | 724 | 4.15625 | 4 | # Write a Python program to multiply all the values in a dictionary.
dct = {'a':1,'b':2,'c':3}
answer = 1
for key in dct:
answer = answer * dct[key]
print(answer)
# Write a Python program to remove a key from a dictionary.
# 1 using pop()
dct2 = {'a':2,'b':4,'c':6,'d':8}
dct2.pop("a")
print(dct2) # {'b':4,'c':6,'d':8}
# 2 using del
if 'a' in dct2:
del dct2['a']
print(dct2) # {'b':4,'c':6,'d':8}
# Write a Python program to map two lists into a dictionary.
keys = ['31', '32', '40']
values = ['Alana','Ben', 'Rodger']
print(dict(zip(keys,values)))
# Write a Python program to sort a dictionary by key.
dct = {'Oscar': 2, 'Michael': 4, 'Ana': 3, 'Seth': 1, 'John': 0}
print(sorted(dct))
|
f34f023d1a9a7d8668b7c2e756ad602710a6f424 | theyujisamfull/EP-Google | /tarefa2.py | 8,555 | 3.96875 | 4 |
# Define funçoes para operar com matrizes e vetores
def mult(A,b):
'''Multiplica uma matriz quadrada por um vetor'''
return( [sum( A[i][j]*b[j] for j in range(len(A)) ) for i in range(len(A))] )
def soma(A,B):
'''Soma duas matrizes quadradas de mesmo tamanho'''
return( [A[j] + B[j] for j in range(len(A))] )
def sub(a,b):
'''Subtrai dois vetores de mesmo tamanho'''
return( [a[i]-b[i] for i in range(len(a))] )
def norma(a):
'''Calcula a norma de primeira ordem de um vetor'''
return( sum( [abs(x) for x in a] ) )
def multEscalar(A,e):
'''Multiplica uma matriz quadrada por um número'''
return( [e*A[j] for j in range(len(A))] )
def gerar_matriz_grupos_e_paginas_cacique():
'''Não recebe parâmetro e retorna uma lista de listas, e uma lista de numeros.
matriz_grupos é uma lista de listas na forma
[[1,2],[3,4,5],[6,7,8,9],...,[210,211,...,230]]
Cada uma das listas internas representa um grupo de paginas,
e o valor de seus elementos identificam as páginas.
A primeira página de cada grupo é sempre um cacique, isto é, as
páginas 1,3,6,...,210 são caciques.
paginas_cacique é uma lista na forma
[1,3,6,10,...,210]
Cada um desses valores representa uma página cacique
'''
matriz_grupos = []
paginas_cacique = []
for grupo in range(1,21):
pagina_cacique = int((grupo * (grupo + 1)) / 2)
paginas_cacique.append(pagina_cacique)
quantidade_paginas_indio = grupo
matriz_grupo = []
for pagina in range(pagina_cacique, pagina_cacique + quantidade_paginas_indio + 1):
matriz_grupo.append(pagina)
matriz_grupos.append(matriz_grupo)
return (matriz_grupos,paginas_cacique)
def gerar_pesos_links(matriz_grupos):
'''Recebe uma lista de listas, e retorna uma lista de números.
pesos_links é uma lista de numeros que representam os pesos relativos
de cada página, isto é, o valor que cada link saindo dessa página adicionara
na importancia da pagina para qual aponta.
Esse valor é igual a um divido pelo número de links que saem da página
'''
pesos_links=[]
for grupo in range(0,20):
for posicao_pagina in range(len(matriz_grupos[grupo])):
if posicao_pagina == 0: # significa que é cacique
quantidade_links = len(matriz_grupos[grupo]) - 1 + 20 - 1 # 20 caciques
pesos_links.append(1 / quantidade_links)
else: # significa que é indio
quantidade_links = len(matriz_grupos[grupo]) - 1
pesos_links.append(1 / quantidade_links)
return pesos_links
def encontrar_grupo(matriz_grupos, pagina):
'''Recebe uma lista de listas e um número, e retorna um número.
Dado um número que representa uma página, retorna o índice
da sublista de matriz_grupos que contém esse número, este indice
representa o grupo em que a página está contida
'''
for grupo in range(0,20):
if pagina in matriz_grupos[grupo]:
return grupo
def gerar_matriz_de_ligacao(matriz_grupos, paginas_cacique, pesos_links):
matriz_de_ligacao=[]
V=[]
L=[]
C=[]
# Cada uma das 230 pagina_chegada representam cada uma das linhas da matriz
# de ligação
for pagina_chegada in range(1,231):
#Verifica se a pagina_chegada é cacique
if pagina_chegada in paginas_cacique:
#Encontra a qual grupo tal pagina_chegada pertence
grupo_da_pagina = encontrar_grupo(matriz_grupos, pagina_chegada)
#A pagina_chegada é apontada pelos elementos do seu grupo e por
#os outros caciques. Ordena-se as paginas que apontam para pagina_chegada
p= paginas_cacique+matriz_grupos[grupo_da_pagina]
p.sort()
#pagina_saida são todas as paginas que apontam para pagina_chegada
for pagina_saida in p:
#Adiciona os pesos (1/numero de paginas que saem) das paginas
#que apontam pra pagina_chegada na matriz V.
#E pra cada um desses pesos adiciona-se nas matrizes L e C
#a linha e a coluna em que se encontram na matriz de ligação
#obs: o pagina_chegada nao aponta pra ela mesma por isso verifica
#se pagina_saida é diferente da pagina_chegada
if pagina_saida != pagina_chegada:
V.append(pesos_links[pagina_saida - 1])
L.append(pagina_chegada - 1)
C.append(pagina_saida - 1)
#A pagina_chegada é indio
else:
#Encontra a qual grupo tal pagina_chegada pertence
grupo_da_pagina = encontrar_grupo(matriz_grupos, pagina_chegada)
#pagina_saida são todas as paginas que apontam para pagina_chegada
for pagina_saida in matriz_grupos[grupo_da_pagina]:
#Adiciona os pesos (1/numero de paginas que saem) das paginas
#que apontam pra pagina_chegada na matriz V.
#E pra cada um desses pesos adiciona-se nas matrizes L e C
#a linha e a coluna em que se encontram na matriz de ligação
#obs: o pagina_chegada nao aponta pra ela mesma por isso verifica
#se pagina_saida é diferente da pagina_chegada
if pagina_saida != pagina_chegada:
V.append(pesos_links[pagina_saida - 1])
L.append(pagina_chegada - 1)
C.append(pagina_saida - 1)
return (V,L,C)
def calcular_y(xi,V,L,C):
'''Recebe quatro listas e retorna uma lista.
Dado um vetor xi que representa os valores das importancias das paginas em
uma certa iteração, utiliza os vetores V, L, e C, para calcular a próxima
iteração do vetor xi de importancias. O vetor V guarda os valores não nulos
da matriz de ligação, e os vetores L e C guardam suas posições da linha e coluna
na matriz de ligação.
'''
y=230*[0]
for s in range(0,3460):
y[L[s]]=y[L[s]]+V[s]*xi[C[s]]
return y
def main():
#Matriz_grupos é a matriz que contém vetores que representam cada um dos
#20 grupos, ou seja, cada um desses vetores possuem as páginas do grupo.
(matriz_grupos, paginas_cacique) = gerar_matriz_grupos_e_paginas_cacique()
#pesos_links é vetor que carrega os pesos (1/numero de paginas que saem
#da pagina) de cada uma das 230 paginas.
pesos_links = gerar_pesos_links(matriz_grupos)
#Gera os vetores V=vetores não nulos da matriz de ligação,L,C são os indices
# da linha e coluna de cada um desses elementos não nulos.
(V,L,C) = gerar_matriz_de_ligacao(matriz_grupos,paginas_cacique,pesos_links)
x0 = 230*[1/230]
y = calcular_y(x0,V,L,C)
x1 = x0
m = 0.15
x2 = soma(multEscalar(y,1-m),multEscalar(x0,m))
while(norma(sub(x2,x1))>10**(-5)):
x1=x2
y=calcular_y(x1,V,L,C)
x2 = soma(multEscalar(y,1-m),multEscalar(x0,m))
# Cria uma lista de tuplas na forma [(pagina,importancia)]
paginas_rankeadas = list(enumerate(x2))
# Cria uma lista na forma [(pagina,importancia)] somente com o cacique e a
# primeira página indio de cada grupo
paginas_rankeadas_sem_repeticao = []
for pagina_cacique in paginas_cacique:
paginas_rankeadas_sem_repeticao.append(paginas_rankeadas[pagina_cacique-1])
paginas_rankeadas_sem_repeticao.append(paginas_rankeadas[pagina_cacique])
# Ordena os elementos da lista criada em ordem descrescente de importância
paginas_rankeadas_sem_repeticao = sorted(paginas_rankeadas_sem_repeticao,
key = lambda item: item[1],
reverse=True)
# Printa uma tabela com os rankings, números da paginas, importancias, e indica
# se é cacique ou não
print("\n|{0:^9}|{1:^8}|{2:^10}|{3:^19}|".format("Ranking","Página","Cacique?","Importância"))
for pagina in enumerate(paginas_rankeadas_sem_repeticao):
print("|{rank:^9}|{pag:^8}|{cacique:^10}|{imp:^19.12}|".format(
rank=pagina[0]+1,
pag=pagina[1][0]+1,
cacique= "Sim" if pagina[1][0]+1 in paginas_cacique else "Não",
imp=pagina[1][1]))
main()
|
f768de451b36a9b17d4086efc0d78307f1b09cbc | Foundations-of-Applied-Mathematics/Advanced-Programming | /2018_WinterMaterials/SolutionsToHardProblems/components-in-graph.py | 2,489 | 3.875 | 4 | # This solves each test case for https://www.hackerrank.com/challenges/components-in-graph/problem
# by implementing a DisjointSet: See https://en.wikipedia.org/wiki/Disjoint-set_data_structure
# Note: this does not implement path compression or flattening, as it is not needed for this problem.
class DisjointSet:
def __init__(self):
# self.size_by_parents is a dictionary from key -> # of vertices
self.size_by_parents = dict()
#self.parents_by_node is a dictionary from node -> parent
self.parents_by_node = dict()
def addBtoA(self,a,b):
"""Given two parent nodes, possibly parents of the singleton set,
Adds the b set, to the 'a' set.
If we aren't already tracking 'a', begin to do so.
Parameters:
a (int) - The integer indicating which vertex a is
b (int) - The integer indicating which vertex b is."""
if b in self.size_by_parents:
added_size = self.size_by_parents.pop(b)
else:
# if b wasn't a parent, we must be adding a single vertex to the set
added_size = 1
if a not in self.size_by_parents:
self.size_by_parents[a] = 1
self.parents_by_node[a] = a
self.size_by_parents[a] += added_size
self.parents_by_node[b] = a
def union(self,a,b):
"""Looks up the parents of a and b, if they belong to separate sets we merge set b into a."""
a_parent = self.findParent(a)
b_parent = self.findParent(b)
# They belong to different sets, add b to a
if a_parent != b_parent:
self.addBtoA(a_parent, b_parent)
def findParent(self,a):
"""Returns the absolute parent of 'a', if 'a' has no parent, then it will return 'a'
Parameters:
a (int) - A vertex in our graph
Returns:
parent_a (int)"""
# if previous ever equals current, we found a node that points to itself
prev = None
current = a
while current in self.parents_by_node:
current,prev = self.parents_by_node[current], current
if prev == current:
return current
return current
dj_set = DisjointSet()
N = int(input())
for _ in range(N):
a,b = [int(x) for x in input().split()]
dj_set.union(a,b)
vertices = sorted(dj_set.size_by_parents.values())
print(vertices[0], vertices[-1]) |
77c23723b7493b8b50781957fc979f9d74601c2a | Rashinkar/Practice | /Infitq2.py | 1,515 | 4.125 | 4 | #Write a Python program to calculate the bill amount to be paid by a customer based on the list of gems and quantity purchased. Any purchase with a total bill amount
#above Rs.30000 is entitled for 5% discount. If any gem required by the customer is not available in the store, then consider total bill amount to be -1.
def calculate_bill_amount(gems_list, price_list, reqd_gems,reqd_quantity):
bill_amount=0
#Write your logic here
for i in range(0,len(reqd_gems)):
for j in range(0,len(gems_list)):
if (reqd_gems[i]==gems_list[j]):
product=reqd_quantity[i]*price_list[j]
bill_amount=bill_amount+product
flag=1
break
if(flag!=1):
bill_amount=-1
break
if(bill_amount>30000):
discount=0.05*bill_amount
bill_amount=bill_amount-discount
return bill_amount
#List of gems available in the store
gems_list=["Emerald","Ivory","Jasper","Ruby","Garnet"]
#Price of gems available in the store. gems_list and price_list have one-to-one correspondence
price_list=[1760,2119,1599,3920,3999]
#List of gems required by the customer
reqd_gems=["Ivory","Emerald","Garnet"]
#Quantity of gems required by the customer. reqd_gems and reqd_quantity have one-to-one correspondence
reqd_quantity=[3,10,12]
bill_amount=calculate_bill_amount(gems_list, price_list, reqd_gems, reqd_quantity)
print(bill_amount)
|
4f53c9a15adb535a34b51cb11a5df1421e243f15 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2158/60835/267424.py | 734 | 3.78125 | 4 | origin = input()
result = 0
is_neg = False
is_effect = True
origin = origin.lstrip().rstrip()
if origin[0] == '-':
is_neg = True
origin = origin[1:]
elif origin[0] >= 'a' and origin[0] <= 'z':
is_effect = False
elif origin[0] >= 'A' and origin[0] <= 'Z':
is_effect = False
mid = ""
n = 0
while n < len(origin) and origin[n] >= '0' and origin[n] <= '9':
mid = mid + origin[n]
n = n + 1
def to_num(string):
int_max = 2**31 - 1
int_min = -2**31
tem = int(string)
if tem > int_max:
return int_max
elif tem < int_min:
return int_min
else:
return tem
if is_effect:
if is_neg:
result = to_num("-" + mid)
else:
result = to_num(mid)
print(result)
|
113cb18529ac12307bed4b49a6e405b554a8da33 | IMDCGP105-1819/portfolio-S197615 | /ex6.py | 924 | 4.1875 | 4 | Name = input("What is your name?")
Age = input("What is your age?")
Height = input("What is your height in inches?")
Weight = input("What is your weight in pounds?")
EyeColour = input("What is your eye colour?")
HairColour = input("What is your hair colour?")
if Age >= str(46):
print("You're older than most")
elif Age <= str(45):
print("You're younger than most")
else:
print("Invalid input")
if Height > str(69):
print("You're above average height for an adult male")
elif Height == str(69):
print("You are the average height for an adult male")
elif Height < str(69):
print("You are below average height for an adult male")
else:
print("Invalid input")
if Weight < str(185):
print("You're weight is above average")
elif Weight == str(185):
print("You are the average weight")
elif Weight > str(185):
print("You weight is below average")
else:
print("Invalid input") |
2e11e47d45ef4c435cae3c5bcd6b8fa05643cf29 | chandni540/tathastu_week_of_code | /Day 6/program9.py | 266 | 4.0625 | 4 | n = int(input("\nEnter size of your list:"))
li=[]
for i in range(n):
list.append(int(input("Enter element :",i+1)))
print("\nThe list is:",list)
k= int(input("\nEnter the value of k:"))
sort = sorted(li)
print("\nThe kth smallest value in list is=",sort[k-1])
|
7bcfb18ecd7aa5e5ef317b885baffb4ff03ce4db | pleielp/apss-py | /Ch04/4.06/jiho.py | 251 | 3.671875 | 4 | def factor(n):
primes = []
div = 2
while n > 1:
if n % div == 0:
n = n // div
primes.append(div)
continue
div += 1
return primes
if __name__ == "__main__":
print(factor(9999))
|
eb7f1c107dc3356cb005694afc3cd0b4c3d6148d | protea-ban/Python_House | /026Python绘制具有描边效果和内部填充的柱状图.py | 391 | 3.640625 | 4 | import numpy as np
import matplotlib.pyplot as plt
#生成测试数据
x = np.linspace(0, 10, 11)
y = 11 - x
plt.bar(x,
y,
color = '#772277',
alpha = 0.5,
edgecolor = 'blue',
linestyle = '--',
linewidth = 1,
hatch='*')
# 为每个柱形添加文本标注
for xx, yy in zip(x, y):
plt.text(xx-0.2, yy+0.1, '%2d' % yy)
plt.show()
|
052fd21de45e56e3f4cc649999b1c5c1aa4c60b1 | adanyear1/Learn-Python-The-Hardway | /ex33.py | 652 | 4.3125 | 4 | i = 0
numbers = []
#while-loop will iterate 6 times or 0 - 5
while i < 8:
print(f"At the top i is {i}")
numbers.append(i)
#print each statement 6 times 0 - 5
i = i + 2
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
print("The numbers: ")
for num in numbers:
print(num)
print("Code bellow will be written using a function")
def whilefunc(i, x, numbers):
numbers = []
if (i < x):
print(f"At the top i is {i}")
numbers.append(i)
i += 1
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
whilefunc(i, x, numbers)
return numbers
numbers = whilefunc(0, 6, [])
for num in numbers:
print(num)
|
cf4ecdbed2b9b82ada3585b08cd831069ef6c9a5 | shweta2425/ML-Python | /Week1/Program36.py | 425 | 4.0625 | 4 | # Write a Python program to determine if variable is defined or not.
x = 'aa'
#checks if it contains any error
try:
x > 1
#execute if try block raises name error
except NameError:
print("You have a variable that is not defined.")
#execute if try block raises data type error
except TypeError:
print("You are comparing values of different type")
else:
print("The 'Try' code was executed without raising any errors!")
|
1a1234183d976be5697747d49348b13b8521e08c | Earthnuker/Py_Intel_8008_Emu | /Stack.py | 494 | 3.609375 | 4 | class Stack(object):
def __init__(self,levels,width,memory):
self.levels=levels*2
self.width=width
self.stackmem=memory.mem[:self.levels]
def push(self,value):
value=value&((1<<self.width)-1)
for b in int.to_bytes(value,2,'little'):
self.stackmem.insert(0,b)
self.stackmem=self.stackmem[:self.levels]
def pop(self):
ret=(self.stackmem[0]<<8)+self.stackmem[1]
del self.stackmem[0]
del self.stackmem[0]
self.stackmem.append(0)
self.stackmem.append(0)
return ret
|
47114cd6b386756f13ba2b0dd892209694417111 | Th3Lourde/l33tcode | /problemSets/300/practice/528.py | 667 | 3.5625 | 4 | import random
class Solution:
def __init__(self, w):
self.arr = w
self.n = len(w)
for i in range(1, self.n):
self.arr[i] += self.arr[i-1]
self.s = self.arr[-1]
def pickIndex(self):
rand_num = random.randint(1, self.s)
l = 0
r = len(self.arr)-1
while l < r:
m = (l+r)//2
if rand_num <= self.arr[m]:
r = m
else:
l = m+1
return l
w = Solution([1,3,7,2,1,5])
w = Solution2([1,3,7,2,1,5])
# Your Solution object will be instantiated and called as such:
# obj = Solution(w)
# param_1 = obj.pickIndex()
|
b1f7a333ea001d21eb06ffa5c7a12cd3dfc77ed6 | kalpajpise/Tik-Tak-Toe | /Game.py | 4,582 | 4.0625 | 4 | import random
def player_input():
# Input for the player
marker = ''
while not (marker == 'X' or marker == 'O'):
marker = input('Player 1: Do you want to be X or O? ').upper()
if marker == 'X':
return ('X', 'O')
else:
return ('O', 'X')
# test cases for the marker generation
# player1_marker,player2_marker=player_input()
# print(player1_marker)
# print(player2_marker)
def choose_first():
# Who will play 1st
if random.randint(0, 1) == 0:
return 'Player 2'
else:
return 'Player 1'
def display_board(board):
print("\n" * 80)
print(" | | ")
print(" " + board[1] + " |" + " " + board[2] + " |" + " " + board[3])
print(" | | ")
print("------------")
print(" | | ")
print(" " + board[4] + " |" + " " + board[5] + " |" + " " + board[6])
print(" | | ")
print("------------")
print(" | | ")
print(" " + board[7] + " |" + " " + board[8] + " |" + " " + board[9])
# the_board=['0',X','O','X','O','X','O','X','X','X','O']
# display_board(the_board)
def space_check(board, position):
return board[position] == ' '
def full_board_check(board):
for i in range(1, 10):
if space_check(board, i):
return False
return True
def player_choice(board, player):
position = 0
while position not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or not space_check(board, position):
position = int(input(f'{player} choose your next position: (1-9) - (From the top left)'))
return position
def place_marker(board, marker, position):
board[position] = marker
def win_check(board, mark):
return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the bottom
(board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle
(board[1] == mark and board[2] == mark and board[3] == mark) or # across the top
(board[7] == mark and board[4] == mark and board[1] == mark) or # down the middle
(board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle
(board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side
(board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal
(board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal
def relpay():
play = input("Do u want to play again. Yes or NO")
return play.lower() == 'y'
def main():
stop = False
while not stop:
game_on = True
the_board = [" "] * 10
player1_marker, player2_marker = player_input()
turn = choose_first()
while game_on:
if turn == 'Player 1':
display_board(the_board)
position = player_choice(the_board, turn)
place_marker(the_board, player1_marker, position)
if win_check(the_board, player1_marker):
display_board(the_board)
print(f"Congratulation {turn} has won the match ")
game_on = False
stop = True
else:
if full_board_check(the_board):
display_board(the_board)
print("The match is draw")
break
else:
turn = "Player 2"
else:
display_board(the_board)
position = player_choice(the_board,turn)
place_marker(the_board, player2_marker, position)
if win_check(the_board, player2_marker):
display_board(the_board)
print(f"Congratulation {turn} has won the match ")
game_on = False
stop = True
else:
if full_board_check(the_board):
display_board(the_board)
print("The match is draw")
break
else:
turn = "Player 1"
if __name__ == '__main__':
Flag = True
print("==== Tik Tak Toe ====")
play_game = input('Are u ready to play Yes or No')
if play_game[0].lower() == 'y':
Flag = True
main()
else:
Flag = False
print("Thanks for playing the game")
while Flag:
if relpay():
main()
else:
Flag = False
print("Thanks for playing the game")
|
d47f3ac5271c75510479148a647c31a7111439b1 | kses1010/algorithm | /programmers/level2/target_number.py | 562 | 3.640625 | 4 | # 타겟 넘버
def solution(numbers, target):
n = len(numbers)
count = 0
# dfs 트리층, 합계
def dfs(layer, total):
if layer == n:
if total == target:
nonlocal count
count += 1
else:
# 마지막 노드까지 못갔다면 dfs 재귀
dfs(layer + 1, total + numbers[layer]) # + 연산
dfs(layer + 1, total - numbers[layer]) # - 연산
dfs(0, 0)
return count
numbers1, target1 = [1, 1, 1, 1, 1], 3
print(solution(numbers1, target1))
|
29efff3f5997e5fe1ae628d205572ee97b305d8c | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc097/A/4927590.py | 152 | 3.796875 | 4 | l = [int(i) for i in input().split()]
print("Yes" if ((abs(l[0] - l[1]) <= l[3]) & (abs(l[1] - l[2]) <= l[3])) or (abs(l[0] - l[2]) <= l[3]) else "No") |
ec184b71ea3d7b20ba797f964961fd336987eddd | Payaj/test | /NameMatch.py | 6,739 | 3.890625 | 4 | import numpy as np
import pandas as pd
import re
import math
##################################################### #1. This section creates the bigrams of the names. These bigrams will be the input of the jeccard index formula/function ####################################################################
################################## For example if we want to match "Morgan" and "Morgana", this function will convert them into respective bigrams: "['Mo', 'or', 'rg', 'ga', 'an']" and "['Mo', 'or', 'rg', 'ga', 'an', 'na']"#####################
####################################################################### Also this function excludes the middle name in the bigram, just take first and last name into account ######################################################################
def get_bigram_1(text):
bi_list = []
u_text = text.split(' ')
i = text.replace(' ', '')
temp = []
for j in u_text:
# print(j)
if len(j) > 0:
temp.append(j)
# below line removes the middle name from the name for bigram
if len(temp) == 3:
i = temp[0] + temp[2]
if len(i) >= 2:
for j in range(len(i) - 1):
bi_list.append(i[j:j + 2])
return bi_list
##################################################### #2. This section is the jaccard index formula (Intersection of Two names / Union of two strings) that matches two names and provide them a match score #######################################
#################################### For the above example the intersection will be: "['Mo', 'an', 'ga', 'or', 'rg']" (length = 5), and union will be "['Mo', 'an', 'ga', 'na', 'or', 'rg']" (length = 6) ##########################################
######################################################## According to the jeccard index formula, match will be 5/6 (Intersection of Two names / Union of two strings) = 0.833 ######################################################################
def compute_jaccard_index(set_1, set_2):
domin = float(len(np.union1d(set_1,set_2)))
if domin == 0:
return -1
return len(np.intersect1d(set_1,set_2)) / domin
####################################################################################################################################################################################################################################################
########################################### #3. This section reads the input file and filter out all the edge cases from the data (such as: name with 4 words, emails, numbers, name with duplicate words in it) ###################################
####################################################################################################################################################################################################################################################
# Below line reads the file
df = pd.read_csv('NameAndCompany.csv')
# Below line rename the column to Name and CompanyCode
# For this code, SellersCompanyCode is taken into account, can get results from SellersCompany
df.columns = ['Name', 'CompanyCode']
# Below function creates column for bigram in the dataset by using "get_bigram_1" from Section 1
df_d['Name_bigram'] = df_d['Name_for_jac'].apply(get_bigram_1)
# Below code creates a list of names by company.
companies = df_d['CompanyCode'].unique()
dfs = []
for i in companies:
dfs.append(df_d[df_d['CompanyCode']==i])
####################################### #4. This section calls the "Section 1" (Jaccard Index formula) for all the Professionals of same company ###############################
def get_jaccard_list(df1, dict_list):
count = 0
# i is the index of one name, which will be matched with all the other names of the same company (with index j - next for loop)
for i in df1.index:
count += 1
if count % 10 == 0:
print(count)
k = 0
max_index = [i]
for j in df1.index:
if i == j:
continue
tmp = compute_jaccard_index(df1.loc[i, 'Name_bigram'], df1.loc[j, 'Name_bigram'])
# here we are only saving the index of the match score in "max_index", if the new match score (tmp) is greater than the previous match score.
if tmp > k:
max_index = [j]
k = tmp
continue
# if there are more names with same match score, below 2 lines will save those match score also
if tmp == k:
max_index.append(j)
# after the completion of one loop of first for loop (index i), the below code saves the index i, max_index (index of the name that was the max. match), and the value of the max. match score (k)
dict_list.append({'index_1': i, 'index_2': max_index, 'jaccard index': k})
######################################################################## 5. Calling of section 4 (above function), and writing final csv ########################################################
dict_list = []
count = 0
# Below code call the above function (section 4) by inputting professional names under the same company.
for df1 in dfs:
print('dfs number',count, 'start','has:' ,len(df1))
count +=1
get_jaccard_list(df1,dict_list)
# below code converts the 'dict_list' (section 4) output into data frame.
df3 = pd.DataFrame.from_records(dict_list)
df_output = df3
# index_2 column in the df_output column can have multiple match, so can have different indexes, below function creates different col. for all those indexes, and then below codes merge the clean data frame with "df_d" by index, and get the right names for the indexes.
def index_clean(line):
indexs = line['index_2']
if line['index_1'] == int(indexs[0]):
return {'index_c0': int(line['index_1'])}
dict_ = dict([('index_c' + str(i), '') for i in range(len(indexs))])
for i in range(len(indexs)):
dict_['index_c' + str(i)] = int(indexs[i])
return dict_
df_index= pd.DataFrame.from_records(df_output.apply(index_clean, axis=1))
df_output = df_output.merge(right = df_index, how='inner', left_index = True, right_index=True)
#df_output.head(10)
df_output = df_output.merge(right = df_d, how='left', left_on='index_1', right_index=True).merge(right = df_d, how='left', left_on='index_c0', right_index=True)
#"Below code exports the dataframe in a csv"
df_output_1.to_csv("name-match-score.v1.csv")
# "Below code exports the dataframe with less col in a csv"
df_output[['index_1', 'index_2','Name_x','Name_y', 'jaccard index', 'Company_x',
'Name_for_jac_x', 'Name_bigram_x',
'Name_for_jac_y', 'Name_bigram_y']].to_csv('name-match-score.v2.csv')
|
75aa8e01a99712e1a7cd1904c91e1768ba1986b1 | lsifang/python | /python核心/python面向对象/python类属性.py | 2,402 | 4.21875 | 4 | class Money:
age=18
count=1
num=666
s=Money()
Money.name='hello'
print(s.age)
print(Money.age)
print(Money.name)
print(s.name)
print(s.__class__)
print(Money.__name__)
print(Money.__class__)
print(dict.__class__)
print(dict.__name__)
#所有说,变量类型就是一个类(__class__)。而我们自定义一个类就相当于自定义了一个变量类型
a=str('hello ersbad asd')
print(a.__class__)
print(str.__class__)
print(s.__class__)
print(Money.__class__)
#对象属性会优先到自己内部去找,没有找到会找类内部去找
s.name='ziji'
print(s.name)
print(Money.name)
###这里发现了一个有意思的东西,既然类名.__dict__可以查询类属性,那么内建的类有什么属性呢?发现想字符串、字典等函数都出来了。以后查询方便啦
# print(str.__dict__)
print(a.title())
# print(dict.__dict__)
a={'a':'b','c':'d','e':'f'}
# print(dict.__dict__)
#原来上边的是我管折弯发现的,python早已为我们准备好了学习的方法。。helphelphelp()help()。这个东西以后要常用
# help(str)
# help(dict)
#__dict__是什么玩意
# __dict__是对象的内置属性,它指向了一个字典,而想对象属性、对象函数、对象方法的(变量名或者是Key)都存储在这个字典内
# 比如
two=Money()
two.__dict__={'name':'lsf','age':18}
print(two.name) #访问到了!!!神奇吧!!
print(two.__dict__['name']) #这样也访问到了!!!神奇吧!!
#注意:不同的对象(物件)的__dict__(内置字典属性)是修改的权限不一样的。对象的可以这样定义或者修改,但是!!类!!不可以
#——————————关键子————__slots__————————————#
#首先他是属于类的关键字(方法?函数?)
#它的作用是限定这个类所衍生(产生?实例化?)的对象所能添加的属性名称
#为什么?防止该类所衍生的对象之间的差异千奇百怪!
class Person:
__slots__ = ['name','age','height','sex'] #以后这个类衍生的对象只能新增这些属性
pass
class student():
count=0
def __init__(self,name):
self.name=name
student.count+=1
def get_count(self):
print(student.count)
sf=student('四方')
sf.get_count()
print(dir(sf))
print(sf.__dict__)
print(dir(student))
print(student.__dict__) |
5cc447777d08b82dd20bd962415d26c3319e0e53 | yo-mama-yo-papa/simple_rock_paper_scissors_game | /main.py | 1,009 | 3.859375 | 4 | import random
while True:
rps = ["ROCK", "PAPER", "SCISSORS"]
computer_answer = random.choice(rps).lower()
player_answer = (input("Rock paper or scissors?\n")).lower()
if computer_answer == player_answer:
print(f"You both answered {computer_answer}, tie.")
elif computer_answer == "rock":
if player_answer == "scissors":
print("Rock beats scissors! You lost :(")
else:
print("Paper beats rock! You won :)")
elif computer_answer == "paper":
if player_answer == "rock":
print("Paper beats rock! You lost :(")
else:
print("Scissors beat paper! You won :)")
elif computer_answer == "scissors":
if player_answer == "rock":
print("Rock beats scissors! You won :)")
else:
print("Scissors beat paper! You lost :(")
replay = int(input("Would you like to play again? Yes[1], No[2]\n"))
if replay != 1:
break
|
aa701754c947b73065439e8fdfd1c66865284a88 | ablimit/cs130r | /solution/hw/hw1/leapyear.py | 322 | 4.09375 | 4 | year = int(input("Please input the year: "))
flag = False
if year % 400 == 0:
flag = True
elif year % 100 == 0:
flag = False
elif year % 4 == 0:
flag = True
else:
flag =False
if flag:
print ("Year", year, "is a leap year.")
else:
print ("Year", year, "is NOT a leap year.")
|
c50db1a7bd428a87b051c7c7f147b3241615019a | VarunGogia101/Sales_Prediction | /Advertising.py | 1,352 | 3.890625 | 4 |
# coding: utf-8
# import necessary modules
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
# read the csv file using pandas
data = pd.read_csv('/home/ubuntu/Desktop/Advertising/Dataset_advertise.csv', index_col = 0)
# Get all the features in a Dataframe
X = data[['TV', 'Radio', 'Newspaper']]
# Get the response in a Series
y = data['Sales']
# Splitting X and y into two datasets just for train/test split for cross validation
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42)
# 2. Instantiate a linear regression object: reg
reg = LinearRegression()
# 3. Fit the model with data
reg.fit(X_train, y_train)
#Check coeffecients(positive or negative)
print (reg.intercept_)
print (reg.coef_)
feature_cols = ['TV', 'Radio', 'Newspaper']
list(zip(feature_cols, linreg.coef_))
# 4. Predict the response for a new observation
y_pred = reg.predict(X_test)
# Comparing the predicted response with the true response
list(zip(y_pred, y_test))
# Computing RMSE for the Sales Prediction of the model
# importing metrics for evaluating the model
from sklearn import metrics
# for finding the sqrt
print (np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
#calculate accuracy
accuracy=reg.score(X_test,y_test)
print(accuracy)
|
5063123c9a06e789549ca24e84ba56409bfcdca4 | bharatmazire/Python | /Programs/Basic/RegularExpressions/start_end_same.py | 354 | 3.984375 | 4 | #!/usr/bin/python
# WAP where 1st word of line present at end
import re
def main():
sentence = input("enter your sentence : ")
sent = re.split(" ",sentence)
first = sent[0]
first = first + "$"
#print (first)
if re.search(first,sentence):
print ("1st and last same")
else:
print("1st and last not same")
if __name__ == '__main__s':
main() |
885073cef4316c23fd68c94bf119bf969918343f | r-malon/python-code | /question_marks.py | 470 | 3.625 | 4 | def qmark(x):
num_list = []
for i in x:
if i.isdigit():
num_list.append(x.index(i))
print(x.index(i))
for i in range(0, len(num_list), 2):
#if '?' in x[num_list[i]:num_list[i + 2]]:
if x[num_list[i]:num_list[i + 2]].count('?') != 3 and '?' in x[num_list[i]:num_list[i + 2]]:
return False
return True
if __name__ == '__main__':
print(qmark("arrb6???4xxbl5???eee5"))
print(qmark("5??aaaaaaaaaaaaaaaaaaa?5?5"))
print(qmark("acc?7??sss?3rr1??????5"))
|
3ad9822dc416b325b2e2c5a072a53bf3e1cb27dd | yqdl945/Data-analysis | /dataquest数据处理/dataquest-cleandata.py | 2,927 | 3.578125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Introduction: The beginning of DA&DS
# ## Over there,
# In[ ]:
from csv import reader
open_apple_file = open('AppleStore.csv')
open_google_file = open('googleplaystore.csv')
apple_data = reader(open_apple_file)
google_data = reader(open_google_file)
apple_data_list = list(apple_data)
google_data_list = list(google_data)
android_header = google_data_list[0]
android_ = google_data_list[1:]
apple_header = apple_data_list[0]
apple_ = apple_data_list[1:]
def explore_data(dataset,start,end,rows_and_columns = False):
datas = dataset[start:end]
for row in dataset:
print(row)
print('\n')
if rows_and_columns:
print('number of rows:',len(dataset))
print('colums:',dataset[0])
print(android_header)
print('\n')
explore_data(android_,0,3,True)
print(apple_header)
print('\n')
explore_data(android_,0,3,True)
# In[ ]:
'''print(android_[10472])
print('\n')
print(android_header)
print('\n')
print(android_[0])'''
print(android_[10472]) # incorrect row
print('\n')
print(android_header) # header
print('\n')
print(android_[0]) # correct row
# In[]:
print(len(android_))
del android_[10472]
print(len(android_))
# In[ ]:
duplicate_apps = [] # 重复的App
unique_apps = [] # 非重复
for app in android_:
name = app[0]
if name in unique_apps:
duplicate_apps.append(name)
else:
unique_apps.append(name)
print('Number of duplicate apps:', len(duplicate_apps))
print('\n')
print('Examples of duplicate apps:', duplicate_apps[:15])
# In[]:
# 更新最大评分值!
reviews_max = {}
for app in android_:
name = app[0]
n_reviews = float(app[3])
if name in reviews_max and reviews_max[name] < n_reviews:
reviews_max[name] = n_reviews
elif name not in reviews_max:
reviews_max[name] = n_reviews
# In[]:
#数据清洗(android + Apple)
android_clean = []
already_added = []
for app in android_:
name = app[0]
n_reviews = float(app[3])
if (reviews_max[name] == n_reviews) and (name not in already_added):
android_clean.append(app)
already_added.append(name) # make sure this is inside the if block
explore_data(android_clean,0,3,True)
# In[]:
# 移除非英语的app
def is_english(string):
for character in string:
if ord(character) > 127:
return False
return True
print(is_english('Instagram'))
print(is_english('爱奇艺PPS -《欢乐颂2》电视剧热播'))
# In[]:
# 增加计数器功能,控制误差范围
def is_english(string):
non_ascii = 0
for character in string:
if ord(character) > 127:
non_ascii += 1
if non_ascii > 3:
return False
else:
return True
print(is_english('Docs To Go™ Free Office Suite'))
print(is_english('Instachat 😜'))
# In[]:
|
791101ead24338dc3ced07592b30ba3758c26597 | khanma1962/Data_Structure_answers_Moe | /100 exercises/day17.py | 1,719 | 4 | 4 | '''
Question 65
Question
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
'''
def assert_list(lst):
for i in lst:
# print(i)
assert i % 2 == 0
# assert_list([2, 4, 6, 7, 8])
"""
Question 66
Question
Please write a program which accepts basic mathematic expression from console and print
the evaluation result.
Example: If the following n is given as input to the program:
35 + 3
Then, the output of the program should be:
38
"""
def math_cal():
info = input('Please input the equation : ')
words = info.split('+')
print(int(words[0] )+ int(words[1]))
# math_cal()
# info = input("please enter equation :")
# print(eval(info))
'''
Question 67
Question
Please write a binary search function which searches an item in a sorted list. The function should
return the index of element to be searched in the list.
'''
def bin_search(lst, num):
left, right = 0, len(lst)-1
while left <= right:
mid = round((left + right) /2)
# print('left, right, mid', left, right, mid)
if lst[mid] == num:
# print(' equal', lst[mid])
print(f'Number {num} is at {mid}')
if lst[mid] > num:
# print(' > ', lst[mid])
right = mid - 1
else:
left = mid + 1
a = [2,3, 4, 5, 6, 7, 8, 9]
# bin_search(a, 5)
'''
Question 68
Question
Please generate a random float where the value is between 10 and 100
using Python module.
'''
# import numpy as np
import random
# print(float(random.uniform(10,100)))
'''
Question 69
Question
Please generate a random float where the value is between 5 and 95
using Python module.
'''
# print(random.uniform(5 , 95))
|
0b579ff701e5fae79e7593e56343fe54418776e6 | Rainboylvx/pcs | /loj/10085/data_generator.py | 1,448 | 3.640625 | 4 | #!/usr/bin/env python
from cyaron import *
#=== 字符串
# s1 = String.random(5) # 生成一个5个字母的单词,从小写字母中随机选择
# s1 = String.random((10, 20), charset="abcd1234") # 生成一个10到20个字母之间的单词,从abcd1234共8个字符中随机选择
# s1 = String.random(10, charset="#######...") # 生成一个10个字母的只有'#'和'.'组成的字符串,'#'的可能性是70%,'.'可能30%。
# s1 = String.random_sentence((10, 20), word_separators=",;", sentence_terminators=None, first_letter_uppercase=False, word_length_range=(2, 10), charset="abcdefg") # 生成一个10到20个单词的句子,以逗号或分号随机分割,第一个单词首字母不大写,结尾没有任何符号,每个单词2到10字母长,从abcdefg共7个字符中随机选择
# 以上所有参数,对于以下所有指令也有效
print(1)
n = 5;
m = 5
w = 3
print(n,m,w)
graph = Graph.graph(n, m+w, self_loop=False, repeated_edges=False,weight_limit=10) # 生成一个n点,m边的无向图,禁止重边和自环
# print(' '.join(list([ str(x+1) for x in range(0,n)])))
for edge in graph.iterate_edges(): # 遍历所有边,其中edge内保存的也是Edge对象
print(edge.start,edge.end,edge.weight)
# edge.start # 获取这条边的起点
# edge.end # 获取这条边的终点
# edge.weight # 获取这条边的边权
# io.input_writeln(edge) # 输出这条边,以u v w的形式
|
c1da7e9ec5b2d8555e392c80a094f1b6f99726ae | jadhavrk/leetcode | /114-Flatten-Binary-Tree-to-Linked-List.py | 1,936 | 4.0625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
[2:00]: I observe that a dfs traversal is done and
returned as a linked list
Brute Force solution would be to do a DFS traversal,
store it in a list
connect each lists right node to each other.
However, it's not inplace, O(n) runtime, O(n) space
Ideally, it's better to do this in constant space
[5:00]: Code brute force
[7:30]: Ran code to verify
[11:30]: Implemented brute force
Edge cases
[] -> []
[1] -> [1]
[13:30]: Brute force passed all test cases
[14:46]: Looked at hint
Using pre-order traversal, point each node's right child to next node
#preorder
node.left
node
node.right
[28:00] Partly understood Moris traversal algo. Wasn't able to implement it
"""
if not root:
return None
dfs_order = []
st = [root]
visited = set()
#dfs
while(st):
curr = st.pop()
if curr not in visited:
visited.add(curr)
dfs_order.append(curr)
if curr.right:
st.append(curr.right)
if curr.left:
st.append(curr.left)
if len(dfs_order) == 1:
return root
root = dfs_order[0]
for i, node in enumerate(dfs_order):
node.left = None
if i != 0:
dfs_order[i - 1].right = node
|
4ed448fcfe9de2e4330d8f5ad319cbcfce032015 | chapman3/syllagetter | /dbOperations.py | 2,777 | 3.84375 | 4 | import sqlite3
def init():
'''
Usage:
creates the wordbank.db database
Args:
none
Returns:
1 if created
0 if already existed
'''
try:
print("Initialising Database")
connection = connect()
print("Creating Inventory Table")
sql_command = """CREATE TABLE wordbank (word VARCHAR(30) PRIMARY KEY, syl_count INTEGER);"""
cursor = connection.cursor()
print("Executing")
cursor.execute(sql_command)
connection.commit()
print("Completed")
cursor.close()
connection.close()
print("Connections Closed")
return 1
except:
print("Database Already Initialized")
return 0
def get_syl(connection, word):
'''
Usage:
searches database for a word, returns syllable count if found
Args:
connection: sqlite3 wordbank.db connection
sku: word to be searched
Returns:
syllable count if word found
None if word not found
'''
cursor = connection.cursor()
retVal = cursor.execute("SELECT syl_count FROM wordbank WHERE word =?", (word,)).fetchone()
cursor.close()
if retVal == None:
return None
else:
return retVal[0]
def add(connection, word, syl_count, log):
'''
Usage:
adds word, syl_count pairs to database
Args:
connection: sqlite3 wordbank.db connection
word: word to be added
syl_count: syl_count to be associated to word
log: logfile to record any errors
Returns:
none, updates database with new words
'''
cursor = connection.cursor()
sql_command = "INSERT INTO wordbank (word, syl_count) VALUES (?, ?);"
try:
cursor.execute(sql_command, (word, syl_count))
connection.commit()
except Exception as e:
print("Could not add word to database | See logfile")
log.write("Encountered exception adding word (" + word + ") to database | Full Exception Code: " + str(e) + '\n')
cursor.close()
def connect():
'''
Usage:
attempts to create wordbank file and table, then connects to the wordbank.db file
Args:
none
Returns:
database connection
'''
connection = sqlite3.connect("wordbank.db")
return connection
def add_basic():
'''
Usage:
adds basic words to wordbank database
Args:
none
Returns:
none, edits database in place
'''
basic_words = open("basicWords.txt", "r")
logfile = open("basic_log.txt", 'w')
connection = connect()
try:
for line in basic_words:
parts = line.strip().split(",")
print parts
add(connection, parts[0], int(parts[1]), logfile)
except Exception as e:
logfile.write("error adding basic word")
def test():
connection = connect()
test_words = ["and","opposite","animalistic"]
assert get_syl(connection, test_words[0]) == 1
assert get_syl(connection, test_words[1]) == 3
assert get_syl(connection, test_words[2]) == None
if __name__ == "__main__":
if init() > 0:
add_basic()
else:
test() |
c063efeb9843c4f24ced05b926153bbfbd5faf96 | domkozz/Repozytorium | /laboratoria/LAB2-zad/zad6.py | 374 | 3.859375 | 4 |
a=int(input("Podaj a: "))
b=int(input("Podaj b: "))
c=int(input("Podaj c: "))
d=int(input("Podaj d: "))
if a>b and a>c and a>d:
print("Największą liczbą jest a: ",a)
elif b>a and b>c and b>d:
print("Największą liczbą jest b: ",b)
elif c>a and c>b and c>d:
print("Największą liczbą jest c: ",c)
elif d>a and d>b and d>c:
print("Największą liczbą jest d: ",d) |
5bd4089d8a599fd871898a105137801dd6dd706c | mellumfluous/cs50w | /project1/import.py | 1,655 | 3.6875 | 4 | # Run *once* to create the necessary tables and insert the books into them.
# If the table(s) is/are already created, comment out the corresponding CREATE TABLE line(s)
import csv
import os
from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
# https://pypi.org/project/python-dotenv/
# how to load the .env file
# load_dotenv()
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
def main():
f = open("books.csv")
reader = csv.reader(f)
# This is how I created the tables. You can comment them out if this isn't helpful. There's one more
# reate statement at the bottom
db.execute("CREATE TABLE books ( bookID SERIAL PRIMARY KEY, isbn VARCHAR UNIQUE, title VARCHAR NOT NULL, author VARCHAR NOT NULL, year INTEGER NOT NULL);")
db.execute("CREATE TABLE users ( userID SERIAL PRIMARY KEY, username VARCHAR UNIQUE, password VARCHAR NOT NULL);")
# first row is the header, use the following line to skip it
next(reader, None)
for isbn, title, author, year in reader:
db.execute("INSERT INTO books (isbn, title, author, year) VALUES (:isbn, :title, :author, :year)",
{"isbn": isbn, "title": title, "author": author, "year": year })
print(f"added isbn: {isbn}, title: {title}, author: {author}, year: {year}")
db.execute("CREATE TABLE reviews ( review VARCHAR, rating, INT, userID int REFERENCES users(userID), bookID int REFERENCES books(bookID), PRIMARY KEY (userID, bookID));")
db.commit()
if __name__ == "__main__":
main() |
298ad13a3b3ed5e0e15cfd3edddc235f63c41416 | jessicagamio/stack_min | /stack_min.py | 1,255 | 4.1875 | 4 | class Stack():
""" build a stack that will show you the most current minum value in stack
"""
def __init__(self):
self._stack = []
self.min = []
def push(self, item):
"""
append item to stack.
If min is empty
append to item to min
elif item less than or equal to last element in min
append item to min """
self._stack.append(item)
if self.min == []:
self.min.append(item)
elif item <= self.min[-1]:
self.min.append(item)
def pop(self):
"""If the most recently added element in min is equal to popped item.
Pop item from min"""
popped_item = self._stack.pop()
if self.min[-1] == popped_item:
self.min.pop()
def min_value(self):
return self.min[-1]
def peek(self):
return self._stack[0]
def isEmpty(self):
if len(self._stack) == 0:
return True
else:
return False
myNewStack=Stack()
myNewStack.push(7)
myNewStack.push(8)
myNewStack.push(1)
myNewStack.push(2)
print(myNewStack.min_value())
myNewStack.pop()
print(myNewStack.min_value())
myNewStack.pop()
print(myNewStack.min_value())
|
c1c765ae3429710f435b26e8c4eac0906ba2f397 | kdaivam/data-structures | /linkedlists/random_double_linked_list.py | 2,140 | 3.90625 | 4 | from double_linked_List_prototype import DoubleListNode
from collections import deque
def print_double_linked_list_forward(head):
nodes = deque()
while head:
nodes.append(head.data)
head = head.next
while nodes:
print(nodes.popleft())
def print_double_linked_list_backward(head):
while head.next != None:
head = head.next
while head != None:
print(head.data)
head = head.prev
def create_node_in_between(head):
curr = head
while curr:
temp = curr.next
curr.next = DoubleListNode(curr.data+10)
curr.next.next = temp
curr = temp
def random_pointers_clone(head):
curr = head
create_node_in_between(head)
while curr != None:
curr.next.prev = curr.prev.next
curr = curr.next.next
original = head
copy =head.next
temp = copy
while original and copy:
original.next = original.next.next
if copy.next != None:
copy.next = copy.next.next
original = original.next
copy = copy.next
return temp
def _insert_node_into_doublylinkedlist(head, tail, val):
if head == None:
head = DoubleListNode(val, prev_node = None)
tail = head
else:
node = DoubleListNode(val)
tail.next = node
node.prev = tail
tail = tail.next
return tail
def create_random_pointers(a):
this_node = a
while this_node.next != None :
print(this_node.prev,'----',this_node.next.next)
this_node.prev = this_node.next.next
this_node = this_node.next
print(this_node.data)
return a
def main():
P5 = DoubleListNode(5, None, None)
P4 = DoubleListNode(4, P5, None)
P3 = DoubleListNode(3, P4, None)
P2 = DoubleListNode(2, P3, None)
P1 = DoubleListNode(1, P2, None)
P1.prev = P3
P4.prev = P1
P5.prev = P3
P2.prev = P1
P3.prev = P5
#a = create_random_pointers(_pList)
print_double_linked_list_forward(P1)
B1 = random_pointers_clone(P1)
print_double_linked_list_forward(B1)
if __name__ == '__main__':
main()
|
e8464aaca4759ee27d135fd3bb4170e256c95aa1 | brandle26/Learning | /Section 6 -Working with data part 2/Lec 35 - Duplicates in DataFrames/Duplicates_in_dataframes.py | 645 | 3.796875 | 4 | import numpy as np
import pandas as pd
from pandas import Series,DataFrame
dframe=DataFrame({"key1":["A"]*2+["B"]*3,
"key2":[2,2,2,3,3]})
print(dframe)
#finding duplicate rows
print("="*50)
print(dframe.duplicated())
#droping duplicates
print("="*50)
print(dframe.drop_duplicates())
print("="*50)
#dropping duplicates from specific keys
dframe.drop_duplicates(["key1"])
print(dframe.drop_duplicates(["key1"]))
print("="*50)
print(dframe)
print("="*50)
#taking last duplicate to drop
print(dframe.drop_duplicates(["key1"],take_last=True))
print(dframe.drop_duplicates(["key1"],keep="last"))
|
2b5068d1ba555495460cba7103841b08a38632bf | kevinhenry/data-structures-and-algorithms | /python/code_challenges/stack_queue_animal_shelter/stack_queue_animal_shelter.py | 1,263 | 3.625 | 4 | class InvalidOperationError(BaseException):
pass
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class AnimalShelter:
def __init__(self):
self.front = None
self.rear = None
def __str__(self):
if self.front == None:
return "null"
output = "Front ->"
front = self.front
rear = self.rear
while front:
output += f"{front.value} -> "
front = front.next
output += "Rear"
return output
def enqueue(self, animal):
animal = animal.lower()
node = Node(animal)
if self.is_empty():
self.front = self.rear = node
else:
self.rear.next = node
self.rear = self.rear.next
def dequeue(self, pref):
pref = pref.lower()
if self.is_empty():
raise InvalidOperationError("Method not allowed")
if pref == "cat" or pref == "dog":
node = self.front
self.frotn = self.front.next
return node.value
else:
return "null"
def is_empty(self):
if self.front == None:
return True
else:
return False
|
ec74f4c2083bcfbcb5730359ee564203d27f45c9 | LPRowe/coding-interview-practice | /old_practice_problems/arcade/the-core/medium/equalPairOfBits.py | 1,147 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 01:26:30 2020
@author: Logan Rowe
Implement the missing code, denoted by ellipses. You may not modify the pre-existing code.
You're given two integers, n and m. Find position of the rightmost pair of equal bits in their binary representations (it is guaranteed that such a pair exists), counting from right to left.
Return the value of 2position_of_the_found_pair (0-based).
Example
For n = 10 and m = 11, the output should be
equalPairOfBits(n, m) = 2.
1010 = 10102, 1110 = 10112, the position of the rightmost pair of equal bits is the bit at position 1 (0-based) from the right in the binary representations.
So the answer is 21 = 2.
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer n
Guaranteed constraints:
0 ≤ n ≤ 230.
[input] integer m
Guaranteed constraints:
0 ≤ m ≤ 230.
[output] integer
"""
def equalPairOfBits(n, m):
return 2**[int(i[0])&int(i[1]) for i in zip(bin(m)[2:][::-1],bin(n)[2:][::-1])].index(1) if 1 in [int(i[0])&int(i[1]) for i in zip(bin(m)[2:][::-1],bin(n)[2:][::-1])] else 2**min(len(bin(n)[2:][::-1])+1,len(bin(m)[2:][::-1])+1)
|
d103bf9aacd32879ac9a1c12abaefecc47bbd083 | alexandraback/datacollection | /solutions_5744014401732608_1/Python/alberist1/b.py | 586 | 3.5 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def solve():
b, m = map(int, input().split())
if 2**(b-2) < m:
return 'IMPOSSIBLE'
m -= 1
result = ['POSSIBLE']
for i in range(b):
line = ''
for j in range(b):
if (i == 0 and j == b-1) or (j > i and (j != b-1 or (m & (1<<(i-1))) != 0)):
line += '1'
else:
line += '0'
result.append(line)
return '\n'.join(result)
if __name__ == '__main__':
t = int(input())
for i in range(t):
print('Case #%d:' % (i+1), solve())
|
cb47d49e9889046535b7d2d3479606bf0943c300 | Jdavies91/Python-Script-for-Aws | /How to change the Instance type.py | 3,456 | 4.09375 | 4 | # Change the size of an EC2 instance.
# The program displays a list of existing instances and the current size of the instance.
# The user is able to run the program with a specific instance ID
# and the new size of the instance.
import boto3
class instanceclass:
def __init__ (self,instancename, instanceid, instancetype ):
self.name = instancename
self.types = instancetype
self.instid= instanceid
def main():
no = "no"
while True:
instances = grabAllAvaibleInstance()
displayAllInstance(instances)
print("Would you Like to go again: Yes or No")
useranswer = input()
if useranswer.lower() == "no":
break
def displayinstancechange(instances):
print("\nPlease type in a number beside the instance name that you would like to change its type")
instanceselection = input()
changeinstance(instances, instanceselection)
def changeinstance(instance, instanceselection):
# this is where it selects the instance and changes it too a particular instance type
i = int(instanceselection)
print("You have selected "+instance[i-1].name+" with type "+ instance[i-1].types)
userinstancetype=instancetypeselection(instance[i-1].name)
changeprocess(userinstancetype,instance,i)
def instancetypeselection(instancename):
print("Please Type in the instance type that you want to change for "+instancename)
userinstancetype = input()
return userinstancetype
def changeprocess(userinstancetype,instance,instanceselection):
print("===========================================================================")
print("Processing")
print("===========================================================================")
print("\n"+ instance[instanceselection-1].name+ " changing instance type to "+ userinstancetype)
client = boto3.client('ec2')
idValueStart = instance[instanceselection-1]
stopinstance(client, idValueStart)
waiter(client, idValueStart)
client.modify_instance_attribute(InstanceId=idValueStart.instid, Attribute='instanceType', Value=userinstancetype)
startinstance(client, idValueStart)
print("Instance Name "+ instance[instanceselection-1].name + " has now changed to " + userinstancetype)
def waiter(client, idValueStart):
print(idValueStart.name+" is waiting to Stop")
waiter=client.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[idValueStart.instid])
def stopinstance(client, idValueStart):
print(idValueStart.name+" is now started the stopping process")
client.stop_instances(InstanceIds=[idValueStart.instid])
def startinstance(client, idValueStart):
print(idValueStart.name+" is now Starting up")
client.start_instances(InstanceIds=[idValueStart.instid])
def grabAllAvaibleInstance():
instancearr = []
types = ""
ec2 = boto3.resource('ec2')
for inst in ec2.instances.all():
name =inst.tags
ids = inst.id
n = name[0]['Value']
instancearr.append(instanceclass(n,ids,inst.instance_type))
types = ""
return instancearr
def displayAllInstance(instances):
arrlength=len(instances)
print("The list Below is all the current instances avaible")
for i in range(0,arrlength):
print(str(i+1) +". "+instances[i].name +" " +instances[i].types)
displayinstancechange(instances)
if __name__ == '__main__':
main()
|
a8ed29210c75f39ba5c97cdea465ac4a803ff7b8 | hyobim/NoshibalKeepGoing | /프로그래머스_3진법 뒤집기.py | 301 | 3.59375 | 4 | def solution(n):
answer = 0
num=[]
while True:
if n<3:
num.append(n)
break
num.append(n%3)
n=int(n/3) # n=n//3
l=len(num)-1
for i in num:
answer+=i*3**(l)
l-=1
return answer
|
6aabb04631d57cbd43d9f0e49f78095efac86edd | RanchDress/EatWhere | /eatwhere.py | 2,387 | 3.6875 | 4 | import json
import datetime
import random
from enum import Enum
class Weekday(Enum):
SUNDAY = 0
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
restaurants = {}
preferences = {}
people_going = input("Who's going? (separated by spaces)\n").split(" ")
restaurants_file = "./restaurants.json"
preferences_file = "./preferences.json"
with open(restaurants_file) as json_file:
restaurants = json.load(json_file)
with open(preferences_file) as json_file:
preferences = json.load(json_file)
today = datetime.datetime.today().isoweekday()
preferences_going = {}
# Filter preferences by people going
for person_name, person_preferences in preferences.items():
if (person_name in people_going):
preferences_going[person_name] = person_preferences
valid_restaurant_names = []
valid_restaurant_weights = []
# Filter and weigh restaurants
for restaurant_name, restaurant_data in restaurants.items():
# Filter restaurants that are closed
is_open = False
for open_day in restaurant_data["open"]:
if Weekday(today).name == open_day.upper():
is_open = True
if not (is_open):
continue
is_vetoed = False
net_weight = 0
weight_modifier = 1/len(preferences_going)
for person_name, person_preferences in preferences_going.items():
# Filter vetoed restaurants
if (restaurant_name in person_preferences["veto"]):
is_vetoed = True
break
if (restaurant_data["cuisine"] in person_preferences["veto"]):
is_vetoed = True
break
# Add and Subtract weights based on preferences
# Things you dislike about a place probably outweigh things you like
if (restaurant_name in person_preferences["dislike"] or restaurant_data["cuisine"] in person_preferences["dislike"]):
net_weight -= weight_modifier
if (restaurant_name in person_preferences["prefer"] or restaurant_data["cuisine"] in person_preferences["prefer"]):
net_weight += weight_modifier
if (is_vetoed):
continue
valid_restaurant_names.append(restaurant_name)
valid_restaurant_weights.append(net_weight + 1)
# Get a random restaurant based on weight
random_restaurant = random.choices(valid_restaurant_names, valid_restaurant_weights)
print(random_restaurant[0]) |
6d2f36f3fbcd9a6ba6e6144c41c3ebb40fd98ecf | jjmpal/risteys | /archives/risteys_sketch_search/data/parse_icd10.py | 608 | 3.578125 | 4 | """
Parses the icd10cm_order_2019.txt to a JSON representation.
"""
import json
from sys import argv
def main(filepath):
res = []
with open(filepath) as f:
lines = f.readlines()
for line in lines:
# We use the fact that the file is column aligned to get the columns we want.
# This is not regular CSV parsing, as it doesn't rely on comma or tab-separated fields.
icd = line[6:13].strip()
desc = line[77:].strip()
if len(icd) == 3:
res.append((icd, desc))
print(json.dumps(res))
if __name__ == '__main__':
r = main(argv[1])
|
e1f4e64923d61f1449839cb58cb91ac69adc6576 | kindaem/Practice | /16.py | 318 | 3.75 | 4 | import datetime
from math import pi
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
r = int(input("Радіус: "))
print("Об'єм:", (4/3)*pi*r**3, "Площа: ", 4*pi*r**2)
printTimeStamp("Денис")
|
57f8db451ec153193f71f94bc34f7a3a36274b76 | priscaogu/Wejapa-Wave3 | /CFU.py | 1,256 | 4.59375 | 5 | #Question: What type of loop should we use?
#You need to write a loop that takes the numbers in a given list named num_list:
#num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
#Your code should add up the odd numbers in the list, but only up to the first 5 odd numbers together. If there are more than 5 odd numbers, you should stop at the fifth. If there are fewer than 5 odd numbers, add all of the odd numbers.
#Would you use a while or a for loop to write this code?
num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
odd_num = []
for each_num in num_list:
if each_num % 2 != 0:
odd_num.append(each_num) #Adds each odd number to list odd_num
if len(odd_num) == 5:
print("Adding first five odd numbers...")
sum_odd_num = sum(odd_num[:5])
print("The sum of the odd numbers up to the fifth is", sum_odd_num)
if len(odd_num) < 5:
print('Odd numbers are less than five')
print("Adding odd numbers...")
sum_odd_num = sum(odd_num)
print(sum_odd_num)
|
8c2ba919ff3cca8bb1a9d2cdfc0fa21cde231d25 | Sri2614/python-practice | /object-oriented-programming/walrus.py | 381 | 4.25 | 4 | # walrus operator :=
# assignment expression
# assigns values to variables as part of a larger expression
foods = list()
while food := input("What food do you like?: ") != "quit":
foods.append(food)
# while True:
# food = input("What food do you like?: ")
# if food == "quit":
# quit()
# foods.append(food)
# print(foods) |
dcffd7a2f38ebc31fc88e300b36816567e273b88 | jasmgang/pythonProject | /hyggehejsa.py | 129 | 3.640625 | 4 |
def svar(d):
if "hej" in d:
return "hej\n"
else:
return "hej\n"
x = input("hejsa \n")
print(svar(x)) |
304c9f605700c20a55e5e06217aac19c2140f749 | Achelics/Python_Test | /algorithms/string.py | 5,669 | 3.75 | 4 | #!/usr/bin/env/ python
# coding=utf-8
__author__ = 'Achelics'
__Date__ = '2016/10/08'
def string_matching_naive(text='', pattern=''):
"""Returns positions where pattern is found in text
We slide the string to match 'pattern' over the text
O((n-m)m)
Example: text = 'ababbababa', pattern = 'aba'
string_matching_navie(t,s) returns [0, 5, 7]
:param text: text to search inside
:param pattern: pattern string to search for
:return: list containing offsets(shifts) where pattern is found inside text
"""
n = len(text)
m = len(pattern)
offsets = []
for i in range(n-m+1):
if pattern == text[i:i+m]:
offsets.append(i)
return offsets
def string_matchong_rabin_karp(text='', pattern='', hash_base=256):
"""Returns positions where pattern is found in text
worst case: O(nm)
O(n+m) if the number of vaild matches is small and the pattern is large.
Performance: ord() is slow so we shouldn't use it here
Example: text = 'ababbababa', pattern = 'aba'
string_matchong_rabin_karp(text, pattern) returns [0, 5, 7]
:param text: text to search inside
:param pattern: string to search for
:param hash_base: base to calculate the hash value
:return: list containing offsets(shifts) where pattern id found inside text
"""
n = len(text)
m = len(pattern)
offsets = []
htext = hash_value(text[:m], hash_base)
hpattern = hash_value(pattern, hash_base)
for i in range(n-m+1):
if htext == hpattern:
if text[i:i+m] == pattern:
offsets.append(i)
if i < n-m:
htext = (hash_base *
(htext -
(ord(text[i]) *
(hash_base ** (m-1))))) + ord(text[i+m])
return offsets
def hash_value(s, base):
"""Calculate the hash value of a string using base.
Example: 'abc' = 97 * base^2 + 98 * base^1 + 99 * base^0
:param s: string to compute hash value for
:param base: base t use to compute hash value
:return: hash value
"""
v = 0
p = len(s) - 1
for i in range(p+1):
v += ord(s[i]) * (base ** p)
p -= 1
return v
def string_matching_knuth_morris_pratt(text='', pattern=''):
"""Returns positions where pattern is found in text.
O(m+n)
Example: text = 'ababbababa', pattern = 'aba'
string_matching_knuth_morris_pratt(text, pattern) returns [0, 5, 7]
:param text: text to search inside
:param pattern: string to search for
:return: list containing offsets(shifts) where pattern is found inside text
"""
n = len(text)
m = len(pattern)
offsets = []
pi = compute_prefix_function(pattern)
q = 0
for i in range(n):
while q > 0 and pattern[q] != text[i]:
q = pi[q - 1]
if pattern[q] == text[i]:
q = q + 1
if q == m:
offsets.append(i - m + 1)
q = pi[q - 1]
return offsets
def compute_prefix_function(p):
m = len(p)
pi = [0] * m
k = 0
for q in range(1, m):
while k > 0 and p[k] != p[q]:
k = pi[k - 1]
if p[k] == p[q]:
k = k + 1
pi[q] = k
return pi
def string_matching_boyer_moore_horspool(text='', pattern=''):
"""Returns positions where pattern is found in text
O(n)
Performance: ord() is slow so we shouldn't use it here
Example: text = 'ababbababa', pattern = 'aba'
string_matching_boyer_moore_horspool(text, pattern) returns [0, 5, 7]
:param text: text to search inside
:param pattern: string to search for
:param hash_base: base to calculate the hash value
:return: list containing offsets(shifts) where pattern id found inside text
"""
m = len(pattern)
n = len(text)
offsets = []
if m > n:
return offsets
skip = []
for k in range(256):
skip.append(m)
for k in range(m-1):
skip[ord(pattern[k])] = m - k - 1
skip = tuple(skip)
k = m -1
while k < n:
j = m-1
i = k
while j >= 0 and text[i] == pattern[j]:
j -= 1
i -= 1
if j == -1:
offsets.append(i + 1)
k += skip[ord(text[k])]
return offsets
def atoi(s):
"""Convert string to integer without doing int(s)
'123' -> 123
:param s: string to convert
:return: integer
"""
if not s:
raise ValueError
i = 0
idx = 0
neg = False
if s[0] == '-':
neg = True
idx += 1
for c in s[idx:]:
i *= 10
i += int(c)
if neg:
i = -i
return i
def reverse_string_words(s):
"""Reverse words inside a string (in place).
Since strings are immutable in Python, we copy the string chars to a list first.
'word1 word2 word3' -> 'word3 word2 word1'
Complexity: O(n)
:param s: string words to reverse.
:return: reversed string words.
"""
def reverse(l, i, j):
# 'word1' -> '1drow'
# Complexity: O(n/2)
while i != j:
l[i], l[j] = l[j], l[i]
i += 1
j -= 1
w = [e for e in s]
i = 0
j = len(w) - 1
reverse(w, i, j)
i = 0
j = 0
while j < len(w):
while j < len(w) and w[j] != ' ':
j += 1
reverse(w, i, j-1)
i = j + 1
j += 1
return ''.join(e for e in w)
if __name__ == '__main__':
text = 'ababbababa'
pattern = 'aba'
print string_matching_boyer_moore_horspool(text, pattern)
string = 'hello world www'
print reverse_string_words(string)
|
dc6173da05ed99a7b8c12161ff266bc17a370ef0 | renan09/Assignments | /Python/PythonAssignments/Assign6/substraction.py | 180 | 3.5625 | 4 | import math
class substraction() :
def __init__(self):
print("Init Method")
def findSubstraction(self,a,b):
value=a-b
print("substract ",value)
|
a40fec32a7be3d1741ce756e67d81c0b85086bc3 | fahadaliawan-nbs/cdkProject | /venv/SearchPractice.py | 1,794 | 4.09375 | 4 | # Used as linear search i.e. one by one comparison search
"""list = [5, 8, 4, 6, 9, 2]
n = 11
pos = 0
def search(list, n):
for x in list:
if x == n:
i = list.index(x) + 1
globals()['pos'] = i
return True
return False
if search(list, n):
print("found "+str(n)+" in the list at position "+str(pos)+".")
else:
print("Not present in the list")
# used for binary search: binary search is whole mechanism and faster than linear search, for binary search list should be sorted.
list = [4, 7, 8, 12, 45, 99]
upperIndex = len(list) - 1
lowerIndex = 0
n = 45
pos = 0
def middleIndex(li, ui):
mi = (li + ui) // 2
return mi
def search (list, n):
for x in list:
mi = middleIndex(globals()['lowerIndex'],globals()['upperIndex'])
if x == n:
globals()['pos'] = list.index(x) + 1
return True
elif list[mi] > n:
globals()['upperIndex'] = mi
else:
globals()['lowerIndex'] = mi
if search(list, n):
print("found "+str(n)+" in the list at position "+str(pos)+".")
else:
print("not found")
# Bubble sort: it will swap the elements and compare them in ascending order.
list = [5, 3, 8, 6, 7, 2]
def sort(list):
for x in range(len(list)-1,0,-1):
for y in range(x):
if list[y] > list[y + 1]:
temp = list[y]
list[y] = list[y + 1]
list[y+ 1] = temp
sort(list)
print(list)"""
#selection sort:
list = [5, 3, 8, 6, 7, 2]
def sort(list):
for x in range(5):
minpos = x
for y in range(x,6):
if list[y] < list[minpos]:
minpos = y
temp = list[x]
list[x] = list[minpos]
list[minpos] = temp
sort(list)
print(list) |
4a19533f03e9571f7deeee4125e122d32e2922f3 | santidev10/ec2-user | /check_user.py | 1,346 | 3.640625 | 4 | #!/usr/bin/env python3
import sys, os, subprocess, pwd, grp, getpass, time, shutil, re
from time import strftime
def die(msg):
print(msg)
os._exit(1)
def checkuser(name):
try:
return pwd.getpwnam(name)
except KeyError:
return None
def getfirst():
fn = ""
try:
while len(fn) == 0:
fn = input("First Name: ")
print(fn)
except KeyboardInterrupt:
die("Interrupt detected, exiting.")
return fn
def getlast():
ln = ""
try:
while len(ln) == 0:
ln = input("Last Name: ")
except KeyboardInterrupt:
die("Interrupt detected, exiting.")
return ln
def getusername(fn, ln):
user = ""
# Build username from first letter in 'fn' and up to 7 letters in 'ln'
# Is this the best way to do it?
fn1 = fn[0:1].lower() # get first character
ln = ln.replace(" ", "") # remove empty spaces, if any
ln7 = ln[0:7].lower() # get first 7 characters
user_rec = fn1 + ln7
if checkuser(user_rec):
print("user existe")
return user_rec
def main():
print(os.system("python3 --version"))
print("Enter user information:")
fn = getfirst()
print(fn)
ln = getlast()
print(fn,ln)
username=getusername(fn,ln)
print(username)
if __name__ == "__main__":
main()
|
f4e3cd652e346f457f77a9ed884cbcdc55f5f0b5 | Somi-Singh/python_loop_Questions | /table2.py | 88 | 3.8125 | 4 | num=int(input("enter any num"))
i=0
while i<=10:
i+=1
print(num,"*",i,"=",num*i) |
ab54f9228fa9a6d7471534c3a9550fb674cdf22c | MrViniciusfb/Python-Crash-Course | /Parte 5/Exemplo/voting.py | 385 | 4.15625 | 4 | #19/07/2021
age = 17
#Após ver sobre condicional é natural usarmos isso para avançar para o if-else
#Estes usam do teste condicional para fazer ou não uma ação
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry,you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
|
dfa8f10c0edee13ed291c91138cfe2a8860b0b88 | kohyt/cpy5p3 | /q3_find_gcd.py | 749 | 4.0625 | 4 | # q3_find_gcd.py
# find greatest common divisor
import numbers
def check():
if a > 0 and b > 0 and isinstance(a, numbers.Integral) and isinstance(b, numbers.Integral):
return True
else:
return False
def gcd(a,b):
if a >= b:
while b != 0:
d = a % b
a = b
b = d
print(a)
elif a < b:
while b != 0:
d = a % b
a = b
b = d
print(a)
# get input
a = int(input("Enter positive integer:"))
b = int(input("Enter 2nd positive integer:"))
if check():
gcd(a,b)
else:
print("Invalid input")
# test
def testrun():
if gcd(24,16) == 8 and gcd(255,25) == 5:
return True
else:
return False
|
da5fb60460245ae40c5fbe479ccd4117d71070d8 | Shakhy101/Hangman | /main.py | 1,053 | 3.90625 | 4 | import random, os
from hangman_art import stages, logo
from hangman_words import word_list
from sys import platform
clear = lambda: os.system("clear")
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
lives = 6
game_ended = False
clear()
print(logo)
display = []
for _ in range(word_length):
display.append("_")
while not game_ended:
guess = (input("Guess a letter: ")).lower()
clear()
if guess in display:
print(f"You've already tried {guess}. Try a different letter.")
for position in range(word_length):
letter = chosen_word[position]
if guess == letter:
display[position] = letter
if guess not in chosen_word:
print(f"{guess} is not in the word. You lose 1 life.")
lives -= 1
if lives == 0:
game_ended = True
print("You lost.")
print(f"{' '.join(display)}")
if "_" not in display:
game_ended = True
print("You won!")
print(stages[lives])
|
9bf7d20ff73a36028dd3153990f433db5ae331f1 | adityaparab04/Python-Exercises | /ex15.py | 272 | 3.625 | 4 | #Reading files
from sys import argv #import argv
script, filename = argv #argument
txt = open(filename)
print(f"Here's your file{filename}")
print(txt.read())
print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read()) |
29ddaf5acb49a51a89c95db28e5dbf6b121bb89f | wooseokoh/python | /python19/class/member.py | 1,135 | 3.96875 | 4 | class Member:
id = ''
pw = ''
grade = ''
mileage = ''
# 생성자
def __init__(self,id,pw,grade,mile):
self.id = id
self.pw = pw
self.grade = grade
self.mile = mile
list_total =[]
for index in range(0,3,1):
list = []
id = input("아이디를 입력하세요 :")
pw = input("비밀번호를 입력하세요 :")
grade = input("등급을 입력하세요 :")
mile = input("마일리지를 입력하세요 :")
list = [id,pw,grade,mile]
list_total.append(list)
print()
p1 = Member(list_total[0][0],list_total[0][1],list_total[0][2],list_total[0][3])
p2 = Member(list_total[1][0],list_total[1][1],list_total[1][2],list_total[1][3])
p3 = Member(list_total[2][0],list_total[2][1],list_total[2][2],list_total[2][3])
sum = int(p1.mile)+int(p2.mile)+int(p3.mile)
print("%s의 비밀번호는 %s입니다 " %(p1.id,p1.pw))
print("%s는 %s이고 마일리지는 %s입니다" %(p2.id, p2.pw, p2.mile))
print("총 마일리지는 %d입니다." %(sum))
print("평균 마일리지는 %d입니다." %(sum/3))
|
4f5dea1aa4a4b7b0cea9344099d3551fc17eaa26 | Hawful/machinelearningpractice | /getResponse.py | 712 | 3.546875 | 4 | #This response system allows neighbors to "vote" for their class attribute, and use the
# majority as a prediction.
#This function assumes that the class that is voted on is the last attribute of each
# queried neighbor.
#Still totally based off machinelearningmastery.com
import operator
def getResponse(neighbors):
classVotes = {}
for x in range(len(neighbors)):
response = neighbors[x][-1]
if response in classVotes:
classVotes[response] += 1
else:
classVotes[response] = 1
sortedVotes = sorted(classVotes.iteritems(), key=operator.itemgetter(1), reverse = True)
return sortedVotes[0][0]
neighbors = [[1,1,1,'a'], [2,2,2,'a'], [3,3,3,'b']]
response = getResponse(neighbors)
print(response)
|
9a1ac7f12609bab848f930dc22ae56d61f8b0cb9 | davidgmor/kata1 | /Kata2/1#if1.py | 373 | 3.671875 | 4 | '''
Almacenar contraseña en una variable y comprobar si es igual
a la que tenemos almacenada en memoria, sin tener en cuanta mayúsculas
y minúsculas
'''
password = 'contraseña'
user_password = input('Introduzca la contraseña: ')
user_password = user_password.lower()
if password == user_password:
print('Password correcto')
else:
print('Password incorrecto')
|
c57cfc014e47d598203f2d97b003e27b5fc40670 | Angold-4/algorithms_in_python | /Chapters/Chapter_1/Answer/1.27.py | 713 | 3.859375 | 4 | # Angold4 20200509 C1.1.27
def factors(n):
k = 1
while k * k < n:
if n % k == 0:
yield k
yield n // k
k += 1
if k * k == 0:
yield k
def fibonacci():
a = 0
b = 1
while a < 100:
yield a
future = a + b
a = b
b = future
def factorsW(n):
k = 1
List = []
while k * k < n:
if n % k == 0:
yield k
List.append(n // k)
k += 1
if k * k == 0:
yield k
for s in List[::-1]:
yield s
if __name__ == "__main__":
for i in factors(100):
print(i)
for j in fibonacci():
print(j)
for s in factorsW(100):
print(s)
|
03fcb6531972ab3c91410ae049c2b08c927248bd | FilipFelipe/BUri | /Python/1065.py | 129 | 3.75 | 4 | count = 0
for op in range(5):
a = int(input())
if a%2 == 0:
count=count+1
print("%d valores pares" % count ) |
0ee4f082d0e4ee167c8851c7a9d287440b30ed87 | NCAR/pyngl | /examples/viewport1.py | 6,137 | 3.578125 | 4 | #
# File:
# viewport1.py
#
# Synopsis:
# Illustrates the difference between the viewport and bounding box.
#
# Categories:
# viewport
# polylines
# polymarkers
# text
#
# Author:
# Mary Haley
#
# Date of initial publication:
# August 2010
#
# Description:
# This example shows how to raw primitives and text using
# NDC coordinates. The draw_ndc_grid function is used as
# a tool to help determine which coordinates to use.
# Effects illustrated:
# o Drawing a simple filled contour plot
# o Drawing a box around a contour plot viewport
# o Drawing the bounding box
# o Changing the color and thickness of polylines
# o Drawing polylines, polymarkers, and text in NDC space
# o Using "getvalues" to retrieve resource values
# o Generating dummy data
#
# Output:
# A single visualization with the viewport and bounding box
# information included.
#
# Notes:
#
from __future__ import print_function
import numpy, Ngl
#********************************************************************
# Draw a box around the viewport of the given object..
#********************************************************************
def draw_vp_box(wks,plot):
# Retrieve the viewport values of the drawable object.
vpx = Ngl.get_float(plot,"vpXF")
vpy = Ngl.get_float(plot,"vpYF")
vpw = Ngl.get_float(plot,"vpWidthF")
vph = Ngl.get_float(plot,"vpHeightF")
print("Viewport x,y,width,height =",vpx,vpy,vpw,vph)
# Make a box with the viewport values.
xbox = [vpx,vpx+vpw,vpx+vpw,vpx,vpx]
ybox = [vpy,vpy,vpy-vph,vpy-vph,vpy]
# Set up some marker resources.
mkres = Ngl.Resources()
mkres.gsMarkerIndex = 16 # filled dot
mkres.gsMarkerSizeF = 0.02 # larger than default
mkres.gsMarkerColor = "ForestGreen"
# Draw a single marker at the vpXF/vpYF location.
Ngl.polymarker_ndc(wks,vpx,vpy,mkres)
# Set up some line resources.
lnres = Ngl.Resources()
lnres.gsLineColor = "NavyBlue" # line color
lnres.gsLineThicknessF = 3.5 # 3.5 times as thick
# Draw a box around the viewport.
Ngl.polyline_ndc(wks,xbox,ybox,lnres)
# Set up some text resources.
txres = Ngl.Resources()
txres.txJust = "CenterLeft"
txres.txFontHeightF = 0.015
txres.txFontColor = "ForestGreen"
txres.txBackgroundFillColor = "white"
# Draw a text string labeling the marker
Ngl.text_ndc(wks,"(vpXF,vpYF)",vpx+0.03,vpy,txres)
# Draw text strings labeling the viewport box.
txres.txFontColor = "black"
txres.txJust = "CenterLeft"
Ngl.text_ndc(wks,"viewport",vpx+vpw/2.,vpy-vph,txres)
Ngl.text_ndc(wks,"viewport",vpx+vpw/2.,vpy,txres)
txres.txAngleF = 90.
Ngl.text_ndc(wks,"viewport",vpx,vpy-vph/2.,txres)
Ngl.text_ndc(wks,"viewport",vpx+vpw,vpy-vph/2.,txres)
return
#********************************************************************
# Draw a box around the bounding box of the given object..
#********************************************************************
def draw_bb_box(wks,plot):
# Retrieve the bounding box of the given object.
bb = Ngl.get_bounding_box(plot)
top = bb[0]
bot = bb[1]
lft = bb[2]
rgt = bb[3]
print("Bounding box top,bottom,left,right =",top,bot,lft,rgt)
# Make a box with the bounding box values.
xbox = [rgt,lft,lft,rgt,rgt]
ybox = [top,top,bot,bot,top]
# Set up some line resources.
lnres = Ngl.Resources()
lnres.gsLineColor = "Brown"
lnres.gsLineThicknessF = 2.5
# Set up some text resources.
txres = Ngl.Resources()
txres.txFontHeightF = 0.015
txres.txBackgroundFillColor = "white"
txres.txJust = "CenterLeft"
# Draw a box showing the bounding box.
Ngl.polyline_ndc(wks,xbox,ybox,lnres)
# Draw text strings labeling the bounding box.
Ngl.text_ndc(wks,"bounding box",lft+0.05,bot,txres)
txres.txJust = "CenterRight"
Ngl.text_ndc(wks,"bounding box",rgt-0.05,top,txres)
txres.txAngleF = 90.
txres.txJust = "CenterRight"
Ngl.text_ndc(wks,"bounding box",lft,top-0.05,txres)
txres.txJust = "CenterLeft"
Ngl.text_ndc(wks,"bounding box",rgt,bot+0.05,txres)
return
#********************************************************************
# Main code
#********************************************************************
wks_type = "png"
wks = Ngl.open_wks(wks_type,"viewport1")
# Add some named colors. This is no longer needed in PyNGL 1.5.0
#forest_green = numpy.array([ 34, 139, 34])/255.
#navy_blue = numpy.array([ 0, 0, 128])/255.
#brown = numpy.array([165, 42, 42])/255.
#ig = Ngl.new_color(wks,forest_green[0],forest_green[1],forest_green[2])
#ib = Ngl.new_color(wks,navy_blue[0], navy_blue[1], navy_blue[2])
#ir = Ngl.new_color(wks,brown[0], brown[1], brown[2])
# Generate some dummy data.
cmin = -19.23
cmax = 16.81
data = Ngl.generate_2d_array([100,100], 10, 10, cmin, cmax)
nice_min,nice_max,nice_spc = Ngl.nice_cntr_levels(cmin,cmax,cint=3)
# Read in color map so we can subset it
cmap = Ngl.read_colormap_file("nrl_sirkes")
# Set up resources for a contour plot.
cnres = Ngl.Resources()
cnres.nglMaximize = True # Maximize plot in frame
cnres.nglDraw = False # Don't draw plot
cnres.nglFrame = False # Don't advance the frame
cnres.cnFillOn = True # Turn on contour fill
cnres.cnFillPalette = cmap[:-3,:]
cnres.cnLevelSelectionMode = "ManualLevels"
cnres.cnLevelSpacingF = nice_spc
cnres.cnMinLevelValF = nice_min
cnres.cnMaxLevelValF = nice_max
cnres.lbOrientation = "Vertical" # Default is horizontal
cnres.tiMainString = "This is a title"
cnres.tiXAxisString = "X axis"
cnres.tiYAxisString = "Y axis"
contourplot = Ngl.contour(wks,data,cnres)
# Draw plot with viewport and bounding boxes.
Ngl.draw(contourplot)
draw_bb_box(wks,contourplot)
draw_vp_box(wks,contourplot)
# Advance frame.
Ngl.frame(wks)
Ngl.end()
|
a0628af8b95f7e3669da9ca2b1e70c77970c78a5 | Deepti3006/pythonProgrammingExamples | /lists/swapFirstAndLastElement.py | 238 | 3.890625 | 4 | def swapFirstAndLast():
a=[1,3,5,8,22,44,60]
f_elem = a[0]
print(f_elem)
l_elem= a[-1]
print(l_elem)
temp = a[0]
a[0] =a[-1]
print(f_elem)
a[-1] =temp
print(l_elem)
print(a)
swapFirstAndLast() |
53bf67c2828e5a48854a684c624d43f85aa8d30a | JorgeTranin/Python_Curso_Em_Video | /Exercicios Curso Em Video Mundo 3/Exe_088.py | 723 | 4.3125 | 4 | '''
Exercício Python 088: Faça um programa que ajude um jogador da MEGA SENA
a criar palpites.O programa vai perguntar quantos jogos serão gerados e
vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em
uma lista composta.
'''
from time import sleep
from random import sample
numeros_megasena = list(range(1, 61))
jogos = list()
print('='*30)
print(' Jogos da mega sena ')
print('='*30)
n = int(input('Quantos jogos você quer gerar? '))
for i in range(0, n):
jogos.append(sample(numeros_megasena, 6))
print('*'*40)
print(f'-======= Sorteando {len(jogos)} jogos -=========')
print('*'*40)
sleep(2)
for c, j in enumerate(jogos) :
j.sort()
sleep(1)
print(f'Jogo {c+1}: {j}') |
d7debea1c4ced924d0f1f610c5e0ce4b21522282 | TheSheepKing/Deep-Learning-Gomoku | /reinforcement.py | 1,971 | 3.71875 | 4 | #!/usr/bin/env python3
"""
play a game against oneself until the end
save labels (state, policy, winning) to file label_{num_game}.label
"""
import numpy as np
from mc_tree_search import turn, expand
from node import Node
def save_tmp_label(board, p, player):
"""
append board, policy vector and current player to tmp file
format => np.array => ((3, 19, 19), 19 * 19, 1)
"""
return
def save_final_label(num, winner):
"""
rewrite tmp file and change player to 1 if == winner, else -1
format => np.array => ((3, 19, 19), 19 * 19, 1)
"""
return
def print_board(board):
"""
debug, print current map to term with colours
"""
board = (board[:,:,:,0] + board[:,:,:,1] * 2)[0]
print ("board:")
for line in board:
l = ""
for tile in line:
if tile == 1:
l += "\033[34;10m" + str(tile) + "\033[0m "
elif tile == 2:
l += "\033[31;10m" + str(tile) + "\033[0m "
else:
l += " "
print (l)
def init_game(network):
"""
init game board, first node, next player turn
"""
node = Node(0)
board = np.zeros((1, 19, 19, 3), np.int8)
expand(node, board, 0, network)
return board, node, 0
def game(network, num_game):
"""
take identifier of a game and play it until the end
num_game: integer
"""
board, root, player = init_game(network)
end = 0
while (not end):
# run mcts simulation: chosen move, new board, policy, new root, game status
_, board, p, root, end = turn(board, player, root, network)
# save board state, policy vector and current player in tmp folder
save_tmp_label(board, p, player)
# next player
player ^= 1
# debug
print_board(board)
print("end game", (player ^ 1) + 1)
# rewrite tmp file to num_game file with final winner info
save_final_label(num_game, player)
|
77972802bb286c250023c4fb3c9ea10b9fe3c512 | manufebie/program-design-method | /python_files_excersises/2_avg_word_len.py | 790 | 4.46875 | 4 | '''
Write a program that will calculate the average word length of a text stored in a file
(i.e the sum of all the lengths of the word tokens in the text, divided by the number of word tokens).
'''
import os
file_path = os.chdir('/home/manu/Desktop/computer_science/semester1/exercises/program_design_methods/files/text_files')
file_n = 'pride_and_prejudice.txt'
with open(file_n, 'r') as f:
f_content = f.read()
char_count = len(f_content) # Total number of characters
word_count = len(f_content.split()) # total number of words
avg = char_count // word_count # Divide num of chars with num of words
# print out result
print('Char total: {}'.format(char_count))
print('Word toal: {}'.format(word_count))
print('Average word length: {}'.format(avg))
|
0a64ab3dff9adcd81dc28d3b8871e71f87abf168 | mateus-n00b/graphs_ufba | /graphs2.0/find_circle.py | 707 | 3.71875 | 4 | # This function allows to find the edges inside the cycle
#
# Mateus-n00b (UFBA), August 2017
#
#
# License GPLv3
# ////////////////////////////////////////////////////////////////////////////////////////////////////
import networkx as nx
def find_cycle_mst(H,u,v,mst):
G = nx.Graph()
for node in range(0,len(H)):
G.add_node(node)
for edge in H[node]:
G.add_edge(node,edge)
cycle = nx.find_cycle(G,source=u)
# cycle = nx.cycle_basis(G,u)
# Filter output
return cycle
# Graph for tests
# H = [
# [1],
# [0,2,6,7],
# [1,7,3,8],
# [2,4,8],
# [3],
# [6],
# [5,1,7],
# [6,2,1,8],
# [2,7,9,3],
# [8]
# ]
#
# print find_cycle_mst(H,7,9,[])
|
6be8e55955d17c4e910db30a94cb161e1ec1f311 | Amangiri99/Dynamic-Web-Scraping | /web_scrapping.py | 4,550 | 3.71875 | 4 | #importing necessary packages
#Selenium - Powerful tool for automation which helps to communicate between the browser and driver
#BeautifulSoup - Is a Python library for pulling data out of HTML and XML files
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import pandas as pd
#Remember the code can be further changed and thus can increase its functionality.
#Example using Explicit Wait function of selenium to let the required classes to load before scrapping
#Using the click function of selenium.
#Using try,except block to make the program more readable.
#URL from which data is to be scrapped.
url = "https://www.magicbricks.com/property-for-sale/residential-real-estate?proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment&cityName=Kolkata&BudgetMin=15-Lacs&BudgetMax=90-Lacs"
#Creating a chrome driver
#Pls ensure you have chrome driver installed and you are giving the correct path/
driver = webdriver.Chrome("C:/chrome_driver/chromedriver.exe")
driver.get(url)
#As magic bricks website is dynamic we need to scroll down to load the whole page
#Using selenium we scroll down the page to load the whole HTML.
y = 500
for timer in range(0,500):
driver.execute_script("window.scrollTo(0, "+str(y)+")")
y += 500
print(timer)
time.sleep(1)
#Function which helps in scrapping the page.
#Returning the data in the form of a list, later saving it as a CSV file.
def get_data():
print("Hi! Inside the functioon");
#Now after loading the whole page.
#We parse the page HTML using BeautifulSoup
soup = BeautifulSoup(driver.page_source, 'html.parser')
#List which stores the data scraped.
all = []
#d refers to div tag inside the HTML page which acts as container.
#The container contains a list of all the type of properties with there data. Properties mention Houses
for d in soup.find_all('div', class_="flex relative clearfix m-srp-card__container"):
print("I am doing my work pls wait dont close me pls pls pls!!!")
#Stores the scrapped data of each iteration.
all_data = []
#div_of_price contains in it the price and sq_ft details
div_of_price = d.find('div', class_="m-srp-card__info flex__item")
#Getting the price insie the div_of_price
price = div_of_price.find('div', class_="m-srp-card__price").text
# Getting the sq_ft_area insie the div_of_price
sq_ft = (div_of_price.find('span', class_="semi-bold"))
#Getting the no. of rooms information.
#Using the d variable which iterates each box of a container.
rooms = d.find('span', class_="m-srp-card__title__bhk").text
# Getting the total_sq_ft area, floor_no and transaction type
div_features = d.find('div', class_="m-srp-card__summary js-collapse__content")
total_sq_ft = (div_features.find_all('div', class_="m-srp-card__summary__info")[0]).text
floor = (div_features.find_all('div', class_="m-srp-card__summary__info")[2]).text
#After collecting the necessary data.
#Grouping the info in a single list:
all_data.append(price)
#Storing the sq_ft info in the list
#If it is None we store it as zero.
#Later it can be deleted or changed as per need.
if sq_ft is not None:
all_data.append(sq_ft.text)
else:
all_data.append('0')
all_data.append(rooms)
all_data.append(total_sq_ft)
all_data.append(floor)
all.append(all_data)
return all
#Creating a list which stores the data returned from the function.
results = []
results.append(get_data())
#Letting the driver rest.
time.sleep(5)
#Converting the result list into a csv file using pandas.
flatten = lambda l: [item for sublist in l for item in sublist]
df = pd.DataFrame(flatten(results),columns=['Price', 'SuperBuild' , 'BHK' , 'Total_Sq_Ft' , 'Floor'])
df.to_csv('magic_bricks.csv', index=False, encoding='utf-8')
#Thank You.
#Do note Web Scrapping is illegal for some websites
#So pls go through the https://website-name/robots.txt page
#To find out if WebScraping is allowed or not.
|
ec8106c2c8a32e8ce8e7fee83792e942937782d6 | rmaiquez/code-wars | /python/8kyu/square(n)-sum.py | 263 | 4.21875 | 4 | # Complete the square sum method so that it squares each number passed into it and then sums the results together.
#
# For example: squareSum([1, 2, 2]) should return 9 because 1^2 + 2^2 + 2^2 = 9.
def square_sum(numbers):
return sum(x ** 2 for x in numbers) |
b3d7d1759c85de5812c9719451fdbaaaedd53ef1 | SimonTheFirst/python_magistracy | /lab3.py | 427 | 4.1875 | 4 | def encode_str(string):
vowel_encode_dict = {
"a": "0",
"e": "1",
"i": "2",
"o": "2",
"u": "3"
}
for key in vowel_encode_dict.keys():
string = string.replace(key, vowel_encode_dict[key])
return str(string[::-1] + "aca")
if __name__ == "__main__":
print("Enter a string:", end=" ")
enc_string = input()
print(encode_str(enc_string))
|
27e367eb218f3e5e9831f6ab78bf8edda2d6bc9b | galemos/ZNC | /Tutoriais de Python/Curso Alura Python/1_introducao.py | 206 | 3.71875 | 4 | # coding: UTF-8
nome = 'Gabriel'
idade = 25
print 'Meu nome é ' + nome + 'e tenho ' + str(idade) + ' anos'
x = 5
y = '9'
print x+int(y)
print 'Meu nome é %s e tenho %s' %(nome, idade)
nome = 'nome'
|
e9a71642c06d9c0e84de9d8c6d3bf9c994f2b3e7 | RomanKalsin/python-project-lvl1 | /brain_games/scripts/brain_even.py | 855 | 3.90625 | 4 | #!/usr/bin/env/ python3
from brain_games.welcome import welcome
from random import randint
import prompt
def main():
name = welcome()
brain_even(name)
def brain_even(name):
print('Answer "yes" if the number is even, otherwise answer "no".')
i = 0
while i < 3:
num = randint(1, 100)
print("Question: {}".format(num))
correct = ""
ansver = prompt.string("Your answer: ")
correct = "yes" if num % 2 == 0 else "no"
if correct != ansver.lower():
print("'{}' is wrong answer ;(. Correct answer was '{}'. "
"\n Let's try again, {}!".format(ansver, correct, name))
break
print("Correct!")
i += 1
else:
print("Congratulations, {}!".format(name))
if __name__ == "__main__":
main()
|
97b16a9798970f1f2d734ed16a60187ae7f3f7e1 | sudhanthiran/Python_Practice | /Competitive Coding/RegEx matching.py | 1,621 | 4.5625 | 5 | """
Given a pattern string and a test string, Your task is to implement RegEx substring matching.
If the pattern is preceded by a ^, the pattern(excluding the ^) will be matched with
the starting position of the text string. Similarly, if it is preceded by a $, the
pattern(excluding the ^) will be matched with the ending position of the text string.
If no such markers are present, it will be checked whether pattern is a substring of test.
Example :
^coal
coaltar
Result : 1
tar$
coaltar
Result : 1
rat
algorate
Result: 1
abcd
efgh
Result :0
Input: The first line of input contains an integer T denoting the no of test cases.
Then T test cases follow. Each test case contains two lines.
The first line of each test case contains a pattern string.
The second line of each test case consists of a text string.
Output: Corresponding to every test case, print 1 or 0 in a new line.
Constrains:
1<=T<=100
1<=length of the string<=1000
"""
def isSubString(test_string,base_string):
flag = base_string.find(test_string)
if(flag == -1):
return False
else:
return True
def test_for_regex():
test_string = str(input())
base_string = str(input())
flag=False
if (test_string.startswith('^')):
flag = (test_string[1:] == base_string[:len(test_string)-1])
elif(test_string.endswith('$')):
flag = (test_string[:len(test_string)-1] == base_string[(len(test_string)-1)*-1:])
else:
flag = (isSubString(test_string, base_string))
if(flag==True):
print("1")
else:
print("0")
t = int(input())
for i in range(t):
test_for_regex() |
466e86f8b79744b9f0e8686f3d95fd041137c4d8 | brittany-fisher21/python_rpg | /python_rpg/rpg-2.py | 2,425 | 4.15625 | 4 | """
In this simple RPG game, the hero fights the goblin. He has the options to:
1. fight goblin
2. do nothing - in which case the goblin will attack him anyway
3. flee
"""
class Character:
def __init__(self, health, power, name):
self.health = health
self.power = power
self.name = name
def attack(self, enemy):
# fight
enemy.health -= self.power
def alive(self):
if self.health > 0:
return True
def print_status(self):
print( "%s has %d health points left" % (self.name,self.health))
class Hero(Character):
def __init__(self, health, power, name):
self.health = health
self.power = power
self.name = name
class Villian(Character):
def __init__(self, health, power, name):
self.health = health
self.power = power
self.name = name
# Object that I'm working with. Make changes here.
black_panther = Hero(50, 20, "black_panther")
killmonger = Villian(50, 20, "killmonger")
def main():
while killmonger.alive() and black_panther.alive():
black_panther.print_status()
killmonger.print_status()
# Leave steps below commented out. Don't remove. Using as reference.
# print("black_panther has %d health and %d power." % (black_panther.health,black_panther.power))
# print("killmonger has %d health and %d power." % (killmonger.health,killmonger.power))
print("What do you want to do?")
print("1. fight killmonger")
print("2. do nothing")
print("3. flee")
print("> ",)
user_input = input()
if user_input == "1":
# black panther attacks killmonger
black_panther.attack(killmonger)
print("You do %d damage to the killmonger." % black_panther.power)
if killmonger.health <= 0:
print("The killmonger is KO.")
elif user_input == "2":
pass
elif user_input == "3":
print("Goodbye.")
break
else:
print("Invalid input %r" % user_input)
if killmonger.health > 0:
# killmonger attacks black panther
killmonger.attack(black_panther)
print("The killmonger does %d damage to you." % killmonger.power)
if black_panther.health <= 0:
print("You are dead.")
main() |
c5bc73f16e38e06c97b1d62223d2defde0ee5f31 | eanopolsky/advent-of-code-2019 | /14/nanofactory2.py | 2,769 | 3.609375 | 4 | #!/usr/bin/python3
from math import ceil
reactions = []
with open("input.txt") as f:
for line in f:
reaction = {"Rs": [], "P": {}}
reagents, product = line.split("=>")
reagents = reagents.strip().split(", ")
product = product.strip()
#print("'{}'".format(reagents))
#print("'{}'".format(product))
reaction["P"]["num"], reaction["P"]["chem"] = product.split(" ")
reaction["P"]["num"] = int(reaction["P"]["num"])
for reagent in reagents:
reagentdict = {}
reagentdict["num"], reagentdict["chem"] = reagent.split(" ")
reagentdict["num"] = int(reagentdict["num"])
reaction["Rs"].append(reagentdict)
reactions.append(reaction)
#print(reaction)
knownchems = [reaction["P"]["chem"] for reaction in reactions]
#print(knownchems)
def findoreneeded(fuelamount):
needed = {}
for knownchem in knownchems:
needed[knownchem] = 0 if knownchem != "FUEL" else fuelamount
needed["ORE"] = 0
#print(needed)
storage = {}
for knownchem in knownchems:
storage[knownchem] = 0
#print(storage)
while True:
for target in needed:
if target == "ORE":
continue
if needed[target] == 0:
continue
if needed[target] <= storage[target]:
storage[target] -= needed[target]
needed[target] = 0
continue
else:
needed[target] -= storage[target]
storage[target] = 0
reaction = [reaction for reaction in reactions if reaction["P"]["chem"] == target][0] #only works when each chem is produced by a single recipe. Might change in part 2?
#print(reaction)
nreactions = ceil(needed[target] / reaction["P"]["num"])
for reagent in reaction["Rs"]:
needed[reagent["chem"]] += nreactions * reagent["num"]
excessproduct = nreactions * reaction["P"]["num"] - needed[target]
storage[target] += excessproduct
needed[target] = 0
#print(storage)
#print(needed)
if sum([needed[chem] for chem in needed if chem != "ORE"]) == 0:
return needed["ORE"]
#print(findoreneeded(1))
low = 1
targetore = 1000 ** 4
high = targetore
guess = ceil((low+high)/2)
while True:
print("fuelguess: {}, ore needed:{}".format(guess,findoreneeded(guess)))
if findoreneeded(guess) <= targetore and \
findoreneeded(guess+1) > targetore:
print("max fuel from {} ore: {}".format(targetore,guess))
exit(0)
if findoreneeded(guess) < targetore:
low = guess
else:
high = guess
guess = ceil((low+high)/2)
|
526819350a7ed114601af2d0be14f7e99594b8cf | ibek01/tasks_all_weeks | /Desktop/bootcamp/week2/practice/task4.py | 1,325 | 3.921875 | 4 | # 4. Изменение списка гостей: вы только что узнали, что один из гостей прийти не сможет,
# поэтому вам придется разослать новые приглашения. Отсутствующего гостя нужно заме-
# нить кем-то другим.
# • Начните с программы из упражнения 3. Добавьте в конец программы команду print
# для вывода имени гостя, который прийти не сможет.
# • Измените список и замените имя гостя, который прийти не сможет, именем нового
# приглашенного.
# • Выведите новый набор сообщений с приглашениями – по одному для каждого участ-
# ника, входящего в список.
guest = ['Azat', 'Azamat', 'Asylbek']
print("I invite you to lunch " + guest[0] + " ")
print("I invite you to lunch " + guest[1] + " ")
print("I invite you to lunch " + guest[2] + " ")
print(guest[0])
guest[0] = 'Davran'
print(guest)
print("Lets go to lunch " + guest[0] + " ")
print("Lets go to lunch " + guest[1] + " ")
print("Lets go to lunch " + guest[2] + " ") |
d6c58c46b3b0010d22bb613fd2788bd996c9fe53 | DanielHa01/Calculator | /calculator.py | 4,399 | 3.875 | 4 | """
Simple Calculator
By Daniel Ha
Contact: bb13112001@gmail.com
"""
from tkinter import *
from math import sqrt
master = Tk()
master.title("Calculator")
e = Entry(master, width = 40, borderwidth = 3)
e.grid(row = 0, column = 0, columnspan = 4, padx = 5, pady = 5)
def show_value(num):
current = e.get()
e.delete(0, END)
e.insert(0, str(current) + str(num))
return
def clear():
e.delete(0,END)
return
def add():
global status
status = 'addition'
fnum = e.get()
global num1
num1 = int(fnum)
e.delete(0, END)
return
def sub():
global status
status = 'subtraction'
fnum = e.get()
global num1
num1 = int(fnum)
e.delete(0, END)
return
def div():
global status
status = 'division'
fnum = e.get()
global num1
num1 = int(fnum)
e.delete(0, END)
return
def multiply():
global status
status = 'multiply'
fnum = e.get()
global num1
num1 = int(fnum)
e.delete(0, END)
return
def square_root():
global status
status = 'square_root'
fnum = e.get()
global num1
num1 = int(fnum)
e.delete(0, END)
return
def power():
global status
status = 'power'
fnum = e.get()
global num1
num1 = int(fnum)
e.delete(0, END)
return
def equal():
if status == 'addition':
num2 = e.get()
e.delete(0, END)
e.insert(0, num1 + int(num2))
elif status == 'subtraction':
num2 = e.get()
e.delete(0, END)
e.insert(0, num1 - int(num2))
elif status == 'division':
num2 = e.get()
e.delete(0, END)
e.insert(0, num1 / int(num2))
elif status == 'multiply':
num2 = e.get()
e.delete(0, END)
e.insert(0, num1 * int(num2))
elif status == 'square_root':
e.insert(0, sqrt(num1))
elif status == 'power':
num2 = e.get()
e.delete(0, END)
e.insert(0, num1 ** int(num2))
return
button1 = Button(master, text = '1',padx = 25, pady = 10, command = lambda :show_value(1))
button2 = Button(master, text = '2',padx = 25, pady = 10, command = lambda :show_value(2))
button3 = Button(master, text = '3',padx = 25, pady = 10, command = lambda :show_value(3))
button4 = Button(master, text = '4',padx = 25, pady = 10, command = lambda :show_value(4))
button5 = Button(master, text = '5',padx = 25, pady = 10, command = lambda :show_value(5))
button6 = Button(master, text = '6',padx = 25, pady = 10, command = lambda :show_value(6))
button7 = Button(master, text = '7',padx = 25, pady = 10, command = lambda :show_value(7))
button8 = Button(master, text = '8',padx = 25, pady = 10, command = lambda :show_value(8))
button9 = Button(master, text = '9',padx = 25, pady = 10, command = lambda :show_value(9))
button0 = Button(master, text = '0',padx = 25, pady = 10, command = lambda :show_value(0))
button_equal = Button(master, text = '=', padx = 90, pady = 10, command = equal)
button_clear = Button(master, text = 'C', padx = 25, pady = 10, command = clear)
button_add = Button(master, text = '+', padx = 25, pady = 10, command = add)
button_subtract = Button(master, text = '-', padx = 25, pady = 10, command = sub)
button_divide = Button(master, text = '/', padx = 25, pady = 10, command = div)
button_multiply = Button(master, text = '*', padx = 25, pady = 10, command = multiply)
button_square_root = Button(master, text = '√', padx = 25, pady = 10, command = square_root)
button_power = Button(master, text = '^', padx = 25, pady = 10, command = power)
button1.grid(row = 4, column = 0)
button2.grid(row = 4, column = 1)
button3.grid(row = 4, column = 2)
button4.grid(row = 3, column = 0)
button5.grid(row = 3, column = 1)
button6.grid(row = 3, column = 2)
button7.grid(row = 2, column = 0)
button8.grid(row = 2, column = 1)
button9.grid(row = 2, column = 2)
button0.grid(row = 5, column = 0)
button_equal.grid(row = 5, column = 1, columnspan = 3)
button_clear.grid(row = 1, column = 0)
button_add.grid(row = 2, column = 3)
button_subtract.grid(row = 1, column = 3)
button_divide.grid(row = 1, column = 1)
button_multiply.grid(row = 1, column = 2)
button_square_root.grid(row = 3, column = 3)
button_power.grid(row = 4, column = 3)
master.mainloop() |
607b2a4070cbe37a7889bb5ef1947e7f4ffbb64a | KaySchus/Project-Euler | /Problem 1 - 50/Problem1.py | 220 | 3.609375 | 4 | def sum_multiple(target, value):
result = 0
for i in range(1, target):
if (i % value == 0):
result += i
return result
final = sum_multiple(1000, 3) + sum_multiple(1000, 5) - sum_multiple(1000, 15)
print(final) |
a3626d98ae60cb29b3b8d8ee6240f56ccd85b7a5 | laboyd001/python-crash-course-ch8 | /user_albums.py | 660 | 4.1875 | 4 | #write a while loop that allows users to enter an album's artist and title. Print the dictionary and be sure to include a quit.
def make_album(artist, album_name):
"""Return an artist and album name, neatly formatted."""
album = {'artist':artist, 'album_name':album_name}
return album
while True:
print("\nPlease tell me an artist and their album:")
print("(enter 'q' at any time to quit)")
artist = input("Artist name: ")
if artist == 'q':
break
album_name = input("Album name: ")
if album_name == 'q':
break
formatted_name = make_album(artist, album_name)
print(formatted_name) |
5065570ef0bf937fd0f419495d1b594962490c76 | cardy31/CTCI | /Random/fib.py | 223 | 3.703125 | 4 | def main():
for i in range(0, 100):
print(fib(i))
# 0, 1, 1, 2, 3, 5, 8, 13...
def fib(n):
if n == 0 or n == 1:
return n
return fib(n - 1) + fib(n - 2)
if __name__ == '__main__':
main()
|
47624bd594724a2245f35e23706b82ef827a86ec | OwlFlash/proste_cw_na_poczatek | /Duration of planet.py | 481 | 3.671875 | 4 | import math
odległość_Ziemii = 150 *pow(10,9)
okres_Ziemii = pow(1314000,2) #w kwadracie
print ("Podaj nazwę planety")
planeta = input()
print("Podaj odległość (W METRACH) planety od Słońca"),format(planeta)
odległość =int( input())
d = float (odległość/odległość_Ziemii)
okres =( math.sqrt( (pow(d, 3))*okres_Ziemii ))/3600
print("Okres planety :{} o odległości od Słońca równej : {} metrów wynosi : {} dni".format(planeta,odległość,okres))
|
eb34f1203b7d10c87bb46277b69a5cb1eb1254cb | jry-king/leetcode | /3.longest-substring-without-repeating-characters.py | 1,442 | 3.796875 | 4 | # brute force, examine longest substring starting from each character and compare their lengths
# O[n**3] time complexity and O[max(m,n)] space complexity
# m, n is the size of the string and the alphabet
# 576 ms, faster than 15.2%
# 13.1 MB, less than 5.51%
'''class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length = 0
substring = ""
for i in range(0, len(s)):
substring = s[i]
j = i + 1
while (j < len(s) and s[j] not in substring):
substring += s[j]
j += 1
length = max(length, len(substring))
return length'''
# optimized sliding window, add character to substring one by one,
# and if duplicate character appears, truncate the former part of the substring divided by this character, then add this character to the end
# O[n] time complexity and O[max(m,n)] space complexity
# m, n is the size of the string and the alphabet
# 80 ms faster than 83.66%
# 13.3 MB, less than 5.05%
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length = 0
substring = ""
for i in range(0, len(s)):
if (s[i] in substring):
length = max(length, len(substring))
substring = substring.split(s[i])[-1] + s[i]
else:
substring += s[i]
length = max(length, len(substring))
return length
|
fc3c79f66963352b0a9a519598b496e1b0743d78 | xiaoxue11/python_learning | /basic/function.py | 1,293 | 3.5625 | 4 | import math
def aa():
return 'something'
def fahrenheit_convet(C):
fahrenheit=C*9/5+32
print (fahrenheit)
def weight_convert(g):
weight=g/1000
return weight;
def triangle_side(a,b):
third_side=math.sqrt(a*a+b*b)
return 'The right triangle third side\'s length is '+str(third_side)
def invest(amount,rate,time):
print('principal amount: '+str(amount))
for i in range(1,time+1):
print('year '+str(i)+' : '+str(amount*(1+rate)**i))
def even(num):
for i in range(1,num):
if(i%2==0):
print(i)
def fibs(num):
result=[0,1]
for i in range(num-2):
result.append(result[-2]+result[-1])
return result
def change(n):
n[0]='Mr.Gumby'
names=['Mrs.Entity','Mrs.Thing']
change(names[:])
print(names)
def init(data):
data['first']={}
data['middle']={}
data['last']={}
def lookup(data,label,name):
return data[label].get(name)
def store(data,full_name):
names=full_name.split()
if len(names)==2: names.insert(1,'')
labels='first','middle','last'
for label,name in zip(labels,names):
people=lookup(data,label,name)
if people:
people.append(full_name)
else:
data[label][name]=[full_name]
|
76cd1e4c0265ae639349fb6265f4cf0b4d74abdd | CHREC/PythonTutorials | /variableTypes.py | 2,545 | 4.53125 | 5 | # Values to variables
inte = 100 # integer variable type
fl = 100.0 # floating variable type
st = 'john' # string variable type
# Multiple Assignment
a = b = c = 1 # all three variables (a,b,c) have a value of 1
a, b, c = 1, 2, 'john' # value of integer 1 to a, integer 2 to b, and string 'john' to c
# 5 data types
# Numbers
var1 = 1
var2 = 10
var3 = 100 # three varialbes instantiated with respective integer values
del var1
del var2, var3 # can delete one or more variables in a line at a time
# 4 numerical variable types
a = 10 # integer variable type
b = 5200000L # 'L' indicates long integer variable type (can be in octal or hexadecimal)
c = 0.5 # float variable type
d = 5.j # complex number with imagianry component
# Strings
strng = "Hello World!"
print strng # displays entire string
print strng[0] # displays first character of string
print strng[2:5] # displays third through the fifth character but not the fifth
print strng[2:] # displays string from the third character onwards
print strng * 2 # displays the string two times
print strng + "TEST" # displays the string and the specified characters after
# Lists (similar to arrays but each item can be of a different data types
lsts = ['abcd', 786, 2.23, 'john', 70.2]
smalllsts = [123, 'john']
print lsts # prints the entire list
print lsts[0] # prints first element in the list
print lsts[1:3] # prints elements from the second to the third items but not the third
print lsts[2:] # prints all the elements starting from the third item
print smalllsts * 2 # prints smalllsts twice
print lsts + smalllsts # prints the two lists
# Tuples ("read-only" lists)
tuples = ('abcd', 786, 2.23, 'john', 70.2)
smalltuple = (123, 'john')
print tuples # prints the entire list
print tuples[0] # prints first element in the list
print tuples[1:3] # prints elements from the second to the third items but not the third
print tuples[2:] # prints all the elements starting from the third item
print smalltuple * 2 # prints smalllsts twice
print tuples + smalltuple # prints the two lists
# tuple[2] = 1000 is invalid as a tuple cannot be updated
# list[2] = 1000 is valid however
# Dictionary
dictnry = {}
dictnry['one'] = "This is one"
dictnry[2] = "This is two"
tinydict = {'name': 'john', 'code': 6734, 'dept': 'sales'}
print dictnry['one'] # Prints value for 'one' key
print dictnry[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values
|
ccf6147c627f75baa0c5374e723a6df0589b7271 | minas528/a2sv | /Introdution to Competitive Programming/D19/Binary Search.py | 547 | 3.671875 | 4 | class Solution:
def search(self, nums: List[int], target: int) -> int:
if not nums :
return -1
def recSearch(nums,target,left,right):
if left>right :
return -1
mid = (left+right)//2
if target == nums[mid] :
return mid
elif target<nums[mid]:
return recSearch(nums,target,left,mid-1)
else:
return recSearch(nums,target,mid+1,right)
return recSearch(nums,target,0,len(nums)-1)
|
99cc7450b8527d654bca3bccdecc78c921e8ec92 | vincent507cpu/Comprehensive-Algorithm-Solution | /LeetCode/easy - Hash Table/350. Intersection of Two Arrays II/.ipynb_checkpoints/solution-checkpoint.py | 1,549 | 3.71875 | 4 | # base model, ugly
class Solution:
def intersect1(self, nums1: List[int], nums2: List[int]) -> List[int]:
if not nums1 or not nums2:
return []
lst = []
for i in range(len(nums1)):
if nums2 and nums1[i] in nums2:
lst.append(nums1[i])
idx = nums2.index(nums1[i])
nums2.pop(idx)
return lst
###################################################
# sorted lists:
def intersect2(self, nums1: List[int], nums2: List[int]) -> List[int]:
if not nums1 or not nums2:
return []
lst = []
# nums1.sort()
# nums2.sort()
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
i += 1
elif nums1[i] > nums2[j]:
j += 1
else:
lst.append(nums1[i])
i += 1
j += 1
return lst
###################################################
# use dictionary
def intersect3(self, nums1: List[int], nums2: List[int]) -> List[int]:
if not nums1 or not nums2:
return []
lst = []
dct = {}
for num in nums2:
dct[num] = dct.get(num, 0) + 1
for num in nums1:
if num in dct and dct[num] > 0:
lst.append(num)
dct[num] -= 1
return lst |
10ee8d8a7153d881b2e36ffcd3a9f9a2ca4c768e | Pumacens/Competitive-Programming-Solutions | /CodeWars-excercises/Python/7_kyu/files/77. Get the Middle Character.py | 190 | 3.53125 | 4 | def get_middle(s):
len_s = len(s)
if len_s <= 2:
return s
return s[len_s//2 - (len_s%2==0) : len_s//2 + 1]
# def get_middle(s):
# return s[(len(s)-1)/2:len(s)/2+1] |
057700b7c97b2191dbaf251ffe7c38dac37a651d | UCSD-CSE100-SS1-2020/set_and_map_using_linked_list | /set_solution.py | 1,267 | 3.828125 | 4 | class ListNode:
next = None
val = None
def __init__(self, v):
self.val = v
class Set:
head = None
size = 0
def __init__(self, h=None):
if h:
self.head = ListNode(h)
self.size += 1
def add(self, e):
if not self.contains(e):
temp = self.head
self.head = ListNode(e)
self.head.next = temp
self.size += 1
def remove(self, e):
prev = None
curr = self.head
while curr:
if curr.val == e:
if not prev:
self.head = curr.next
else:
prev.next = curr.next
self.size -= 1
return
prev = curr
curr = curr.next
def contains(self, e):
curr = self.head
while curr:
if curr.val == e:
return True
curr = curr.next
return False
def isEmpty(self):
return self.size == 0
if __name__ == "__main__":
print("Hello World")
my_set = Set()
my_set.add(2)
my_set.add(3)
print(my_set.contains(2))
print(my_set.size)
my_set.remove(2)
print(my_set.contains(2))
print(my_set.size)
|
5b38d8a2ad85211ff3c79ed6e8635e8987020915 | jonghoonok/Algorithm_Study | /1240.py | 1,242 | 3.5 | 4 | def password_check(numbers):
# 먼저 암호문에 해당되지 않는 행 제거
i = 0
while True:
if not '1' in numbers[i]:
numbers.pop(i)
else:
i += 1
if len(numbers) == i:
break
# 열 제거
for j in range(m-1, 56, -1):
if numbers[0][j] == '0':
continue
else:
for k in range(len(numbers)):
numbers[k] = numbers[k][j-55:j+1]
break
# 암호코드로 변환
check_list=['0001101','0011001','0010011','0111101','0100011','0110001','0101111','0111011','0110111','0001011']
code = [0]*8
i = 0
while i < 7:
code[i] = check_list.index(numbers[0][i*7:i*7+7])
i += 1
code[7] = check_list.index(numbers[0][49:])
# 검증코드가 맞는지 확인
result = 0
for j in range(8):
if j % 2 == 0:
result += 3*code[j]
else:
result += code[j]
if result % 10 == 0:
return sum(code)
else:
return 0
t = int(input())
for test_case in range(t):
n, m = map(int, input().split())
numbers = [input() for _ in range(n)]
print('#' + str(test_case + 1), password_check(numbers)) |
9092b0983f9f8304be95ea4faed7fe17d1f4343d | adityachache/data-structures | /graph.py | 937 | 4.03125 | 4 | class Graph():
def __init__(self):
self.numberofnodes = 0
self.adjacentlist = {}
def addvertex(self,node):
"""add a vertex in the graph"""
self.adjacentlist[node] = []
self.numberofnodes += 1
def addedge(self,node1,node2):
"""add an edge to a vertex"""
self.adjacentlist[node1].append(node2)
self.adjacentlist[node2].append(node1)
def showconnections(self):
"""shows the connection between the vertices"""
for node in self.adjacentlist:
print(f'{node} -->> {" ".join(map(str,self.adjacentlist[node]))}')
#print(f'{node} -->> {" ".join(self.adjacentlist[node])}')
my_graph = Graph()
my_graph.addvertex(1)
my_graph.addvertex(2)
my_graph.addvertex(3)
my_graph.addedge(1,2)
my_graph.addedge(1,3)
my_graph.addedge(2,3)
my_graph.showconnections() |
b145cc89ace12483c90b33f24834b3d413e92289 | mattbingham/Python | /turtle_miniproject.py | 2,455 | 3.8125 | 4 | import turtle
window = turtle.Screen()
window.bgcolor("#87cefa")
window.setup (width=800, height=600, startx=0, starty=0)
class Shapes():
# Make the ground
def ground():
soil = turtle.Turtle()
soil.up()
soil.setpos(-100, -200)
soil.down()
soil.color("brown")
soil.begin_fill()
i = 0
while i < 2:
soil.speed(8)
soil.forward(400)
soil.left(90)
soil.forward(200)
soil.left(90)
i += 1
soil.end_fill()
Shapes.flower()
# Make a flower
def flower():
daisy = turtle.Turtle()
daisy.up()
daisy.setpos(-50, 0)
daisy.down()
daisy.color("#7b68ee", "#ffd700")
daisy.begin_fill()
i = 0
while i < 36:
daisy.speed(10)
daisy.forward(100)
daisy.right(170)
i += 1
daisy.end_fill()
daisy.forward(50)
daisy.pensize(4)
daisy.setheading(270)
daisy.color("green")
daisy.forward(150)
Shapes.circle()
# Make a circle flower
def circle():
pretty = turtle.Turtle()
pretty.up()
pretty.setpos(100, 0)
pretty.down()
pretty.color("#ff69b4", "#ffc0cb")
pretty.begin_fill()
pretty.circle(50)
pretty.end_fill()
pretty.setheading(270)
pretty.pensize(3)
pretty.color("green")
pretty.forward(150)
pretty.up()
pretty.setheading(0)
pretty.forward(180)
pretty.setheading(90)
pretty.forward(200)
pretty.pensize(3)
pretty.color("#48d1cc", "#ffd700")
pretty.begin_fill()
pretty.circle(50)
pretty.end_fill()
pretty.setheading(180)
pretty.up()
pretty.forward(50)
pretty.pensize(4)
pretty.setheading(270)
pretty.color("green")
pretty.down()
pretty.forward(200)
Shapes.sun()
# Sunshine
def sun():
shine = turtle.Turtle()
shine.color("#ffff00", "#ffd700")
shine.up()
shine.setpos(-300, 150)
shine.down()
shine.begin_fill()
i = 0
while i < 36:
shine.speed(8)
shine.forward(180)
shine.right(170)
i += 1
shine.end_fill()
window.exitonclick()
Shapes.ground()
|
7af2ead36b52e7e7fc6b57c271aa2f9d40c7bf75 | inauski/SistGestEmp | /Tareas/Act02. If....else/ejer04/ejer04.py | 613 | 4.0625 | 4 | print("Comparador de multiplos")
num1 = int(input("Escriba un numero: "))
num2 = int(input("Escriba otro numero: "))
if ((num1 > num2) and ((num1 % num2)==0) ):
print (str(num1) + " es multiplo de " + str(num2))
elif ((num2>num1) and ((num2 % num1)==0)):
print(str(num2) + " es multiplo de " + str(num1))
elif ((num1 > num2) and ((num1 % num2)!=0) ):
print(str(num1) + " no es multiplo de " + str(num2))
elif ((num2>num1) and ((num2 % num1)!=0)):
print(str(num2) + " no es multiplo de " + str(num1))
elif ((num1==num2) and ((num2 % num1)==0)):
print(str(num1) + " es multiplo de " + str(num2)) |
eb4b3363e7c4c9c6932fdc77bc2e6a676fbd23fb | SpykeX3/NSUPython2021 | /problems-3/a-ushaev/problem3.py | 2,210 | 3.515625 | 4 | #!/usr/bin/env python3
class Vector():
def __init__(self, *args):
if len(args) > 0:
if isinstance(args[0], (tuple, list)):
self._components = list(args[0])
else:
self._components = list(args)
else:
self._components = [0,0]
def __str__(self):
return str(self._components)
def __repr__(self):
return f'Vector({self._components})'
def __len__(self):
return len(self._components)
def __getitem__(self, key):
return self._components[key]
def __add__(self, other):
if isinstance(other, (int, float)):
new_vec = [el + other for el in self._components]
else:
new_vec = [el + other_el for el, other_el in zip(self._components, other)]
return Vector(new_vec)
def __radd__(self, other):
return self.__add__(other)
def __iadd__(self, other):
return self.__add__(other)
def __sub__(self, other):
if isinstance(other, (int, float)):
new_vec = [el - other for el in self._components]
else:
new_vec = [el - other_el for el, other_el in zip(self._components, other)]
return Vector(new_vec)
def __rsub__(self, other):
return self.__sub__(other)
def __isub__(self, other):
return self.__sub__(other)
def __mul__(self, other):
if isinstance(other, (int, float)):
new_vec = [el * other for el in self._components]
return Vector(new_vec)
else:
dot_prod = sum(el * other_el for el, other_el in zip(self._components, other))
return dot_prod
def __rmul__(self, other):
return self.__mul__(other)
def __imul__(self, other):
return self.__mul__(other)
def __eq__(self, other):
return self._components == other._components
if __name__ == '__main__':
x = Vector(2,5,7)
y = Vector([10,3,5])
print(f'x = {x}')
print(f'y = {y}')
print(f'x + y = {x + y}')
print(f'x - y = {x - y}')
print(f'x * 4 = {x * 4}')
print(f'x * y = {x * y}')
print(f'length of x is {len(x)}')
print(f'x[2] = {x[2]}') |
77e15071634e4e79cc73df64f6035be62c09e54c | UX404/Leetcode-Exercises | /#976 Largest Perimeter Triangle.py | 685 | 3.859375 | 4 | '''
Given an array A of positive lengths, return the largest perimeter of a triangle with non-zero area, formed from 3 of these lengths.
If it is impossible to form any triangle of non-zero area, return 0.
Example 1:
Input: [2,1,2]
Output: 5
Example 2:
Input: [1,2,1]
Output: 0
Example 3:
Input: [3,2,3,4]
Output: 10
Example 4:
Input: [3,6,2,3]
Output: 8
Note:
3 <= A.length <= 10000
1 <= A[i] <= 10^6
'''
class Solution:
def largestPerimeter(self, A: List[int]) -> int:
A.sort()
for n in range(len(A)-1, 1, -1):
if A[n] < A[n-1] + A[n-2]:
return A[n] + A[n-1] + A[n-2]
return 0 |
e78dfb5863286090be0641073479c1362759f3a8 | monkeydunkey/interviewCakeProblems | /sumNumbers.py | 400 | 3.71875 | 4 | def sumNumbers(st):
num = ''
runSum = 0
for d in st:
if d.isdigit():
num += d
else:
if len(num) > 0:
runSum += int(num)
num = ''
if len(num) > 0:
runSum += int(num)
return runSum
if __name__ == '__main__':
print sumNumbers("abc123xyz")
print sumNumbers("aa11b33")
print sumNumbers("7 11")
|
f4058434293c27f9b4ed4d93515948176118adfc | Ricksou/Python_L3 | /Episode 4.py | 2,876 | 3.8125 | 4 |
chaine = "Python"
for lettre in chaine:
print(lettre)
print()
chaine = str(input("Ecrire un mot afin de compter les occurence de chaque lettre dans ce mot "))
i=0
cnt=0
while i <= len(chaine)-1 :
compteur = chaine.count(chaine[i])
i+=1
index=i
i-=1
while i>=0:
if chaine[index-1] == chaine[i]:
cnt+=1
i-=1
if cnt ==1:
print("La lettre "+chaine[index-1]+ " est affiché "+str(compteur)+ " fois")
cnt=0
i =index
chaine = str(input("Ecrire un mot "))
char = str(input("Saisissez la lettre a rechercher dans le mot "))
for i in range(0,len(chaine),1):
if char == chaine[i]:
print("La lettre "+char+" se trouve à la position "+str(i+1))
l = ["laptop", "iphon", "tablet"]
for item in l:
print(item + " possède " + str(len(item))+ " caractères")
chaine = str(input("Ecrire un mot "))
char=chaine[-1]
char1= chaine[0]
chaine2=""
for i in range(0,len(chaine),1):
if i==0:
chaine2=chaine[-1]
elif i==len(chaine)-1:
chaine2=chaine2+chaine[0]
else:
chaine2= chaine2+chaine[i]
print(chaine2)
chaine = str(input("Ecrire un mot "))
cnt=0
for lettre in chaine:
if lettre in "aeiouy":
cnt +=1
print("Il y'a "+str(cnt)+" voyelles dans ce mot")
chaine = str(input("Ecrire une phrase "))
i=0
first=""
while chaine[i] != " " :
first = first+chaine[i]
i+=1
print(first)
chaine = str(input("Ecrire le nom d'un fichier "))
ext=""
for i in range(0,len(chaine),1):
if chaine[i]==".":
for i in range(i,len(chaine),1):
ext= ext+chaine[i]
print("L'extension du fichier est "+ext)
chaine = str(input("Ecrire un mot "))
mirroir=""
l=len(chaine)
for i in range(0,l,1):
mirroir=mirroir+chaine[l-1-i]
if mirroir==chaine:
print("C'est bien un palindrome")
else:
print("Ce n'est pas un palindrome")
chaine = str(input("Ecrire un mot "))
mirroir=""
l=len(chaine)
for i in range(0,l,1):
mirroir=mirroir+chaine[l-1-i]
print(mirroir)
chaine = str(input("Ecrire un texte "))
char = str(input("Saisissez la lettre a rechercher dans le texte "))
l=len(chaine)
mot=""
i=0
if chaine[0]==char:
while chaine[i]!=" ":
mot=mot+chaine[i]
i+=1
print(mot)
for i in range(0,l,1):
if chaine[i]==char and chaine[i-1]==" ":
mot=""
while chaine[i]!=" " and i < l-1:
mot=mot+chaine[i]
if i==l-2:
mot=mot+chaine[i+1]
i+=1
print(mot)
chaine = input("Ecrire un texte ").split(" ")
char = input("Saisissez la lettre a rechercher dans le texte ")
for item in chaine:
if item[0]==char:
print(item)
|
db08ec9595799f93780870eca2fdf579f642e87a | Balu862/everyday_assignments | /day6assignment-26july/26thjuly2021_Balasubramaniyam_assignment/day6practiced/inheritance1.py | 388 | 3.71875 | 4 | class Person(object):
def __init__(self, name):
self.name = name
def getName(self):
return self.name
class Employee(Person):
def __init__(self, name,id):
self.id=id
super().__init__(name)
def getName(self):
return self.name,self.id
emp = Person("Balu")
print(emp.getName())
emp1=Employee("Balu",1)
print(emp1.getName()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.