blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
e64bc951c27896293f8b1da440cc731de5ff8f3e | sabhishekpratap5/Python_Programs | /tuple/program10.py | 284 | 4.21875 | 4 | # # Write a Python program to reverse a tuple.
#
# tuple1 = "abhishekSingh"
# rev_tuple = reversed(tuple1)
# print(tuple(rev_tuple))
import time
st = time.time()
a = tuple(range(0, 100000000))
a = set(a)
a = list(a)
print(a)
ed = time.time()
to = ed - st
print(time.time() - st) |
9aac6d23d587955773c791cc7d597de0c30fb98d | PPerminov/python | /stuff/chessboard.py | 1,028 | 3.546875 | 4 | import sys
sys.setrecursionlimit(20000)
def chessBoard_loops():
board = "----------\n"
for r in range(8):
line = '|'
for c in range(8):
if ((c + r) % 2 == 0):
line += "x"
else:
line += " "
board += line + "|\n"
return board + "----------"
def chessBoard_recursion(row=0, col=0, size=8):
if row == (size - 1) and col == size:
line=""
for i in range(size+2):
line+='-'
return "\n"+line
if col == size:
return "\n" + chessBoard_recursion(row + 1, 0)
if ((col + row) % 2 == 0):
current = "x"
else:
current = " "
if col == 0:
current = '|' + current
if col == size-1:
current += '|'
if row == 0 and col == 0:
line=""
for i in range(size+2):
line+='-'
current = line + "\n" + current
return current + chessBoard_recursion(row, col + 1)
print(chessBoard_recursion())
print(chessBoard_loops())
|
3d64f6a5db4532b004e3ee92e2e45bb111f23f9e | chenlei0x/leetcode | /728/728.py | 419 | 3.59375 | 4 | #! /usr/bin/env python3
class Solution:
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
res = []
for i in range(left, right + 1):
cur = i
while cur != 0:
digit = cur % 10
if digit == 0:
break
cur = cur// 10
if i % digit != 0:
break
else:
res.append(i)
return res
s = Solution()
s.selfDividingNumbers(1, 22)
|
c74db4ea2fc30a2797d899c8e2828781ad8e0291 | AlbanerPabaMandon/IA | /nqueens_FINAL.py | 2,309 | 3.5625 | 4 | import random
tablero=[]
DIMENSIONES=15
#Establece la matriz vacia para el tablero
def establecer():
global tablero
for i in range(DIMENSIONES):
tablero.append([])
for j in range(DIMENSIONES):
tablero[i].append(None)
for x in range(DIMENSIONES):
for y in range(DIMENSIONES):
tablero[x][y]="_"
#Imprime el tablero
def imprimir():
global tablero
for y in range(DIMENSIONES):
print str([i[y] for i in tablero])+"\n"
#Ejecuta las funciones necesarias para la simulacion
def simular():
#Posiciones de la dama aleatoria
x=random.randint(0, DIMENSIONES-1)
y=random.randint(0, DIMENSIONES-1)
#Dama aleatoria distingida por la letra R
posicionar(x,y,"R")
iterar(x,y)
print "Damas Colocadas: "+str(contar())+" \n \n "
#Algoritmo para colocar las damas
def iterar(x,y):
global tablero
y=(y+3)%DIMENSIONES
for i in range(DIMENSIONES):
x=(x+1)%DIMENSIONES
for j in range(DIMENSIONES):
if(tablero[x][(y+j)%DIMENSIONES]=="_"):
posicionar(x,(y+j)%DIMENSIONES,"Q")#str(i))
j=DIMENSIONES+1
y=(((y+j)%DIMENSIONES)+3)%DIMENSIONES
#Posiciona y define los ataques de una dama
def posicionar(x,y,letra):
global tablero
for i in range(DIMENSIONES):
#Ataques en cruz
tablero[x][i]="*"
tablero[i][y]="*"
#Ataques en diagonal
if((x+i)<DIMENSIONES and (y+i)<DIMENSIONES):
tablero[(x+i)][(y+i)]="*"
if((x-i)>=0 and (y+i)<DIMENSIONES):
tablero[(x-i)][(y+i)]="*"
if((x+i)<DIMENSIONES and (y-i)>=0):
tablero[(x+i)][(y-i)]="*"
if((x-i)>=0 and (y-i)>=0):
tablero[(x-i)][(y-i)]="*"
#Coloca la ficha en la posicion indicaca
tablero[x][y]=letra
#Cuenta cuantas damas hay en el tablero
def contar():
global tablero
counter=0
for x in range(DIMENSIONES):
for y in range(DIMENSIONES):
if(tablero[x][y]!="_" and tablero[x][y]!="*"):
counter=counter+1
return counter
establecer()
simular()
imprimir()
|
d4cfa42d8dcc953856c25b20e828a3d800ba2aa3 | bradstrat/ContinuousAveragelist | /average_via_input.py | 981 | 4.03125 | 4 | from functools import reduce
def programy():
running = True
print("I output the average of a list that you add files to. \nType MENU to access the menu. \n")
listy = []
while running == True:
def listaverage(givenlist):
print(sum(listy) / len(listy))
currentnum = input("Please type a number to add to the list: ")
if currentnum.isdigit():
listy.append(int(currentnum))
listaverage(listy)
else:
if str(currentnum.lower()) == "menu":
running = False
else:
print("Not a number!")
active = True
while active == True:
answer = input("Please type either: EXIT or START\n")
if str(answer.lower()) == "start":
print("Starting... \n")
programy()
if str(answer.lower()) == "exit":
print("Now exiting...")
active = False
else:
print("Not valid answer...\n")
|
5d3211bb98c70a56db6b1ff6ebfd881c488bc219 | CallumTCarter/Python-Code- | /mazeSolver.py | 5,557 | 3.765625 | 4 | # def addTempBlock():
# global tempBlock
# # currentPos[0][1] = position(y,x)
# global currentPos
# y = currentPos[0]
# x = currentPos[1]
# try:
# if (maze[y+1][x] != 1) and (y+1!= height+1):
# possibleDirection +=1
# print 'can move down'
# except: pass
# try:
# if (maze[y-1][x] != 1) and (y-1 != -1):
# possibleDirection +=1
# print 'can move up'
# except: pass
# try:
# if (maze[y][x+1] != 1) and (x+1 != width):
# possibleDirection +=1
# print 'can move right'
# except: pass
# try:
# if (maze[y][x-1] != 1) and (x-1 != -1):
# possibleDirection +=1
# print 'can move left'
# except: pass
#
def direction():
global currentPos
y = currentPos[0]
x = currentPos[1]
try:
if (maze[y+1][x] != 1) and (hasAlreadyBeenVisited([y+1,x]) == False) and (y+1!= height+1):
return 'down'
except:
print 'down is off index'
try:
if (maze[y-1][x] != 1) and (hasAlreadyBeenVisited([y-1,x]) == False) and (y-1 != -1):
return 'up'
except:
print 'up is off index'
try:
if (maze[y][x+1] != 1) and (hasAlreadyBeenVisited([y,x+1]) == False) and (x+1 != width):
return 'right'
except:
print 'right is off index'
try:
if (maze[y][x-1] != 1) and (hasAlreadyBeenVisited([y,x-1]) == False) and (x-1 != -1):
return 'left'
except:
print 'left is off index'
def markLocationAsVisited():
global currentPos
global alreadyVisitedLocations
alreadyVisitedLocations.append(currentPos)
def returnToSavedLocation():
global currentPos
global savedLocations
currentPos = savedLocations[(len(savedLocations)-1)]
del savedLocations[-1]
def move (x):
global currentPos
global previousLocation
previousLocation = currentPos
if (x == 'up'):
currentPos = [(previousLocation[0]-1), (previousLocation[1])]
print 'moved up'
if (x == 'right'):
currentPos = [(previousLocation[0]), (previousLocation[1]+1)]
print 'moved right'
if (x == 'down'):
currentPos = [(previousLocation[0]+1), (previousLocation[1])]
print 'moved down'
if (x == 'left'):
currentPos = [(previousLocation[0]), (previousLocation[1]-1)]
print 'moved left'
return
def lookForIntersection ():
# currentPos[0][1] = position(y,x)
global currentPos
possibleDirection = 0
y = currentPos[0]
x = currentPos[1]
try:
if (maze[y+1][x] != 1) and (hasAlreadyBeenVisited([y+1,x]) == False) and (y+1!= height+1):
possibleDirection +=1
print 'can move down'
except: pass
try:
if (maze[y-1][x] != 1) and (hasAlreadyBeenVisited([y-1,x]) == False) and (y-1 != -1):
possibleDirection +=1
print 'can move up'
except: pass
try:
if (maze[y][x+1] != 1) and (hasAlreadyBeenVisited([y,x+1]) == False) and (x+1 != width):
possibleDirection +=1
print 'can move right'
except: pass
try:
if (maze[y][x-1] != 1) and (hasAlreadyBeenVisited([y,x-1]) == False) and (x-1 != -1):
possibleDirection +=1
print 'can move left'
except: pass
return (possibleDirection)
def hasAlreadyBeenVisited (nextPos):
global previousLocation
global tempBlock
for location in alreadyVisitedLocations:
if location == nextPos:
return True
if nextPos == previousLocation:
return True
for location in tempBlock:
if location == nextPos:
return True
return False
def answer(map):
# x
# --->
# | [0,1,1,0]
# y | [0,0,0,1]
# v [0,1,0,1]
# [1,1,0,0]
# when doing co-ordinates use (y,x)!
global alreadyVisitedLocations
global width
global height
global previousLocation
global currentPos
global savedLocations
global steps
global tempBlock
# Arrays
# -To hold one coord
previousLocation = [0,0]
currentPos = [0,0]
# -To hold a list of coords
savedLocations = []
alreadyVisitedLocations = [[0,0]]
tempBlock = []
# Variables
width = len(map[0])
height = len(map)
steps = 0
print 'while loop starting'
while (currentPos != [height-1,width-1]) or (len(savedLocations) != 0):
print lookForIntersection()
# if your at a dead end
if (lookForIntersection() == 0):
print 'DEAD END!'
print savedLocations
returnToSavedLocation()
del tempBlock[:]
# at an intersection
if (lookForIntersection() > 1):
alreadyVisitedLocations.append(previousLocation)
savedLocations.append(currentPos)
# addTempBlock()
move(direction())
alreadyVisitedLocations.append(currentPos)
print 'SAVING LOCATION'
print savedLocations
print tempBlock
# one way to go
if (lookForIntersection() == 1):
move(direction())
print currentPos
steps+=1
for i in maze:
print i
return(steps)
maze = [[0,0,0,0,0],
[0,1,1,1,1],
[0,1,0,0,0],
[0,0,0,1,0]]
print(answer(maze))
|
777a61fecc4184078a49b8a29c97545315492d35 | raswolf/Python | /module6/more_functions/inner_functions_assignment.py | 707 | 4.5 | 4 | """
Program: inner_functions_assignment.py
Author: Rachael Wolf
Last date modified: 10/03/2020
The purpose of this program is to.
"""
def measurements(m_list):
"""Takes the length and width of a rectangle and describes the perimeter and area
:param m_list, a list containing the side measurements of the rectangle
:returns a string describing the perimeter and area of the specified rectangle"""
def area(a_list):
return float(a_list[0]) * float(a_list[len(a_list) - 1])
def perimeter(a_list):
return (float(a_list[0]) + float(a_list[len(a_list) - 1])) * 2
description = 'Perimeter = ' + str(perimeter(m_list)) + ' Area = ' + str(area(m_list))
return description
|
f9df93cca75e97d2db761e5100ca81b99894e42c | dp1608/python | /LeetCode/1806/180612implement_strstr.py | 1,185 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# @Start_Time : 2018/6/12 16:13
# @End_time:
# @Author : Andy
# @Site :
# @File : 180612implement_strstr.py
"""
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string.
This is consistent to C's strstr() and Java's indexOf().
"""
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == "":
return 0
size = len(needle)
for i in range(len(haystack)):
# j = 0
if haystack[i:size + i] == needle[0:size]:
return i
# while j < size:
# if haystack
return -1
print(Solution().strStr("hello","ll"))
# print("hello"[2:4])
|
396d27598c32e1d62655b7fbfd3c2fd42f3133c6 | sbsdevlec/PythonEx | /Hello/Lecture/Day04/Tuple/06. TupleEx.py | 671 | 4.5625 | 5 | # empty tuple
# Output: ()
my_tuple = ()
print(my_tuple, type(my_tuple))
# tuple having integers
# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
# Output: (1, "Hello", 3.4)
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
# tuple can be created without parentheses
# also called tuple packing
# Output: 3, 4.6, "dog"
my_tuple = 3, 4.6, "dog"
print(my_tuple, type(my_tuple))
# tuple unpacking is also possible
# Output:
# 3
# 4.6
# dog
a, b, c = my_tuple
print(a)
print(b)
print(c) |
f2f3bc568c9e7696c48658432c1ce5ed84e6094e | Kailash-Sankar/learning_python | /day3/ping.py | 695 | 3.671875 | 4 | '''
ping a list of hosts to check status
'''
import os
def clean_hosts(x):
x = x.strip()
print x
if not x.startswith('#'):
return x
return None
fin = open("hosts.txt", "r")
# hosts = map(lambda x: x.rstrip() if not x.lstrip().startswith('#') else pass , fin.readlines())
# hosts = filter(lambda x: x.strip() if not x.lstrip().startswith('#') else None, fin.readlines())
hosts = filter(clean_hosts, fin.readlines())
fin.close()
print hosts
def isdown(host, n=1):
pingstr = "ping {} -n {} >> ping.log"
return os.system(pingstr.format(host, n))
for host in hosts:
if isdown(host):
print host + " is down"
else:
print host + " is up"
|
8d78ec28fd6910f170b11d3e316e8ce609d1f5fa | suzywho/Million-Song-Database | /asn2.py | 6,445 | 4.1875 | 4 | ## CS 2120 Assignment #2 -- Zombie Apocalypse
## Name: Shi (Susan) Hu
## Student number: 250687453
import numpy
import pylab as P
#### This stuff you just have to use, you're not expected to know how it works.
#### You just need to read the plain English function headers.
#### If you want to learn more, by all means follow along (and ask questions if
#### you're curious). But you certainly don't have to.
def make_city(name,neighbours):
"""
Create a city (implemented as a list).
:param name: String containing the city name
:param neighbours: The city's row from an adjacency matrix.
:return: [name, Infection status, List of neighbours]
"""
return [name, False, list(numpy.where(neighbours==1)[0])]
def make_connections(n,density=0.25):
"""
This function will return a random adjacency matrix of size
n x n. You read the matrix like this:
if matrix[2,7] = 1, then cities '2' and '7' are connected.
if matrix[2,7] = 0, then the cities are _not_ connected.
:param n: number of cities
:param density: controls the ratio of 1s to 0s in the matrix
:returns: an n x n adjacency matrix
"""
import networkx
# Generate a random adjacency matrix and use it to build a networkx graph
a=numpy.int32(numpy.triu((numpy.random.random_sample(size=(n,n))<density)))
G=networkx.from_numpy_matrix(a)
# If the network is 'not connected' (i.e., there are isolated nodes)
# generate a new one. Keep doing this until we get a connected one.
# Yes, there are more elegant ways to do this, but I'm demonstrating
# while loops!
while not networkx.is_connected(G):
a=numpy.int32(numpy.triu((numpy.random.random_sample(size=(n,n))<density)))
G=networkx.from_numpy_matrix(a)
# Cities should be connected to themselves.
numpy.fill_diagonal(a,1)
return a + numpy.triu(a,1).T
def set_up_cities(names=['City 0', 'City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6', 'City 7', 'City 8', 'City 9', 'City 10', 'City 11', 'City 12', 'City 13', 'City 14', 'City 15']):
"""
Set up a collection of cities (world) for our simulator.
Each city is a 3 element list, and our world will be a list of cities.
:param names: A list with the names of the cities in the world.
:return: a list of cities
"""
# Make an adjacency matrix describing how all the cities are connected.
con = make_connections(len(names))
# Add each city to the list
city_list = []
for n in enumerate(names):
city_list += [ make_city(n[1],con[n[0]]) ]
return city_list
def draw_world(world):
"""
Given a list of cities, produces a nice graph visualization. Infected
cities are drawn as red nodes, clean cities as blue. Edges are drawn
between neighbouring cities.
:param world: a list of cities
"""
import networkx
import matplotlib.pyplot as plt
G = networkx.Graph()
bluelist=[]
redlist=[]
plt.clf()
# For each city, add a node to the graph and figure out if
# the node should be red (infected) or blue (not infected)
for city in enumerate(world):
if city[1][1] == False:
G.add_node(city[0])
bluelist.append(city[0])
else:
G.add_node(city[0],node_color='r')
redlist.append(city[0])
for neighbour in city[1][2]:
G.add_edge(city[0],neighbour)
# Lay out the nodes of the graph
position = networkx.circular_layout(G)
# Draw the nodes
networkx.draw_networkx_nodes(G,position,nodelist=bluelist, node_color="b")
networkx.draw_networkx_nodes(G,position,nodelist=redlist, node_color="r")
# Draw the edges and labels
networkx.draw_networkx_edges(G,position)
networkx.draw_networkx_labels(G,position)
# Force Python to display the updated graph
plt.show()
plt.draw()
def print_world(world):
"""
In case the graphics don't work for you, this function will print
out the current state of the world as text.
:param world: a list of cities
"""
import string
print string.ljust('City',15), 'Zombies?'
print '------------------------'
for city in world:
print string.ljust(city[0],15), city[1]
#### That's the end of the stuff provided for you.
#### Put *your* code after this comment.
#Zombify the chosen city in the list of cities
def zombify(cities,cityno):
#Set the infected property to True
cities[cityno][1] = True
#Cure the chosen city in the list of cities
def cure(cities,cityno):
#Make sure that the zeroth city is not cured
if (cityno != 0):
#Set the infected property to True
cities[cityno][1] = False
#Do one simulation of the zombie plague based on the values of p_spread and p_cure
def sim_step(cities,p_spread,p_cure):
#counter to keep track of the index of the city
counter = 0;
#Iterate through every city in the list of cities
for city in cities:
#If the city is infected , infect one of its neighbour
if city[1] and numpy.random.rand() < p_spread:
no_of_neighbours = len(city[2])
#Generate random index based on the length of the neighbour
random_city = city[2][numpy.random.randint(0, no_of_neighbours)]
#Zombify the random city
zombify(cities,random_city)
#If the city is infected , attemp to cure it
if city[1] and numpy.random.rand() < p_cure:
#Cure the current city
cure(cities,counter)
counter += 1
#Function to check whether it is the end of the world
def is_end_of_world(cities):
#Iterate through every city in the list of cities
for city in cities:
if not(city[1]):
#Return False if the city is not infected
return False
#Return true if the loop didnt find any cured cities
return True
#Function that counts how many steps it takes to reach the end of the world
def time_to_end_of_world(p_spread,p_cure):
#Sets up city
world = set_up_cities()
#Infect world 0 since it is always infected
zombify(world,0)
#Counter to keep track of the number of days it takes
day_counter = 0
#Simulate another step and count the days while its not the end of the world
while not(is_end_of_world(world)):
sim_step(world, p_spread, p_cure)
day_counter += 1
return day_counter
#Execute time_to_end_of_world n times
def end_world_many_times(n,p_spread,p_cure):
times_to_the_end_of_the_world = []
for x in range(0, n):
#Appends the number of days to a list to be returned
times_to_the_end_of_the_world.append(time_to_end_of_world(p_spread,p_cure))
print x
return times_to_the_end_of_the_world
#Graphing code
ttl = end_world_many_times(500, 1, 0)
P.hist(ttl)
P.ylabel("Number Per Bin")
P.xlabel("Number of Days")
P.show()
|
60edb9e2614232e5fc35fa876e47af3e5e1c49f7 | tehs0ap/Project-Euler-Python | /Solutions/Problems_20-29/Problem_29.py | 813 | 3.796875 | 4 | '''
Created on 2012-12-26
@author: Marty
'''
'''
Consider all integer combinations of a**b for 2 <= a => 5 and 2 <= b => 5:
2**2=4, 2**3=8, 2**4=16, 2**5=32
3**2=9, 3**3=27, 3**4=81, 3**5=243
4**2=16, 4**3=64, 4**4=256, 4**5=1024
5**2=25, 5**3=125, 5**4=625, 5**5=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by a**b for 2 <= a => 100 and 2 <= b >= 100?
'''
import time
startTime = time.time()
distinctTerms = set()
for a in range(2,101):
for b in range(2,101):
distinctTerms.add(a**b)
print len(distinctTerms)
print "Time Elapsed: " + str(time.time() - startTime)
|
7dca0bcc61a7eff04a45a22e9dae87afc02972a3 | karolinaewagorska/lesson2 | /str.py | 1,095 | 4.125 | 4 | # Вывести последнюю букву в слове
word = 'Архангельск'
print(word[-1:])
# Вывести количество букв а в слове
word = 'Архангельск'
print(len(word))
# Вывести количество гласных букв в слове
word = 'Архангельск'
vowels_sum = 0
for letter in word:
if letter in "а, А, е":
vowels_sum = vowels_sum + 1
print("vowels_sum =", vowels_sum)
# Вывести количество слов в предложении
sentence = 'Мы приехали в гости'
words = sentence.split()
print(len(words))
# Вывести первую букву каждого слова на отдельной строке
sentence = 'Мы приехали в гости'
words = sentence.split()
letters = [word[0] for word in words]
print("".join(letters))
# Вывести усреднённую длину слова.
sentence = 'Мы приехали в гости'
words = sentence.split()
average = sum(len(word) for word in words) / len(words)
print(average) |
5d9548eb01f4c012e96ff9fb68bbe9738a00aadd | einorjohn/Pycharm | /Lec 10 Ex. 1.py | 460 | 3.609375 | 4 | fname = input('Enter file name: ')
try:
fhandle = open(fname)
except:
print('File cannot be opened:', fname)
exit()
emails = dict()
for line in fhandle:
if line.startswith('From '):
line = line.split()
email = line[1]
emails[email] = emails.get(email,0) + 1
emailslist = []
for email, count in emails.items():
emailslist.append( (count, email) )
emailslist.sort(reverse=True)
for count, email in emailslist[:1]:
print(email, count) |
363d4f9d7f6a17bbab322c10fcb0db8bf8c5642d | generationzcode/question-13 | /main.py | 244 | 3.65625 | 4 | Registered = input("Are you registered with us?")
if Registered == "Y":
username = input("user:")
password = input("pass:")
elif Registered == "N":
print("go to the registration page")
else:
print("please try again. Input Y/N")
|
edc5bb48d56e8c065d92cb8473a4426267aa8e13 | JoseVictorHendz/estudo-de-inteligencia-artificial | /aula3/terceiroNeoronio.py | 1,148 | 3.921875 | 4 | def calculoDeSaida(soma):
saida = 0
if (tipoCalculo == 1):
if (soma < 0):
saida = 0
elif (soma >= 0 & soma <= 1):
saida = soma
elif (soma > 1):
saida = 1
elif (tipoCalculo == 2):
if (soma <= 0):
saida = -1
elif (soma > 0):
saida = 1
elif (tipoCalculo == 3):
if (soma >= 0):
saida = 1 - 1 / (1 + soma)
elif (soma < 0):
saida = -1 + 1 / (1 - soma)
return saida
peso1 = -2
peso2 = 2
peso3 = 2
peso4 = -1
peso5 = 1
peso6 = 1
saida = 0
continua =1
while continua == 1:
entrada1 = int(input("Digite a primeira entra: "))
entrada2 = int(input("Digite a segunda entrada: "))
tipoCalculo = int(input('Digite qual calculo: 1-fr 2-lr 3-fs '))
soma1 = (entrada1 * peso1) + (entrada2 * peso2)
saida1 = calculoDeSaida(soma1)
soma2 = (entrada1 * peso3) + (entrada2 * peso4)
saida2 = calculoDeSaida(soma2)
soma3 = (saida1 * peso5) + (saida2 * peso6)
print(calculoDeSaida(soma3))
continua = int(input("Continuar? 0 para sair 1 - para continuar"))
|
3e1fce5c0ff0bf5de817f9a58e5e98a3c0262d2b | ephillips408/cribbage_repo | /declarations.py | 2,110 | 3.609375 | 4 | import random
import scoring as score
values = {
"Ace": 1,
"Two": 2,
"Three": 3,
"Four": 4,
"Five": 5,
"Six": 6,
"Seven": 7,
"Eight": 8,
"Nine": 9,
"Ten": 10,
"Jack": 10,
"Queen": 10,
"King": 10,
}
straight_ranks = {
"Ace": 1,
"Two": 2,
"Three": 3,
"Four": 4,
"Five": 5,
"Six": 6,
"Seven": 7,
"Eight": 8,
"Nine": 9,
"Ten": 10,
"Jack": 11,
"Queen": 12,
"King": 13,
}
suits = ("H", "D", "S", "C")
ranks = ( "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
self.value = values[rank]
self.straight_rank = straight_ranks[rank]
def __str__(self):
return f"{self.rank}:{self.suit}"
class Deck:
def __init__(self):
self.all_cards = []
for suit in suits:
for rank in ranks:
created_card = Card(suit, rank)
self.all_cards.append(created_card)
def shuffle(self):
random.shuffle(self.all_cards)
def deal_one(self):
return self.all_cards.pop()
class Player:
def __init__(self):
self.hand = []
self.is_dealer = None
self.score = 0
def discard_two(self, list, indices):
# Fix the issue when a user inputs a higher number before a lower number.
if indices[0] > indices[-1]:
for entry in indices:
del list[entry]
else:
rev_indices = indices[::-1] #Reversed to allow for accurately deleting list elements.
for entry in rev_indices:
del list[entry]
def find_score(list_one, list_two, list_three):
#list_one will represent the value list, list two will represent the straight rank list, and list three is the suit list.
points = score.find_fifteens(list_one) + score.find_matches(list_two) + score.find_straights(list_two) + score.find_flush(list_three)
return points
|
f8882e85f00f79b59cc2d563da472cd423320fc6 | sp33daemon/design_patterns | /python/iterator.py | 304 | 4.125 | 4 | def month_name(number):
list_of_month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
iterator = zip(range(number),list_of_month)
for position, monthname in iterator:
yield monthname
val = month_name(4)
print(type(val))
for month in val:
print("{}".format(month))
|
2e0d27b414109d56736df8df10dcd69b6e6ba981 | cuibjut/binary_tree | /binary_tree_traversal.py | 2,220 | 4.21875 | 4 | #!coding=UTF_8
"""
参考:http://www.cnblogs.com/freeman818/p/7252041.html
"""
class Node:
"""
如何表达一棵树:
使用一个类的__init__()方法,方法中含有3个参数,分别是value, left, right, 并为其赋初识值
"""
def __init__(self, value=None, left=None, right=None):
self.value = value
self.left = left
self.right = right
def pre_traverse(root):
"""
前序遍历二叉树
:param root: root为一颗二叉树
:return:
"""
if not root: # 首先要判断边界条件
return
print(root.value, end=" ")
pre_traverse(root.left)
pre_traverse(root.right)
def mid_traverse(root):
"""
中序遍历二叉树
:param root: root为一颗二叉树
:return:
"""
if not root:
return
mid_traverse(root.left)
print(root.value, end=" ")
mid_traverse(root.right)
def after_traverse(root):
"""
后序遍历二叉树
:param root: root为一颗二叉树
:return:
"""
if not root:
return
after_traverse(root.left)
after_traverse(root.right)
print(root.value, end=" ")
def traverse(root):
"""
二叉树的层次遍历
:param root:
:return: 返回一颗按层次遍历的二叉树
"""
# 基本上都是用两个list来实现的,一个是用来存储值,一个是用来存储指针的
if not root:
return
q = [root]
result = [root.value]
while len(q) != 0:
pop_node = q.pop(0)
if pop_node.left is not None:
q.append(pop_node.left)
result.append(pop_node.left.value)
if pop_node.right is not None:
q.append(pop_node.right)
result.append(pop_node.right.value)
return result
if __name__ == "__main__":
root = Node('D', Node('B', Node('A'), Node('C')), Node('E', right=Node('G', Node('F'))))
print("前序遍历:")
pre_traverse(root)
print("\n---------------------\n")
print("中序遍历:")
mid_traverse(root)
print("\n---------------------\n")
print("后序遍历:")
after_traverse(root)
traverse(root)
print("层次遍历:", traverse(root))
|
5b8f2c835b193f3dd0fbbd3d7abdfb693a70ee2d | pron1n/HH | /task_2.py | 240 | 3.65625 | 4 | def strToList(n):
list = []
for i in n:
list.append(i)
return(list)
for i in range(10, 10000):
x5 = strToList(str(i * 5))
x5.sort()
x6 = strToList(str(i * 6))
x6.sort()
if x5 == x6:
print(i) |
f0d3e5fab08eea30ef57af8b37848642cf05c47a | benfred/py-spy | /tests/scripts/recursive.py | 93 | 3.625 | 4 | def recurse(x):
if x == 0:
return
recurse(x-1)
while True:
recurse(20)
|
4175702418560f8aee1f2c04bd740e068e21bc0f | screechingghost/Calculator-1.0 | /Calculator-1.0.py | 1,314 | 4.1875 | 4 | print("Hello")
print("welcome to calculator-1.0")
start=input("PRESS 'R' TO ACTIVATE OR PRESS ANY KEY TO CLOSE- CALCULATO")
try:
if start=="R" or start=="r" :
import math
print("mode of calculation:")
print("+~Add")
print("-~Subtract")
print("x~Multiply")
print("/~Divide")
print("s~Square root")
l='y'
while l=="y" or l=="Y":
option=input("please enter your mode of calculation (+|-|x|/|s): ")
if option=="s":
num=float(input("enter number="))
elif option=="+" or option=="-" or option=="x" or option=="X" or option=="/" :
num1=float(input("enter first number="))
num2=float(input("enter second number="))
else:
print('Invalid input please choose from above options')
if option=="+":
print(num1,"+",num2,"=",num1+num2)
elif option=="-":
print(num1,"-",num2,"=", num1-num2)
elif option=="x":
print(num1,"x",num2,"=",num1*num2)
elif option=="/":
print(num1,"/",num2,"=",num1/num2)
elif option=="s" or option=="S":
print(num,"square root is",math.sqrt(num))
l=input("Do you have more calculation- y,n:")
if l=="n" or l=="N":
print("Thanks For Using calculator")
else:
print("thanks for using calculator ")
except:
print("Invalid Entry")
|
c9fb18b668e8de811e9c8a7841ed394d47bfd8e9 | xiaojinghu/Leetcode | /Leetcode0090_Backtrack.py | 742 | 3.75 | 4 | class Solution(object):
def backtracking(self, nums, i, path, res):
res.append(path)
# for each number in nums[i:], we choose one to add into our path
# we need to avoid duplicate in this situation
for j in range(i, len(nums)):
if j == i or nums[j]!=nums[j-1]:
#this means nums[j] is the first unique one behind i
self.backtracking(nums,j+1,path+[nums[j]], res )
return
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res = []
path = []
self.backtracking(nums, 0, path, res)
return res
|
53c13339f8c20e1d15c12fc617d35aa39904b225 | peterjpierce/project_euler | /solutions/010.py | 534 | 3.671875 | 4 | """
Problem 10
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
from shared import util
def run():
start_time = util.now()
total, count = 0, 0
maximum = 2000000
for prime in util.primes(maximum, verbose=True):
count += 1
total += prime
answer = {'sum': total, 'count': count}
print('answer is: %s' % str(answer))
print('elapsed seconds: %f' % (util.now() - start_time).total_seconds())
if __name__ == '__main__':
run()
|
284a0900bc95b98dc107c1e714be92967779bd43 | jngmk/Training | /Python/Programmers/[2019카카오공채] 징검다리 건너기/solution2.py | 640 | 3.5625 | 4 | # 통과
def check(stones, num, k):
impossible = 0
for stone in stones:
if stone < num:
impossible += 1
else:
impossible = 0
if impossible >= k:
return False
return True
def solution(stones, k):
answer = 1
left = 1
right = max(stones) + 1
while left < right:
mid = (left + right) // 2
if check(stones, mid, k):
answer = mid
left = mid + 1
else:
right = mid
return answer
dataset = [
[[2, 4, 5, 3, 2, 1, 4, 2, 5, 1], 3]
]
for stones, k in dataset:
print(solution(stones, k)) |
d79aa165cf588cf944c9629999f1423d272e3640 | camohe90/mision_tic_G6 | /s14/13.10_ejercicio2.py | 448 | 3.8125 | 4 | """Escribir un programa que permita al usuario ingresar dos años y
luego imprima todos los años en ese rango, que sean bisiestos y
múltiplos de 10"""
anio1 = int(input("Ingrese el primer año que desea validar"))
anio2 = int(input("Ingrese el segundo año que desea validar"))
for anio in range(anio1,anio2):
if(anio % 4 == 0 and (anio % 100 != 0 or anio % 400 == 0)) and anio % 10 == 0:
print(f"{anio} es bisiesto")
|
1fa0d38cc1b2618e766308333a3bf4bd2eaf67c0 | EverettBerry/ie336 | /hw1/stocksimulation.py | 435 | 3.90625 | 4 | import matplotlib.pyplot as plt
import random
def binomial_model():
up = 500
price = 1
stock = []
for x in range(1000):
if random.random() < up / 1000:
price = price * 1.02
up -= 1
else:
price = price / 1.02
up += 1
stock.append(price)
plt.plot(stock)
plt.ylabel('Stock price')
plt.xlabel('Days')
plt.show()
binomial_model()
|
9a9d2d0727521adfe19c206327327c1dda8f6fba | YeasirArafatRatul/Python | /SortingAlgorithms/InsertionSort.py | 1,359 | 4.375 | 4 | #insertion sort
def insertion_sort(a_list):
n = len(a_list)
for i in range(1,n):
#assign the vlaue of a_list[i] in the variable item
item = a_list[i]
j = i-1
while j >= 0 and a_list[j] > item:
a_list[j+1] = a_list[j]
j = j-1
a_list[j+1] = item
if __name__ == "__main__":
L = [2,4,1,5,6]
print("before sorting",L)
insertion_sort(L)
print("after_sorting",L)
"""
for i = 1 item = 4
then j= i-1
=1-1
=0
aList[0] = 2 is not greater than item = 4
(so the program will not enter in while loop)
for i = 2 item = 1
then j= i-1
=2-1
=1
aList[1] = 4 is greater than item = 1
(so the program will enter in the while loop)
alist[1+1=2] = alist[1]
= 4
then j = j-1
=1-1
=0
alist[j+1/0+1=1] = item which is 1 (swapped the value)
list after this step = [2,1,4,5,6]
now,
j = 0 so
a_list[0] = 2 and item = 1
so, a_list[j] is less than item
so it will again enter in the while loop and swap the value
after this iteration the list is = [1,2,4,5,6]
"""
"""
complexity of insertion sort is O(n^2)
if the list is sorted first then it is O(n) cz it will execute the for loop
"""
|
d75a05dfd428b9b8dc19dbe88e5dbe7b5d6071e1 | lungen/algorithms | /chapter-4/423-01-reverseString.py | 226 | 4.15625 | 4 | # a function that takes a string and returns a reverse
def revString(s):
s = str(s)
if len(s) == 1: #BASE CASE
return s[0]
else:
return s[-1] + revString(s[:-1])
print(revString('salami'))
|
47457fca82689454308e6644e7a489a80718dd9c | AnthonyDeFallo/F19352 | /ADMDProg1.py | 532 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def bSort(listT) :
for cnt in range (0, len(listT) - 1):
for cnt2 in range(0, len(listT) - 1 - cnt):
if listT[cnt2] > listT[cnt2+1]:
listT[cnt2], listT[cnt2+1] = listT[cnt2+1], listT[cnt2]
return listT
listT = []
i = int(input("Enter the length of the list: "))
for j in range(0, i):
eInt = int(input())
listT.append(eInt)
print (bSort(listT))
print (bSort(listT)[::-1]) |
05c542b502d90a2bafc5134b273ae1dadbdbf877 | MHakem/Axelrod | /axelrod/strategies/axelrod_second.py | 6,186 | 3.703125 | 4 | """
Additional strategies from Axelrod's second tournament.
"""
import random
from axelrod.action import Action
from axelrod.player import Player
from axelrod.random_ import random_choice
C, D = Action.C, Action.D
class Champion(Player):
"""
Strategy submitted to Axelrod's second tournament by Danny Champion.
This player cooperates on the first 10 moves and plays Tit for Tat for the
next 15 more moves. After 25 moves, the program cooperates unless all the
following are true: the other player defected on the previous move, the
other player cooperated less than 60% and the random number between 0 and 1
is greater that the other player's cooperation rate.
Names:
- Champion: [Axelrod1980b]_
"""
name = "Champion"
classifier = {
'memory_depth': float('inf'),
'stochastic': True,
'makes_use_of': set(["length"]),
'long_run_time': False,
'inspects_source': False,
'manipulates_source': False,
'manipulates_state': False
}
def strategy(self, opponent: Player) -> Action:
current_round = len(self.history)
expected_length = self.match_attributes['length']
# Cooperate for the first 1/20-th of the game
if current_round == 0:
return C
if current_round < expected_length / 20:
return C
# Mirror partner for the next phase
if current_round < expected_length * 5 / 40:
return opponent.history[-1]
# Now cooperate unless all of the necessary conditions are true
defection_prop = opponent.defections / len(opponent.history)
if opponent.history[-1] == D:
r = random.random()
if defection_prop >= max(0.4, r):
return D
return C
class Eatherley(Player):
"""
Strategy submitted to Axelrod's second tournament by Graham Eatherley.
A player that keeps track of how many times in the game the other player
defected. After the other player defects, it defects with a probability
equal to the ratio of the other's total defections to the total moves to
that point.
Names:
- Eatherley: [Axelrod1980b]_
"""
name = "Eatherley"
classifier = {
'memory_depth': float('inf'),
'stochastic': True,
'makes_use_of': set(),
'long_run_time': False,
'inspects_source': False,
'manipulates_source': False,
'manipulates_state': False
}
@staticmethod
def strategy(opponent: Player) -> Action:
# Cooperate on the first move
if not len(opponent.history):
return C
# Reciprocate cooperation
if opponent.history[-1] == C:
return C
# Respond to defections with probability equal to opponent's total
# proportion of defections
defection_prop = opponent.defections / len(opponent.history)
return random_choice(1 - defection_prop)
class Tester(Player):
"""
Submitted to Axelrod's second tournament by David Gladstein.
This strategy is a TFT variant that attempts to exploit certain strategies. It
defects on the first move. If the opponent ever defects, TESTER 'apologies' by
cooperating and then plays TFT for the rest of the game. Otherwise TESTER
alternates cooperation and defection.
This strategy came 46th in Axelrod's second tournament.
Names:
- Tester: [Axelrod1980b]_
"""
name = "Tester"
classifier = {
'memory_depth': float('inf'),
'stochastic': False,
'makes_use_of': set(),
'long_run_time': False,
'inspects_source': False,
'manipulates_source': False,
'manipulates_state': False
}
def __init__(self) -> None:
super().__init__()
self.is_TFT = False
def strategy(self, opponent: Player) -> Action:
# Defect on the first move
if not opponent.history:
return D
# Am I TFT?
if self.is_TFT:
return D if opponent.history[-1:] == [D] else C
else:
# Did opponent defect?
if opponent.history[-1] == D:
self.is_TFT = True
return C
if len(self.history) in [1, 2]:
return C
# Alternate C and D
return self.history[-1].flip()
class Gladstein(Player):
"""
Submitted to Axelrod's second tournament by David Gladstein.
This strategy is also known as Tester and is based on the reverse
engineering of the Fortran strategies from Axelrod's second tournament.
This strategy is a TFT variant that defects on the first round in order to
test the opponent's response. If the opponent ever defects, the strategy
'apologizes' by cooperating and then plays TFT for the rest of the game.
Otherwise, it defects as much as possible subject to the constraint that
the ratio of its defections to moves remains under 0.5, not counting the
first defection.
Names:
- Gladstein: [Axelrod1980b]_
- Tester: [Axelrod1980b]_
"""
name = "Gladstein"
classifier = {
'memory_depth': float('inf'),
'stochastic': False,
'makes_use_of': set(),
'long_run_time': False,
'inspects_source': False,
'manipulates_source': False,
'manipulates_state': False
}
def __init__(self) -> None:
super().__init__()
# This strategy assumes the opponent is a patsy
self.patsy = True
def strategy(self, opponent: Player) -> Action:
# Defect on the first move
if not self.history:
return D
# Is the opponent a patsy?
if self.patsy:
# If the opponent defects, apologize and play TFT.
if opponent.history[-1] == D:
self.patsy = False
return C
# Cooperate as long as the cooperation ratio is below 0.5
cooperation_ratio = self.cooperations / len(self.history)
if cooperation_ratio > 0.5:
return D
return C
else:
# Play TFT
return opponent.history[-1]
|
4b2399b5af397bf62a13cf3458e6bc5432566a89 | lucNovais/Caminho-Minimo---Grafos | /teste.py | 105 | 3.5 | 4 | q = [1, 2, 3, 4]
e = [0, 3, 5, 2]
for i in q:
print(i)
q.remove(3)
print()
for i in q:
print(i) |
c8c8f7b9d127d2762ccddabf54e7e6b917ffb167 | agalyaswami/infytq-python | /circle color.py | 331 | 3.734375 | 4 | alex.color("green") # alex has a color
alex.right(60) # alex turns 60 degrees right
alex.left(60) # alex turns 60 degrees left
color = ["green", "blue", "red"]
for i in range(0,3):
alex.color(color[i])
for counter in range(1,5):
alex.circle(20*counter)
alex.right(120)
alex.left(0)
|
ad50ab5335c7ecc42e9a71c0141a96df6ab21689 | cseshahriar/The-python-mega-course-practice-repo | /function_and_condition/func.py | 1,005 | 3.96875 | 4 | """ functions """
def mean(value):
"""
isinstance(object, type)
The isinstance() function returns True if the specified object is of
the specified type, otherwise False
"""
if isinstance(value == dict):
the_mean = sum(value.values()) / len(value)
else:
the_mean = sum(value) / len(value)
return the_mean
my_list = [1, 2, 3, 4, 5, 6]
print(mean(my_list))
""" print or none """
# by default return none
def mean_another(my_list):
the_mean = sum(my_list) + len(my_list)
# print(the_mean) # wrong
return the_mean
mymean = mean_another([0, 3, 4])
print(mymean + 10) # unsupported operand type(s) for +: 'NoneType' and 'int'
# always use return for function, not print
""" use of white spaces """
if 3 > 1: # wrong
print('a')
print('aa')
print('aaa')
if 3>1: # worng
print('b')
print('bb')
print('bbb')
# correct
if 3 > 1:
print('c')
# break line for if S
print('cc')
print('ccc')
# break line
def foo():
pass |
8359b4b2795185252a9f18dc0276fc46f78d1f52 | Mohammad-Nobaveh/count-votes | /count-votes-2.py | 598 | 3.75 | 4 | #importing library collections for counting items
import collections
#creat a list to save inputs(candidates)
list1=[]
votes=int(input())
#bring iterable for set range
for i in range(0,votes):
candidates=input()
#add input items to list1
list1.append(candidates)
#sort list of strings
list1.sort()
#use counter from collections library
list2=collections.Counter(list1)
#turn list2 to dictionary
d=dict(list2)
#use below code to control all items in dictionary
for key in d:
#use below code to print keys and values in each lines
print(key,d[key])
|
495f25772b7196ba065ee32306b0f2f95edb6ad1 | filbertlai/Image-Processing | /image_processing.py | 31,257 | 3.546875 | 4 | import subprocess
import sys
import os
subprocess.check_call([sys.executable, "-m", "pip", "install", 'PySimpleGUI'])
subprocess.check_call([sys.executable, "-m", "pip", "install", 'Pillow'])
subprocess.check_call([sys.executable, "-m", "pip", "install", 'opencv-python'])
import PySimpleGUI as sg
from PIL import Image
import cv2
'''
This function will split a larger image into serveral smaller equal-sized images.
This function is fully coded by myself using basic functions provided by PIL module, such as crop and paste.
There are three input parameter:
1. image path: it is a string that contains the path of the image stored.
2. horizontal_number: it is an integer that represents the number of splitting on the horizontal side. (e.g. 2 means splitting the image into left and right)
3. vertical_number: it is an integer that represents the number of splitting on the vertical side. (e.g. 2 means splitting the image into up and down)
The output will be the smaller images saved on the local storage.
Note that this function is different from other functions, this function will not open the processed images after processing since the number of images processed may be large.
'''
def split_image(image_path, horizontal_number, vertical_number):
# Updating status widget
status_widget("Status: Splitting image")
# Open the larger image that stored in the image path
larger_image=Image.open(image_path)
# Print the number of pixels on horizontal side and vertical side respectively
print("Size of larger image:", larger_image.size[0], "x", larger_image.size[1])
# Determine the number of pixels on horizontal side of smaller image
# It can only be an integer so floor division is used
horizontal_length=larger_image.size[0]//horizontal_number
print("Horizontal length of smaller image:", horizontal_length)
# Determine the number of pixels on vertical side of smaller image
# It can only be an integer so floor division is used
vertical_length=larger_image.size[1]//vertical_number
print("Vertical length of smaller image:", vertical_length)
# The horizontal position to crop the larger image which is the position of 'left edge'
horizontal_position=0
# The vertical position to crop the larger image which is the position of 'top edge'
vertical_position=0
# The order to crop the larger image (let the image be 2 pixels x 2 pixels):
# 1 2
# 3 4
for i in range(vertical_number):
for o in range(horizontal_number):
# loop counter that start from 1
counter=i*horizontal_number+o+1
print('\nLooping',counter,'/',vertical_number*horizontal_number,':')
# Create smaller image so that part of larger image can be pasted into it
# Size of smaller image: horizontal_length x vertical_length
# Color space: RGB
# Color: White (250, 250, 250)
smaller_image=Image.new('RGB', (horizontal_length, vertical_length), (250,250,250))
# Cropping the image with the position of 'left edge', 'top edge', 'right edge', 'bottom edge'
print('Cropping larger image at position:',(horizontal_position, vertical_position, horizontal_position + horizontal_length, vertical_position + vertical_length),"(left, top, right, bottom)")
cropped_image=larger_image.crop((horizontal_position, vertical_position, horizontal_position + horizontal_length, vertical_position + vertical_length))
# Paste the cropped image onto the smaller image created at position (0,0) (fully cover the smaller image)
smaller_image.paste(cropped_image,(0,0))
# Save the smaller image as jpg
smaller_image.save('cropped image '+str(counter)+'.jpg',"JPEG")
# Update the progress bar
progress_widget( int( counter/(vertical_number*horizontal_number)*10000 ) )
# Update horizontal position to crop the next image in the same row
horizontal_position+=horizontal_length
# Update vertical position to crop the next row
vertical_position+=vertical_length
# Update hoizontal position to crop the leftest image in the next row
horizontal_position=0
# End of splitting images
print('\nImage splitted successfully at path', os.getcwd())
# Initialize the progress bar to zero
progress_widget(0)
# Update the status widget
status_widget(str(vertical_number*horizontal_number)+' images saved at path: '+os.getcwd())
return
'''
This function will cartooning an image.
This function is referenced from the url: https://www.geeksforgeeks.org/cartooning-an-image-using-opencv-python/
Changes of code:
1. Usability: the code from url allows fixed path of image only while this program allows selection of path of image with graphical user interface.
2. Customization: the code from url has fixed setting of processing while this program allows customized setting, such as the level of image smoothing.
3. Speed: many unused lines are removed to enhance speed, such as image resizing.
4. Comment: many comment lines are added for explaination.
5. Reactivity: progress bar and status widget are provided to report the progress.
There are four input parameters:
1. image path: it is a string that contains the path of the image stored.
2. numDownSamples: it is an integer that determines the number of downsampling to process using Guassian pyramid.
3. numBilateralFilters: it is an integer that determines the number of bilateral filter to apply.
4. thickness: it is an integer that determines the number of nearest neighbour pixels used in adaptive threshold.
The output will be the cartoon version of image saved on the local storage.
'''
def cartooning_image(image_path, numDownSamples, numBilateralFilters, thickness):
# Updating status widget
status_widget('Start cartooning image')
# Initialized as zero to used for updating progress bar
current_progress=0
# Used for updating progress bar, it is the number of processing steps
total_progress=numDownSamples*2+numBilateralFilters+7
print('\nReading image that stored in the image path')
img_rgb = cv2.imread(image_path)
print('Duplicating image for later processing')
img_color = img_rgb
# Downsampling image for faster processing speed
# More downsampling will lead to lower quality
# Default number of downsampling is 1
for i in range(numDownSamples):
print('Downsampling image using Gaussian pyramid',i+1,'/',numDownSamples)
img_color = cv2.pyrDown(img_color)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Applying bilateral filter to smoothing image
# Bilateral filter replaces the intensity of each pixel with a weighted average of intensity values from nearby pixels
# Default number of applying is 50.
for i in range(numBilateralFilters):
print('Applying bilateral filter to reduce noise',i+1,'/',numBilateralFilters)
img_color = cv2.bilateralFilter(img_color, 9, 9, 7)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Upsampling image to restore it
# Number of upscaling = number of downscaling
for i in range(numDownSamples):
print('Upsampling image to the original size',i+1,'/',numDownSamples)
img_color = cv2.pyrUp(img_color)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Convert the image to grayscale so that the edges can be detected later
print('Converting image to grayscale to enhancing edges')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
print('Applying median blur to make the edges sharper')
img_blur = cv2.medianBlur(img_gray, 3)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
print('Applying adaptiveThreshold to detect and enhance edges')
# Adaptive threshold using 'thickness' nearest neighbour pixels
# Default setting of 'thickness' is 4
# The number can only be odd number and larger than 1
thickness=2*thickness+1 # Make the number be odd and larger than 1
img_edge = cv2.adaptiveThreshold(img_blur, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, thickness, 2)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
print('Obtaining the shape detail of the colored image')
# x, y, z are the number of rows, columns, and channels
(x,y,z) = img_color.shape
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
print('Resizing the edged image to fit the shape of colored image')
img_edge = cv2.resize(img_edge,(y,x))
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
print("Converting the image from grayscale to color so that it can be bit-ANDed with colored image")
img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
print("Merging the edged image and colored image to form the cartoon version of image")
res=cv2.bitwise_and(img_color, img_edge) # bit-ANDed two images
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Saving the cartoon version of the image with the filename 'Cartoon version.jpg'
cv2.imwrite("Cartoon version.jpg", res)
# Showing the cartoon version of the image for viewing
cv2.imshow("Cartoon version", res)
# Update the status widget
status_widget('Image cartooned successfully saved at path: '+os.getcwd())
# Initialize the progress bar to zero
progress_widget(0)
# Make the showing of image not disappeared immediately
cv2.waitKey(0)
cv2.destroyAllWindows()
return
'''
This function will draw the edges of an image.
This function is referenced from the url: https://www.geeksforgeeks.org/cartooning-an-image-using-opencv-python/ (the same link as above)
Changes of code:
1. Usability: the code from url allows fixed path of image only while this program allows selection of path of image with graphical user interface.
2. Customization: the code from url has fixed setting of processing while this program allows customized setting, such as the level of image smoothing.
3. Speed: many unused lines are removed to enhance speed, such as image resizing.
4. Comment: many comment lines are added for explaination.
5. Reactivity: progress bar and status widget are provided to report the progress.
There are four input parameters:
1. image path: it is a string that contains the path of the image stored.
2. numDownSamples: it is an integer that determines the number of downsampling to process using Guassian pyramid.
3. numBilateralFilters: it is an integer that determines the number of bilateral filter to apply.
4. thickness: it is an integer that determines the number of nearest neighbour pixels used in adaptive threshold.
The output will be the edges version of the image saved on the local storage.
'''
def edging_image(image_path, numDownSamples, numBilateralFilters, thickness):
# Updating status widget
status_widget('Start edging image')
# Initialized as zero to used for updating progress bar
current_progress=0
# Used for updating progress bar, it is the number of processing steps
total_progress=numDownSamples*2+numBilateralFilters+3
print('\nReading image that stored in the image path')
img_rgb = cv2.imread(image_path)
# Downsampling image for faster processing speed
# More downsampling will lead to lower quality
# Default number of downsampling is 1
for i in range(numDownSamples):
print('Downsampling image using Gaussian pyramid',i+1,'/',numDownSamples)
img_rgb = cv2.pyrDown(img_rgb)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Applying bilateral filter to smoothing image
# Bilateral filter replaces the intensity of each pixel with a weighted average of intensity values from nearby pixels
# Default number of applying is 50.
for i in range(numBilateralFilters):
print('Applying bilateral filter to reduce noise',i+1,'/',numBilateralFilters)
img_rgb = cv2.bilateralFilter(img_rgb, 9, 9, 7)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Upsampling image to restore it
# Number of upscaling = number of downscaling
for i in range(numDownSamples):
print('Upsampling image to the original size',i+1,'/',numDownSamples)
img_rgb = cv2.pyrUp(img_rgb)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Convert the image to grayscale so that the edges can be detected later
print('Converting image to grayscale to enhancing edges')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
print('Applying median blur to make the edges sharper')
img_blur = cv2.medianBlur(img_gray, 3)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
print('Applying adaptiveThreshold to detect and enhance edges')
# Adaptive threshold using 'thickness' nearest neighbour pixels
# Default setting of 'thickness' is 4
# The number can only be odd number and larger than 1
thickness=2*thickness+1 # Make the number be odd and larger than 1
img_edge = cv2.adaptiveThreshold(img_blur, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY, thickness, 2)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Saving the edges version of the image with the filename 'Edge version.jpg'
cv2.imwrite("Edges version.jpg", img_edge)
# Showing the edges version of the image for viewing
cv2.imshow("Edges version", img_edge)
# Update the status widget
status_widget('Edges of image successfully saved at path: '+os.getcwd())
# Initialize the progress bar to zero
progress_widget(0)
# Make the showing of image not disappeared immediately
cv2.waitKey(0)
cv2.destroyAllWindows()
return
'''
This function will grayscale an image.
This function is referenced from the url: https://www.geeksforgeeks.org/cartooning-an-image-using-opencv-python/ (the same link as above)
Changes of code:
1. Usability: the code from url allows fixed path of image only while this program allows selection of path of image with graphical user interface.
2. Customization: the code from url has fixed setting of processing while this program allows customized setting, such as the level of image smoothing.
3. Speed: many unused lines are removed to enhance speed, such as image resizing.
4. Comment: many comment lines are added for explaination.
5. Reactivity: progress bar and status widget are provided to report the progress.
There are three input parameters:
1. image path: it is a string that contains the path of the image stored.
2. numDownSamples: it is an integer that determines the number of downsampling to process using Guassian pyramid.
3. numBilateralFilters: it is an integer that determines the number of bilateral filter to apply.
The output will be the grayscale version of the image.
Note that the variable 'thickness' is not related to this function as the edge version of image will not be generated in this function.
'''
def grayscaling_image(image_path, numDownSamples, numBilateralFilters):
# Updating status widget
status_widget('Start grayscaling image')
# Initialized as zero to used for updating progress bar
current_progress=0
# Used for updating progress bar, it is the number of processing steps
total_progress=numDownSamples*2+numBilateralFilters+1
print('\nReading image that stored in the image path')
img_rgb = cv2.imread(image_path)
# Downsampling image for faster processing speed
# More downsampling will lead to lower quality
# Default number of downsampling is 1
for i in range(numDownSamples):
print('Downsampling image using Gaussian pyramid',i+1,'/',numDownSamples)
img_rgb = cv2.pyrDown(img_rgb)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Applying bilateral filter to smoothing image
# Bilateral filter replaces the intensity of each pixel with a weighted average of intensity values from nearby pixels
# Default number of applying is 50.
for i in range(numBilateralFilters):
print('Applying bilateral filter to reduce noise',i+1,'/',numBilateralFilters)
img_rgb = cv2.bilateralFilter(img_rgb, 9, 9, 7)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Upsampling image to restore it
# Number of upscaling = number of downscaling
for i in range(numDownSamples):
print('Upsampling image to the original size',i+1,'/',numDownSamples)
img_rgb = cv2.pyrUp(img_rgb)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Convert the image to grayscale
print('Converting image to grayscale')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
# Update progress bar
current_progress+=1
progress_widget(int(current_progress/total_progress*10000))
# Saving the grayscale version of the image with the filename 'Grayscale version.jpg'
cv2.imwrite("Grayscale version.jpg", img_gray)
# Showing the Grayscale version of the image for viewing
cv2.imshow("Grayscale version", img_gray)
# Update the status widget
status_widget('Grayscale version of image successfully saved at path: '+os.getcwd())
# Initialize the progress bar to zero
progress_widget(0)
# Make the showing of image not disappeared immediately
cv2.waitKey(0)
cv2.destroyAllWindows()
return
'''
This function will blur an image.
This function is referenced from the url: https://www.geeksforgeeks.org/python-image-blurring-using-opencv/
Changes of code:
1. Usability: the code from url allows fixed path of image only while this program allows selection of path of image with graphical user interface.
2. Customization: the code from url has fixed level of blurring while this program allows customized level of blurring.
3. Speed: many unused lines are removed to enhance speed, including two other blurring methods. Only Gaussian Blur is adapted in this function.
4. Comment: comment lines are added for explaination.
5. Reactivity: progress bar and status widget are provided to report the progress.
There are two input parameters:
1. image path: it is a string that contains the path of the image stored.
2. blur_level: it is an integer that determines the level of blurring.
The output will be the blurred version of the image.
'''
def blurring_image(image_path, blur_level):
# Updating status widget
status_widget('Start blurring image')
# Update progress bar
progress_widget(int(1/3*10000))
print('\nReading image that stored in the image path')
image = cv2.imread(image_path)
# Update progress bar
progress_widget(int(2/3*10000))
# Perform Gaussian Blur
# The blur level can only be odd number and larger than 1
# Default setting of the blurring level is 4
blur_level=2*blur_level+1 # Make the number be odd and larger than 1
print('Performing Gaussian Blur')
Gaussian = cv2.GaussianBlur(image, (blur_level, blur_level), 0)
# Update progress bar
progress_widget(int(3/3*10000))
# Saving the blurred version of the image with the filename 'Blurred version.jpg'
cv2.imwrite("Blurred version.jpg", Gaussian)
# Showing the Blurred version of the image for viewing
cv2.imshow("Blurred version", Gaussian)
# Update the status widget
status_widget('Blurred version of image successfully saved at path: '+os.getcwd())
# Initialize the progress bar to zero
progress_widget(0)
# Make the showing of image not disappeared immediately
cv2.waitKey(0)
cv2.destroyAllWindows()
return
'''
This function will denoise an image.
This function is referenced from the url: https://www.geeksforgeeks.org/python-denoising-of-colored-images-using-opencv/
Changes of code:
1. Usability: the code from url allows fixed path of image only while this program allows selection of path of image with graphical user interface.
2. Customization: the code from url has fixed level of setting while this program allows customized setting, such as filter strength.
3. Comment: Comment lines are added for explaination.
4. Reactivity: progress bar and status widget are provided to report the progress.
There are three input parameters:
1. image path: it is a string that contains the path of the image stored.
2. performance: it is an integer that determines the performance. Larger values will consume more time.
3. filter_strength: it is an interger that determines the filter strength. Larger values may lead to loss of image details.
The output will be the denoised version of the image.
'''
def denoising_image(image_path, performance, filter_strength):
# Updating status widget
status_widget('Start denoising image')
# Update progress bar
progress_widget(int(1/3*10000))
print('\nReading image that stored in the image path')
image = cv2.imread(image_path)
# Update progress bar
progress_widget(int(2/3*10000))
# Perform Denoising
# Default setting of the performance is 10.
# Default setting of the filter strength is 15.
print('Performing Denoising')
img_denoised= cv2.fastNlMeansDenoisingColored(image, None, 10, 10, performance, filter_strength)
# Update progress bar
progress_widget(int(3/3*10000))
# Saving the Denoised version of the image with the filename 'Denoised version.jpg'
cv2.imwrite("Denoised version.jpg", img_denoised)
# Showing the Denoised version of the image for viewing
cv2.imshow("Denoised version", img_denoised)
# Update the status widget
status_widget('Denoised version of image successfully saved at path: '+os.getcwd())
# Initialize the progress bar to zero
progress_widget(0)
# Make the showing of image not disappeared immediately
cv2.waitKey(0)
cv2.destroyAllWindows()
return
# Declare some commonly used elements in order to update them easily
# Showing path of image
# have '\t' to reserve space as the length of initialized string will be the maxium length
path_widget=sg.Text('Image not selected\t\t\t\t\t\t\t\t\t\t')
# Showing status of program
# have '\t' to reserve space as the length of initialized string will be the maxium length
status_widget=sg.Text('Status: Pending\t\t\t\t\t\t\t\t\t\t')
# Showing progress of program
progress_widget=sg.ProgressBar(10000, orientation='h')
# Declare some layouts that will be included in frames
path_layout=[[path_widget, sg.FileBrowse('Browse an image', key='file')]]
split_layout=[[sg.Text('Number of photos on horizontal side:'), sg.Input(key='h', size=(5,5)), sg.Text('Number of photos on vertical side:'), sg.Input(key='v', size=(5,5)), sg.Button('Split the image')]]
cartoon_layout=[[sg.Text('Processing speed \n(may sacrifice quality):'), sg.Slider( range=(1,3), default_value = 1, orientation='horizontal', key='downsample', size=(5,20) ), sg.Text('Image smoothing:'), sg.Slider( range=(25,75), default_value = 50, orientation='horizontal', key='bilateral', size=(10,20) ), sg.Text('Thickness of edge\n(Not related to grayscaling):'), sg.Slider( range=(1,7), default_value = 4, orientation='horizontal', key='thickness', size=(10,20) )]
,[sg.Button('Cartooning the image'), sg.Button('Draw Edges of the image'), sg.Button('Grayscaling the image')]]
blur_layout=[[sg.Text('\nBlurring level:'), sg.Slider( range=(1,100), default_value = 4, orientation='horizontal', key='blur', size=(40,20) ), sg.Button('Blurring the image')]]
denoise_layout=[[sg.Text('Performance\n(consume more time):'), sg.Slider( range=(1,20), default_value = 10, orientation='horizontal', key='performance', size=(10,20) ), sg.Text('Filter strength\n(may sacrifice detail of image):'), sg.Slider( range=(15,30), default_value = 10, orientation='horizontal', key='filter', size=(10,20) ), sg.Button('Denoising the image')]]
# Declare layout of the main gui window
layout=[[sg.Text('Please pick an image first. Then choose the image processing function(s).\nYou are recommended to use default settings but you are still free to change the settings.')]
,[sg.Frame(layout=path_layout, title='Path of image')]
,[sg.Text('\nImage Processing Functions:\n')]
,[sg.Frame(layout=split_layout, title='1. Split the photo into equal-sized smaller photos which can be posted on Instagram.')]
,[sg.Text('')]
,[sg.Frame(layout=cartoon_layout, title='2. Cartoon the image to look more entertaining. 3. Draw the edges of the image to focus the shape. 4. Grayscaling the image to focus the detail.')]
,[sg.Text('')]
,[sg.Frame(layout=blur_layout, title='5. Blur the image for products that not announced yet.')]
,[sg.Text('')]
,[sg.Frame(layout=denoise_layout, title='6. Denoise the image to restore the true image.')]
,[sg.Text('')]
,[status_widget, sg.Button('Open folder of processed images')]
,[progress_widget]]
# Declare a window with the layout aforementioned
window=sg.Window("Image Processing",layout)
while True:
event, values=window.read(timeout=20) # gui window refresh every 20 ms
# Error may occur if user closes the window but the program is still reading the value of 'file'
try:
# Read the values of input field with key 'file'
image_path=values['file']
# Users have chosen the path of image
if len(image_path)>0:
# Update the path widget to show the path of image
path_widget(image_path)
except:
pass
# User closes the gui window
if event==sg.WIN_CLOSED:
break
# User presses the button 'Split the image'
if event=='Split the image':
# Check if image path is empty
if len(image_path)==0:
sg.popup('Please browse a image first.')
continue
# Try to read the number of smaller images on horizontal and vertical sides
try:
horizontal_number=int(values['h'])
vertical_number=int(values['v'])
print('There will be',horizontal_number,'images per row and',vertical_number,'images per column.')
except:
status_widget('Status: Error! Please confirm the two numbers you entered are integers')
sg.popup('Error! Please confirm the two numbers you entered are integers')
print('Error! Please confirm the two numbers you entered are integers')
continue
split_image(image_path, horizontal_number, vertical_number)
# User presses the button 'Cartooning the image'
if event=='Cartooning the image':
# Check if image path is empty
if len(image_path)==0:
sg.popup('Please browse a image first.')
continue
# Read the values of three sliders
numDownSamples=int(values['downsample'])
numBilateralFilters=int(values['bilateral'])
thickness=int(values['thickness'])
cartooning_image(image_path, numDownSamples, numBilateralFilters, thickness)
# User presses the button 'Draw Edges of the image'
if event=='Draw Edges of the image':
# Check if image path is empty
if len(image_path)==0:
sg.popup('Please browse a image first.')
continue
# Read the values of three sliders
numDownSamples=int(values['downsample'])
numBilateralFilters=int(values['bilateral'])
thickness=int(values['thickness'])
edging_image(image_path, numDownSamples, numBilateralFilters, thickness)
# User presses the button 'Grayscaling the image'
if event=='Grayscaling the image':
# Check if image path is empty
if len(image_path)==0:
sg.popup('Please browse a image first.')
continue
# Read the values of two sliders
numDownSamples=int(values['downsample'])
numBilateralFilters=int(values['bilateral'])
grayscaling_image(image_path, numDownSamples, numBilateralFilters)
# User presses the button 'Blurring the image'
if event=='Blurring the image':
# Check if image path is empty
if len(image_path)==0:
sg.popup('Please browse a image first.')
continue
# Read the value of blur level in the slider
blur_level=int(values['blur'])
blurring_image(image_path, blur_level)
# User presses the button 'Denoising the image'
if event=='Denoising the image':
# Check if image path is empty
if len(image_path)==0:
sg.popup('Please browse a image first.')
continue
# Read the values of two sliders
performance=int(values['performance'])
filter_strength=int(values['filter'])
denoising_image(image_path, performance, filter_strength)
# User presses the button 'Open folder of processed images'
if event=='Open folder of processed images':
subprocess.Popen('explorer '+os.getcwd())
window.close()
|
634ac1cc131f9af01f7fedd450a5c17edebb3896 | sdpython/teachpyx | /teachpyx/practice/rues_paris.py | 17,689 | 3.640625 | 4 | # -*- coding: utf-8 -*-
from typing import Callable, Dict, List, Optional, Tuple
import random
import math
from ..tools.data_helper import download_and_unzip
def distance_paris(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
"""
Distance euclidienne approchant la distance de Haversine
(uniquement pour Paris).
"""
return ((lat1 - lat2) ** 2 + (lng1 - lng2) ** 2) ** 0.5 * 90
def distance_haversine(lat1: float, lng1: float, lat2: float, lng2: float) -> float:
"""
Calcule la distance de Haversine
`Haversine formula <http://en.wikipedia.org/wiki/Haversine_formula>`_
"""
radius = 6371
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lng2 - lng1)
a = math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(
math.radians(lat1)
) * math.cos(math.radians(lat2)) * math.sin(dlon / 2) * math.sin(dlon / 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = radius * c
return d
def get_data(
url: str = "https://github.com/sdpython/teachpyx/raw/main/_data/paris_54000.zip",
dest: str = ".",
timeout: int = 10,
verbose: bool = False,
keep: int = -1,
) -> List[Tuple[int, int, int, Tuple[float, float], Tuple[float, float], float]]:
"""
Retourne les données des rues de Paris. On suppose que les arcs sont uniques
et qu'il si :math:`j \\rightarrow k` est présent,
:math:`j \\rightarrow k` ne l'est pas.
Ceci est vérifié par un test.
:param url: location of the data
:param dest: répertoire dans lequel télécharger les données
:param timeout: timeout (seconds) when estabishing the connection
:param verbose: affiche le progrès
:param keep: garde tout si la valeur est -1,
sinon garde les 1000 premières rues, ces rues sont choisies
de façon à construire un ensemble connexe
:return: liste d'arcs
Un arc est défini par un 6-uple contenant les informations suivantes :
- v1: indice du premier noeud
- v2: indice du second noeud
- ways: sens unique ou deux sens
- p1: coordonnées du noeud 1
- p2: coordonnées du noeud 2
- d: distance
"""
data = download_and_unzip(url=url, timeout=timeout, verbose=verbose)
name = data[0]
with open(name, "r") as f:
lines = f.readlines()
vertices = []
edges = []
for i, line in enumerate(lines):
spl = line.strip("\n\r").split(" ")
if len(spl) == 2:
vertices.append((float(spl[0]), float(spl[1])))
elif len(spl) == 5 and i > 0:
v1, v2 = int(spl[0]), int(spl[1])
ways = int(spl[2]) # dans les deux sens ou pas
p1 = vertices[v1]
p2 = vertices[v2]
edges.append(
(v1, v2, ways, p1, p2, distance_haversine(p1[0], p1[1], p2[0], p2[1]))
)
elif i > 0:
raise RuntimeError(f"Unable to interpret line {i}: {line!r}")
pairs = {}
for e in edges:
p = e[:2]
if p in pairs:
raise ValueError(f"Unexpected pairs, already present: {e}")
pairs[p] = True
if keep is not None:
new_vertices = {}
already_added = set()
new_edges = []
for _ in range(0, int(keep**0.5) + 1):
for edge in edges:
if edge[:2] in already_added:
continue
p1, p2 = edge[-3:-1]
if (
len(new_vertices) > 0
and p1 not in new_vertices
and p2 not in new_vertices
):
# On considère des rues connectées à des rues déjà sélectionnées.
continue
if p1 not in new_vertices:
new_vertices[p1] = len(new_vertices)
if p2 not in new_vertices:
new_vertices[p2] = len(new_vertices)
i1, i2 = new_vertices[p1], new_vertices[p2]
new_edges.append((i1, i2, edge[2], p1, p2, edge[-1]))
already_added.add(edge[:2])
if len(new_edges) >= keep:
break
if len(new_edges) >= keep:
break
items = [(v, i) for i, v in new_vertices.items()]
items.sort()
vertices = [_[1] for _ in items]
edges = new_edges
return edges, vertices
def graph_degree(
edges: List[Tuple[int, int, int, Tuple[float, float], Tuple[float, float], float]]
) -> Dict[Tuple[int, int], int]:
"""
Calcul le degré de chaque noeud.
:param edges: list des arcs
:return: degrés
"""
nb_edges = {}
for edge in edges:
v1, v2 = edge[:2]
nb_edges[v1] = nb_edges.get(v1, 0) + 1
nb_edges[v2] = nb_edges.get(v2, 0) + 1
return nb_edges
def possible_edges(
edges: List[Tuple[int, int, int, Tuple[float, float], Tuple[float, float], float]],
threshold: float,
distance: Callable = distance_haversine,
):
"""
Construit la liste de tous les arcs possibles en
filtrant sur la distance à vol d'oiseau.
:param edges: list des arcs
:param threshold: seuil au-delà duquel deux noeuds ne seront pas connectés
:param distance: la distance de Haversine est beaucoup trop
longue sur de grands graphes, on peut la changer
:return: arcs possibles (symétrique --> incluant edges)
"""
vertices: Dict[int : Tuple[float, float]] = {e[0]: e[3] for e in edges}
vertices.update({e[1]: e[4] for e in edges})
possibles = {(e[0], e[1]): e[-1] for e in edges}
possibles.update({(e[1], e[0]): e[-1] for e in edges})
# initial = possibles.copy()
for i1, v1 in vertices.items():
for i2, v2 in vertices.items():
if i1 >= i2:
continue
d = distance(*(v1 + v2))
if d < threshold:
possibles[i1, i2] = d
possibles[i2, i1] = d
return possibles
def bellman(
edges: List[Tuple[int, int, int, Tuple[float, float], Tuple[float, float], float]],
max_iter: int = 20,
allow: Optional[Callable] = None,
init: Optional[Dict[Tuple[int, int], float]] = None,
verbose: bool = False,
) -> Dict[Tuple[int, int], float]:
"""
Implémente l'algorithme de `Bellman-Ford <http://fr.wikipedia.org/wiki/Algorithme_de_Bellman-Ford>`_.
:param edges: liste de tuples (noeud 1, noeud 2, ?, ?, ?, poids)
:param max_iter: nombre d'itérations maximal
:param allow: fonction déterminant si l'algorithme
doit envisager cette liaison ou pas
:param init: initialisation (pour pouvoir continuer après une première exécution)
:param verbose: afficher le progrès
:return: listes des arcs et des distances calculées
"""
if init is None:
init: Dict[Tuple[int, int], float] = {(e[0], e[1]): e[-1] for e in edges}
init.update({(e[1], e[0]): e[-1] for e in edges})
def always_true(e):
return True
if allow is None:
allow = always_true
edges_from = {}
for e in edges:
if e[0] not in edges_from:
edges_from[e[0]] = []
if e[1] not in edges_from:
edges_from[e[1]] = []
edges_from[e[0]].append(e)
if len(e) == 2:
edges_from[e[1]].append((e[1], e[0], 1.0))
elif len(e) == 3:
edges_from[e[1]].append((e[1], e[0], e[2]))
elif len(e) == 6:
edges_from[e[1]].append((e[1], e[0], e[2], e[4], e[3], e[5]))
else:
raise ValueError(
f"an edge should be a tuple of 2, 3, or 6 elements, "
f"last item is the weight, not:\n{e}"
)
modif = 1
total_possible_edges = (len(edges_from) ** 2 - len(edges_from)) // 2
it = 0
while modif > 0:
modif = 0
# to avoid RuntimeError: dictionary changed size during iteration
initc = init.copy()
s = 0
for i, d in initc.items():
if allow(i):
fromi2 = edges_from[i[1]]
s += d
for e in fromi2:
# on fait attention à ne pas ajouter de boucle sur le même
# noeud
if i[0] == e[1]:
continue
new_e = i[0], e[1]
new_d = d + e[-1]
if new_e not in init or init[new_e] > new_d:
init[new_e] = new_d
modif += 1
if verbose:
print(
f"iteration {it} #modif {modif} # "
f"{len(initc) // 2}/{total_possible_edges} = "
f"{len(initc) * 50 / total_possible_edges:1.2f}%"
)
it += 1
if it > max_iter:
break
return init
def kruskal(
edges: List[Tuple[int, int, int, Tuple[float, float], Tuple[float, float], float]],
extension: Dict[Tuple[int, int], float],
) -> List[Tuple[int, int]]:
"""
Applique l'algorithme de Kruskal (ou ressemblant) pour choisir les arcs à ajouter.
:param edges: listes des arcs
:param extension: résultat de l'algorithme de Bellman
:return: added_edges
"""
original: Dict[Tuple[int, int], float] = {(e[0], e[1]): e[-1] for e in edges}
original.update({(e[1], e[0]): e[-1] for e in edges})
additions: Dict[Tuple[int, int], float] = {
k: v for k, v in extension.items() if k not in original
}
additions.update({(k[1], k[0]): v for k, v in additions.items()})
degre: Dict[Tuple[int, int], int] = {}
for k, v in original.items(): # original est symétrique
degre[k[0]] = degre.get(k[0], 0) + 1
tri = [
(v, k)
for k, v in additions.items()
if degre[k[0]] % 2 == 1 and degre[k[1]] % 2 == 1
]
tri.extend(
[
(v, k)
for k, v in original.items()
if degre[k[0]] % 2 == 1 and degre[k[1]] % 2 == 1
]
)
tri.sort()
impairs = sum(v % 2 for k, v in degre.items())
added_edges = []
if impairs > 2:
for v, a in tri:
if degre[a[0]] % 2 == 1 and degre[a[1]] % 2 == 1:
# il faut refaire le test car degre peut changer à chaque
# itération
degre[a[0]] += 1
degre[a[1]] += 1
added_edges.append(a + (v,))
impairs -= 2
if impairs <= 0:
break
return added_edges
def eulerien_extension(
edges: List[Tuple[int, int, int, Tuple[float, float], Tuple[float, float], float]],
max_iter: int = 20,
alpha: float = 0.5,
distance: Callable = distance_haversine,
verbose: bool = False,
) -> List[Tuple[int, int]]:
"""
Construit une extension eulérienne d'un graphe.
:param edges: liste des arcs
:param max_iter: nombre d'itérations pour la fonction @see fn bellman
:param alpha: coefficient multiplicatif de ``max_segment``
:param distance: la distance de Haversine est beaucoup trop
longue sur de grands graphes, on peut la changer
:param verbose: afficher l'avancement
:return: added edges
"""
max_segment = max(e[-1] for e in edges)
possibles = possible_edges(edges, max_segment * alpha, distance=distance)
init = bellman(edges, allow=lambda e: e in possibles)
added = kruskal(edges, init)
d = graph_degree(edges + added)
allow = [k for k, v in d.items() if v % 2 == 1]
totali = 0
while len(allow) > 0:
if verbose:
print(f"------- # odd vertices {len(allow)} iteration {totali}")
allowset = set(allow)
init = bellman(
edges,
max_iter=max_iter,
allow=lambda e: e in possibles or e[0] in allowset or e[1] in allowset,
init=init,
verbose=verbose,
)
added = kruskal(edges, init)
d = graph_degree(edges + added)
allow = [k for k, v in d.items() if v % 2 == 1]
totali += 1
if totali > 20:
# tant pis, ça ne marche pas
break
return added
def connected_components(
edges: List[Tuple[int, int, int, Tuple[float, float], Tuple[float, float], float]]
) -> Dict[int, int]:
"""
Computes the connected components.
:param edges: edges
:return: dictionary { vertex : id of connected components }
"""
res = {}
for k in edges:
for _ in k[:2]:
if _ not in res:
res[_] = _
modif = 1
while modif > 0:
modif = 0
for k in edges:
a, b = k[:2]
r, s = res[a], res[b]
if r != s:
m = min(res[a], res[b])
res[a] = res[b] = m
modif += 1
return res
def euler_path(
edges: List[Tuple[int, int, int, Tuple[float, float], Tuple[float, float], float]],
added_edges,
):
"""
Computes an eulerian path. We assume every vertex has an even degree.
:param edges: initial edges
:param added_edges: added edges
:return: path, list of `(vertex, edge)`
"""
alledges = {}
edges_from = {}
somme = 0
for e in edges:
k = e[:2] # indices des noeuds
v = e[-1] # distance
alledges[k] = ["street", *k, v]
a, b = k
alledges[b, a] = alledges[a, b]
if a not in edges_from:
edges_from[a] = []
if b not in edges_from:
edges_from[b] = []
edges_from[a].append(alledges[a, b])
edges_from[b].append(alledges[a, b])
somme += v
for e in added_edges: # il ne faut pas enlever les doublons
k = e[:2] # indices ds noeuds
v = e[-1] # distance
a, b = k
alledges[k] = ["jump", *k, v]
alledges[b, a] = alledges[a, b]
if a not in edges_from:
edges_from[a] = []
if b not in edges_from:
edges_from[b] = []
edges_from[a].append(alledges[a, b])
edges_from[b].append(alledges[a, b])
somme += v
# les noeuds de degré impair
odd = [a for a, v in edges_from.items() if len(v) % 2 == 1]
if len(odd) > 0:
raise ValueError("Some vertices have an odd degree.")
# les noeuds de degré 2, on les traverse qu'une fois
two = [a for a, v in edges_from.items() if len(v) == 2]
begin = two[0]
# checking
for v, le in edges_from.items():
# v est une extrémité
for e in le:
# to est l'autre extrémité
to = e[1] if v != e[1] else e[2]
if to not in edges_from:
raise RuntimeError(f"Unable to find vertex {to} for edge {to},{v}")
if to == v:
raise RuntimeError(f"Circular edge {to}")
# On sait qu'il existe un chemin. La fonction explore les arcs
# jusqu'à revenir à son point de départ. Elle supprime les arcs
# utilisées de edges_from.
path = _explore_path(edges_from, begin)
# Il faut s'assurer que le chemin ne contient pas de boucles non visitées.
while len(edges_from) > 0:
# Il reste des arcs non visités. On cherche le premier
# arc connecté au chemin existant.
start = None
for i, p in enumerate(path):
if p[0] in edges_from:
start = i, p
break
if start is None:
raise RuntimeError(
f"start should not be None\npath={path}\nedges_from={edges_from}"
)
sub = _explore_path(edges_from, start[1][0])
i = start[0]
path[i : i + 1] = path[i : i + 1] + sub
return path
def _delete_edge(edges_from, n: int, to: int):
"""
Removes an edge from the graph.
:param edges_from: structure which contains the edges (will be modified)
:param n: first vertex
:param to: second vertex
:return: the edge
"""
le = edges_from[to]
f = None
for i, e in enumerate(le):
if (e[1] == to and e[2] == n) or (e[2] == to and e[1] == n):
f = i
break
assert f is not None
del le[f]
if len(le) == 0:
del edges_from[to]
le = edges_from[n]
f = None
for i, e in enumerate(le):
if (e[1] == to and e[2] == n) or (e[2] == to and e[1] == n):
f = i
break
assert f is not None
keep = le[f]
del le[f]
if len(le) == 0:
del edges_from[n]
return keep
def _explore_path(edges_from, begin):
"""
Explores an eulerian path, remove used edges from edges_from.
:param edges_from: structure which contains the edges (will be modified)
:param begin: first vertex to use
:return: path
"""
path = [(begin, None)]
stay = True
while stay and len(edges_from) > 0:
n = path[-1][0]
if n not in edges_from:
# fin
break
le = edges_from[n]
if len(le) == 1:
h = 0
e = le[h]
to = e[1] if n != e[1] else e[2]
else:
to = None
nb = 100
while to is None or to == begin:
h = random.randint(0, len(le) - 1) if len(le) > 1 else 0
e = le[h]
to = e[1] if n != e[1] else e[2]
nb -= 1
if nb < 0:
raise RuntimeError(f"algorithm issue {len(path)}")
if len(edges_from[to]) == 1:
if begin != to:
raise RuntimeError("wrong algorithm")
else:
stay = False
keep = _delete_edge(edges_from, n, to)
path.append((to, keep))
return path[1:]
|
1519e6d70a647222cc8c97744987ed69dac524e8 | martinaoliver/GTA | /ssb/m1a/exercise_answers/ex7a.py | 508 | 4 | 4 | months = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August',9:'September', 10:'October', 11:'November', 12:'December'}
for m in months.keys():
print (m, "is", months[m])
# Or if the keys are stored as strings:
months = {'1':'January', '2':'February', '3':'March', '4':'April', '5':'May', '6':'June', '7':'July', '8':'August', '9':'September', '10':'October', '11':'November', '12':'December'}
for m in months.keys():
print (m, "is", months[m])
|
b920f867017fd8e708fe0ed96633b251aff5304a | brunorijsman/euler-problems-python | /euler/problem068.py | 3,030 | 3.59375 | 4 | import math
import itertools
from tkinter import *
canvas_width = 800
canvas_height = 800
ring_radius = 100
point_radius = 20
def point_location(point, nr_points):
arm = point // 2
nr_arms = nr_points // 2
mid_x = canvas_width // 2
mid_y = canvas_height // 2
base_angle = -math.pi / 2
one_arm_angle = 2 * math.pi / nr_arms
angle = base_angle + arm * one_arm_angle
inner_x = mid_x + math.cos(angle) * ring_radius
inner_y = mid_y + math.sin(angle) * ring_radius
if point % 2 == 0:
next_x = mid_x + math.cos(angle + one_arm_angle) * ring_radius
next_y = mid_y + math.sin(angle + one_arm_angle) * ring_radius
dx = next_x - inner_x
dy = next_y - inner_y
x = inner_x - dx
y = inner_y - dy
else:
x = inner_x
y = inner_y
return (x, y)
def draw_solution(solution):
nr_points = len(solution)
nr_arms = nr_points // 2
tk = Tk()
canvas = Canvas(tk, width=canvas_width, height=canvas_height)
canvas.pack()
for arm in range(nr_arms):
i1 = (arm*2) % nr_points
i3 = (arm*2 + 3) % nr_points
(x1, y1) = point_location(i1, nr_points)
(x2, y2) = point_location(i3, nr_points)
canvas.create_line(x1, y1, x2, y2, fill="blue")
for point in range(nr_points):
(x, y) = point_location(point, nr_points)
canvas.create_oval(x - point_radius, y - point_radius,
x + point_radius, y + point_radius,
outline="blue",
fill="lightblue")
nr = solution[point]
canvas.create_text(x, y, text=str(nr))
canvas.pack()
def same_sums(candidate):
nr_points = len(candidate)
nr_arms = nr_points // 2
sums = []
for arm in range(nr_arms):
i1 = (arm*2) % nr_points
i2 = (arm*2 + 1) % nr_points
i3 = (arm*2 + 3) % nr_points
sums.append(candidate[i1] + candidate[i2] + candidate[i3])
for arm in range(nr_arms - 1):
if sums[arm] != sums[arm+1]:
return False
return True
def first_arm_lowest(candidate):
nr_points = len(candidate)
nr_arms = nr_points // 2
for arm in range(1, nr_arms):
i = (arm*2) % nr_points
if candidate[i] < candidate[0]:
return False
return True
def to_nr(candidate):
nr_points = len(candidate)
nr_arms = nr_points // 2
nr_str = ""
for arm in range(nr_arms):
i1 = (arm*2) % nr_points
i2 = (arm*2 + 1) % nr_points
i3 = (arm*2 + 3) % nr_points
nr_str += str(candidate[i1])
nr_str += str(candidate[i2])
nr_str += str(candidate[i3])
return int(nr_str)
def find_best_solution(nr_points, digits):
max_nr = 0
best_solution = None
numbers = list(range(1, nr_points+1))
for candidate in itertools.permutations(numbers):
candidate = list(candidate)
if first_arm_lowest(candidate) and same_sums(candidate):
nr = to_nr(candidate)
if (nr > max_nr) and (len(str(nr)) == digits):
max_nr = nr
best_solution = candidate
return best_solution
def solve():
solution = find_best_solution(10, 16)
draw_solution(solution)
print(to_nr(solution))
|
b711961aa017e140327e8ccdc681619e3a85611a | jimmus69/python-projects | /Ch10_OO/Classic_vs_New_Classes/New/TomCat.py | 254 | 3.546875 | 4 | from Cat import Cat
class TomCat(Cat):
def talk(self):
"""
To call a method in the superclass when the method is
overridden in the current class. use
super(current_class_name, self).method()
"""
super(TomCat, self).talk()
print "Burp!"
|
cc184e3a4546ada02065c7216610341e791e9931 | khygu0919/codefight | /Intro/matrixElementsSum.py | 904 | 4.15625 | 4 | '''
After they became famous, the CodeBots all decided to move to a new building and live together. The building is represented by a rectangular matrix of rooms. Each cell in the matrix contains an integer that represents the price of the room. Some rooms are free (their cost is 0), but that's probably because they are haunted, so all the bots are afraid of them. That is why any room that is free or is located anywhere below a free room in the same column is not considered suitable for the bots to live in.
Help the bots calculate the total price of all the rooms that are suitable for them.
'''
def matrixElementsSum(matrix):
a=len(matrix)
b=[]
c=0
for i in range(0,a):
for k in b:
matrix[i][k]=0
b=[]
for j in range(0,len(matrix[i])):
if matrix[i][j]==0:
b.append(j)
else:c+=matrix[i][j]
return c |
ca44d1179fb8094ef56c2290b4ffa59ac45b3e23 | dongqui/problemSolving | /structure/Stack.py | 752 | 3.78125 | 4 | import unittest
class Stack:
def __init__(self):
self.items = []
self.max = 5
def push(self, item):
if len(self.items) < max:
self.items.append(item)
else:
print("stack overflow")
def popitem(self):
self.items.pop()
def peak(self):
return self.items[len(self.items)-1]
def print_stack(self):
print(self.items)
class StackTest(unittest.TestCase):
def test(self):
st = Stack()
st.push(1)
st.push(2)
st.print_stack()
st.popitem()
st.print_stack()
st.push(3)
st.push(3)
self.assertEquals(st.peak(), 3)
st.popitem()
st.popitem()
st.print_stack()
|
c8fa6e5addfc64a1cf7cc203f1d5e295c343bc44 | SaanyaV/RSAEncryption | /testTimeForPrime.py | 1,583 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Code to create PrimeNumbers
"""
import math
import time
def testPrimeBrute(a):
if a <= 1:
return False
elif a == 2:
return True
for i in range(2, math.ceil(a**.5)+1):
if a % i == 0:
return False
return True
def firstPrime(biggerThan = 10):
numAdd = 1
while testPrimeBrute(biggerThan + numAdd) == False:
numAdd = numAdd + 1
return biggerThan + numAdd
def createPrimes(biggerThan = 10, quantity = 5):
result = []
while len(result) < quantity:
prime = firstPrime(biggerThan)
result.append(prime)
biggerThan = prime
return result
def primeFactorList(a):
for i in range(2,math.ceil(a/2)+1):
if testPrimeBrute(i):
if a % i == 0:
return [i,a/i]
#s = firstPrime(10000000000000000000)
#print(f"The number is {len(str(s))} digit long and is {s}. Time taken is {round(time.time() - start_time,2)} seconds")
for x in range(1,10):
biggerThan = int(10**x)
smallPrime = createPrimes(biggerThan,1)
bigPrime = createPrimes(10**10,1)
num = int(smallPrime[0]*bigPrime[0])
start_time = time.time()
lenP = len(str(smallPrime[0]))
t = primeFactorList(num)
print(f"It took {round(time.time() - start_time,2)} seconds to find the prime factors. The smallest prime factor is {lenP} digits long.")
#print(f"The prime numbers greater than {len(str(biggerThan))-1} digit long are {s}. Time taken is {round(time.time() - start_time,2)} seconds")
|
194cd1716c79d967d656779d7698e4be6982a7ed | CRHS-Winter-2021/project---tic-tac-toe-TylerKennedy1660 | /main.py | 2,740 | 3.703125 | 4 | # Tic Tak Toe
# Tyler Kennedy
# Feb 17th 2021
import sys
#constants
turn = 0
stop = 0
X_O_pos = []
def print_board():
the_board = (' | | \n '+ X_O_pos[7] + ' | '+ X_O_pos[8] + ' | '+ X_O_pos[9] + ' \n_____|_____|_____\n | | \n '+ X_O_pos[4] + ' | '+ X_O_pos[5] + ' | '+ X_O_pos[6] + ' \n_____|_____|_____\n | | \n '+ X_O_pos[1] + ' | '+ X_O_pos[2] + ' | '+ X_O_pos[3] + ' \n | | \n')
print(the_board)
def check_win():
if X_O_pos[1] == 'X' and X_O_pos[2] == 'X' and X_O_pos[3] == 'X' or X_O_pos[4] == 'X' and X_O_pos[5] == 'X' and X_O_pos[6] == 'X' or X_O_pos[7] == 'X' and X_O_pos[8] == 'X' and X_O_pos[9] == 'X' or X_O_pos[7] == 'X' and X_O_pos[4] == 'X' and X_O_pos[1] == 'X' or X_O_pos[8] == 'X' and X_O_pos[5] == 'X' and X_O_pos[2] == 'X' or X_O_pos[9] == 'X' and X_O_pos[6] == 'X' and X_O_pos[3] == 'X' or X_O_pos[7] == 'X' and X_O_pos[5] == 'X' and X_O_pos[3] == 'X' or X_O_pos[9] == 'X' and X_O_pos[5] == 'X' and X_O_pos[1] == 'X':
print('X Wins!')
sys.exit()
if X_O_pos[1] == 'O' and X_O_pos[2] == 'O' and X_O_pos[3] == 'O' or X_O_pos[4] == 'O' and X_O_pos[5] == 'O' and X_O_pos[6] == 'O' or X_O_pos[7] == 'O' and X_O_pos[8] == 'O' and X_O_pos[9] == 'O' or X_O_pos[7] == 'O' and X_O_pos[4] == 'O' and X_O_pos[1] == 'O' or X_O_pos[8] == 'O' and X_O_pos[5] == 'O' and X_O_pos[2] == 'O' or X_O_pos[9] == 'O' and X_O_pos[6] == 'O' and X_O_pos[3] == 'o' or X_O_pos[7] == 'O' and X_O_pos[5] == 'O' and X_O_pos[3] == 'O' or X_O_pos[9] == 'O' and X_O_pos[5] == 'O' and X_O_pos[1] == 'O':
print('O Wins!')
sys.exit()
def check_draw():
if X_O_pos.count(' ') == 0:
stop = 1
print('Draw!')
sys.exit()
def play():
global turn
while stop == 0:
if turn % 2 == 0:
x_o = 'X'
print("X's Turn")
else:
x_o = 'O'
print("O's Turn")
move = input('Where would you like to play ')
while move not in ['1','2','3','4','5','6','7','8','9'] or X_O_pos[int(move)] != ' ':
print('Invalid move')
move = input('Where would you like to play ')
X_O_pos[int(move)] = x_o
print_board()
check_win()
check_draw()
turn +=1
def setup():
global X_O_pos
global turn
print("Welcome to Tyler's Tic Tac Toe\nThe spaces are related to the numbers on the number pad")
first_move = input("Player 1 would you like to be:\nX (1)\nO (2)\n")
while first_move != '1' and first_move != '2':
print('You must pick 1 or 2')
first_move = input("Player 1 would you like to be:\nX (1)\nO (2)\n")
if first_move == '2':
turn += 1
X_O_pos = ['not a space',' ',' ',' ',' ',' ',' ',' ',' ',' ']
setup()
print_board()
play()
|
4708f35ef7dd0de9f716643970b0f242e17cd736 | aderas2/Zuri | /OOP deep dive.py | 2,406 | 4.0625 | 4 | class Animal:
animal_type = 'Mammal'
counter = 0
def __init__(self,name,number_of_legs):
self.name=name
self.number_of_legs =number_of_legs
Animal.counter +=1
def can_run(self):
print('Animal %s runs with %s' %(self.name,self.number_of_legs))
@classmethod #class mwthod comes with all the declarations
def can_see(cls):
print('Animal can see')
@staticmethod
def tail_wiggle():
print('Animal can wiggle it"s tail')
animal_1 = Animal('rat', 4)
animal_2 = Animal('cat', 4)
animal_1.can_run()
animal_2.can_run()
print('='*40)
print(animal_1.animal_type)
print(animal_2.animal_type)
print('='*60)
animal_1.can_see()
animal_2.can_see()
print(Animal.counter)
#types of method in classes: instance method, class method and static method
print('\n')
#inheritance and composition
# 1. Inheritance is a relationship
#class BaseClass:
#class SubClass(BaseClass):
print('='*60)
class food:
def solid_food(self):
return 'hard foods'
class water(food):
pass
food_1 = water().solid_food()
print(food_1)
print('\n')
print('\n')
print('='*60)
class CustomException(Exception):
pass
#raise CustomException('An error occurred')
class ValueTooSmallException(CustomException):
pass
class ValueTooBigException(CustomException):
pass
number_value = 20
while True:
try:
input_number = int(input('Enter a number \n'))
if input_number < number_value:
raise ValueTooSmallException
elif input_number > number_value:
raise ValueTooBigException
break
except ValueTooSmallException as _:
print('Value too small')
except ValueTooBigException as _:
print('Value too big')
except Exception as _:
print(_.__str__())
print('Hey you got it correctly')
print('='*60)
print('\n')
#2. Composition shows has a relationship
class Employee:
def __init__(self,name,department,salary):
self.name = name
self.department = department
self.salary = salary
def check_salary(self):
return self.salary.check_salary()
class Salary:
def __init__(self,amount,bonus):
self.amount = amount
self.bonus = bonus
def check_salary(self):
return ('Marketer"s salary is %d+ (%d*%d) with bonus of %d' %(self.amount,self.amount,self.bonus,self.bonus) )
marketer_salary = Salary(400000,5)
marketer_employee = Employee("Jones",'MArketing',marketer_salary)
print(marketer_employee.check_salary())
|
822880148669ac16f0428a0ce163ed646a46cc4a | prabhurd/DataScientistPython | /exerciseleetcodeArraysStrings.py | 2,244 | 3.625 | 4 | from typing import List
class Solution:
def moveZerosToBack(self, nums:List[int]) -> None:
print("moveZerosToBack")
print(nums)
j = 0
for num in nums:
if num != 0:
nums[j] = num
j = j+1
else:
for c_index in range(j,len(nums)):
nums[c_index] = 0
print(nums)
# Time Complexity: O(2n) => O(n) [Linear algorithm]
# Space Complexity: 0(1)
def moveZerosToFront(self, nums: List[int]) -> None:
print("moveZerosToFront")
print(nums)
j = len(nums)-1
for c_index in range(len(nums)-1,-1,-1):
if nums[c_index] != 0:
nums[j] = nums[c_index]
j= j-1
else:
for c_index in range(j+1):
nums[c_index] = 0
print(nums)
# Time Complexity: O(2n) => O(n) [Linear algorithm]
# Space Complexity: 0(1)
def boats_to_save_people(self,persons_weight:List[int],max_weight:int):
persons_weight.sort();
print(persons_weight)
left = 0;
right = len(persons_weight)-1
no_of_boats = 0
while(left <= right):
if left == right:
no_of_boats = no_of_boats + 1
break;
elif persons_weight[left] + persons_weight[right] <= max_weight:
left = left+1
no_of_boats = no_of_boats+1
right = right-1
print(no_of_boats)
# Time Complexity: O(nlog(n)) - because of Sorting Algorithm
# Space Complexity: 0(n)
def valid_mountain_array(self,nums:List[int]):
j = 1
while j < len(nums) and nums[j] > nums[j-1]:
j += 1
if j == 1 or j == len(nums):
return False
while j < len(nums) and nums[j] < nums[j-1]:
j += 1
return j == len(nums)
# Time Complexity: O(N)
# Space Complexity: O(1)
solution = Solution()
nums = [1,2,3,4,0,0,5,4,0,4,6]
persons_weight = [2,2,1,1,1,1,1,1,3]
# solution.moveZerosToBack(nums)
# solution.moveZerosToFront(nums)
# solution.boats_to_save_people(persons_weight,3)
print(solution.valid_mountain_array([0,2,3,4,5,2,1])) |
669e61e7b45996d477f77dc8413ca545a0b926f1 | Wyqq-kerio/Lab2 | /lab2/fun3.py | 903 | 3.953125 | 4 | import string
import os
import re
# Count the number of "if else" structures
def count_if_else(lines):
# Number of structures
if_else_num = []
if_else_total=0
for line in lines:
line1=line.strip().split('\n')
# Convert the list to a string
line2=''.join(line1)
# remove "else if" interference
if line2.find("else if")!=-1:
if_else_num.append('0')
# mark "if" and "else" with '1' and '2' respectively
elif line2.find("if")!=-1:
if_else_num.append('1')
elif line2.find("else")!=-1:
if_else_num.append('2')
else:
continue
for i in range(len(if_else_num)):
if if_else_num[i]=='1' and if_else_num[i+1]=='2':
if_else_total+=1
print("\nif-else num: ",if_else_total)
return if_else_total
|
5ac8c4d1a16c14a2ed34e072f71e57c33a3de963 | Jayshri-Rathod/loop | /sum.py | 319 | 3.890625 | 4 | # counter = 0
# while counter < 5:
# print ("NavGurukul")
# counter = counter + 1
# print ("one time print" )
# number=0
# sum=0
# while number <= 10:
# sum=sum+number
# number=number+1
# print(sum)
# num=10
# sum=0
# while num>=0:
# sum=sum+num
# num=num-1
# print(sum)
|
d24fa0880322cfab9bd4c687a8f3e092dbcdc6af | Ca11me1ce/PSU-CMPSC122-LAB | /LAB8.py | 2,242 | 3.65625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return "Node({})".format(self.value)
__repr__ = __str__
class OrderedLinkedList:
def __init__(self):
self.head=None
self.tail=None
def __str__(self):
temp=self.head
out=''
while temp:
out+=str(temp.value)+ ' '
temp=temp.next
return ('Head:{}\nTail:{}\nList:{}'.format(self.head,self.tail,out))
__repr__=__str__
def add(self, value):
tmp=None
if isinstance(value, Node):tmp=value
else:tmp=Node(value)
if not self.head:self.head=tmp
else:
node=self.head
while node.next:node=node.next
node.next=tmp
if self.head is None:return
curr=self.head.next
while curr!=None:
curr_next, ptr=curr.value, self.head
while ptr!=curr and ptr.value<=curr_next:ptr=ptr.next
while ptr!=curr:
curr_next,ptr.value=ptr.value,curr_next
ptr=ptr.next
curr.value=curr_next
curr=curr.next
self.tail=tmp
def pop(self):
if self.head==None:return 'List is empty'
tmp=self.head
if tmp.next==None:
n=tmp.value
self.head,self.tail=None
return n
while tmp.next.next!=None:
tmp=tmp.next
self.tail=tmp
n=tmp.next.value
tmp.next=None
return n
def isEmpty(self):
return (self.head==None)
def size(self):
if self.head==None:return 0
count, curr=1, self.head
while curr!=self.tail:
count+=1
curr=curr.next
return count
#############################
# #
# test cases, do not copy #
# #
#############################
x=OrderedLinkedList()
print(x.size())
print(x.isEmpty())
print(x.pop())
#x.isEmpty()
x.add(7)
x.add(-11)
x.add(9)
x.add(1)
x.add(-1000)
print(x)
print(x.isEmpty())
print(x.size())
|
1bc83d914187103ec00d3e15a9e1113fd91ddc64 | xuyanlinux/code | /module04/chapter01/09线程的互斥锁.py | 789 | 3.515625 | 4 | #Author:Timmy
from threading import Thread
import time
n = 100
def task():
global n
num = n
time.sleep(0.1)
n = num - 1
if __name__ == '__main__':
t_l = []
for i in range(100):
t = Thread(target=task)
t_l.append(t)
t.start()
print(len(t_l))
for t in t_l:
t.join()
print('主',n)
# from threading import Thread,Lock
# import time
#
# n = 100
# def task(lock):
# global n
# lock.acquire()
# num = n
# time.sleep(0.1)
# n = num - 1
# lock.release()
#
# if __name__ == '__main__':
# lock = Lock()
# t_l = []
# for i in range(100):
# t = Thread(target=task,args=(lock,))
# t_l.append(t)
# t.start()
#
# for t in t_l:
# t.join()
# print('主',n)
|
8d52912d9fe99cf044f9e24063faaa284f34d7d1 | alanaalfeche/ml-sandbox | /kaggle/data_cleaning/scaling_and_normalization.py | 2,995 | 3.78125 | 4 | # # Get our environment set up
# To practice scaling and normalization, we're going to use a [dataset of Kickstarter campaigns](https://www.kaggle.com/kemical/kickstarter-projects).
import pandas as pd
import numpy as np
# for Box-Cox Transformation
from scipy import stats
# for min_max scaling
from mlxtend.preprocessing import minmax_scaling
# plotting modules
import seaborn as sns
import matplotlib.pyplot as plt
# read in all our data
kickstarters_2017 = pd.read_csv("../input/kickstarter-projects/ks-projects-201801.csv")
np.random.seed(0)
# # 1) Scaling - Change the range of data so that it fits within a specific scale e.g. 0-100, 0-1
# Let's start by scaling the goals of each campaign, which is how much money they were asking for.
# select the usd_goal_real column
original_data = pd.DataFrame(kickstarters_2017.usd_goal_real)
# scale the goals from 0 to 1
scaled_data = minmax_scaling(original_data, columns=['usd_goal_real'])
# plot the original & scaled data together to compare
fig, ax=plt.subplots(1,2,figsize=(15,3))
sns.distplot(kickstarters_2017.usd_goal_real, ax=ax[0])
ax[0].set_title("Original Data")
sns.distplot(scaled_data, ax=ax[1])
ax[1].set_title("Scaled data")
# After scaling, all values lie between 0 and 1 (you can read this in the horizontal axis of the second plot above, and we verify in the code cell below).
print('Original data\nPreview:\n', original_data.head())
print('Minimum value:', float(original_data.min()),
'\nMaximum value:', float(original_data.max()))
print('_'*30)
print('\nScaled data\nPreview:\n', scaled_data.head())
print('Minimum value:', float(scaled_data.min()),
'\nMaximum value:', float(scaled_data.max()))
# # 2) Normalization - Change the shape of the distribution of your data to be more like of a normal 'gaussian' distribution
# Now you'll practice normalization. We begin by normalizing the amount of money pledged to each campaign.
# get the index of all positive pledges (Box-Cox only takes positive values)
index_of_positive_pledges = kickstarters_2017.usd_pledged_real > 0
# get only positive pledges (using their indexes)
positive_pledges = kickstarters_2017.usd_pledged_real.loc[index_of_positive_pledges]
# normalize the pledges (w/ Box-Cox)
normalized_pledges = pd.Series(stats.boxcox(positive_pledges)[0],
name='usd_pledged_real', index=positive_pledges.index)
# plot both together to compare
fig, ax=plt.subplots(1,2,figsize=(15,3))
sns.distplot(positive_pledges, ax=ax[0])
ax[0].set_title("Original Data")
sns.distplot(normalized_pledges, ax=ax[1])
ax[1].set_title("Normalized data")
print('Original data\nPreview:\n', positive_pledges.head())
print('Minimum value:', float(positive_pledges.min()),
'\nMaximum value:', float(positive_pledges.max()))
print('_'*30)
print('\nNormalized data\nPreview:\n', normalized_pledges.head())
print('Minimum value:', float(normalized_pledges.min()),
'\nMaximum value:', float(normalized_pledges.max())) |
0453665d8a19a952cc781c8bbdfbc3b621236cb6 | InimigoMortal/Casino | /Casino2.py | 3,201 | 3.640625 | 4 | import tkinter as tk
from random import *
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.msg = tk.Label(self,text="Quantidade de dinheiro apostado:")
self.msg.pack()
self.en = tk.Entry(self)
self.en.pack()
self.banco = float(500)
self.valban = tk.Label(self,text="Saldo: " + str(self.banco), bg = "green")
self.valban.pack()
self.lb = tk.Label(self,text="O dado vai cair em um valor maior ou menor que 3?")
self.lb2 = tk.Label(self,text="")
self.bmaior = tk.Button(self,text = "Maior", command = self.jogaDadoMaior)
self.bmenor = tk.Button(self,text = "Menor", command = self.jogaDadoMenor)
self.lb.pack()
self.bmaior.pack()
self.bmenor.pack()
self.lb2.pack()
def jogaDadoMaior(self):
self.valorap = self.en.get()
if float(self.valorap) > self.banco:
if self.banco == 0:
self.gameOver()
else:
self.lb2['text'] = "Aposta maior do que Saldo!"
else:
self.numero = randint(1,6)
if self.numero > 3:
self.lb2['text'] = "Caiu: " + str(self.numero) + "\n Você Ganhou!"
self.banco += float(self.valorap)*2
self.valban['text'] = str(self.banco)
if self.numero < 3 :
self.lb2['text'] = "Caiu: " + str(self.numero) + "\n Você Perdeu!"
self.banco -= float(self.valorap)
self.valban['text'] = str(self.banco)
if self.numero == 3:
self.lb2['text'] = "Caiu: " + str(self.numero) + "\n Empate!"
def jogaDadoMenor(self):
self.valorap = self.en.get()
if float(self.valorap) > self.banco:
if self.banco == 0:
self.gameOver()
else:
self.lb2['text'] = "Aposta maior do que Saldo!"
else:
self.numero = randint(1,6)
if self.numero < 3:
self.lb2['text'] = "Caiu: " + str(self.numero) + "\n Você Ganhou!"
self.banco += float(self.valorap)*2
self.valban['text'] = str(self.banco)
if self.numero > 3:
self.lb2['text'] = "Caiu: " + str(self.numero) + "\n Você Perdeu!"
self.banco -= float(self.valorap)
self.valban['text'] = str(self.banco)
if self.numero == 3:
self.lb2['text'] = "Caiu: " + str(self.numero) + "\n Empate!"
def gameOver(self):
self.msg.pack_forget()
self.lb.pack_forget()
self.en.pack_forget()
self.valban.pack_forget()
self.lb.pack_forget()
self.bmaior.pack_forget()
self.bmenor.pack_forget()
self.lb2['text'] = "Você perdeu todo o seu dinheiro e foi expulso do Casino!"
casino2 = App()
casino2.geometry("350x200")
casino2.title("Casino")
casino2.mainloop()
|
b44b7669d5697f2dda9fa909ba4104929aeff70d | liliancor/cursoemvideo | /desafio08.1aula07.py | 159 | 3.734375 | 4 | m = float(input('metragem: '))
print('O valor de {}m corresponde a {}km, {}hm, {}dam, {}dm, {}cm e {}mm.'.format(m, m/1000, m/100, m/10, m*10, m*100, m*1000)) |
dfa5055c60f77e2d511af6da21e4ed07ae48bfd5 | xxw1122/Leetcode | /Python/Linked-List-Cycle-II.py | 621 | 3.65625 | 4 | #!/usr/bin/env python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
if head == None:
return None
node1 = head
node2 = head
while node1 != None:
node2 = node2.next
node1 = node1.next
if node1 == None:
return None
node1 = node1.next
if node2 == node1:
break
if node1 == None:
return None
node2 = head
while node2 != node1:
node1 = node1.next
node2 = node2.next
return node2 |
0cb61163cd2888fa76f8fb2c4671da98b85f89cc | yubanUpreti/IWAcademy_PythonAssignment | /Python Assignment/Data Types/question29.py | 173 | 3.6875 | 4 | dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
for key,value in dic2.items():
dic1[key]=value
for key,value in dic3.items():
dic1[key]=value
print(dic1) |
0b0e7597bc21a71b267b2426225bd341cf6fc35f | Kayransteelink/F1M1PYT | /ditbenik3.py | 533 | 3.953125 | 4 | import datetime
print('hallo!')
print('ik ben kayran')
naam = input('')
print(f"hallo {naam}")
print(f"datum en tijd is {datetime.datetime.today()}")
print(f"{naam} wil jij dit programma nog een keer doen?\nType Y/N")
option = input ('')
if option.lower() == 'yes':
print("wil je hem im stukjes?")
else:
print("fout")
if option.lower() == 'ja':
print("zit je in klas sd1d?")
else:
print("fout")
if option.lower() == 'y':
print("ben ik een mens?")
else:
print("fout")
|
afcc520df8830d7804404e90fe4a34540d6d5dcc | VenkataChadalawada/Machine-Learning | /Apriori_Python/apriori_mine.py | 1,488 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 7 17:39:50 2018
@author: vchadalawada
"""
# we are going to use apyori.py in the same directory which we got from python community
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing the dataset
dataset = pd.read_csv('Market_Basket_Optimisation.csv', header = None) #header none as by default pandas makes first line as header but here we dont have any header in data file
#apriori expection a list of lists eg - a list of transaction lists
#transform the dataset
transactions = []
# we need to travers all the rows
for i in range(0, 7501):
transactions.append([str(dataset.values[i, j]) for j in range(0, 20)])
#training Apriori on the dataset
from apyori import apriori
rules = apriori(transactions, min_support=0.003, min_confidence=0.2, min_lift = 3, min_length=2) #min_length helps to tell algorithm that it should take minimum 2 transactions in basket to be considered
# how to compute support , confidence, lift?
# let say you wanna fix with an idea that if an apple purchased 3 times a day which is 7*3 = 21 times a week
# now support would be on our weekly data set = 21/7500 = 0.0028 =~0.003
# similarly 0.2 is a good confidence percentage
#Visualising the results
results = list(rules)
results_list = []
for i in range(0, len(results)):
results_list.append('RULE:\t' + str(results[i][0]) + '\nSUPPORT:\t' + str(results[i][1]))
# these rules are sorted |
9726c0156515cc567a57aa75647ed990f339bb09 | rbangamm/algos | /dcp254.py | 1,068 | 3.90625 | 4 | def prune(node):
if node.left is None and node.right is None:
return node
if node.left is not None and node.right is not None:
node.left = prune(node.left)
node.right = prune(node.right)
return node
if node.right is None:
return prune(node.left)
if node.left is None:
return prune(node.right)
class Node():
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
def in_order(node):
if node is None:
return
in_order(node.left)
print(node.val)
in_order(node.right)
return
n = Node(0,
Node(1,
Node(3,
None,
Node(5,
None,
None)),
None),
Node(2,
None,
Node(4,
Node(6,
None,
None),
Node(7,
None,
None))))
in_order(n)
print("\n")
n = prune(n)
in_order(n)
|
36f3f34cb2a65f30750fe0cc99eec96e975f57f4 | amandabrosseau/planets | /planets.py | 1,156 | 4.125 | 4 | #!/usr/bin/env python3
worlds = { "mercury" : "burning",
"venus" : "greenhousy",
"earth" : "comfy",
"mars" : "ruddy",
"jupiter" : "biggly",
"saturn" : "ringy",
"neptune" : "bluey",
"uranus" : "buttly",
"pluto" : "NOT A PLANET", }
def solar_sys_info():
""" Instructional function that takes input from the user and prints
information to the screen about the corresponding planet.
Args: none
Returns: none """
print("\nHello, it is time to learn about the planets!")
while True :
planet = input("What planet would you like to learn about?\n Enter Q to quit\n").lower()
if planet == "q" :
print("No more learning today...")
break
else :
try :
print("The planet {0}, is {1}!\n".format(planet, worlds[planet]))
except KeyError :
print("This isn't grade school, I know that's not a planet!\n")
except :
print("No idea what went wrong here...")
if __name__ == '__main__':
solar_sys_info() |
9843995d491549aaf05cbc767d4616aea48b05eb | brynelee/gk_dataanalysis_practices | /dataminingDemo1/xdtools.py | 214 | 3.5 | 4 | def print_line(char,times):
print(char * times)
def print_one_line():
print_line('*', 50)
def print_lines():
row = 0
while row < 5:
print_line("*",50)
row += 1
print_lines()
|
f8316ffaf8958285dbdbcce324f6e9a6b4b539cb | dylanplayer/ACS-1100 | /lesson-8/example-1.py | 669 | 4.125 | 4 | '''
Let's practice using .read()!
.read() reads the entire file.
If want it to read a number of characters, pass the number (int) between the parentheses.
'''
# STEP 1: Store file name in a variable
input_file_name = 'languages.txt'
# STEP 2: Open the file in read mode ('r')
infile = open(input_file_name, "r")
# STEP 3:
# Example: Using .read() read the first 100 characters of the file and print results
read_data = infile.read(5) # Read a number of characters
print(read_data)
entire_file = infile.read(3) # Remove the number to read the entire file
print(entire_file)
# STEP 4: Close the file (We will learn about this the next few slides!)
infile.close() |
4b36dbeec9ce211536bc602a56613b0b7402a7ad | nicoglennon/project-euler | /problem-1.py | 367 | 4.0625 | 4 | # Problem 1: Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
# my solution:
i = 1
sum = 0
while i < 1000:
if (i % 3 == 0) or (i % 5 == 0):
sum = sum + i
i = i + 1
print(sum) # 233168
|
b032b929a6b2b37e6c254dad6db7665980b11c5f | hlissner/practice | /codeeval/hard/014stringpermutations/solution.py | 459 | 3.71875 | 4 | #!/usr/bin/env python
from sys import argv
def permutations(word):
if len(word) == 1:
return [word]
first = word[0]
perms = permutations(word[1:])
result = []
for perm in perms:
for i in range(len(perm)+1):
result.append(perm[:i] + first + perm[i:])
return result
for line in open(argv[1], 'r'):
line = line.strip()
if line == "":
continue
print(",".join(sorted(permutations(line))))
|
21c0978fc961abe52c49ac489715a591a0259427 | wsims/CS434 | /src/assignment_3/mlp_relu.py | 2,987 | 4.09375 | 4 | """Use this to complete part 2
Usage:
$ python mlp_relu.py
Trains a three layer neural network using the relu function as the
activation function. Trains on four different learning rates
(0.1, 0.01, 0.001, 0.0001) and plots the results. Finally,
performs a classifier test on the testing data set from CIFAR10
and prints the results.
"""
import mlp
#import matplotlib.pyplot as plt
EPOCHS = 100
if __name__ == '__main__':
train_loader = mlp.get_cifar10_data(train=True)
validation_loader = mlp.get_cifar10_data(train=False)
test_loader = mlp.get_cifar10_test_data()
# training and validation
train_loss1, accv1, model1 = mlp.relu_NN_train_and_val(train_loader, validation_loader,
lr=0.1, epochs=EPOCHS)
train_loss2, accv2, model2 = mlp.relu_NN_train_and_val(train_loader, validation_loader,
lr=0.01, epochs=EPOCHS)
train_loss3, accv3, model3 = mlp.relu_NN_train_and_val(train_loader, validation_loader,
lr=0.001, epochs=EPOCHS)
train_loss4, accv4, model4 = mlp.relu_NN_train_and_val(train_loader, validation_loader,
lr=0.0001, epochs=EPOCHS)
epochs = range(1, EPOCHS + 1)
# Training loss plot
#plt.figure(1)
#plt.plot(epochs, train_loss1, '-b', label='lr=0.1')
#plt.plot(epochs, train_loss2, '-r', label='lr=0.01')
#plt.plot(epochs, train_loss3, '-g', label='lr=0.001')
#plt.plot(epochs, train_loss4, '-p', label='lr=0.0001')
#plt.legend(loc='lower right')
#plt.xlabel('Number of epochs')
#plt.ylabel('Average loss')
#plt.title('Negative Log Loss on Training Data as a Function of Epochs')
#plt.savefig("relu_training_loss.png")
#print 'Plot saved as "relu_training_loss.png"'
# Validation accuracy plot
#plt.figure(2)
#plt.plot(epochs, accv1, '-b', label='lr=0.1')
#plt.plot(epochs, accv2, '-r', label='lr=0.01')
#plt.plot(epochs, accv3, '-g', label='lr=0.001')
#plt.plot(epochs, accv4, '-p', label='lr=0.0001')
#plt.legend(loc='lower right')
#plt.xlabel('Number of epochs')
#plt.ylabel('Accuracy')
#plt.title('Classifier Accuracy on Validation Data as a Function of Epochs')
#plt.savefig("relu_accuracy.png")
#print 'Plot saved as "relu_accuracy.png"'
# Determine which model is best and then perform validation on test data
modelv = [model1, model2, model3, model4]
model_accuracy = [accv1[EPOCHS-1], accv2[EPOCHS-1], accv3[EPOCHS-1], accv4[EPOCHS-1]]
model_index = model_accuracy.index(max(model_accuracy))
best_model = modelv[model_index]
print("\nBest model -- Learning rate of %f" % (10**(-1*(model_index + 1))))
print("Results of validation on testing set:")
lossv, accv = [], []
mlp.validate(lossv, accv, best_model, test_loader)
|
70b8cc0039e61655f3b38eb26a141e7b359f7c79 | rudzy123-zz/Py2 | /A11.py | 2,314 | 4 | 4 | #Rudolf Musika
#CIS 1400
#Chapter 11 Assignment
ConstantMealPlan1 = 560.00
ConstantMealPlan2 = 900.00
ConstantMealPlan3 = 1300.00
def main():
while True:
displayMenu()
if menuSelectedNumber ==1:
calcNumberOfSemesterTot()
if menuSelectedNumber ==2:
calcNumberOfSemesterTot()
if menuSelectedNumber==3:
calcNumberOfSemesterTot()
if menuSelectedNumber ==4:
print("Goodbye!")
break;
# displayMenu Calls the menu on which the user will read the instructions
def displayMenu():
print('COLLEGE OF DUPAGE MENU PLAN OPTIONS')
print('1. One-Meal-A-Day Plan -7 meals per week for $560.00 ')
print('2. Two-Meal-A-Day -14 meals per week for $900.00')
print('3. Unlimited-Meals-A-Day Plan - $1300.00')
print('4. END THE PROGRAM')
global menuSelectedNumber
menuSelectedNumber = int(input("Enter Your Selection: "))
# Input Validation loop
while menuSelectedNumber <1 or menuSelectedNumber > 4:
print ("That is an invalid selection")
menuSelectedNumber = int(input("Enter 1,2, 3 or 4: "))
#calcNumberOfSemesterTot is the module that calculates the total price for the semesters also as specified by user
def calcNumberOfSemesterTot():
semesterCount = float(input("Enter the number of semesters -1 or 2: "))
# Input Validation loop
while semesterCount<1 or semesterCount>2:
print("It is up to only 2 semesters per year, so please enter either 1 or 2, ")
semesterCount = float(input("Enter the number of semesters -1 or 2: "))
while True:
if menuSelectedNumber == 1:
totalPrice = semesterCount*ConstantMealPlan1
print("The total price of one meal a day for "+str(semesterCount)+"semesters is $ ",format(totalPrice,".0f"),"\n")
if menuSelectedNumber == 2:
totalPrice = semesterCount*ConstantMealPlan2
print("The total price of two meals a day for "+str(semesterCount)+"semesters is $ ",format(totalPrice,".0f"),"\n")
if menuSelectedNumber == 3:
totalPrice = semesterCount*ConstantMealPlan3
print("Unlimited total price for "+str(semesterCount)+"semesters is $ ",format(totalPrice,".0f"),"\n")
break;
main()
|
c2357a66972665c4c40431bbd189bf150a811c62 | cbass2404/bottega_homework | /day08/string_index.py | 170 | 3.953125 | 4 | sentence = 'The quick brown fox jumps over the lazy dog'
# sentence = 'T'
if len(sentence) < 2:
print('Empty String')
else:
print(sentence[0:2] + sentence[-2:]) |
16c3986a4505e8b657f12b80991c3317e79906fb | UnixLoverSaurabh/AssistantYui | /tasks/2048/2048.py | 4,349 | 3.859375 | 4 | import random
import single_input
class Board(object):
def __init__(self, size):
self.size = size
self.board = [[0] * self.size for i in range (self.size)]
self.empty_cell = []
def update_empty_cell(self):
self.empty_cell[:] = []
for i in range (self.size):
for j in range (self.size):
if self.board[i][j] == 0:
self.empty_cell.append((i, j))
return len(self.empty_cell)
def generate_random(self):
if self.update_empty_cell():
random.seed(None)
index = random.randrange(len(self.empty_cell))
value = random.randrange(1, 3) * 2
x, y = self.empty_cell[index]
self.board[x][y] = value
return True
return False
def print_board(self):
for row in range (self.size):
for col in range(self.size):
print self.board[row][col],
print
print
class Game(object):
def __init__(self, name, board):
self.score = 0
self.name = name
self.board = board
self.size = self.board.size
def handle_up_util(self):
for col in range (self.size):
for row in range(self.size):
temp = row
while (self.board.board[temp][col] != 0) and \
(temp - 1 >= 0) and (self.board.board[temp - 1][col] == 0):
self.board.board[temp - 1][col] = self.board.board[temp][col]
self.board.board[temp][col] = 0
temp -= 1
def handle_up(self):
self.handle_up_util()
for col in range (self.size):
for row in range(self.size):
if (self.board.board[row][col] != 0) and \
(row - 1 >= 0) and (self.board.board[row][col] ==\
self.board.board[row - 1][col]):
self.board.board[row - 1][col] *= 2
self.board.board[row][col] = 0
self.handle_up_util()
def handle_left_util(self):
for row in range (self.size):
for col in range(self.size):
temp = col
while (self.board.board[row][temp] != 0) and \
(temp - 1 >= 0) and (self.board.board[row][temp - 1] == 0):
self.board.board[row][temp - 1] = self.board.board[row][temp]
self.board.board[row][temp] = 0
temp -= 1
def handle_left(self):
self.handle_left_util()
for row in range (self.size):
for col in range(self.size):
if (self.board.board[row][col] != 0) and \
(col - 1 >= 0) and (self.board.board[row][col] ==\
self.board.board[row][col - 1]):
self.board.board[row][col - 1] *= 2
self.board.board[row][col] = 0
self.handle_left_util()
def handle_down_util(self):
for col in range (self.size):
for row in xrange(self.size - 1, -1, -1):
temp = row
while (self.board.board[temp][col] != 0) and \
(temp + 1 < self.size) and (self.board.board[temp + 1][col] == 0):
self.board.board[temp + 1][col] = self.board.board[temp][col]
self.board.board[temp][col] = 0
temp += 1
def handle_down(self):
self.handle_down_util()
for col in range (self.size):
for row in xrange(self.size - 1, -1, -1):
if (self.board.board[row][col] != 0) and \
(row + 1 < self.size) and (self.board.board[row][col] ==\
self.board.board[row + 1][col]):
self.board.board[row + 1][col] *= 2
self.board.board[row][col] = 0
self.handle_down_util()
def handle_right_util(self):
for row in range (self.size):
for col in xrange(self.size - 1, -1, -1):
temp = col
while (self.board.board[row][temp] != 0) and \
(temp + 1 < self.size) and (self.board.board[row][temp + 1] == 0):
self.board.board[row][temp + 1] = self.board.board[row][temp]
self.board.board[row][temp] = 0
temp += 1
def handle_right(self):
self.handle_right_util()
for row in range (self.size):
for col in xrange(self.size - 1, -1, -1):
if (self.board.board[row][col] != 0) and \
(col + 1 < self.size) and (self.board.board[row][col] ==\
self.board.board[row][col + 1]):
self.board.board[row][col + 1] *= 2
self.board.board[row][col] = 0
self.handle_right_util()
def handle_move(self, move):
if move == 'w':
self.handle_up()
elif move == 'a':
self.handle_left()
elif move == 's':
self.handle_down()
elif move == 'd':
self.handle_right()
elif move == 'q':
exit(0)
else:
print "Invalid move! Try again"
def play(self):
while self.board.generate_random():
self.board.print_board()
self.handle_move(single_input.getch())
print "Game Over"
board = Board(4)
game = Game("Prakhar", board)
game.play() |
99fd98d9c1165ebec531b144afedb9942a5502be | MSDubey25/Python-Programs | /Python_Progs/DictionaryPython.py | 842 | 4.21875 | 4 | print("Accessing elements from a Dictionary")
dict1={1:1,2:2,3:3}
print(dict1)
print(dict1[1])
print(dict1.get(6))
print("adding a value")
dict1[4]="Namaste"
print(dict1)
print("creating dictionary of squares")
squares={1:1,2:4,3:9,4:16,5:25}
print(squares)
print("removing a particular item :25")
print(squares.pop(5))
print(squares)
print("removing arbitary item")
print(squares.popitem())
print(squares)
del squares
print("creating a new dictionary using comprehension")
squares={x:x*x for x in range (7)}
print(squares)
print("There is a membership test but they are only for keys not values")
print("iterating through a dictionary using- for")
for i in squares:
print(squares[i])
print("built in functions")
print("len() and sorted")
print(len(squares))
print("sorted() will sort the keys in order")
print(sorted(squares))
|
81447881ee0e3dd76ed4e5efd2369a7a735efab5 | akshatakulkarni98/ProblemSolving | /DataStructures/stacks/remove_adjacent_dups.py | 625 | 3.59375 | 4 | # https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string
#TC:O(N)
#SC:O(N-D)D=duplicates
class Solution:
def stack_helper(self, S):
stack=list()
for i in range(len(S)):
ch=S[i]
if not stack:
stack.append(ch)
else:
if ch==stack[-1]:
stack.pop()
else:
stack.append(ch)
return ''.join(stack)
def removeDuplicates(self, S: str) -> str:
if not S:
return S
return self.stack_helper(S)
|
2357cd42f5eacbc449c3410adb17b18016167afa | kriti-ixix/ml830 | /python/dictionary hw.py | 452 | 3.921875 | 4 | students = []
keys = ['Name', 'Roll No', 'Marks', 'Percentage']
for i in range(3):
studentDict = {}
for key in keys:
if key == 'Name':
studentDict[key] = input("Enter your " + key + ": ")
elif key == 'Percentage':
studentDict[key] = (studentDict['Marks'] * 100) / 50
else:
studentDict[key] = int(input("Enter your " + key + ": "))
students.append(studentDict)
print(students)
|
254977ce67f3fd6df19edc592334e5cf893c7015 | jmorgancusick/micheals-project | /calculator.py | 551 | 4.09375 | 4 | print 'Welcome to my calculator!'
x = raw_input('Enter your first number: ')
y = raw_input('Enter your second number: ')
operation = raw_input('Enter your operation (+-*/): ')
answer = 0
if operation == '+':
answer = float(x) + float(y)
elif operation == '-':
answer = float(x) - float(y)
elif operation == '/':
answer = float(x) / float(y)
elif operation == '*':
answer = float(x) * float(y)
else:
print "invalid operation"
int_answer = answer - int(answer)
if int_answer == 0:
print int(answer)
else:
print float(answer)
|
0c5c6f5374ca68d35a13bac473ae09925eb17d5a | nguyentrantrung986/python | /pythonLearnToProgram/test_palindrome.py | 1,910 | 3.734375 | 4 | import unittest
import palindrome_v3
class TestPalindrome(unittest.TestCase):
def test_palindrome_1(self):
"""Test is_palindrome with an empty string ''"""
actual = palindrome_v3.is_palindrome_v3('')
expected = True
self.assertEqual(actual,expected)
def test_palindrome_2(self):
"""Test is_palindrome with a string of length 1"""
actual = palindrome_v3.is_palindrome_v3('a')
expected = True
self.assertEqual(actual,expected)
def test_palindrome_3(self):
"""Test is_palindrome_v3 with a string of length 2"""
actual = palindrome_v3.is_palindrome_v3('ab')
expected = False
self.assertEqual(actual,expected)
def test_palindrome_4(self):
"""Test is_palindrome_v3 with a string of length 2"""
actual = palindrome_v3.is_palindrome_v3('11')
expected = True
self.assertEqual(actual,expected)
def test_palindrome_5(self):
"""Test is_palindrome_v3 with a string of odd length > 2"""
actual = palindrome_v3.is_palindrome_v3('ad1')
expected = False
self.assertEqual(actual,expected)
def test_palindrome_6(self):
"""Test is_palindrome_v3 with a string of odd length > 2"""
actual = palindrome_v3.is_palindrome_v3('racecar')
expected = True
self.assertEqual(actual,expected)
def test_palindrome_7(self):
"""Test is_palindrome_v3 with a string of even length > 2"""
actual = palindrome_v3.is_palindrome_v3('pendent')
expected = False
self.assertEqual(actual,expected)
def test_palindrome_8(self):
"""Test is_palindrome_v3 with a string of even length > 2"""
actual = palindrome_v3.is_palindrome_v3('HannaH')
expected = True
self.assertEqual(actual,expected)
if __name__ == '__main__':
unittest.main(exit=False)
|
4d4e8d75d7a21560c19ff350e441a2834c64871c | alinemitri/Python_para_zumbis | /Lista_II/L2E4.py | 290 | 3.921875 | 4 | n1 = float (input ('Digite o primeiro valor: '))
n2 = float (input ('Digite o segundo valor: '))
n3 = float (input ('Digite o terceiro valor: '))
if n1 > n2 and n1 > n3 :
print ('%f é o maior' %n1)
elif n2 > n3 :
print ('%f é o maior' %n2)
else :
print ('%f é o maior' %n3)
|
40779b8cb5b68d58d1894cc85d1edfd97e661a68 | jim1949/car_controller | /src/kalman_1D.py | 2,415 | 3.921875 | 4 | # Kalman filter example demo in Python
# A Python implementation of the example given in pages 11-15 of "An
# Introduction to the Kalman Filter" by Greg Welch and Gary Bishop,
# University of North Carolina at Chapel Hill, Department of Computer
# Science, TR 95-041,
# http://www.cs.unc.edu/~welch/kalman/kalmanIntro.html
# by Andrew D. Straw
import numpy as np
import matplotlib.pyplot as plt
pose = np.loadtxt("/Users/jj/car_controller_ws/src/car_controller/src/data/test2/people_position.dat")
# N = 20
# true_x = np.linspace(0.0, 10.0, N)
# true_y = true_x**3
# print(pose)
# observed_x = true_x + 0.05*np.random.random(N)*true_x
# observed_y = true_y + 0.05*np.random.random(N)*true_y
true_x=[]
true_y=[]
observed_x=[]
observed_y=[]
for i in range(len(pose)):
# print(i)
true_x.append(pose[i-1][2])
true_y.append(pose[i-1][3]-5)
observed_x.append(pose[i-1][0])
observed_y.append(pose[i-1][1])
plt.rcParams['figure.figsize'] = (10, 8)
# intial parameters
n_iter = len(true_x)
sz = (n_iter,) # size of array
x = np.array(true_x) # truth value (typo in example at top of p. 13 calls this z)
z = observed_x # observations (normal about x, sigma=0.1)
Q = 1e-5 # process variance
# allocate space for arrays
xhat=np.zeros(sz) # a posteri estimate of x
P=np.zeros(sz) # a posteri error estimate
xhatminus=np.zeros(sz) # a priori estimate of x
Pminus=np.zeros(sz) # a priori error estimate
K=np.zeros(sz) # gain or blending factor
R = 0.1**2 # estimate of measurement variance, change to see effect
# intial guesses
xhat[0] = 0.0
P[0] = 1.0
for k in range(1,n_iter):
# time update
xhatminus[k] = xhat[k-1]
Pminus[k] = P[k-1]+Q
# measurement update
K[k] = Pminus[k]/( Pminus[k]+R )
xhat[k] = xhatminus[k]+K[k]*(z[k]-xhatminus[k])
P[k] = (1-K[k])*Pminus[k]
plt.figure()
plt.plot(z,'k+',label='noisy measurements')
plt.plot(xhat,'b-',label='a posteri estimate')
plt.plot(x,color='g',label='truth value')
plt.legend()
plt.title('Estimate vs. iteration step', fontweight='bold')
plt.xlabel('Iteration')
plt.ylabel('x axis')
plt.figure()
valid_iter = range(1,n_iter) # Pminus not valid at step 0
plt.plot(valid_iter,Pminus[valid_iter],label='a priori error estimate')
plt.title('Estimated $\it{\mathbf{a \ priori}}$ error vs. iteration step', fontweight='bold')
plt.xlabel('Iteration')
plt.ylabel('x axis')
plt.setp(plt.gca(),'ylim',[0,.01])
plt.show() |
aa98aab4fa9a956c0abc16bb4c7036dcaff7528d | caoxiang104/Practical_Python | /ins_sort.py | 320 | 3.65625 | 4 | # O(n^2)
def ins_sort(seq):
for i in range(1, len(seq)):
j = i
while j > 0 and seq[j] < seq[j - 1]:
seq[j], seq[j - 1] = seq[j - 1], seq[j]
j -= 1
def main():
seq = [1, 5, 3, 4, 6, 2]
ins_sort(seq)
print("".join(str(seq)))
if __name__ == '__main__':
main() |
e212ea22916e688fde81bcdc65f16d7d3382d727 | sbhavisha/As_Practical | /pra33.py | 673 | 4.21875 | 4 | #!/usr/bin/python
####### Code written by Shah Bhavisha ##########
####### This code is for comparing that the no is divisible by 2 and 3 ######
import sys
import math
def compare():
try:
a = raw_input("Enter an number:") ####Taking An input####
n = int(a)
print "Number:",n
while n >=0:
if n%2 == 0 and n%3 == 0:
print "BOTH"
break
elif (n%2 == 0 and n%3 != 0) or (n%2 != 0 and n%3 == 0):
print "ONE"
break
elif n%2 != 0 and n%3 !=0:
print "NEITHER"
break
else:
print "NONE"
break
print "Please enter positive number"
except ValueError:
print "Enter valid no"
def main():
compare()
if __name__ == '__main__':
main() |
9ec5a04acbbe7c60d00d927e90497f2be0e1187a | CynthiaYbz/coder-algorithm | /algorithm/strings/last_word_length.py | 279 | 4.03125 | 4 | def get_last_word_length(s: str) -> int:
result = s.rstrip()
return len(result.split(" ")[-1])
if __name__ == "__main__":
print(get_last_word_length("hello world "))
print(get_last_word_length("hello world"))
print(get_last_word_length(" hello world ")) |
b9dcb17056eb66317404d7b088bf27f2ed5ecaee | Riversubs/PythonElementaryCourses | /认识python/py_24迭代遍历.py | 212 | 3.59375 | 4 | name_list = ["czh","lhz","river","chenzhihe","subs"]
"""
顺序的从列表中依次获取数据
每次获取的数据都将保存在my_name中
"""
for my_name in name_list:
print("我的名字叫%s" % my_name) |
712e614caeb29f21b795ab8b61dc0867f610bd1f | Eric-J-G/Eric-J-G | /Chess Stuff.py | 1,565 | 3.546875 | 4 | #Permutations mapped to the board
from itertools import permutations
list = list(range(8))
perms = permutations(list)
for perm in perms:
print(perm)
table = [[0]*8 for _ in range(8)]
def print_table():
for row in range(8):
print(table[row])
def put_queen(x,y):
if table[y][x] == 0:
for m in range(8):
table[y][m] = 1
table[m][x] = 1
table[y][x] = 2
if y+m <= 7 and x+m <= 7:
table[y+m][x+m] = 1
if y-m >= 0 and x+m <= 7:
table[y-m][x+m] = 1
if y+m <= 7 and x-m >= 0:
table[y+m][x-m] = 1
if y-m >= 0 and x-m >= 0:
table[y-m][x-m] = 1
return True
else:
return False
list = list(range(8))
perms = permutations(list)
num_comb = 0
for perm in perms:
if put_queen(perm[0], 0) == True:
if put_queen(perm[1], 1) == True:
if put_queen(perm[2], 2) == True:
if put_queen(perm[3], 3) == True:
if put_queen(perm[4], 4) == True:
if put_queen(perm[5], 5) == True:
if put_queen(perm[6], 6) == True:
if put_queen(perm[7], 7) == True:
print_table()
num_comb += 1
print(f"solution{num_comb}")
print(" ")
table = [[0] * 8 for _ in range(8)] |
4f6bc663340501d5742237bdf6e1d0d20cb2171c | lihongwen1/XB1929_- | /ch02/strtoint.py | 251 | 3.640625 | 4 | no1=input("請輸入甲班全班人數:")
no2=input("請輸入乙班全班人數:")
total1=no1+no2
print(type(total1))
print("兩班總人數為%s" %total1)
total2=int(no1)+int(no2)
print(type(total2))
print("兩班總人數為%d" %total2)
|
8f867909f42278e959735c0133059efc457923b9 | x0215hui/learnpython | /openpyxlstudy.py | 5,404 | 3.671875 | 4 | '''
要使用Python对Excel表格进行读取,我们需要安装一个用于读取数据的工具 openpyxl 。openpyxl 是一个用于读、写Excel文件的开源模块。
安装openpyxl非常简单,在终端中输入代码:pip install openpyxl即可。
如果在自己电脑上安装不上或安装缓慢,可在命令后添加如下配置进行加速:
pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple/
'''
import openpyxl
# 在安装和导入openpyxl之后,读取指定路径的工作簿需要使用函数:openpyxl.load_workbook()。
# 工作簿文件的路径需要作为函数参数传入。
wb = openpyxl.load_workbook("文件路径")
# 得到了工作表名称后,我们可以通过在变量wb后添加中括号[ ]和工作表名称的方式来获得对应的工作表对象。
orderSheet = wb["工作表名称"]
# 如果事先不知道工作簿内有哪些工作表,我们可以通过访问工作簿的 .sheetnames 属性来获取一个包含所有工作表名称的列表。
# 具体操作为在变量wb之后添加代码 .sheetnames 。
# print(wb.sheetnames)
# 要获取工作表中指定的单元格对象,我们可以通过在中括号[ ]内填入列号和行号的方式去获取。
print(orderSheet["A1"]) # <Cell '工作表名称'.A1>
# 输出单元格对象并没有输出单元格内的值。要访问单元格里的值,我们可以在单元格对象后加一个 .value 。
print(orderSheet["A1"].value)
# 若单元格中包含公式,现有方式读取出的值是公式本身。若需要读取公式计算后的值,要在读取工作簿的代码部分,传入一个参数: data_only=True ,便可以得出公式计算后的值了。
wb = openpyxl.load_workbook("文件路径", data_only=True)
print(orderSheet["A1"].value)
# 要对整个工作表的每一行数据进行浏览查询,可以使用for循环对工作表对象的行属性(rows)进行遍历。具体代码为 for rowData in orderSheet.rows:
# 这样程序就会以从上到下的顺序,逐个获取到指定工作表内的每一行数据。
# 可以从运行结果中看到,读取出的每一行数据是由单元格对象组成的元组。
for rowData in orderSheet.rows:
print(rowData)
# 行遍历的输出结果,是由单元格对象组成的元组。在元组中要定位到具体的列需要用索引。
productName = rowData[2].value
print(productName)
# 如果要定位的列数字比较大,比如在第I列,通过肉眼观察来确定索引略显繁琐。这时,可以使用函数:openpyxl.utils.cell.column_index_from_string(),来获取列号对应的数字,比如传入参数“E”就会获取到数字5,表示“E”列是第5列。这个数字减一即可得到对应的索引。
priceIndex = openpyxl.utils.cell.column_index_from_string("I") - 1
price = rowData[priceIndex].value
print(price)
"""
对于重复的取表,可以采用定义函数的方法,将上述内容打包为函数。
"""
# 将计算单月销售额的步骤移到函数getMonthlySold中
# 获取单月“火龙果可乐”销售额的函数
# 参数 filePath: 销售数据Excel文件路径
# 返回值: 计算出的销售额结果
def getMonthlySold(filePath):
# 使用openpyxl.load_workbook()函数读取工作簿
# 文件路径使用函数参数filePath,然后赋值给变量wb
# 添加data_only=True打开工作簿,获取公式计算后的值
wb = openpyxl.load_workbook(filePath, data_only = True)
# 通过工作簿对象wb获取名为“销售订单数据”的工作表对象,并赋值给变量orderSheet
orderSheet = wb["销售订单数据"]
# 定义一个变量colaSold用来表示本月“火龙果可乐”的销售金额
colaSold = 0
# 遍历工作表的所有行数据
for rowData in orderSheet.rows:
productName = rowData[2].value
priceIndex = openpyxl.utils.cell.column_index_from_string("I") - 1
price = rowData[priceIndex].value
if productName == "目标":
colaSold = colaSold + price
return colaSold
# 接下来,通过观察销售订单的Excel文件名,我们可以发现,每个文件名仅有月份数字不同。
# 因此,我们可以很方便的使用for循环加range()函数,配合上格式化字符串,来批量生成每个Excel表格的文件路径:2019年{month}月销售订单.xlsx。
# 再把这个文件路径传入到getMonthlySold函数中,来计算各个月份的销售额。最后逐个添加到一个列表soldList中。
soldList = []
for month in range(1,13):
monthlySold = getMonthlySold(f"2019年{month}月销售订单.xlsx")
soldList.append(monthlySold)
print(soldList)
# 要获取一个列表中的最大值,可以使用Python内置的max()函数。
maxSold = max(soldList)
print(maxSold)
# 当我们知道了列表中的一个元素,想要去列表中找到这个元素位于什么位置,可以使用列表的index()函数。
# 通过要查询的列表对象使用index()函数,将要查询的元素作为参数传入,则该元素从左往右第一次出现的索引将会被返回。
# 如果查询的元素不在列表中,会报一个ValueError的错误。
maxMonth = soldList.index(maxSold) + 1
print(f"火龙果可乐在{maxMonth}月份卖得最好") |
8b4e4066d54d94f63d324415fd65e356be989ac7 | VaibhavSi47/CB | /covid_bot_test4/text_to_speech.py | 688 | 3.515625 | 4 | # import the required module for text to speech recognition
import os
import subprocess
from gtts import gTTS
# The text that you want to convert to audio
mytext = "Welcome to Covid-19 Fighting bot!"
# language in which you want to convert
language = 'en'
# Passing the text and language to the engine,
# here we have marked slow=False. which tells
# the module that the converted audio should
# have a high speed
myobj = gTTS(text=mytext, lang=language)
# Saving the converted audio in a mp3 file named "welcome.mp3"
myobj.save("welcome.mp3")
# playing the converted file
#subprocess.call(['MPyg321', "welcome.mp3", '--play-and-exit'], shell = True)
os.system("start welcome.mp3")
|
b132edf3ca3db843191f6c40d5939df7f4c0e5db | pettybai/my_practice | /function/closure.py | 897 | 4.25 | 4 | # 一个函数返回了一个内部函数,该内部函数引用了外部函数的相关参数和变量,我们把该返回的内部函数称为闭包(Closure)
def make_pow(n):
def inner(x):
return pow(x, n)
return inner
a = make_pow(2)
print(a(7))
##################################################
# 闭包的最大特点就是引用了自由变量,即使生成闭包的环境已经释放,闭包仍然存在。
# 闭包在运行时可以有多个实例,即使传入的参数相同。
# 闭包实现类
class point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def get_distance(self, u, v):
return (self.x - u) ** 2 + (self.y - v) ** 2
# def point(x, y):
# def get_distance(u, v):
# return (x - u) ** 2 + (y - v) ** 2
#
# return get_distance
init_point = point(4, 4)
print(init_point.get_distance(7, 8))
|
19613f6ff6cf5ab1bf888c6b817f28c91d8e0f46 | fitzcn/oojhs-code | /functions/deck.py | 950 | 4.0625 | 4 | # coding: utf-8
import random
"""
write a function that prints a random card in the deck.
"""
def selectRandom(lst):
index = random.randint(0,51)
print lst[index]
"""
write a function that will print each card in a deck.
hint: use a "for/in" loop.
"""
def nameYourFunction(nameYourVariable):
None
"""
write a function that prints each card in a deck in reverse
you can use:
1-as a "for/in" loop
2-as a "while" loop
3-as a "in range" loop
"""
def yourReverseFunction(yourVariable):
None
deck = ["A♠","2♠","3♠","4♠","5♠","6♠","7♠","8♠","9♠","10♠","J♠","Q♠","K♠",
"A♥","2♥","3♥","4♥","5♥","6♥","7♥","8♥","9♥","10♥","J♥","Q♥","K♥",
"A♦","2♦","3♦","4♦","5♦","6♦","7♦","8♦","9♦","10♦","J♦","Q♦","K♦",
"A♣","2♣","3♣","4♣","5♣","6♣","7♣","8♣","9♣","10♣","J♣","Q♣","K♣"]
selectRandom(deck)
printEach(deck)
printEachInReverse(deck)
printEach(deck) |
1e7127a4ba6cf8a3d89b32e1cb756e93c7c50708 | nebofeng/python-study | /03python-books/python3-cookbook/第一章:数据结构和算法/1.6 字典中的键映射多个值.py | 1,984 | 3.765625 | 4 | #怎样实现一个键对应多个值的字典(也叫 multidict)?
#可以很方便的使用 collections 模块中的 defaultdict 来构造这样的字典。
# defaultdict 的一个特征是它会自动初始化每个 key 刚开始对应的值,所以你只需要关注添加元素操作了。比如:
from collections import defaultdict
#允许多个重复
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['a'].append(2)
d['b'].append(4)
#重复 只有一个
dset = defaultdict(set)
dset['a'].add(1)
dset['a'].add(1)
dset['b'].add(4)
print(d)
print(dset)
#需要注意的是, defaultdict 会自动为将要访问的键(就算目前字典中并不存在这样的键)创建映射实体。
'''
映射是指 k v 对应
https://www.cnblogs.com/colorfulday/p/10833078.html
defaultdict类的初始化函数接受一个类型作为参数,当所访问的键不存在的时候,可以实例化一个值作为默认值:
>>> dd['foo']
[]
>>> dd
defaultdict(<type 'list'>, {'foo': []})
>>> dd['bar'].append('quux')
>>> dd
defaultdict(<type 'list'>, {'foo': [], 'bar': ['quux']})
需要注意的是,这种形式的默认值只有在通过dict.__getitem__(key)访问的时候才有效
https://www.cnblogs.com/jidongdeatao/p/6930325.html
'''
# 如果你并不需要这样的特性,你可以在一个普通的字典上使用 setdefault() 方法来代替。比如:
d = {} # 一个普通的字典
d.setdefault('a', []).append(1)
d.setdefault('a', []).append(2)
d.setdefault('b', []).append(4)
#一般来讲,创建一个多值映射字典是很简单的。但是,如果你选择自己实现的话,那么对于值的初始化可能会有点麻烦, 你可能会像下面这样来实现:
pairs=[('a',"b"),('a',"c")]
d = {}
for key, value in pairs:
if key not in d:
d[key] = []
d[key].append(value)
#如果使用 defaultdict 的话代码就更加简洁了:
d = defaultdict(list)
for key, value in pairs:
d[key].append(value) |
f416e7b2495b4c3f5459ca3ad02507883e344a56 | akimasa-l/aidemy | /learned/supervised-learning/H1juFh8jIeG.py | 655 | 3.90625 | 4 | # 必要なモジュールのインポート
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
# データの生成
X, y = make_regression(n_samples=100, n_features=10, n_informative=3, n_targets=1, noise=5.0, random_state=42)
train_X, test_X, train_y, test_y = train_test_split(X, y, random_state=42)
# 以下にコードを記述してください
model = LinearRegression()
model.fit(train_X, train_y)
model.score(test_X, test_y)
# test_Xに対する推測結果を出力してください(print関数を用います。)
print(model.predict(test_X)) |
779968d8357a729a4e0142ba19eafda9a9251fa3 | pruhnuhv/Historical-Stock-Data | /Getdata.py | 2,225 | 3.515625 | 4 | import urllib.request
import sys
from datetime import date
default_date=date(int("2019"),int("01"),int("01")) #Python3 can't take 0 as the first char here due to octal interpretation
default_equivalence=1546300800
print("Welcome! Keep Starting-Ending dates and Stock Tickers handy as we proceed :) \n")
for i in (0,2):
if i==0:
input_taken='Starting'
else:
input_taken='Ending'
rawInput=input("Enter the {} date in the YYYY-MM-DD format with no spaces between the hiphens: ".format(input_taken))
try:
YYYY,MM,DD=map(int,rawInput.split('-'))
if i==False:
starting_date=date(YYYY,MM,DD)
delta=starting_date-default_date
starting_equivalence=default_equivalence+(86400*delta.days) #This can be changed by yahoo to avoid scrapers
else: #Just let me know if that happens we can compute it again ;)
ending_date=date(YYYY, MM, DD)
delta=ending_date-default_date
ending_equivalence=default_equivalence+(86400*delta.days+86400)
except:
print("The format of the entered date was incorrect, the program terminates here. \n")
sys.exit()
if starting_equivalence>ending_equivalence: #You actually deserve to be confused by a HTTPS bad request error here. But I'm a good guy :)
print("Starting Date cannot be after ending date \n")
sys.exit()
ticker=input("Nice, now type in the ticker for the stock (All caps): ")
url="""https://query1.finance.yahoo.com/v7/finance/download/"""+ticker+"""?period1="""+str(starting_equivalence)+"""&period2="""+str(ending_equivalence)+"""&interval=1d&events=history"""
file_name=input("What should we name the the downloaded csv file? (File name should have a .csv extension & Enter exact path if this isn't the desired download directory): ")
try:
urllib.request.urlretrieve(url,file_name)
print("Downloaded Successfully! \n")
except:
print("Something Went wrong, I'd request you to try again and recheck your ticker.") #Invalid ticker, file name without csv and unstable internet connections are the possible issues here.
|
b6df3a2729ccb35b58d91efab8b63e2557028fbe | ji3g4freddy/NBA3PointContest | /Three_Pointer_Contest.py | 11,296 | 3.578125 | 4 | import random
import math
import csv
import matplotlib.pyplot as plt
# Define the class player
class player:
name=''
FG_3PCT = 0
stamina = 0
onfire = 0
variance = 0
def __init__(self,attr_list,bonus=1,strategy=0):
self.name = attr_list[0]
self.FG_3PCT=eval(attr_list[1])
self.stamina= eval(attr_list[2])
self.onfire = eval(attr_list[3])
self.variance=eval(attr_list[4])
self.bonus = bonus
self.strategy = strategy
def get_score(self):
"""
simulate the score based on the shooting percetage of the player
:param FG_3PCT: shooting percentage of a player
:return score: the simulated score of the player
"""
score=0
onfire = self.onfire
lefttime = 60.0
for i in range(25):
shoot = random.randint(1,100)
runtime = self.runtime(i)
shootingtime = self.shootingtime(i, lefttime)
# run out of time
if lefttime<shootingtime:
break
# making shot
elif shoot <= self.FG_3PCT * (1-self.stamina/100*(i)) \
* math.log2(min(2.5,(0.5*shootingtime+1))) \
+ self.variance * self.get_onfire(onfire):
# Moneyball spot
if i in range(self.bonus * 5 - 4, self.bonus * 5 + 1):
score += 2
onfire += 5
else:
score += 1
onfire += 5
# fail to make the shot
else:
onfire -= 3
# time deduction
lefttime -= shootingtime + runtime
return score
def get_onfire(self, onfire):
"""
define the if a player is in onfire_mode or oncold_mode(onfire_mode = -1) for each shoot.
:param onfire: the basic probability that the player get into the on_fire mode
:return: onfire_mode: 1 means player is in onfire_mode which can increase their shooting %
and 0 means player is not in the onfire_mode, and there's no shooing % increase
and -1 means player is in the oncold_mode which would decrease their shooting %
"""
prob = random.randint(1,100)
# player get onfire
if prob <= onfire:
onfire_mode = 1
# player shoot as normal
elif prob <= onfire+50:
onfire_mode = 0
# player get oncold
else:
onfire_mode = -1
return onfire_mode
def runtime(self, i):
"""
simulate the time to run between each shooting spot
:param i: the number of shoot
:return: the simulated time spent of each run
"""
# after 5 shoots, player moves to the next spot
if (i + 1) % 5 == 0 and i < 24:
runtime = random.uniform(2, 4)
else:
runtime = 0
return runtime
def choose_strategy(self,simulation_time):
"""
let the player simulate every possible strategy and bonus point to find out the best combination
:param: simulation_time: The number of times of the simulation
"""
best_bonus = 0
best_strategy = 0
best_score = 0.0
for bonus in range(1,6):
self.bonus = bonus
for strategy in range(0,6):
score_list = []
self.strategy=strategy
for r in range(simulation_time):
score = self.get_score()
score_list.append(score)
avg_score = round((sum(score_list)/len(score_list)),2)
print('{:5} {:12} {:15} '.format(self.bonus,self.strategy,avg_score))
if avg_score>best_score:
best_score = avg_score
best_bonus = self.bonus
best_strategy=self.strategy
self.bonus = best_bonus
self.strategy=best_strategy
print('\n >>> The best strategy for {} is: bonus {} and strategy {} \n >>> Average score = {} \n'.format(self.name,self.bonus,self.strategy,best_score))
def shootingtime(self, i, lefttime):
"""
simulate the time to shoot each ball
:param i: the number of shoot
:param lefttime: total time left in the game
:return: the simulated shooting time for each shoot
"""
shootingtime = 0
# quick release
if self.strategy == 0:
shootingtime = random.uniform(1, 3)
# high quality
elif self.strategy == 1:
shootingtime = random.uniform(2, 4)
# high quality & time controlling
elif self.strategy == 2:
shootingtime= random.uniform(2, lefttime / (25-i))
# focus on bonus spot
elif self.strategy == 3:
if i in range(self.bonus * 5 - 4, self.bonus * 5 + 1):
shootingtime = random.uniform(3, 4)
else:
shootingtime = random.uniform(1, lefttime/(25-i))
# focus on first ten shots
elif self.strategy == 4:
if i in range(10):
shootingtime = random.uniform(2, 4)
else:
shootingtime = random.uniform(1, lefttime / (25 - i))
# focus on last ten shots
elif self.strategy == 5:
if i in range(16,25):
shootingtime = random.uniform(2, 4)
else:
shootingtime = random.uniform(1, lefttime / (25 - i))
return shootingtime
def sort_dic(dic):
"""
get the sorted game result based on the socres
:param dic: the game result
:return: the sorted game result
>>> dic = {'Curry':18, 'George':13, 'Thompson':15, 'Booker':20}
>>> sort_dic(dic)
[('Booker', 20), ('Curry', 18), ('Thompson', 15), ('George', 13)]
"""
return sorted(dic.items(),key = lambda item:item[1],reverse=True)
def get_game_result(player_list):
"""
To get the result of the game based on the player list of current round.
:param player_list: the player list of current round
:return result: the result of the game
"""
result = {}
for player in player_list:
score = player.get_score()
result[player.name] = score
return result
def get_next_round(candidate_number, result):
"""
Based on the game result and the assign candidate_number to choose the candidate for next round
:param candidate_number: how many candidates can advance to next round
:param result: the game result with the players' scores
:return: the candidate list for next round
"""
next_round_candidate = {}
next_round_candidate_list = []
# set the threshold for next round candidate
threshold = sort_dic(result)[candidate_number-1][1]
for key, value in result.items():
if value >= threshold:
next_round_candidate[key] = value
for player in player_list:
if player.name in next_round_candidate.keys():
next_round_candidate_list.append(player)
return next_round_candidate_list
def one_simulation(player_list):
"""
Simulate one game
:param player_list: player list who attend the competition
:return: The winner of the game
"""
over_time_flag=True
candidate_list = get_next_round(3,get_game_result(player_list))
candidate_list = get_next_round(1,get_game_result(candidate_list))
while over_time_flag:
if len(candidate_list)==1:
over_time_flag=False
else:
candidate_list=get_next_round(1,get_game_result(candidate_list))
winner = candidate_list[0].name
return winner
if __name__ == '__main__':
# read csv file with player data
file = csv.reader(open('player_data.csv'))
headers = next(file)
player_list=[]
for row in file:
num = 0
attr_list=[]
for header in headers:
attr_list.append(row[num])
num+=1
player_list.append(player(attr_list))
# simulation one game
print('\nOne game simulation: \n')
# first round
first = get_game_result(player_list)
print('=========================')
print("First round")
print('=========================')
print('Player Score')
print('-------------- -----')
for key, value in first.items():
print('{:20} {:<5}'.format(key, value))
next_round_candidate_list = get_next_round(3, first)
# Final round
print('\n=========================')
print("Final round")
print('=========================')
print('Player Score')
print('-------------- -----')
final = get_game_result(next_round_candidate_list)
for key, value in final.items():
print('{:20} {:<5}'.format(key, value))
next_round_candidate_list = get_next_round(1, final)
# OverTime or Winner
while len(next_round_candidate_list) != 1:
print('\n=========================')
print("Overtime")
print('=========================')
print('Player Score')
print('-------------- -----')
ot = get_game_result(next_round_candidate_list)
for key, value in ot.items():
print('{:20} {:<5}'.format(key, value))
next_round_candidate_list = get_next_round(1, ot)
print('\n>>> The winner is: {}\n'.format(next_round_candidate_list[0].name))
print('===================================\n')
print('Strategy Detail: \n')
for player in player_list:
print(player.name)
print('\nBonus Strategy Average Score')
print('----- -------- -------------')
player.choose_strategy(1200)
winner_list = []
for index in range(1000):
winner = one_simulation(player_list)
winner_list.append(winner)
print('\n===============================================')
print("Winning rate")
print('===============================================')
print('\nPlayer Bonus Strategy Winning %')
print('------------- ----- -------- ---------')
for player in player_list:
print('{:15} {:6} {:10} {:10}%'.format(player.name, player.bonus, player.strategy, round(winner_list.count(player.name) / len(winner_list)*100, 2)))
#print('(Bonus:{}, Strategy:{})'.format(player.bonus, player.strategy))
print('\n================================================================')
print("Winning rate when Love & Thompson apply bad bonus and strategy")
print('================================================================')
print('\nPlayer Bonus Strategy Winning %')
print('------------- ----- -------- ---------')
player_list[3].bonus = 5
player_list[3].strategy = 1
player_list[4].bonus = 1
player_list[4].strategy = 5
winner_list = []
for index in range(1000):
winner = one_simulation(player_list)
winner_list.append(winner)
for player in player_list:
print('{:15} {:6} {:10} {:10}%'.format(player.name, player.bonus, player.strategy,
round(winner_list.count(player.name) / len(winner_list) * 100, 2)))
|
2356c82bf653aa6061863ba3654ccfb812cd8c4f | dzhao14/HackerRank_code | /practice/algorithms/DP/fibonacci_modified.py | 486 | 3.9375 | 4 | #https://www.hackerrank.com/challenges/fibonacci-modified
def solution(f1, f2, n, memo):
key = n
if key in memo:
return memo[key]
if n == 1:
return f1
elif n == 2:
return f2
else:
memo[key] = pow(solution(f1, f2, n-1, memo), 2) + solution(f1,f2, n-2, memo)
return memo[key]
if __name__ == "__main__":
f1, f2, n = [int(temp) for temp in input().strip().split()]
ans = solution(f1, f2, n, {})
print(str(ans))
|
9ead14450e474c717142142a3d909fc05f9a47f5 | enzngin/Guessing-a-number-Binary-Search- | /Part3.py | 938 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 23:14:32 2020
@author: USER
"""
from random import randint
def guess_number_pc(upper_bound):
a_number = randint(0, upper_bound) #7
up= upper_bound
down = 0
attempts = 0
print("A: I guess a number from 1 to {upper}".format(upper = upper_bound))
i = True
while i:
mid = (up+down) / 2 #5
b_number = mid #9
attempts = attempts + 1
print("B: your number is: {number}".format(number = b_number))
if b_number < a_number:
print("A: My number is bigger")
down = mid
elif b_number > a_number:
print("A: My number is smaller")
up = mid
elif b_number == a_number:
print("Yeah, that is it!")
print("Estimated on {number} attempts".format(number = attempts))
i = False
guess_number_pc(10)
|
218a5781eb0cef4203307dcc05ad2617a3149739 | yosef8234/test | /hackerrank/python/math/triangle-quest-1.py | 866 | 4.25 | 4 | # -*- coding: utf-8 -*-
# You are given a positive integer NN. Print a numerical triangle of height N−1N−1 like the one below:
# 1
# 22
# 333
# 4444
# 55555
# ......
# Can you do it using only arithmetic operations, a single for loop and print statement?
# Use no more than two lines. The first line (the for statement) is already written for you. You have to complete the print statement.
# Note: Using anything related to strings will give a score of 00.
# Input Format
# A single line containing integer, NN.
# Constraints
# 1≤N≤91≤N≤9
# Output Format
# Print N−1N−1 lines as explained above.
# Sample Input
# 5
# Sample Output
# 1
# 22
# 333
# 4444
for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also
# print((pow(10,i)/9)*i)
print(sum(map(lambda x: i * 10**x, range(i))))
|
bfb3370c8ac7d9af56d3f44b2551d4d321160f60 | zzdxlee/Sword2Offer_Python | /位运算/不用加减乘除做加法.py | 2,750 | 3.53125 | 4 | # -*- coding:utf-8 -*-
# 写一个函数,求两个整数之和,要求在函数体内不得使用 +、-、 * 、 / 四则运算符号。
# https: // blog.csdn.net / zhongjiekangping / article / details / 6855864
# 用位运算实现加法也就是计算机用二进制进行运算,32
# 位的CPU只能表示32位内的数,这里先用1位数的加法来进行,在不考虑进位的基础上,如下
#
# 1 + 1 = 0
# 1 + 0 = 1
# 0 + 1 = 1
# 0 + 0 = 0
#
# 很明显这几个表达式可以用位运算的“ ^ ”来代替,如下
#
# 1 ^ 1 = 0
# 1 ^ 0 = 1
# 0 ^ 1 = 1
# 0 ^ 0 = 0
# 这样我们就完成了简单的一位数加法,那么要进行二位的加法,这个方法可行不可行呢?肯定是不行的,矛盾就在于,如何去
# 获取进位?要获取进位我们可以如下思考:
#
# 0 + 0 = 0
# 1 + 0 = 0
# 0 + 1 = 0
# 1 + 1 = 1
# // 换个角度看就是这样
# 0 & 0 = 不进位
# 1 & 0 = 不进位
# 0 & 1 = 不进位
# 1 & 1 = 进位
# 正好,在位运算中,我们用“ << ”表示向左移动一位,也就是“进位”。那么我们就可以得到如下的表达式
#
# // 进位可以用如下表示:
# (x & y) << 1
# 到这里,我们基本上拥有了这样两个表达式
#
# x ^ y // 执行加法
# (x & y) << 1 // 进位操作
# 我们来做个2位数的加法,在不考虑进位的情况下
#
# 11 + 01 = 100 // 本来的算法
#
# // 用推算的表达式计算
# (11 & 01) << 1 = 10
# 11 ^ 01 = 10
#
# // 到这里
# 我们用普通的加法去运算这两个数的时候就可以得到
# 10 + 10 = 100
# // 但是我们不需要加法,所以要想别的方法,如果让两个数再按刚才的算法计算一次呢
# (10 & 10) << 1 = 100
# 10 ^ 10 = 00
#
# 到这里基本上就得出结论了,其实后面的那个 “00” 已经不用再去计算了,因为第一个表达式就已经算出了结果。
# 继续推理可以得出三位数的加法只需重复的计算三次得到第一个表达式的值就是计算出来的结果。
# 其余基础知识:关于原补反,计算机中整数都是以补码形式存储的。正数的原反补是一样的,
# 而负数的原码是符号位置1;负数的反码是在原码的基础上,符号位不变,其余位置取反;负数的补码是在反码的基础上再加1。
# [+1] = [00000001]原 = [00000001]反 = [00000001]补
# [-1] = [10000001]原 = [11111110]反 = [11111111]补
class Solution:
def Add(self, carry, sum):
if carry == 0:
# // a = ~b +1,b = ~(a-1)
return sum if sum <= 0x7FFFFFFF else -(~(sum - 1) & 0x7FFFFFFF)
return self.Add((carry & sum) << 1, (carry ^ sum) & 0x7FFFFFFF)
if __name__ == '__main__':
s = Solution()
print(s.Add(-1, 3))
|
e940071fc294ac24363b86f6feb0a5a1eaf5ae87 | Sefan90/AdventOfCode2020 | /Day10/Day10.py | 979 | 3.65625 | 4 | def Part1():
f = open("input.txt","r")
currentsum = 0
jolt = [0,0,1] #your device's built-in adapter is always 3 higher than the highest adapter
inputlist = sorted([int(i) for i in f.readlines()])
for i in inputlist:
jolt[i - currentsum-1] += 1
currentsum = i
print(jolt[0]*jolt[2])
def Part2():
f = open("input.txt","r")
inputlist = [0] + sorted([int(i) for i in f.readlines()])
inputlist.append(max(inputlist)+3)
result = 1
counter = 0
for i in range(len(inputlist)-1):
if inputlist[i+1] - inputlist[i] == 1:
counter += 1
elif inputlist[i+1] - inputlist[i] == 3:
if counter == 2:
result *= 2
elif counter == 3:
result *= 4
elif counter == 4:
result *= 7
counter = 0
print(result)
import time
start_time = time.time()
Part2()
print("--- %s seconds ---" % (time.time() - start_time))
|
338f8ea126e9f6d585b9ade56a50110db4ead224 | VD2410/Data_Structure_And_Algorithms | /Basics of Python/Task4.py | 1,539 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
calls_from_num = list([item[0] for item in calls]) # ''' Complexity n'''
calls_to_num = list([item[1] for item in calls]) # ''' Complexity n'''
text_from_num = list([item[0] for item in texts]) # ''' Complexity n'''
text_to_num = list([item[1] for item in texts]) # ''' Complexity n'''
telemarketers = list() # ''' Complexity 1'''
for n in calls_from_num: # ''' Complexity n'''
if n not in calls_to_num and n not in text_from_num and n not in text_to_num: # ''' Complexity n'''
telemarketers.append(n) # ''' Complexity m'''
print("These numbers could be telemarketers: ") # ''' Complexity 1'''
print("\n".join(sorted(set(telemarketers),key=str))) # ''' Complexity n log n'''
# ''' Complexity O(n log n))''' |
51f765a32817a1141edd8115869a8ed789566ced | Nehal31/Python | /PProgramz/pz11.py | 366 | 4.3125 | 4 | ''' check the given year is leap or not '''
#taking the given year
y = int(input('Enter the year : '))
#check the Leap year
if y % 4 == 0:
if y % 100 == 0:
if y % 400 == 0 :
print('Leap Year')
else:
print('Not leap Number')
else :
print('Leap year ')
else:
print('Not leap Year')
|
08989484c0b5ed100c5203aa10102812439acb30 | maike-hilda/pythonLearning | /count_items.py | 390 | 4.125 | 4 | #Count items in a loop
nums = [3, 41, 12, 9, 74, 15]
count = 0
for itervar in nums: #itervar is the iteration variable
count = count + 1
print 'Count: ', count
#Add up items in a loop
total = 0
for itervar in nums:
total = total + itervar
print 'Total: ', total
#But there are built-in functions for this
print 'Count: ', len(nums)
print 'Total: ', sum(nums)
|
f8840974a55f960b4a9bcf8b236bb3f7a331c90f | Kblens56/ccbb_pythonspring2014 | /2014-05-21_class_pt2.py | 2,969 | 3.546875 | 4 | import pandas
import numpy
cd documents/ccbb_pythonspring2014/
# open sites_complicated in pandas as an Excell file and then parse out Sheet 1
xl_c = pandas.ExcelFile('sites_complicated.xlsx')
df_c = xl_c.parse('Sheet1')
# how to output file in pandas
# to write file in pandas and make csv will be called output.csv
outfile = open('output.csv', 'w')
df_c.to_csv(outfile)
outfile.close()
# to import all "*" from pandas
from pandas import *
# now can write excell file from pandas
writer = ExcelWriter('output.xlsx')
df_c.to_excel(writer, 'Sheet1')
## now moving onto ploting
#import all "*" from ggplot
from ggplot import *
# open and parse sites simple
xl = pandas.ExcelFile('sites_simple.xlsx')
df = xl.parse('Sheet1', index_col = 0, header = 0)
# make a plot saying what data will use etc
my_plot = ggplot(df, aes(x = 'Expenditure', y = 'Species')) + geom_point() + xlim(0,350) + ylim(0,25)
# to see plot
my_plot
#to save the plot
# can save while looking at the plot by pushing the save button
# or can save it programaticaly
ggsave(my_plot, "demo_plot", "png")
# now we will switch to working with a very large excel document
# to import the data and name it big_matrix
big_matrix = pandas.read_csv('big_matrix.csv')
# to see the beginning of "big_matric"
big_matrix.head()
# this is what I see, April saw several of the first columns I assume this is a setting thing
Out[37]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Columns: 1001 entries, 0 to 0.5034046342
dtypes: float64(1000), int64(1)
# to import te dat in a slightly differnt way ... not sure why the collumn now says entries 0 to 100 instead of 1 to 0.5
big_matrix = pandas.read_csv('big_matrix.csv', index_col=None, header=None)
big_matrix.head()
Out[40]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Columns: 1001 entries, 0 to 1000
dtypes: float64(1000), int64(1)
# to add a 1002nd collumn that will say Me for the first 250 rows and then My_Labmate for the rest of the rows
big_matrix['1002'][0:250] = 'Me'
big_matrix['1002'][250:] = 'My_Labmatee'
# to display a sample of what column 1002 looks like
big_matrix['1002']
# this is what it looks like
Out[49]:
0 Me
1 Me
2 Me
3 Me
4 Me
5 Me
6 Me
7 Me
8 Me
9 Me
10 Me
11 Me
12 Me
13 Me
14 Me
...
485 My_Labmatee
486 My_Labmatee
487 My_Labmatee
488 My_Labmatee
489 My_Labmatee
490 My_Labmatee
491 My_Labmatee
492 My_Labmatee
493 My_Labmatee
494 My_Labmatee
495 My_Labmatee
496 My_Labmatee
497 My_Labmatee
498 My_Labmatee
499 My_Labmatee
Name: 1002, Length: 500, dtype: object
# make a plot where me and my labmates data are differnt colors on a scatterplot
overlay = ggplot(aes(x=big_matrix.ix[0:499,2], y = big_matrix.ix[:,1], color='1002'), data=big_matrix) + geom_point() +geom_jitter() + ylab("Y Axis") + xlab("X Axis") +ylim(0,1) + xlim(0,1) + theme_bw()
# to see plot
overlay |
db486b71520901b6b817e2696bf40e354de504dd | Snehal2605/Technical-Interview-Preparation | /ProblemSolving/450DSA/Python/src/arrays/MaximumProductSubarray.py | 1,047 | 4.09375 | 4 | """
@author Anirudh Sharma
Given an integer array nums, find the contiguous subarray within an array
(containing at least one number) which has the largest product.
"""
def maxProduct(nums):
# Special cases
if nums is None or len(nums) == 0:
return -1
# Overall maximum product
globalMaxima = nums[0]
# Maximum product until the current index
localMaxima = nums[0]
# Minimum product until the current index
localMinima = nums[0]
# Loop for the remaining elements
for i in range(1, len(nums)):
# Save localMaxima for localMinima calculation
temp = localMaxima
localMaxima = max(nums[i], max(localMaxima * nums[i], localMinima * nums[i]))
localMinima = min(nums[i], min(temp * nums[i], localMinima * nums[i]))
globalMaxima = max(localMaxima, globalMaxima)
return globalMaxima
if __name__ == "__main__":
print(maxProduct([2, 3, -2, 4]))
print(maxProduct([-2, 0, -1]))
print(maxProduct([6, -3, -10, 0, 2]))
print(maxProduct([2, 3, 4, 5, -1, 0]))
|
6179f1b62ff82ca0972f5414654e5734b4f1a290 | mgijax/lib_py_misc | /symbolsort.py | 3,042 | 3.703125 | 4 | # Name: symbolsort.py
# Purpose: provide a splitter() function that can be shared across Python products to
# consistently split an alphanumeric string into a tuple of integers and strings for
# sorting.
# global dictionaries used by splitter() for speedy lookups:
sdict = { '' : ('') }
digits = { '1' : 1, '2' : 1, '3' : 1, '4' : 1,
'5' : 1, '6' : 1, '7' : 1, '8' : 1,
'9' : 1, '0' : 1 }
intPrefix = 9999999999
def splitter (s):
# Purpose: split string 's' into a tuple of strings and integers,
# representing the contents of 's' for sorting purposes
# Returns: tuple containing a list of strings and integers
# Assumes: s is a string or None
# Effects: nothing
# Throws: nothing
# Notes: Because Python 3.7 does not allow strings to be compared with
# integers, we must ensure that all tuples have the same ordering of
# integers and strings.
# (So even for ones that would begin with a string, we'll prepend an integer
# to force it to appear after those beginning with integers.)
# Examples:
# 'Ren1' ==> (999999999, 'ren', 1)
# 'abc123def' ==> (9999999999, 'abc', 123, 'def')
# '789xyz32' ==> (789, 'xyz', 32)
global sdict
if s == None:
return (intPrefix,)
if s in sdict:
return sdict[s]
last = 0
items = []
sl = s.lower ()
in_digits = sl[0] in digits
for i in range(0, len(sl)):
if (sl[i] in digits) != in_digits:
if in_digits:
items.append (int(sl[last:i]))
else:
items.append (sl[last:i])
last = i
in_digits = not in_digits
if in_digits:
items.append (int(sl[last:]))
else:
items.append (sl[last:])
if type(items[0]) != int:
items.insert(0, intPrefix)
sdict[s] = tuple(items)
return sdict[s]
#
# Warranty Disclaimer and Copyright Notice
#
# THE JACKSON LABORATORY MAKES NO REPRESENTATION ABOUT THE SUITABILITY OR
# ACCURACY OF THIS SOFTWARE OR DATA FOR ANY PURPOSE, AND MAKES NO WARRANTIES,
# EITHER EXPRESS OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE OR THAT THE USE OF THIS SOFTWARE OR DATA WILL NOT
# INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS, OR OTHER RIGHTS.
# THE SOFTWARE AND DATA ARE PROVIDED "AS IS".
#
# This software and data are provided to enhance knowledge and encourage
# progress in the scientific community and are to be used only for research
# and educational purposes. Any reproduction or use for commercial purpose
# is prohibited without the prior express written permission of the Jackson
# Laboratory.
#
# Copyright (c) 1996, 1999, 2002 by The Jackson Laboratory
# All Rights Reserved
#
|
eca23bf18497424a3c47d939e717251934041869 | tiagolsouza/exercicios-Curso-em-video-PYTHON | /exercicios/exe030/exe030.py | 108 | 3.859375 | 4 | a = int(input('Digite um numero inteiro: '))
b = a % 2
if b != 0:
print('impar')
else:
print('par')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.