blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
130b0e7ffbf29b50607f03b190b3637d145492d4
|
andonyan/Python-Advanced
|
/Tuples and Sets - Lab/Parking Lot.py
| 409 | 3.921875 | 4 |
n = int(input())
parking_lot = set()
for _ in range(n):
(direction, license_plate) = input().split(', ')
if direction == 'IN':
parking_lot.add(license_plate)
elif direction == 'OUT' and license_plate in parking_lot:
parking_lot.remove(license_plate)
else:
if parking_lot:
for car in parking_lot:
print(car)
else:
print('Parking Lot is Empty')
|
2d540b404ac7a0e8482ad4dce1173c63616f2719
|
danishprakash/courses
|
/coursera-uom/Part1/p1w7a52.py
| 315 | 4.09375 | 4 |
#largest = None
#smallest = None
numList = []
while True:
try:
num = input("Enter a number: ")
if num == 'done':
break
numList.append(int(num))
#print(num)
except:
print('Invalid input')
print("Maximum is", max(numList))
print("Minimum is", min(numList))
|
ccf6654bd4ec5fd455a879627e49f1cf00e7c3f3
|
talibzaz/awesome-py
|
/dataStructures/ds.py
| 342 | 3.578125 | 4 |
from collections import deque
fruits = ['orange', 'apple', 'apple', 'pear', 'banana', 'mango', 'kiwi']
print(fruits.count('apple'))
print(fruits.pop())
print(fruits)
queue = deque(['Eric', 'Michael', 'John'])
queue.append('Jerry')
print(queue)
print(queue.popleft())
print(queue.pop())
print(queue)
arr = [1, 5, 9, 7]
print(sum(arr))
|
a95c390604c50ef42b2c9eeffc4eac37c6bfed22
|
Lucian-N/CS50
|
/pset6/similarities/helpers.py
| 1,622 | 3.828125 | 4 |
from enum import Enum
class Operation(Enum):
"""Operations"""
DELETED = 1
INSERTED = 2
SUBSTITUTED = 3
def __str__(self):
return str(self.name.lower())
def distances(a, b):
"""Calculate edit distance from a to b"""
end_range_a = len(a) + 1
end_range_b = len(b) + 1
# Array to store words declaration
word = [[(0, None) for x in range(end_range_b)] for y in range(end_range_a)]
# Initialize first row and column of Array
for i in range(1, end_range_a):
word[i][0] = (i, Operation.DELETED)
for j in range(1, end_range_b):
word[0][j] = (j, Operation.INSERTED)
# Initialize rest of array using min cost
for i in range(1, end_range_a):
for j in range(1, end_range_b):
deletion = (word[i - 1][j])[0]
insertion = (word[i][j - 1])[0]
substitution = (word[i - 1][j - 1])[0]
deletion += 1
insertion += 1
substitution += 1
# If substitution is the minimal cost action
# Determine if substituted character is the same
if (a[i - 1] == b[j - 1]):
substitution -= 1
if (deletion < insertion and deletion < substitution):
word[i][j] = (deletion, Operation.DELETED)
elif (insertion < deletion and insertion < substitution):
word[i][j] = (insertion, Operation.INSERTED)
else:
word[i][j] = (substitution, Operation.SUBSTITUTED)
# Returns tuple of minimal cost to perform transformation
# and last operation used
return word
|
9e8e1281973783e03ab2c636672ecd67f11c74df
|
vlad8130/python9
|
/brilliant.py
| 1,353 | 4.125 | 4 |
# Задача 2. Бриллиант
# Входным данным является целое число. Необходимо:
# написать проверку, чтобы в работу пускать только положительные нечетные числа
# для правильного числа нужно построить бриллиант из звездочек или любых других символов и вывести его в консоли. Для числа 1 он выглядит как одна взездочка,
# для числа три он выглядит как звезда, потом три звезды, потом опять одна, для пятерки - звезда, три, пять, три, одна...
# i = int(input())
# print(i*"*")
n = int(input())
if n > 0 and n % 2 !=0:
# print("Pattern 1")
else:
print("введенное число не соответствует")
for a1 in range(1, (n+1)//2 + 1): #from row 1 to 5
for a2 in range((n+1)//2 - a1):
print(" ", end = "")
for a3 in range((a1*2)-1):
print("*", end = "")
print()
for a1 in range((n+1)//2 + 1, n + 1): #from row 6 to 9
for a2 in range(a1 - (n+1)//2):
print(" ", end = "")
for a3 in range((n+1 - a1)*2 - 1):
print("*", end = "")
print()
|
a50c9e707d23c124f43eb9309664e44904820123
|
shirshandu/ExplorePython
|
/pg3_duplicate.py
| 184 | 3.515625 | 4 |
prev = None
for line in sorted(open('file')):
line = line.strip()
if prev is not None and not line.startswith(prev):
print prev
prev = line
if prev is not None:
print prev
|
c553adda586c88a671ab74f546c7e3d8d88c0bbf
|
jmanning1/python_course
|
/HelloWorld/HelloWorld.py
| 322 | 4.09375 | 4 |
print('Hello World!')
print(1+2)
print(7*6)
print()
print("The End")
print("Python Strings are easy to use. We can also use 'Quotes' in Strings")
print ("Hello" + "World")
greeting = "Hello"
name = "Bruce"
print(greeting + name)
#If we want a space use a hash for comments/notes
print(greeting + " " + name)
|
7b1d8a08651291e4a813a4db09603b6b87b56f0b
|
krohak/Bioinformatics
|
/Chapter 1/1_4_1.py
| 352 | 4.125 | 4 |
# Input: A DNA string Pattern
# Output: The reverse complement of Pattern
def ReverseComplement(Pattern):
return Reverse(Complement(Pattern))
def Reverse(Pattern):
return ''.join(list(reversed(Pattern)))
def Complement(Pattern):
complementMap = {'A':'T','T':'A','G':'C','C':'G'}
return ''.join([complementMap[c] for c in Pattern])
|
691d6be9a77a7608f0c3662ddae4a868690639bd
|
OlgaLitv/Algorithms
|
/lesson2/task2.py
| 513 | 4.28125 | 4 |
""" Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560,
то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). """
n = input('Введите натуральное число\n')
odd = 0
even = 0
for letter in n:
if int(letter) % 2 == 0:
even += 1
else:
odd += 1
print(f'Нечетных цифр {odd}, четных {even}')
|
b5189a0f63422c0af9fff4edde495654e88398d7
|
saggarwal98/Practice
|
/Python/tuples.py
| 78 | 3.578125 | 4 |
tuple1=("abc","def","ghi")
print(len(tuple1))
print(tuple1)
print(tuple1[0:2])
|
e29b56c230f6e72e9e8f26cb4cd3e94f7f0306b2
|
eecs110/winter2021
|
/course-files/lectures/lecture14/answers/02a_list_animation_from_class.py
| 787 | 3.546875 | 4 |
from tkinter import Canvas, Tk
import time
import utilities
import math
import random
gui = Tk()
gui.title('Animation')
canvas = Canvas(gui, width=500, height=500, background='white')
canvas.pack()
########################## YOUR CODE BELOW THIS LINE ##############################
for i in range(1, 101):
x = random.randint(0, 500)
y = random.randint(0, 500)
r = random.randint(5, 25)
tag_name = 'circle' + str(i)
utilities.make_circle(canvas, (x, y), r, color=None, tag=tag_name)
while True:
for i in range(1, 101):
utilities.move(canvas, 'circle' + str(i), x=0, y=1)
gui.update()
time.sleep(.001)
########################## YOUR CODE ABOVE THIS LINE ##############################
# makes sure the canvas keeps running:
canvas.mainloop()
|
3c2fa1290926bf5ace70583a5b1ca5bf746cf4c0
|
maomao905/algo
|
/sorted-integers-by-the-number-of-1bits.py
| 736 | 3.890625 | 4 |
"""
- how to get the number of 1 bit?
get right-most 1 bit and substruct it
continue this process until the number becomes zero O(32) = O(1)
time: O(NlogN) space: O(1)
"""
from typing import List
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
def count_one_bit(x):
cnt = 0
while x > 0:
# rightmost_one_bit = x & -x
# x -= rightmost_one_bit
x &= (x-1)
cnt += 1
return cnt
return sorted(arr, key=lambda x: (count_one_bit(x), x))
s = Solution()
print(s.sortByBits([0,1,2,3,4,5,6,7,8]))
print(s.sortByBits([1024,512,256,128,64,32,16,8,4,2,1]))
print(s.sortByBits([2,3,5,7,11,13,17,19]))
|
129845b77a736f553d99e97cff15c7b94c3a741d
|
Atlasias/Algorithm
|
/programmers/skill_checks/849.py
| 444 | 3.625 | 4 |
def solution(n):
answer = ''
while True:
if n == 0:
break
m = n % 3
n = n // 3
if m == 1:
answer = 'a' + answer
elif m == 2:
answer = 'b' + answer
else:
answer = 'c' + answer
answer.replace('a', '1')
answer.replace('b', '2')
answer.replace('c', '4')
return answer
for i in range(1, 10):
print(solution(i))
|
abdcef196759e872d15d5f8b0e3d4cdfda3a3a85
|
AliceTheHive/releases-openstar-Enterprise
|
/openstar/bash/py/file.py
| 1,658 | 3.625 | 4 |
#!/usr/bin/env python 2.x
# -*- coding: utf-8 -*-
# version = 1.0
import os
class ScanFile(object):
def __init__(self, directory, prefix=None, postfix=None):
self.directory = directory
self.prefix = prefix
self.postfix = postfix
self.files_list = []
self.dir_list = []
def scan(self):
for dirpath, dirnames, filenames in os.walk(self.directory):
'''''
dirpath is a string, the path to the directory.
dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..').
filenames is a list of the names of the non-directory files in dirpath.
'''
self.dir_list.append(dirpath)
for special_file in filenames:
if self.postfix:
if special_file.endswith(self.postfix):
self.files_list.append(os.path.join(dirpath, special_file))
elif self.prefix:
if special_file.startswith(self.prefix):
self.files_list.append(os.path.join(dirpath, special_file))
else:
self.files_list.append(os.path.join(dirpath, special_file))
return self.dir_list, self.files_list
if __name__ == "__main__":
dir = u"D:\\360Downloads"
scan = ScanFile(dir, None, '.ini')
subdirs, files = scan.scan()
print("subdirs len:" + str(len(subdirs)) + "\nfiles len:" + str(len(files)))
print("The subdirs scaned are:")
for subdir in subdirs:
print(subdir)
print("The files scaned are:")
for file in files:
print(file)
|
b54e88e134c035a8e04575f16982c7f469470b61
|
gavinsyw/CombatDeepfake
|
/InterceptFace.py
| 741 | 3.53125 | 4 |
import cv2
def crop_face(imagePath):
# Read the image
image = cv2.imread(imagePath)
# turn the image to Gray
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Create the haar cascade
faceCascade =cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
# Detect face in the image
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5
)
# print("Found {0} faces!".format(len(faces)))
#
x,y,w,h = faces[0]
image = image[y:y+h, x:x+w]
# cv2.imwrite("F:\\kejian\\2020 spring\\computer network\\final project\\code\\DeepFakeDetection-master\\Experiments_DeepFakeDetection\\res1.jpg", image)
return image
|
3772936a664ccd3f7ecb8c41a176ecae15c6f1fa
|
KateDetsyk/see_battle
|
/canvas.py
| 2,689 | 4.1875 | 4 |
class Rectangle:
def __init__(self, corner, size, border='*', inside=' '):
"""
Initialize new rectangle.
:param corner: corner coordinates.
:param size: size of rectangle
:param border: symbol that is used to display rectangle border.
:param inside: symbol that is used to display rectangle border.
"""
self._corner = corner
self._size = size
self.border = border
self.inside = inside
def view(self, coordinate):
"""
Display view of rectangle by coordinate.
:param coordinate: coordinate of cell.
:return: view of rectangle by coordinate.
"""
if coordinate[0] == self._corner[0] or coordinate[1] == self._corner[1] or \
coordinate[0] == self._corner[0] + self._size[0] - 1 or coordinate[1] == self._corner[1] + self._size[1] - 1:
return self.border
else:
return self.inside
class Canvas:
def __init__(self, width, height):
"""
Initialize new canvas.
:param width: canvas width.
:param height: canvas height.
"""
self.width = width
self.height = height
self.cells = [[None] * width for i in range(height)]
def add_rectangle(self, corner, size, border='*', inside=' '):
"""
Add rectangle to canvas.
:param corner: corner coordinates.
:param size: size of rectangle
:param border: symbol that is used to display rectangle border.
:param inside: symbol that is used to display rectangle border.
:return: recatngle that has been added.
"""
r = Rectangle(corner, size, border=border, inside=inside)
for i in range(size[0]):
for j in range(size[1]):
coordinate = (corner[0] + i, corner[1] + j)
if 0 <= coordinate[0] < self.height and 0 <= coordinate[1] < self.width:
if self.cells[coordinate[0]][coordinate[1]] != None:
self.cells[coordinate[0]][coordinate[1]].append(r)
else:
self.cells[coordinate[0]][coordinate[1]] = [r]
return r
def __str__(self):
"""
View of canvas.
:return: view of canvas.
"""
s = ''
for i in range(self.height):
for j in range(self.width):
cell = self.cells[i][j]
if cell != None:
s += cell[-1].view((i, j))
else:
s += ' '
s += '\n'
return s
|
cb4985bc00256a6d37a252942c81be46f5e1c20f
|
vsfh/pyukf_kinect_body_tracking
|
/src/regression.py
| 224 | 3.5 | 4 |
import math
import numpy as np
def mean_squared_error(y, t, test_num):
y = np.array(y).reshape(test_num, (int)(len(y)/test_num))
t = np.array(t).reshape(test_num, (int)(len(t)/test_num))
return ((y-t)**2).mean(axis=None)
|
abb1a7f3641605ba8c57cf9ad04646423a444a41
|
JoannaKielas/testing-with-Robot-Framework-
|
/code/TC10/TC10_import_csv.py
| 335 | 3.921875 | 4 |
import csv
def read_csv_file(filename):
list_of_countries =[]
with open(filename) as csvfile:
reader = csv.reader(csvfile)
for line in reader:
list_of_countries.extend(line)
print(list_of_countries, "line")
print(list_of_countries)
return list_of_countries
|
dc0162c665e3cf8f1479e49561e6f7559b790f9c
|
beezy12/pythonPractice
|
/network/pythonhack/sock.py
| 942 | 3.828125 | 4 |
# this program creates a simple server. to connect, open Filezilla and connect to the server using localhost on port 1249
# came from my udemy ethical hacking course
# notes in my Bear notebook
# docs here: https://docs.python.org/3.6/howto/sockets.html
import socket
# create a socket object
s = socket.socket()
print('created socket....')
# reserve a port number
port = 1249
# bind to the port
# we bind with empty string to allow the socket to connect to any IP. If I set it as localhost or 127.0.0.1, the socket would only be visible within the same machine
s.bind(('', port))
print('socket binded to %s' %(port))
# from the docs:
# serversocket.bind((socket.gethostname(), 80))
# put socket into listening mode
s.listen(5)
print('socket is listening....')
# a forever loop until we exit or an error occurs
while True:
# establish connection with the client
c, addr = s.accept()
print('got connection from: ', addr)
|
aa7fd0504ca8c075cafbeb43e6c438ace88114a1
|
LondonComputadores/Procedural
|
/orientacao_objetos/classe_e_composicao/oop/pessoa.py
| 1,199 | 4.03125 | 4 |
class Pessoa:
olhos=2
def __init__(self, *filhos, nome=None, idade=36):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá! {id(self)}'
@staticmethod
def metodo_estatico():
return 42
@classmethod
def nome_e_atributo_de_classe(cls):
return f'{cls} - olhos {cls.olhos}'
if __name__ == '__main__':
alex = Pessoa(nome='Ahlex')
london = Pessoa(alex, nome='London')
print(Pessoa.cumprimentar(london))
print(id(alex))
print(alex.cumprimentar())
print(alex.nome)
alex.nome = 'Alexandre'
print(alex.nome)
print(alex.idade)
for filho in london.filhos:
print(filho.nome)
london.sobrenome = 'Computadores'
del london.filhos
print(london.__dict__)
print(alex.__dict__)
Pessoa.olhos = 3
print(Pessoa.olhos)
print('Name: {}',format(alex))
print(alex.olhos)
print(id(Pessoa.olhos), id(alex.olhos), id(london.olhos))
print(Pessoa.metodo_estatico(), london.metodo_estatico())
print(Pessoa.nome_e_atributo_de_classe(), alex.nome_e_atributo_de_classe())
|
6f27800bd37d78a4b327a5ac870abd338246b6d0
|
punzoamh/StockMarket_MachineLearning
|
/days.py
| 1,950 | 3.890625 | 4 |
import time
import calendar
import datetime
from dateutil import rrule
from datetime import date, timedelta
def main():
text_file = open("start_dates.txt", "w")
date_start_obj = date(2014, 3, 17)
date_end_obj = date(2015, 3, 17)
days = 100
"""
Find_dates_cpy() will get the start date
for a given numner of days and a given end date
"""
#print find_dates_cpy(300, date_start_obj)
"""
From the date that find_dates_cpy() returns to
date_start_obj is 300 days
"""
#print get_working_days(find_dates_cpy(300, date_start_obj),date_start_obj)
while(days < 5000):
text_file.write(str(days) + ' ' + str(find_dates_cpy(days,date_end_obj)) + '\n')
print days, ' ', find_dates_cpy(days,date_end_obj)
days += 100
text_file.close()
"""
Gets number of days excluding weekends between two dates
"""
def get_working_days(date_start_obj, date_end_obj):
weekdays = rrule.rrule(rrule.DAILY, byweekday=range(0, 5), dtstart=date_start_obj, until=date_end_obj)
weekdays = len(list(weekdays))
if int(time.strftime('%H')) >= 18:
weekdays -= 1
return weekdays
"""
Finds the start date given a number of days and the end date
"""
def find_dates_cpy(days, end_date):
end_date = end_date
days = days
month = end_date.month
year = end_date.year
the_day = end_date.day
start_date = date(year,month,the_day)
while(days > get_working_days(start_date,end_date)):
start_date = start_date - datetime.timedelta(days=1)
#print get_working_days(start_date,end_date)
#print start_date, end_date
#print start_date
return start_date
"""
Gets the last day of the given month of a given year
The input for this function will be calendar.monthrange(year,month)
but we don't really need this anymore
"""
def get_day_month(dates):
dates = str(dates)
days = dates[4] + dates[5]
return days
main()
|
fced51021403b2c1b6ee87cf7f67f5273aa462a6
|
JeisyLiu/Repository_Charlie
|
/VariousFeatures/ComputerVision/geometricTransform.py
| 1,862 | 3.671875 | 4 |
import matplotlib.pyplot as plt
import numpy as np
import cv2 as cv
#####################-------------GEOMETRIC TRANSFORMATIONS IN MATRIX LEVEL-----------------#####################
imgsrc = cv2.imread('resource/bflog.png')
height, width, thickness = imgsrc.shape
# resize/scale the image
alpha = cv2.resize(imgsrc, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
cv2.imshow('alpha', alpha)
cv2.waitKey(0)
apples = cv2.resize(imgsrc, (width*2, height*2), interpolation=cv2.INTER_CUBIC)
cv2.imshow('apples', apples)
cv2.waitKey(0)
cv2.destroyAllWindows()
# translate the image
bravo = np.float32([[1, 0, 20], [0, 1, 100]]) # this is a multiplied matrix
res = cv2.warpAffine(imgsrc, bravo, (width *2, height *2))
cv2.imshow('bravo', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
#rotate the image
#charlie = cv2.getRotationMatrix2D(((width-1)/2.0, (height)/2.0), 90, 1) # set the center of the rotated image
charlie = cv2.getRotationMatrix2D((width/2, height/2), 90, 1)
res = cv2.warpAffine(imgsrc, charlie, (height* 2, width* 2))
cv2.imshow('charlie', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
# affine transformation
pts1 = np.float32([[50,50],[200,50],[50,200]])
pts2 = np.float32([[10,100],[200,50],[100,250]])
delta = cv2.getAffineTransform(pts1,pts2)
dst = cv2.warpAffine(imgsrc,delta,(width, height))
plt.subplot(121),plt.imshow(imgsrc),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()
# Perspective transformation
pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])
echo = cv2.getPerspectiveTransform(pts1,pts2)
dst = cv2.warpPerspective(imgsrc,echo,(300,300))
plt.subplot(121),plt.imshow(imgsrc),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()
|
91bd2e803e12dae1fb6dad102e24e11db4dfdb03
|
ZainabFatima507/my
|
/check_if_+_-_0.py
| 210 | 4.1875 | 4 |
num = input ( "type a number:")
if num >= "0":
if num > "0":
print ("the number is positive.")
else:
print("the number is zero.")
else:
print ("the number is negative.")
|
e83307352d949e4f20c8e1c1acb181de0a56a496
|
Creater2kTen/Path-Finding-Alogrithms-Visual-Representation
|
/algorithms/a_star_m.py
| 4,543 | 4.1875 | 4 |
from queue import PriorityQueue
from algorithms.heuristics import h1
import time
import pygame
def algorithm(start, end, grid, draw, win):
"""
This implementation uses a priority queue for its frontier.
The runtime and space complexity depends on the heuristic.
This is a version of weighted A* search which can calculate
shortest path when the path weights are not all the same.
A* Search is guaranteed to return the shortest path.
The theoretical time complexity is O(b ^ d)
The space complexity is also O(b ^ d)
where b is the branching factor (number of successor nodes per state)
and d is the depth of the shortest path to the end node
"""
start_time = time.time()
# Used for a tiebreaker in case of two nodes with similar F scores
position = 0
# Priority Queue to pop the current best node (node with lowest f_score)
# The frontier is the queue of nodes that are currently being considered
frontier = PriorityQueue()
frontier.put((0, position, start))
# Keeps track of the paths by saving references to where each node came from
path = {}
# A set of all nodes that were visited
visited = {start}
# G score is the distance (num of nodes) between the current node and the starting node
# A dictionary that holds a Node mapped to its individual G score for every node in grid
g_score = {Node: float("inf") for row in grid for Node in row}
g_score[start] = 0
# F score = G score + H score, where H score is the Heuristic (manhattan distance)
# A dictionary that holds a Node mapped to its individual F score for every node in grid
f_score = {Node: float("inf") for row in grid for Node in row}
f_score[start] = h1(start.get_position(), end.get_position())
# While there is still a possible path
while not frontier.empty():
draw()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
win.paused = not win.paused
if pygame.mouse.get_pressed(3)[0]:
pos = pygame.mouse.get_pos()
if 660 <= pos[1] <= 690:
if 150 <= pos[0] <= 270:
if win.speed == "Fast":
win.speed = "Medium"
elif win.speed == "Medium":
win.speed = "Slow"
else:
win.speed = "Fast"
if win.speed == "Medium":
pygame.time.wait(10)
elif win.speed == "Slow":
pygame.time.wait(50)
if win.paused:
continue
# At the start of every iteration, pop the lowest f score node from priority queue
current_node = frontier.get()[2]
# If we found the solution, draw the path
if current_node == end:
time_taken = float(round(time.time() - start_time, 2))
cost = win.draw_solution(start, end, path, draw)
win.previous_results = [
"A* Manhattan Search Results",
"Total Cost of Path: " + str(cost),
"Time Taken: " + str(time_taken) + " seconds",
"Visited Nodes: " + str(len(visited))]
return True
# This will be the next g score for any neighbours with lower costs
next_g_score = g_score[current_node] + current_node.weight
for neighbour in current_node.neighbours:
# If we found a neighbour node that has a lower cost for reaching goal node
if next_g_score < g_score[neighbour]:
g_score[neighbour] = next_g_score
f_score[neighbour] = next_g_score + h1(neighbour.get_position(), end.get_position()) + neighbour.weight
# Make sure not to add duplicate nodes into the frontier and path
if neighbour not in visited:
path[neighbour] = current_node
visited.add(neighbour)
neighbour.draw_open()
# Increment position in queue
position += 1
frontier.put((f_score[neighbour], position, neighbour))
# Close off the current node because we will not need to look at it again
if current_node not in (start, end):
current_node.draw_visited()
return False
|
c016fa2ea002e0a0e47d4f37063ea975e6a57166
|
MoserMichael/pythoncourse
|
/turtle-clickme.py
| 218 | 3.5 | 4 |
import turtle
s = turtle.Screen()
size = s.screensize()
print("screen size {}", size)
def moveme(x,y):
print("moveme {} {}", x, y)
t.goto(x,y)
t = turtle.Turtle('turtle')
s.onclick( moveme )
turtle.done()
|
fbf776c80d096a6baa836bc16759f7946454780e
|
alexheyuzhang/InteractionLogic
|
/week3_Game.py
| 6,775 | 3.75 | 4 |
# an object describing our player
import re
player = {
"name": "p1",
"items" : [],
"location" : "start"
}
def sword():
print "Do you want to pick it up?"
pcmd = raw_input("please choose yes or no >")
if (pcmd.lower() == "yes"):
print "OH NO! You accidentally woke up the bear who's protecting the diamond!"
pcmd = raw_input("Do you choose to run or fight?")
if (pcmd.lower() =="run"):
print "Sorry! You're not running fast enough because you're carrying the diamond and the sword. The bear caught you and you're dead."
else:
print "Congratulations! Becuase you picked up the sword, you managed to beat the bear and got the diamond!"
print "You're such a warrior! You can now gloriously walk back home and brag about your experience now!"
raw_input("press enter >")
print "to be continued..."
else:
print "Sadly, you will be walking home with empty hands. Your boss might be angry and you could get fired :("
print "But you got another opportunity!"
raw_input("press enter >")
sword()
def steak():
pcmd = raw_input("Do you want to eat it or keep it?")
if (pcmd.lower().strip()[0] == 'e'):
print "Now you've enjoyed the wonderful meal, it's time to move forward..."
raw_input("press enter >")
print "You keep walking, but you got tripped by something..."
raw_input("press enter >")
print "There is a diamond by your feet! How lucky!"
pcmd = raw_input("Do you want to pick it up?")
if (pcmd.lower() == "yes"):
print "OH NO! You accidentally woke up the bear who's protecting the diamond!"
pcmd = raw_input("Do you choose to run or fight?")
if (pcmd.lower() =="run"):
print "Because you ate the steak, you run incredibly fast and you succesfully survived!"
raw_input("press enter >")
print "to be continued..."
else:
print "Sorry, because you didn't pick up the sword before, you have no weapon and you're dead :( "
else:
print "Sadly, you will be walking home with empty hands. Your boss might be angry and you could get fired :("
raw_input("press enter >")
print "to be continued..."
else:
print "Let's keep the meat in the bag and move forward..."
raw_input("press enter >")
print "You keep walking, but you got tripped by something..."
raw_input("press enter >")
print "There is a diamond by your feet! How lucky!"
pcmd = raw_input("Do you want to pick it up?")
if (pcmd.lower() == "yes"):
print "OH NO! You accidentally woke up the bear who's protecting the diamond!"
pcmd = raw_input("Do you choose to feed or fight?")
if (pcmd.lower() == "feed"):
print "Because you kept the steak, you succesfully survived by running when he's eating the steak!"
raw_input("press enter >")
print "to be continued..."
else:
print "Sorry, because you didn't pick up the sword before, you have no weapon and you're dead :( "
else:
print "Sadly, you will be walking home with empty hands. Your boss might be angry and you could get fired :("
raw_input("press enter >")
print "to be continued..."
def InCave():
print "Now you are in cave, you kept walking, and suddenly you see a sword and a steak!"
print "Which one do you choose?"
pcmd = raw_input("Sword or steak?")
if (pcmd.lower() == "sword"):
print ' '
print ' 11 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print '11 1111 11'
print '1111111111'
print ' 11111111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' 1111 '
print ' '
print "You've got a sword! Let's move forward"
raw_input("press enter >")
print "You keep walking, but you got tripped by something..."
raw_input("press enter >")
print "There is a diamond by your feet! How lucky!"
sword()
elif (pcmd.lower() == 'steak'):
print "You've got a "
print' ______ _________ ______ ________ ___ ___ '
print'/_____/\ /________/\/_____/\ /_______/\ /___/\/__/\ '
print'\::::_\/_\__.::.__\/\::::_\/_\::: _ \ \\::.\ \\ \ \ '
print' \:\/___/\ \::\ \ \:\/___/\\::(_) \ \\:: \/_) \ \ '
print' \_::._\:\ \::\ \ \::___\/_\:: __ \ \\:. __ ( ( '
print' /____\:\ \::\ \ \:\____/\\:.\ \ \ \\: \ ) \ \ '
print' \_____\/ \__\/ \_____\/ \__\/\__\/ \__\/\__\/ '
steak()
else:
print 'Sorry you may only choose one'
InCave()
def introStory():
print "Do you have the courage to explore the cave?"
pcmd = raw_input("please choose yes or no >")
# the player can choose yes or no
if (pcmd == "yes"):
print "Great! A miner should be very risk-taking..."
raw_input("press enter >")
InCave()
else:
print "Sorry, you'll starve to death if you don't go"
pcmd = raw_input("press enter >")
introStory() # repeat over and over until the player chooses yes!
# let's introduce them to our world
print "What should I call you?"
player["name"] = raw_input("Please enter your name >")
# intro story, quick and dirty (think star wars style)
print ' _____ ______ _ _ ______ _ _ _______ '
print ' (____ \ /\ (_____ \| | / ) / _____) /\| | | (_______)'
print ' _ \ \ / \ _____) ) | / / | / / \ | | |_____ '
print ' | | | / /\ (_____ (| |< < | | / /\ \ \/ /| ___) '
print ' | |__/ / |__| | | | | \ \ | \_____| |__| \ / | |_____ '
print 'Welcome to the |_____/|______| |_|_| \_) \______)______|\/ |_______)' + " " + player["name"] + "!"
print "You're an experienced miner, and you just discovered a myeterious new cave..."
print "It is pitch dark in the front, and your flashlight is about to run out..."
#print "Do you dare to explore the cave?"
introStory()
|
7fd2447f42c990447529f3bb998c85514a825557
|
nomihadar/Anastomotic-Leak-Prediction
|
/Code/utils/defs_functions.py
| 738 | 3.828125 | 4 |
import pandas as pd
#if string contains Hebrew chars
def containHebrewChars(s):
return any("\u0590" <= c <= "\u05EA" for c in s)
#returns series of Hebrew words in a given df
def getHebrewWords(df):
if (type(df) == pd.Series) or (type(df) == list):
df = pd.DataFrame(df)
hebrewVals = []
#for each column
for column in df:
#if type of column is string
if df[column].dtype == object:
#get unique values
uniqueVals = df[column].astype(str).unique()
#get Hebrew values
hebrew = [val for val in uniqueVals if containHebrewChars(val)]
#save words
hebrewVals.extend(hebrew)
return pd.Series(hebrewVals)
|
d8658563f9d0c93ef9d8636fcf8c05e0a3f5758e
|
schmidt-jake/socialitics
|
/proj1/q2/utils.py
| 2,362 | 3.671875 | 4 |
def scrape(query, n_tweets, lang='en'):
"""
Scrapes Twitter using Tweepy. Returns a dataframe of the most recent tweets that could be found. Also pickles this dataframe as 'raw_tweets/{query}.p'.
Parameters
----------
query: str
Twitter search query.
n_tweets: int
The number of tweets to scrape.
lang: str
The language of tweets to search for. Default is 'en'.
Returns
-------
tweets: Pandas DataFrame
DataFrame where rows are tweets and columns are: timestamp, user_id, user_name, user_loc, user_lang, user_n_follows, text, n_rt
"""
import pandas as pd, tweepy as tp
import time
from tqdm import tqdm_notebook # progress bar
import os
auth = tp.OAuthHandler('wHg7ow24tSmLMR59IVZxWjvwI', 'z0BdVVSTqjYHLFb7TldKssRCOWo7VqvYDAbaKtQLtmx9Cp9Sr9')
auth.set_access_token('1634605514-QSQa8EkY3gWQLdrP44zAKjinRPN99fpdcifOdw6', 'CIRdV9KyWV0PyyaUKfrTDxJyz6T24qjk6dIb0Cs9upjK0')
api = tp.API(auth)
searched_tweets = []
last_id = -1
pbar = tqdm_notebook(total=n_tweets)
while pbar.n < n_tweets:
try:
new_tweets = api.search(q=query, count=1000, max_id=str(last_id - 1), lang=lang) # get tweets older than oldest tweet in last batch
if not new_tweets:
break
for tweet in new_tweets:
searched_tweets.append(dict(
timestamp = tweet.created_at,
user_id = tweet.user.id,
user_name = tweet.user.screen_name,
user_loc = tweet.user.location,
user_lang = tweet.user.lang,
user_n_follows = tweet.user.friends_count,
text = tweet.text,
n_rt = tweet.retweet_count
))
last_id = tweet.id
pbar.update()
if pbar.n >= n_tweets:
pbar.close()
break
except tp.TweepError as e: # we've hit the Twitter API rate limit, need to wait
print('sleeping at', dt.datetime.now().strftime('%-H:%M'))
time.sleep(15*60+30) # sleep 15 min 30 sec -- Twitter API's minimum wait time
if not os.path.exists('raw_tweets'):
os.makedirs('raw_tweets')
pd.DataFrame(searched_tweets).to_pickle(f'raw_tweets/{query.replace(" ","_")}.p')
pbar.close()
return pd.DataFrame(searched_tweets)
|
7f1cef2727c9389bd43bf5dca70acb75be0cceb4
|
ssampaleanu/python-challenge
|
/pyParagraph_SSampaleanu/pyParagraph_SSampaleanu.py
| 1,488 | 3.671875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 12:01:29 2018
@author: Stef
"""
words = []
# stores each word's length as element of list
sentences = []
# stores each sentence's length as element of list
pyPar = open('pyParagraphTest.txt','r')
paragraph = pyPar.read()
print("Here is the passage we'll analyze:")
print('"' + paragraph + '"')
for i in range(0,len(paragraph)):
if paragraph[i] == " ":
# if char is a space
words.append(wordLength)
wordLength = 0
sentenceLength = sentenceLength + 1
elif (paragraph[i] == "." or paragraph[i] == "?" or paragraph[i] == "!"):
# if char is ending punctuation
sentences.append(sentenceLength)
sentenceLength = 0
if i == len(paragraph)-1:
words.append(wordLength)
elif (paragraph[i] != "-" and paragraph[i] != "'" and paragraph[i] != '"'):
# if char is a letter
wordLength = wordLength + 1
wordCount = len(words)
sentCount = len(sentences)
print("--------------------------------")
print("Paragraph Analysis")
print("--------------------------------")
print("Approximate number of words: " + str(wordCount))
print("Approximate number of sentences: " + str(sentCount))
print("Average word length: " + str((sum(words))/wordCount) + " characters")
print("Average sentence length: " + str(wordCount/sentCount) + " words")
|
de1b6587390c72aea50b7c56424c4d751e3c588e
|
hero24/Algorithms
|
/python/cryptography/playfair_cipher.py
| 2,784 | 3.609375 | 4 |
from string import ascii_lowercase
"""
"DON’T WORRY ABOUT THE WORLD ENDING TODAY,
IT’S ALREADY TOMORROW IN AUSTRALIA."
~ CHARLES M. SCHULZ
"""
class PlayfairCipher():
def __init__(self, key=None):
self.mat = [[]]
if key:
alpha = key
else:
alpha = ""
alpha = alpha + ascii_lowercase + ' ' + '0' + '_' + ','
for j in range(36):
for k in range(len(self.mat)):
if not alpha:
break
if alpha[0] in self.mat[k]:
alpha = alpha[1:]
break
else:
if len(self.mat[-1]) > 5:
self.mat.append([])
self.mat[-1].append(alpha[0])
alpha = alpha[1:]
def __rc_check(self, ctl, ptl):
ialph, jalph = None, None
for j in range(len(self.mat)):
if ctl in self.mat[j]:
jalph = self.mat[j]
if ptl in self.mat[j]:
ialph = self.mat[j]
if ialph and jalph:
return ialph, jalph
def __it_pad(self, text):
while len(text) % 2 != 0:
text += ' '
return text.lower()
def encrypt(self, text):
s, text = '', self.__it_pad(text)
for i in range(1,len(text), 2):
ialph, jalph = self.__rc_check(text[i], text[i-1])
if ialph is jalph:
# same row
s += ialph[(ialph.index(text[i-1])+1)%len(ialph)]
s += jalph[(jalph.index(text[i])+1)%len(jalph)]
elif jalph.index(text[i]) == ialph.index(text[i-1]):
# same column
jdx, idx = self.mat.index(jalph), self.mat.index(ialph)
s += self.mat[(idx+1)%len(self.mat)][ialph.index(text[i-1])]
s += self.mat[(jdx+1)%len(self.mat)][jalph.index(text[i])]
else:
s += jalph[(ialph.index(text[i-1])+1)%len(ialph)]
s += ialph[(jalph.index(text[i])+1)%len(jalph)]
return s
def decrypt(self, text):
s, text = "", text.lower()
for i in range(1, len(text), 2):
ialph, jalph = self.__rc_check(text[i], text[i-1])
if ialph is jalph:
s += ialph[ialph.index(text[i-1])-1]
s += jalph[jalph.index(text[i])-1]
elif jalph.index(text[i]) == ialph.index(text[i-1]):
jdx, idx = self.mat.index(jalph), self.mat.index(ialph)
s += self.mat[idx-1][ialph.index(text[i-1])]
s += self.mat[jdx-1][jalph.index(text[i])]
else:
s += jalph[ialph.index(text[i-1])-1]
s += ialph[jalph.index(text[i])-1]
return s
|
9204d593a5997198b10dbd76265ff09fb3750796
|
Midnightbara/COGS-Final-Project
|
/Tester.py
| 789 | 3.578125 | 4 |
"""
Author: Tracy Pham
PID: A13917165
This file contains a method to test the methods in the Dessert.py file.
"""
import pytest
def test_points():
"""
Description: A unit test to test the function called points() in the Dessert.py file.
"""
# Invalid dessert name input
result = points(["carrot cake"])
assert result == [0, 0, 0, 0, 0]
# If the input includes correct inputs
result = points(["fruit tart", "cookies", "chocolate cake", "strawberry shortcake", "panna cotta"])
assert result == [1, 1, 1, 1, 1]
# If the input is not a list
result = points(2)
assert result == [0, 0, 0, 0, 0]
# If the input is not a list of strings
result = points([1, 2, 3, 4, 5])
assert result == [0, 0, 0, 0, 0]
|
aa2744e329c657e00daea0047fe8ac5a01bdcdc6
|
kalebjuliu/Fundamentals-PythonExercises
|
/1/7.py
| 388 | 4.3125 | 4 |
#Exercise 7 : Max of Three
a = 1
b = 5
c = 3
def max_three(num_1, num_2, num_3):
if num_1 > num_2 and num_1 > num_3:
print("The first number is the largest")
elif num_2 > num_1 and num_2 > num_3:
print("The second number is the largest")
if num_3 > num_2 and num_3 > num_1:
print("The third number is the largest")
max_three(a,b,c)
|
65cf972045a5ad1c030c8b19ad06a7740d437259
|
jdf/processing.py
|
/mode/examples/Basics/Structure/Recursion/Recursion.pyde
| 624 | 4 | 4 |
"""
Recursion.
A demonstration of recursion, which means functions call themselves.
Notice how the drawCircle() function calls itself at the end of its block.
It continues to do this until the variable "level" is equal to 1.
"""
def setup():
size(640, 360)
noStroke()
noLoop()
def draw():
drawCircle(width / 2, 280, 6)
def drawCircle(x, radius, level):
tt = 126 * level / 4.0
fill(tt)
ellipse(x, height / 2, radius * 2, radius * 2)
if level > 1:
level = level - 1
drawCircle(x - radius / 2, radius / 2, level)
drawCircle(x + radius / 2, radius / 2, level)
|
fcae7b9b7c3c0ba7a361769637ed544ce25255b8
|
big-data-ai/homemade-machine-learning
|
/homemade/DeepLearn-with-Python/5.1-introduction-to-convnets.py
| 2,366 | 3.734375 | 4 |
from keras import layers
from keras import models
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
print(model.summary())
"""
Using TensorFlow backend.
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 26, 26, 32) 320 = (3*3*1 单元+1个共享参数)*32
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 13, 13, 32) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 11, 11, 64) 18496 = (3*3*32+1)*64
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 5, 5, 64) 0
_________________________________________________________________
conv2d_3 (Conv2D) (None, 3, 3, 64) 36928 = (3*3*64+1)*64
=================================================================
Total params: 55,744
Trainable params: 55,744
Non-trainable params: 0
_________________________________________________________________
None
"""
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
print("Full Network Params: %s", model.summary())
from keras.datasets import mnist
from keras.utils import to_categorical
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1))
test_images = test_images.astype('float32') / 255
train_labels = to_categorical(train_labels)
print("train_labels is:", train_labels)
test_labels = to_categorical(test_labels)
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5, batch_size=64)
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(test_acc)
|
5c604fbb4a46cc704f0d9d73a0c182ccbd8fccc6
|
teddymcw/pythonds_algos
|
/searching_sorting/searches_and_sorts.py
| 3,384 | 4.0625 | 4 |
def binarySearch(alist, item):
if len(alist) == 0:
return False
else:
midpoint = len(alist)//2
if alist[midpoint]==item:
return True
else:
if item<alist[midpoint]:
return binarySearch(alist[:midpoint],item)
else:
return binarySearch(alist[midpoint+1:],item)
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print("binary search 1")
print(binarySearch(testlist, 3))
print("binary search 2")
print(binarySearch(testlist, 2))
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
#print section below shortbubblesort
def shortBubbleSort(alist):
exchanges = True
passnum = len(alist)-1
while passnum > 0 and exchanges:
exchanges = False
for i in range(passnum):
if alist[i]>alist[i+1]:
exchanges = True
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
passnum = passnum-1
alist=[20,30,40,90,50,60,70,80,100,110]
shortBubbleSort(alist)
print(alist)
alist = [54,26,93,17,77,31,44,55,20]
bubbleSort(alist)
print(alist)
print(len(alist))
alist = range(7)
def analyze_bubble_sort1(list):
n = len(list) - 1
print("bub1")
print(n)
#the notebook calls this 'bubble trace'
def analyze_bubble_sort(list):
n = len(list) - 1
print(n)
bubble_comparisons = .5 * n ** 2 - (.5 * n)
return bubble_comparisons
print(analyze_bubble_sort(alist))
def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if alist[location]>alist[positionOfMax]:
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist)
print(alist)
print("insertion sort")
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)
print("why use this range stuff")
def rangeStuff(alist):
print(range(1,len(alist)))
rangeStuff(alist)
print("merge sort")
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i<len(lefthalf) and j<len(righthalf):
if lefthalf[i]<righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i<len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j<len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
|
be5d95f39122b6d0e632f219408e3dbb2d2cd5a8
|
mag-id/epam_python_autumn_2020
|
/homework_3/tasks/task_1.py
| 1,771 | 4.28125 | 4 |
"""
In previous homework task 4,
you wrote a cache function that remembers other function output value.
Modify it to be a parametrized decorator, so that the following code::
```
@cache(times=3)
def some_function():
pass
```
Would give out cached value up to `times` number only.
Example:
```
@cache(times=2)
def f():
return input('? ') # careful with input() in python2, use raw_input() instead
> f()
? 1
'1'
> f() # will remember previous value
'1'
> f() # but use it up to two times only
'1'
> f()
? 2
'2'
```
"""
from typing import Callable
NON_VALID_TIMES = "times must be > 0."
def cache(times=3) -> Callable:
"""
Accepts `function` and returns a result.
If `args`, `kwargs` were called before -
returns corresponded result from cache.
Cached result removed if it was call
more than `times`, by default `times = 3`.
If `times` < 1, `ValueError("times must be > 0.")`
will be raised.
"""
cached, timing = {}, {}
if times < 1:
raise ValueError(NON_VALID_TIMES)
def decorate(function: Callable):
def listen(*args, **kwargs):
"""
Listens `args`, `kwargs` and return an answer.
Tracks how much `times` answer called.
"""
call = f"[{args},{kwargs}]"
if call in timing:
answer = cached[call]
if timing[call] == 1:
del timing[call]
del cached[call]
else:
timing[call] -= 1
return answer
answer = function(*args, **kwargs)
timing[call] = times
cached[call] = answer
return answer
return listen
return decorate
|
e0d307f323f61f45e2a394134483e443cebe863a
|
odora/CodesNotes
|
/Python_cheatsheet/statement_example.py
| 1,501 | 4.21875 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/4/17 23:04
@Author : luocai
@file : statement_example.py
@concat : [email protected]
@site :
@software: PyCharm Community Edition
@desc :
条件、循环语句
"""
a = 3
# if 语句
if a > 0:
print('a =', a)
# if-else
if a > 2:
print('a is ', a)
else:
print('a is less 2')
# if-elif-else
if a > 5:
print('a>5')
elif a > 3:
print('a>3')
else:
print('a<=3')
# 嵌套语句
if a < 0:
print('a<0')
else:
if a > 3:
print('a>3')
else:
print('0<a<=3')
# while 循环
n = 3
while n > 0:
print(n)
n -= 1
# input
promt = "\ninput something, and repeat it."
promt += "\nEnter 'q' to end the program.\n"
message = ""
while message != 'q':
message = input(promt)
print(message)
# for
l1 = [i for i in range(3)]
for v in l1:
print(v)
l2 = ['a', 'b', 'c', 'dd', 'nm']
# 指定区间
for i in range(2, 5):
print(i)
# 指定区间,并加入步长为 10
for j in range(10, 30, 10):
print(j)
# 结合 len 来遍历列表
for i in range(len(l2)):
print('{}: {}'.format(i, l2[i]))
# enumerate()
for i, v in enumerate(l2):
print('{}: {}'.format(i, v))
# continue
for a in range(5):
if a == 3:
continue
print(a)
# break
for a in range(5):
if a == 3:
break
print(a)
# else
for a in range(5):
print(a)
else:
print('finish!')
|
715bf396874f157e67a090a3de84e3759f8c4164
|
codeAligned/Competitive-Programming-4
|
/codeforces/problemset/python_sol/270a.py
| 225 | 3.71875 | 4 |
def Main():
t = int(input())
for i in range(t):
a = int(input())
if a > 59 and 360%(180-a) == 0:
print("YES")
else:
print("NO")
if __name__ == "__main__":
Main()
|
e2a5dd3fcc8c2069539e88b2edf4b81f4cfbf709
|
EslamAmin151/09-21-2018-Remove-Duplicate-and-Pyramid
|
/pyramid.py
| 444 | 3.828125 | 4 |
num = eval(input("Enter an integer from 1 to 15: "))
def as_str(i):
s = ""
if i <10: s = " "
return s + str(i)
#num = 15
allrows = ""
for j in range(1,num+2):
#leading spaces
row = " "*3*(num-j+1)
#backward
for i in range(j-1,1,-1):
s = as_str(i)
row+=s + " "
#forward
for i in range(1,j):
s = as_str(i)
row+=s + " "
row +="\n"
allrows +=row
print (allrows)
|
3a12b562893389a93115d515dfd1438d1244917b
|
harshu232/PythonCode
|
/quiz.py
| 166 | 3.65625 | 4 |
counter = 100
loop_run = 0
while counter >= 1 :
print("Loop Variable Value ",counter)
counter = counter - 5
loop_run = loop_run + 1
print(loop_run)
|
07b0e955ec63968fcac59fd7cbc1aa327dcd7224
|
Barret-ma/leetcode
|
/437. Path Sum III.py
| 1,990 | 3.921875 | 4 |
# You are given a binary tree in which each node contains an integer value.
# Find the number of paths that sum to a given value.
# The path does not need to start or end at the root or a leaf,
# but it must go downwards (traveling only from parent nodes to child nodes).
# The tree has no more than 1,000 nodes and the values are in the
# range -1,000,000 to 1,000,000.
# Example:
# root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
# 10
# / \
# 5 -3
# / \ \
# 3 2 11
# / \ \
# 3 -2 1
# Return 3. The paths that sum to 8 are:
# 1. 5 -> 3
# 2. 5 -> 2 -> 1
# 3. -3 -> 11
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
count = 0
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
if not root:
return
self.count = 0
stack = []
stack.append(root)
while len(stack) > 0:
node = stack.pop()
self.travel(node, sum, node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return self.count
def travel(self, root, target, sum):
if not root:
return
if sum == target:
self.count += 1
# return
if root.left:
self.travel(root.left, target, sum + root.left.val)
if root.right:
self.travel(root.right, target, sum + root.right.val)
root = TreeNode(1)
root_2_1 = TreeNode(-2)
root_3 = TreeNode(-3)
root1 = TreeNode(1)
root3 = TreeNode(3)
root_2_2 = TreeNode(-2)
root_1 = TreeNode(-1)
# [1,-2,-3,1,3,-2,null,-1]
root.left = root_2_1
root.right = root_3
root_2_1.left = root1
root_2_1.right = root3
root_3.left = root_2_2
s = Solution()
print(s.pathSum(root, -1))
|
44ee0bcd14bc6f2dc0cbc010dbde8fcae9b0c0cb
|
rafaelperazzo/programacao-web
|
/moodledata/vpl_data/458/usersdata/316/109645/submittedfiles/programa.py
| 283 | 3.875 | 4 |
# -*- coding: utf-8 -*-
n=int(input('digite a dimensao do tabuleiro: '))
tabuleiro=[]
for i in range(0,n,1):
colunas=[]
for j in range(0,n,1):
colunas.append(float(input('digite o elemento da linhas%d, coluna%d :' %((j+1),(i+1)))))
tabuleiro.append(colunas)
|
04673a56c32021c15acf0b4eec81b6fedf59d8f1
|
epassaro/hcc
|
/06 - Método de Montecarlo/mcpi_parallel.py
| 566 | 3.796875 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 11 03:06:42 2018
@author: epassaro
Simplest 'pure' Python Montecarlo approximation of Pi.
"""
#%%
import numpy as np
from numba import njit, prange
@njit
def mc_pi(n):
x = np.random.uniform(-1, 1, n)
y = np.random.uniform(-1, 1, n)
r = x*x + y*y
return 4.*r[ r <= 1 ].size/n
@njit
def parallel_mc_pi(n,m):
pi_sum = 0.0
for i in prange(m):
pi_sum += mc_pi(n)
return pi_sum/m
print('pi ≃ %.5f' % parallel_mc_pi(100000,100))
|
12ecd86c6b13299496d10598994286931fac8987
|
tiggerntatie/hhs-cp-site
|
/hhscp/static/exemplars/c09exceptions.py
| 2,603 | 3.671875 | 4 |
__author__ = 'ericdennison'
class Square(object):
def __init__(self, side = 1.0):
self.b = side
def area(self):
return self.b**2
def _userinputgeneric(self, member, paramname):
inp = input("What is the {0}? ".format(paramname))
try:
self.__dict__[member] = abs(float(inp))
except ValueError:
print("Sorry: {0} is not a valid {1}.".format(inp, paramname))
raise
def userinput(self):
self._userinputgeneric('b','side length')
def useroutput(self):
print("The area is {0:.6}.".format(self.area()))
class Rectangle(Square):
def __init__(self, base = 1.0, height = 1.0):
self.b = base
self.h = height
def area(self):
return self.b*self.h
def userinput(self):
self._userinputgeneric('b','base length')
self._userinputgeneric('h','height')
class Parallelogram(Rectangle):
pass
class Triangle(Rectangle):
def area(self):
return 0.5*self.b*self.h
class Trapezoid(Rectangle):
def __init__(self, base1 = 1.0, base2 = 1.0, height = 1.0):
self.b = base1
self.b2 = base2
self.h = height
def area(self):
return self.h*(self.b+self.b2)/2.0
def userinput(self):
self._userinputgeneric('b','base length')
self._userinputgeneric('b2','second base length')
self._userinputgeneric('h','height')
class Kite(Square):
def __init__(self, diam1 = 1.0, diam2 = 1.0):
self.d1 = diam1
self.d2 = diam2
def area(self):
return self.d1*self.d2/2.0
def userinput(self):
self._userinputgeneric('d1','diagonal length')
self._userinputgeneric('d2','other diagonal length')
# handlers dictionary relates user command to objects to use
handlers = {
'trapezoid': Trapezoid(),
'square':Square(),
'rectangle':Rectangle(),
'parallelogram':Parallelogram(),
'triangle':Triangle(),
'kite':Kite()}
choice = None
while choice != "none":
choice = input("Find area of a square, rectangle, triangle, parallelogram, trapezoid or kite (or none)? ")
obj = handlers.get(choice,None) # retrieve an object of the correct type, or None if not recognized
if obj:
try:
obj.userinput() # Retrieve values
obj.useroutput() # What is the area
except ValueError:
print("Please try again!")
elif choice != "none":
print ("I'm sorry: I don't know how to find the area of a {0}!".format(choice))
|
da02a8b688d54e39c803c9d8abba3496c1a86632
|
R151153/lasya
|
/addition of sinusoidals.py
| 411 | 3.84375 | 4 |
import matplotlib.pyplot as plt
import numpy as np
f=float(input("enter the frequency"))
fs=float(input("enter the sampled frequency"))
x=np.arange(0,100,0.5)
y=np.sin(2*np.pi*f*x/fs)
plt.subplot(1,5,1)
plt.plot(x,y)
b=np.cos(2*np.pi*f*x/fs)
plt.subplot(1,5,2)
plt.plot(x,b)
c=y+b
plt.subplot(1,5,3)
plt.plot(x,c)
d=y-b
plt.subplot(1,5,4)
plt.plot(x,d)
plt.show()
plt.stem(x,y)
plt.show()
|
20787ae11dd9c7a63f53af2f791cdc737f36b05d
|
andreeavis/python_the_hard_way
|
/ex5.py
| 844 | 4.375 | 4 |
name = "Zara Zaraza"
age = 35 #not a lie
height = 74 # inches
weight = 180 #pounds
eyes = 'Brown'
teeth = 'White'
hair = "Brown"
print(f"Let's talk about {name}.")
print(f"He's {height} inches tall.")
print(f"He's {weight} kg heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hair.")
print(f"His teeth are usually {teeth} depending on the coffee.")
#this line is tricky, try to get it exactly right
total = age + height + weight
print(f"If I add {age}, {height}, and {weight} I get{total}.")
# Try to write some variables that convert the inches and pounds to centimeters and kilograms.
# Do not just type in the measurements. Work out the math in Python.
inches_to_cm = height * 2.54
pounds_to_kg = weight * 0.453596
print(f"His weight is {pounds_to_kg} kg.")
print(f"His height is {inches_to_cm} cm.")
|
59480d948c98983ebb8629ea00a1ac214d40b386
|
frameworkdartboard/ComeOnFeelTheExercism
|
/python/hamming/hamming.py
| 656 | 3.53125 | 4 |
def distance(strand_a, strand_b):
if (strand_a == "" and strand_b != ""):
raise ValueError("strand_a is an empty string but not strand_b.")
elif (strand_b == "" and strand_a != ""):
raise ValueError("strand_b is the empty string but not strand_a.")
lena = len(strand_a)
lenb = len(strand_b)
if (lena > lenb):
raise ValueError("strand_a is longer than strand_b.")
elif (lenb > lena):
raise ValueError("strand_b is longer than strand_a.")
numdiffs = 0
for ii in range(lena):
if (strand_a[ii] != strand_b[ii]):
numdiffs = numdiffs + 1
return(numdiffs)
|
2514dac98084ff0c40730731797cff30b2d358f9
|
kevinb22/BinarizedNMT
|
/translation/models/components/binarization.py
| 10,177 | 3.5 | 4 |
'''
This module implements the binarization of a 1 dimensional convolutional model.
Based on the XNOR net paper: https://arxiv.org/pdf/1603.05279.pdf
Implementation: https://github.com/jiecaoyu/XNOR-Net-PyTorch
The paper and implementation target 2 dimensional convolutions for image classification tasks (MNIST, CIFAR, Imagenet)
where as here we target 1 dimensional convolutions for NLP tasks in particular Neural Machine Translation.
'''
import sys
import math
import torch.nn as nn
import torch
import torch.nn.functional as F
from .binarized_convolution import (
BinConv1d,
)
from .binarized_linear import (
BinLinear,
)
class Binarize(object):
'''
This object wraps the model passed in, to allow binary network training
as described in the xnor paper: Algorithm 1
It cycles through all the modules that the model is using,
and targets every nn.Conv1D being used.
It supports the following methods
binarization(self):
converts all the weights to binarized versions
restore(self):
resets the convolution weights to what they were
before binarization
updateGradients(self):
Updates the gradients using the estimated binarized weights
ex:
binarized_model = Binarize(model)
for ....
binarized_model.binarization()
# compute loss
loss = model.loss(...)
loss.backward()
binarized_model.restore()
binarized_model.updateGradients()
# update the actual model
optimizer.step()
'''
def __init__(
self,
model: nn.Module,
):
super(Binarize, self).__init__()
self.modules = [
BinarizeConvolutionalModule(model),
BinarizeLinearModule(model),
]
def binarization(self):
for module in self.modules:
module.binarization()
def restore(self):
for module in self.modules:
module.restore()
def update_gradients(self):
for module in self.modules:
module.update_gradients()
class BinarizeModule(object):
def __init__(self, model: nn.Module):
pass
def binarization(self) -> None:
pass
def restore(self) -> None:
pass
def update_gradients(self) -> None:
pass
class BinarizeConvolutionalModule(BinarizeModule):
def __init__(
self,
model: nn.Module,
):
super(BinarizeConvolutionalModule, self).__init__(model)
self.model = model
# get the number of conv1d modules
conv1d_count = 0
for m in model.modules():
if isinstance(m, BinConv1d):
conv1d_count += 1
start_range = 0
end_range = conv1d_count
self.bin_range = [i for i in range(start_range, end_range)]
self.num_of_params = len(self.bin_range)
self.saved_params = []
self.target_params = []
self.target_modules = []
index = 0
for m in model.modules():
if isinstance(m, BinConv1d):
# save the weight
m = m.conv
saved_weight = m.weight.data.clone()
self.saved_params.append(saved_weight)
self.target_modules.append(m.weight)
# weight has the shape:
# (out_channel, in_channel, kernel_size)
print("Targeting {} convolutions.".format(len(self.target_modules)))
def meanCenterConvParams(self):
for index in range(len(self.target_modules)):
s = self.target_modules[index].data.size()
negMean = self.target_modules[index].data.mean(1, keepdim=True).\
mul(-1).expand_as(self.target_modules[index].data)
self.target_modules[index].data = self.target_modules[index].data.add(negMean)
def clampConvParams(self):
for index in range(len(self.target_modules)):
self.target_modules[index].data = \
self.target_modules[index].data.clamp(-1.0, 1.0)
def save_params(self):
for index in range(len(self.target_modules)):
self.saved_params[index].copy_(self.target_modules[index].data)
def binarize_conv_params(self):
for index in range(len(self.target_modules)):
# n = kernel_size * in_channels
curr_module = self.target_modules[index].data
n = curr_module[0].nelement()
s = curr_module.size()
# abs mean normalizes every filter and divides by n to get the
# normalized mean
abs_mean = curr_module.norm(1, 2, keepdim=True).sum(1, keepdim=True).div(n).expand(s)
# binarized weight is
# sign(W) * abs_mean
self.target_modules[index].data = curr_module.sign().mul(abs_mean)
def binarization(self):
self.meanCenterConvParams()
self.clampConvParams()
self.save_params()
self.binarize_conv_params()
def restore(self):
for index in range(len(self.target_modules)):
self.target_modules[index].data.copy_(self.saved_params[index])
def update_gradients(self):
for index in range(len(self.target_modules)):
curr_module = self.target_modules[index].data
n = curr_module[0].nelement()
s = curr_module.size()
m = curr_module.norm(1, 2, keepdim=True).sum(1, keepdim=True).div(n).expand(s)
# clamping
m[curr_module.lt(-1.0)] = 0
m[curr_module.gt(1.0)] = 0
# multiply gradients by norm
m = m.mul(self.target_modules[index].grad.data)
# multiply gradients by sign
m_add = curr_module.sign().mul(self.target_modules[index].grad.data)
# sum all the gradients by the sign
m_add = m_add.sum(2, keepdim=True)\
.sum(1, keepdim=True).div(n).expand(s)
# multiply the sum of gradients by sign of th module
m_add = m_add.mul(curr_module.sign())
self.target_modules[index].grad.data = m.add(m_add).mul(1.0-1.0/s[1]).mul(n)
class BinarizeLinearModule(BinarizeModule):
def __init__(
self,
model: nn.Module,
):
super(BinarizeLinearModule, self).__init__(model)
self.model = model
# get the number of conv1d modules
linear_count = 0
for m in model.modules():
if isinstance(m, BinLinear):
linear_count += 1
start_range = 0
end_range = linear_count
self.bin_range = [i for i in range(start_range, end_range)]
self.num_of_params = len(self.bin_range)
self.saved_params = []
self.target_params = []
self.target_modules = []
index = 0
for m in model.modules():
if isinstance(m, BinLinear):
# save the weight
m = m.linear
saved_weight = m.weight.data.clone()
self.saved_params.append(saved_weight)
self.target_modules.append(m.weight)
# weight has the shape:
# (out_dim, in_dim)
print("Targeting {} linear layers.".format(len(self.target_modules)))
def mean_center_conv_params(self):
for index in range(len(self.target_modules)):
s = self.target_modules[index].data.size()
negMean = self.target_modules[index].data.mean(1, keepdim=True).\
mul(-1).expand_as(self.target_modules[index].data)
self.target_modules[index].data = self.target_modules[index].data.add(negMean)
def clamp_conv_params(self):
for index in range(len(self.target_modules)):
self.target_modules[index].data = \
self.target_modules[index].data.clamp(-1.0, 1.0)
def save_params(self):
for index in range(len(self.target_modules)):
self.saved_params[index].copy_(self.target_modules[index].data)
def binarize_conv_params(self):
for index in range(len(self.target_modules)):
# n = kernel_size * in_channels
curr_module = self.target_modules[index].data
n = curr_module[0].nelement()
s = curr_module.size()
# abs mean normalizes every filter and divides by n to get the
# normalized mean
abs_mean = curr_module.norm(1, 1, keepdim=True).div(n).expand(s)
# binarized weight is
# sign(W) * abs_mean
self.target_modules[index].data = curr_module.sign().mul(abs_mean)
def binarization(self):
self.mean_center_conv_params()
self.clamp_conv_params()
self.save_params()
self.binarize_conv_params()
def restore(self):
for index in range(len(self.target_modules)):
self.target_modules[index].data.copy_(self.saved_params[index])
def update_gradients(self):
for index in range(len(self.target_modules)):
if (self.target_modules[index].grad is None):
# ('skipping {}'.format(index))
continue
curr_module = self.target_modules[index].data
n = curr_module[0].nelement()
s = curr_module.size()
m = curr_module.norm(1, 1, keepdim=True).div(n).expand(s)
# clamping
m[curr_module.lt(-1.0)] = 0
m[curr_module.gt(1.0)] = 0
# multiply gradients by norm
m = m.mul(self.target_modules[index].grad.data)
# multiply gradients by sign
m_add = curr_module.sign().mul(self.target_modules[index].grad.data)
# sum all the gradients by the sign
m_add = m_add.sum(1, keepdim=True).div(n).expand(s)
# multiply the sum of gradients by sign of the module
m_add = m_add.mul(curr_module.sign())
self.target_modules[index].grad.data = m.add(m_add).mul(1.0-1.0/s[1]).mul(n)
|
abb7083123fdee70c6d00dc657f165d9db40c550
|
BurnFaithful/KW
|
/Programming_Practice/Python/Base/Bigdata_day1014/FUNCTION05.py
| 736 | 3.8125 | 4 |
# 사칙연산 함수
def inputValue():
return int(input("Enter Input : "))
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
def printValue(x, y):
print(f"{x} + {y} = {add(x, y)}")
print(f"{x} - {y} = {sub(x, y)}")
print(f"{x} * {y} = {mul(x, y)}")
print(f"{x} / {y} = {div(x, y):.2f}")
if __name__ == "__main__":
#a = int(input("Enter First Input : "))
#b = int(input("Enter Second Input : "))
a = inputValue()
b = inputValue()
printValue(a, b)
#print(f"{a} + {b} = {add(a, b)}")
#print(f"{a} - {b} = {sub(a, b)}")
#print(f"{a} * {b} = {mul(a, b)}")
#print(f"{a} / {b} = {div(a, b):.2f}")
|
a2eaee348136d4aeab0b2578332cadfe25883749
|
dedekinds/pyleetcode
|
/base_datastructure/并查集.py
| 488 | 3.515625 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 14:44:23 2019
@author: dedekinds
"""
def findRedundantConnection(edges):
parent = [-1]*(1+max(sum(edges,[])))
def find_root(x):
if parent[x] == -1:return x
parent[x] = find_root(parent[x])
return parent[x]
for u,v in edges:
pu,pv = find_root(u),find_root(v)
if pu == pv:return [u,v]
parent[pu] = pv
edges = [[1,2],[1,3],[2,3]]
print(findRedundantConnection(edges))
|
3558f9cc638a599a7641c54ed215f0a921c62ec1
|
RunzZhang/runze
|
/Test/python_plot_tutorial.py
| 23,765 | 4.03125 | 4 |
# Introduction########
# 1.pycharm 的一些技巧
# comment:
# python comment 行以 "#" 开始
# 但是你可以用鼠标多选多行,然后ctrl+/ 键一次commeent多行
# ctrl + F 查找,这个一般程序都有的,但是查找可以锁定大小写
# ctrl + G 跳段落。当报错告诉你某一行出错的时候,用这个快捷键可以快速跳到某一行
# insert 键。这个可能会被误触。知道再按insert键就可以恢复了
"""另外一种办法是英文的双引号,只需要在段落前后加上即可"""
#2 结构
# 一般是:
# import 部分
# 导入包
# function 部分
# 自定义函数
# class 部分
# 自定义 类
# main 部分
# 主函数
# 这个和c和java应该是类似的,但是c会把函数和类与主函数分开到不同的代码里
""""更多的科学画图的教程:
https://towardsdatascience.com/an-introduction-to-making-scientific-publication-plots-with-python-ea19dfa7f51e
matplot: https://towardsdatascience.com/an-introduction-to-making-scientific-publication-plots-with-python-ea19dfa7f51e
pandas: https://pandas.pydata.org/
有些英文过长也可以去b站找教程,但是元数据都在上面这里。此外这个教程并没有教授一维频率直方图和饼状图,考虑到其潜在使用频率较少的情况。如有
需要,也可以上述matplot的链接查找"""
# 那么现在开始
# 1.import部分
import matplotlib.pyplot as plt # 导入matplotlib中的pyplot包,并且将它在此代码中重命名为plt
import matplotlib as mpl # 导入matplotlib,并且将它在此代码中重命名为mpl
# 主要的python绘画包
from matplotlib import colors, cm # 从matplottlib中导入颜色包
import matplotlib.font_manager as fm
# 从 matplot 中导入字体
import numpy as np
# 导入numpy,主要的处理数据(加减乘除,log,exp函数,还有array(类似于数列,但是可操作性更强))
import pandas as pd
# 导入pandas,主要用于导入数据(csv,excel等),和数据表的批量处理(选出符合标准的行,列,各行列加减的运算)
import os
# 导入系统操作(读入系统路径)
# 2.暂时没有需要定义的全局函数,跳过函数定义部分
# 定义类
class custom_plot():
def __init__(self): # 类的初始化
# def 是因为这是这个类的函数,只能作用于custom_plot类上,在其他类或者主函数中是不能被调用的
# init 表示这个函数里的内容会在类被调用的时候就运行(所以叫初始化),类似于开机就会跑windows系统(初始化)
# 但是其他软件需要手动点击(除初始化函数以外的函数)
# self 表示这个函数作用在custom——plot 类本身上,类定义里的函数变量里第一个都是self(因为这些函数只能作用在本类上)
# ,一开始迷惑不用不用太过纠结
self.currentdir= os.getcwd() # 得到当前文件夹路径
self.base = "D:\\path\\to\\your\\file"
self.base = "C:\\Users\\ZRZ\\Desktop\\python_scientific_plot"
# 类内的变量定义,一开始学习可以粗暴得认为类里得函数都是self+变量名
# 这里是数据得基础路径
# 也可以把当前路径当作基础路径,我这里这么做了
self.address = 'test.xlsx'
# 数据得名称
self.fulladdress = os.path.join(self.base, self.address)
self.waddresss = self.base
# 设置写入路径,它和基础路径一致,当然你也可以自定义
# 数据全路径等于基础路径加数据的文件名
# 回忆os是跟系统路经有关得包
def read_Information(self):
# self.df = pd.read_csv(self.fulladdress)
self.df = pd.read_excel(self.fulladdress)
# 根据你的文件类型,选择读取csv或者excel文件,读取路径是fulladress,并将这个文件保存在df里
# 这里我们用了pandas得包,之后df(dataframe)就可以直接批量操作了
def pandas_practice(self):
# 这里介绍一下pandas的一些操作,可跳过,如果后续不理解可以回溯
# 这里可以当作预处理一个df(data frame)
# 先设置一个空的dictionary
self.blank_dic={}
""" uncomment above to see what is index"""
for idx in range(len(self.df.index)): # for loop
# range取的for loop的循环上下限
# len取得一个列表的长度
# self.df.index 是你的excel表左侧第0行形成的数列,可以看上面绿色的comment
# idx 指的就是行数
if idx % 2 == 0: # idx(行)是偶数
self.blank_dic[idx]=self.df[idx]["column_name"]
"""那么在blank dic里添加一个项目,它的key是idx的数字,他的值是第idx行,名称为《column_name》的列的交叉项"""
"""pandas的一些教程
总体上来说,pandas实现的包含了excel的选取和函数功能
一切都是以self.df 为基础的
其结构:
如果excel表结构是
| A |B |
0 |column1|column2|...
1 | value1| value2|
那么 df的结构是
idx |column1|column2|...
0 | value1| value2|
...
选中行列 self.df[行数][列的名字]
比如 self.df[0][column1]就是value1
当然也可以选择多行,多列,并新建一个新的df
self.df1 = self.df[r1:r2] 选中以r1开始(包含r1)到r2(不包含r2)的所有行
self.df1 = self.df[column_number] 选中名字为colunm_name的列
比如 self.df1 = self.df[column2] 那么 print(self.df1) 就是这样:
idx |column2|
0 | value2|
...
第三种常用的是条件选择
self.df2 = self.df[self.df[column1]=='somevalue']['column3']
《选中列1里值为somevalue的行》 《在这些行里选择列名为column3的那一列》
idx |Sex | ID |city|
0 | Male | 101 |shanghai
1 | Female| 3736 |beijing
2 | Female| 377 | hangzhou
3 | Male | 937 | hefei
self.df2 = self.df[self.df[Sex]=='Female']['city']
那么print(self.df2)就是
idx |city|
1 | beijing
2 | hangzhou
当然不等式条件也是可以的
self.df2 = self.df[self.df[ID]>'400']['city']
idx |city|
1 |beijing
3 | hefei
4.当然平均值mean,方差std都是有的
print(self.df[columnname].mean())
print(self.df[columnname].std())
输出这一列的均值、标准差
如果print(self.df.mean())则会输出所有列的可用均值"""
wdf = pd.DataFrame.from_dict(self.blank_dic, orient = 'index', columns=["column_name"])
# 把上面的self.blank_dic从dict转化为data frame的格式,orient 指的把key设为idx列,把key的value设为column__name的值
wdf.to_csv(self.waddresss+"output.csv", sep=',')
# 把上面的df文档写为output。csv文档,分隔符设为逗号
"""这两部如果不懂可以跳过,除非你需要用到重新写数据"""
def pandas_select(self):
# 从excel表格里选取特定的数据为后续处理
# 以下假设你的表格是m*n 的矩阵,有的有缺省项(NA) ,m 行, n 列
# 这一步的目的是选出作为后续数据处理的横坐标和纵坐标
self.value1 = ""
self.condition1 = ''
self.column11 = ''
self.column12 = ''
self.x1=self.df[self.df[self.condition1]==self.value1][self.column11].to_list()
self.y1=self.df[self.df[self.condition1]==self.value1][self.column12].to_list()
"""不要觉得这很复杂,只是带入很多。这里说的是选取在condition1名称列下其值等于value1的所有数据行
比如,选取性别(condition1)列为男性(value1)的所有行
然后再取这些子表格里的两列(column11, column12)为x和y
比如月份(column11)为x,收入(column12)为y
总体就是选取性别为男性的收入随月份变化
这里需要你自己填写上述变量的值
to_list()函数是把dataframe 的种类变成list [1,2,4]这样的数列"""
self.value2 = ""
self.condition2 = ''
self.column21 = ''
self.column22 = ''
self.x2 = self.df[self.df[self.condition2] == self.value2][self.column21].to_list()
self.y2 = self.df[self.df[self.condition2] == self.value2][self.column22].to_list()
"""一样,选出另一组数据。这里如果需要在同一幅图里画多组数据,那么需要多组数据"""
def plot_line_example(self):
# 给出了x1,y1,x2,y2 在plot_line(没有example后缀) 函数里,你需要利用panda_select得到输入表里的两组数据
# 折线图,输入是两个list,长度需要相等
fig, axs = plt.subplots(1,1,figsize = (3,3)) # 建立画的底板,一共有1行,一列,也就是1*1幅画,x轴y轴长宽比3:3
#当然这里也可以一次性画多张图,不过那个稍微复杂一些,现阶段跳过
self.label1= "Correct"
self.label2 ="Session"
self.title= "Sample of Plot Line" # 图的标题
self.xlabel=r"$\mathregular{\lambda}$ (nm)" # x轴的名字
# r重申后面是字符串(string), \mathregular使用latex,
# $\mathregular{'Command goes here'}$ 来使用latex
self.ylabel='y value' # y轴的名字
self.xlow=0 # x轴下限
self.xhigh=10 # x轴上限
self.ylow = 0 # y轴下限
self.yhigh = 10 # y轴上限
axs.plot(self.x1,self.y1,color="red",label=self.label1)
axs.plot(self.x2, self.y2, color='green',label= self.label2)
# 画出不同颜色的折线,颜色分别为红和绿(可以选择其他的),曲线分别标记label1 和2
axs.legend() # 显示
axs.set_title(self.title)
axs.set_xlabel(self.xlabel, labelpad=10) # labelpad: 调整x轴名称和x轴的距离
axs.set_ylabel(self.ylabel, labelpad=10)
# axs.set_xlim(self.xlow,self.xhigh)
# axs.set_ylim(self.ylow,self.yhigh)
# 如果不想设置一个,直接comment掉那一行
"""此处以下部分为额外要求,有需求可以从中查找,不需要全部设置"""
"""################### || ####################"""
"""####################\ || /#####################"""
"""#################### __ ###################"""
font_names = [f.name for f in fm.fontManager.ttflist] # 列出全部的可选字体
print('font list:', font_names) # 输出上述的list
mpl.rcParams['font.family'] = 'DejaVu Sans Mono' # 选出字体
plt.rcParams['font.size'] = 18 # 选出字号
plt.rcParams['axes.linewidth'] = 2 # 选出坐标轴线宽
axs.spines['right'].set_visible(True)
axs.spines['top'].set_visible(True)
# 选择要不要把图画上和右侧的框去掉,False指去掉
axs.xaxis.set_tick_params(which='major', size=10, width=2, direction='in', top='on')
#设置x轴主要坐标点的大小宽度方向,以及是否在画面上方x轴出现
axs.xaxis.set_tick_params(which='minor', size=5, width=2, direction='in', top='on')
# 设置x轴“次”要坐标点的大小宽度方向,以及是否在画面上方x轴出现
axs.yaxis.set_tick_params(which='major', size=10, width=2, direction='in', right='on')
# 设置y轴主要坐标点的大小宽度方向,以及是否在画面上方x轴出现
axs.yaxis.set_tick_params(which='minor', size=5, width=2, direction='in', right='on')
# 设置y轴次要坐标点的大小宽度方向,以及是否在画面上方x轴出现
# axs.xaxis.set_major_locator(mpl.ticker.MultipleLocator(50))
# #把x轴主要坐标点的间距设为100
# axs.xaxis.set_minor_locator(mpl.ticker.MultipleLocator(25))
# # 把x轴次要坐标点的间距设为25
# axs.yaxis.set_major_locator(mpl.ticker.MultipleLocator(50))
# # 把y轴主要坐标点的间距设为100
# axs.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(20))
# # 把y轴主要坐标点的间距设为20
# 更全面的设置在这个代码一开始的绿色comment里的链接里寻找
# 把文章中的ax换成axs就好了
"""################### -- ##################"""
"""###################/ || \######################"""
"""################### || #####################"""
"""此处以上部分为可选"""
plt.show() #显示图
#显示之后可以直接点击保存来保存
def plot_line(self):
#折线图,输入是两个list,长度需要相等,需要先用pandas_select保存x1,x2,y1,y2
fig, axs = plt.subplots(1,1,figsize = (3,3),sharex= True) #建立画的底板,一共有1行,一列,也就是1*1幅画,x轴y轴长宽比3:3,两个折线图共享x轴
self.label1= ""
self.label2 =" "
self.title="" #图的标题
self.xlabel=r"$\mathregular{\lambda}$ (nm)" #x轴的名字
# r重申后面是字符串(string), \mathregular使用latex,
# $\mathregular{'Command goes here'}$ 来使用latex
self.ylabel='' #y轴的名字
self.xlow=0 #x轴下限
self.xhigh=100 #x轴上限
self.ylow = 0 #y轴下限
self.yhigh = 100 #y轴上限
axs.plot(self.x1,self.y1,color="red",label=self.label1)
axs.plot(self.x2, self.y2, color='green',label= self.label2)
#画出不同颜色的折线,颜色分别为红和绿(可以选择其他的),曲线分别标记label1 和2
axs.legend()# 显示
axs.set_title(self.title)
axs.set_xlabel(self.xlabel, labelpad=10) #labelpad: 调整x轴名称和x轴的距离
axs.set_ylabel(self.ylabel, labelpad=10)
axs.set_xlim(self.xlow,self.xhigh)
axs.set_ylim(self.ylow,self.yhigh)
#如果不想设置一个,直接comment掉那一行
"""此处以下部分为额外要求,有需求可以从中查找,不需要全部设置"""
"""################### || ####################"""
"""####################\ || /#####################"""
"""#################### __ ###################"""
font_names = [f.name for f in fm.fontManager.ttflist]#列出全部的可选字体
print('font list:',font_names) #输出上述的list
mpl.rcParams['font.family'] = 'Avenir' #选出字体
plt.rcParams['font.size'] = 18 #选出字号
plt.rcParams['axes.linewidth'] = 2 #选出坐标轴线宽
axs.spines['right'].set_visible(True)
axs.spines['top'].set_visible(True)
# 选择要不要把图画上和右侧的框去掉,False指去掉
axs.xaxis.set_tick_params(which='major', size=15, width=2, direction='in', top='on')
#设置x轴主要坐标点的大小宽度方向,以及是否在画面上方x轴出现
axs.xaxis.set_tick_params(which='minor', size=7, width=2, direction='in', top='on')
# 设置x轴“次”要坐标点的大小宽度方向,以及是否在画面上方x轴出现
axs.yaxis.set_tick_params(which='major', size=15, width=2, direction='in', right='on')
# 设置y轴主要坐标点的大小宽度方向,以及是否在画面上方x轴出现
axs.yaxis.set_tick_params(which='minor', size=7, width=2, direction='in', right='on')
# 设置y轴次要坐标点的大小宽度方向,以及是否在画面上方x轴出现
axs.xaxis.set_major_locator(mpl.ticker.MultipleLocator(50))
#把x轴主要坐标点的间距设为100
axs.xaxis.set_minor_locator(mpl.ticker.MultipleLocator(25))
# 把x轴次要坐标点的间距设为25
axs.yaxis.set_major_locator(mpl.ticker.MultipleLocator(50))
# 把y轴主要坐标点的间距设为100
axs.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(20))
# 把y轴主要坐标点的间距设为20
# 更全面的设置在这个代码一开始的绿色comment里的链接里寻找
# 把文章中的ax换成axs就好了
"""################### -- ##################"""
"""###################/ || \######################"""
"""################### || #####################"""
"""此处以上部分为可选"""
plt.show() # 显示图
# 显示之后可以直接点击保存来保存
def bar_1d(self):
# 柱状图,可以区分下bar(柱状图)和hist(直方图)的区别。他们很类似,但是也有区别
# hist偏向统计,记录的是频次。但是bar不用,当记录的值是频次的时候他等于直方图,当不是的时候就不等于
# 举个例子。柱状图的输入是[1月到12月],[1月到12月的下雨天数]。直方图记录的是[1-365天][有没有下雨],然后再把365天按照12月分下来
# 但是如果柱状图表示的是1-12月平均气温,就没有直接等同的直方图了。
# 总体来说,直方图更偏向统计意义
# 预输入和line_plot类似,但是分享横坐标,所以只有一个x
# self.x1, self.y1, self.y2
distance = 0.2 # 两相邻需要比较的bar之间的距离
x_position = np.arange(len(self.x1)) #需要给各bar安排位置,
label1 = 'Correct'
label2= ' Session'
fig, axs = plt.subplots(1, 1, figsize=(3, 3))
axs.bar(x_position - distance, self.y1, 0.4, label=label1)
# 画出数组1的bar,x位置在标准位置向左偏distance,高度为self.y1,宽度为0.4,记录为label1
axs.bar(x_position + distance, self.y2, 0.4, label=label2)
# 画出数组2的bar,x位置在标准位置向右偏distance,高度为self.y2,宽度为0.4,记录为label2
axs.legend()
# 有label就需要legend显示label
axs.set_xticks(x_position)
axs.set_xticklabels(self.x1)
# 其他选项和line类似
plt.show()
def color_hist_2d(self):
# 2d 平面颜色渲染的直方图
# 数据需要预处理
# 假设一组数据,出现的坐标分别为(v0,w0),(v1,w1)....那么需要x1,y1满足
# self.x1=[v0,v1,v2...]
# self.y1=[w0,w1,w2...]
# 画出这组数据的折方图
bins= 40 # 因为是直方统计,所以需要bin数
fig, axs = plt.subplots(1, 1, figsize=(3, 3)) # 建立画的底板,一共有1行,一列,也就是1*1幅画,x轴y轴长宽比3:3
(h, xedge, yedge, image)=axs.hist2d(self.x1, self.y1, bins=bins, norm=colors.Normalize(), cmap='plasma')
# 等式的含义这里是指先运算(绘画)等式右边的内容,再把计算得到的其他参数赋值到左边
# 左边的比较复杂,可以查询资料,这里不多阐述
# bin是每边的统计格数,如果20就是20个格子。
# norm是说值要不要归一化,一般选择是
# plasma是颜色的渐变条件,plasma是从蓝到红
fig.colorbar(image, ax=axs)
# fig 和image 是上一步得到的输出,这里我们在这幅图旁画上归一化的颜色参考比例尺
#####################################################
####### 其他参数设置和line_plot一致,都是对axs设置 ##########
#####################################################
plt.show()
def color_2d(self):
# 数据依旧需要预处理
# 需要一个2d的矩阵
# [[v00,v01,v02,v03,...],
# [v10,v11,...........],
# [v20,v21,...........],
# .......................]
# color_2d 和color_hist_2d的区别是,hist输入的是每次数据的坐标,而前者是该坐标下的函数值(但是不含坐标,坐标有额外的输入)
# 举个例子,如果把一把沙撒到地上,那么每粒沙落到地面的坐标组成的一组坐标列,就是hist
# 而如果把地面各地点沙子高度的值记录下来,就是非hist
# 可以把color_2d理解为2d的bar(柱状图),而hist是频数直方图
self.array = [[5,2],[7,3]]
self.xlow= 0
self.xhigh = 10
self.ylow = 0
self.yhigh = 10
# xy轴(坐标系)的范围
fig, axs = plt.subplots(1, 1, figsize=(3, 3))
image = axs.imshow(self.array, extent=(self.xlow,self.xhigh,self.ylow,self.yhigh), cmap='plasma')
# 类似得,在(self.xlow,self.xhigh,self.ylow,self.yhigh)的范围里画出图像
fig.colorbar(image, ax=axs)
plt.show()
def pandas_select_sample(self):
# 这是一个案例,真实如何选择需要去pandas_select里编辑
# 用不等式替代了等式条件
self.x1=self.df[self.df['Correct']>=6]['Name'].to_list()
self.y1=self.df[self.df['Correct']>=6]["Correct"].to_list()
self.x2 = self.df[self.df['Correct']>=6]['Name'].to_list()
self.y2 = self.df[self.df['Correct']>=6]["Session"].to_list()
# 这里是主函数,在这里调用我们编写的类和函数
if __name__=="__main__":
""" 这部分是一个案例,如果不能运行,应该是环境或者IDE设置的问题。"""
practice =custom_plot() # 调用类,放到一个新的变量里,这里类的__init__函数会自动运行
practice.read_Information() # 读入示例的数据
practice.pandas_select_sample() # 使用pandas在读入的表里,选入某个条件下的x1,y1,x2,y2的值
practice.plot_line_example() # 利用数据画出折线图
practice.bar_1d() # 利用数据画出柱状图
practice.x1=practice.y2 # color_hist_2d的预处理,为了画频率图,因为函数默认处理x1,y1,但是示例里x1是字符串,所以把y2赋值给x1,让x1,y1都是数
# 这一步也可以看出,可以在主函数中给self.x1和self.y1直接赋值。如果这一步发生在类的函数里那就是self.x1=self.y2(因为self就是custom_plot类本身)
practice.color_hist_2d() # 利用数据画2d频率直方图
practice.color_2d() # 利用数据画出2d柱状图
"""在上面的可以运行后,想要运行你自己的数据,你需要执行以下几步
1.调整class custom_plot里的self.base和self.address的值,使得最后的路径读取你需要的excel表格
2.在read_information()里, 调整读取的是excel还是csv类型。comment 掉你不需要的部分
3.在pandas_select函数里,选择你自己挑选的条件
4.在plot_line/bar_1d/color_hist_2d/color_2d里,设置你需要的参数
5.然后运行以下代码,别忘了comment掉这个段落前的案例"""
# practice = custom_plot()
# practice.read_Information()
# practice.pandas_select()
# practice.plot_line()
# practice.bar_1d()
# # practice.color_hist_2d()
# # practice.color_2d()
# 选择你需要的函数uncomment,如果有多个没有被comment, 那么会同时画出多个图片
|
a937235ef801c6c1515ed047a2eafd4b03d02356
|
samyakjain101/DSA
|
/bit_manupulation/q020_power_of_two.py
| 346 | 3.6875 | 4 |
"""Problem Statement
https://leetcode.com/problems/power-of-two/
"""
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n <= 0:
return False
if n & (n-1) == 0:
return True
return False
if __name__ == "__main__":
num = 16
test = Solution()
print(test.isPowerOfTwo(num))
|
fa5f70bb6bb03ef0132db5d17b76a54d88982c47
|
Aasthaengg/IBMdataset
|
/Python_codes/p02417/s271430431.py
| 290 | 3.625 | 4 |
alphabets = "abcdefghijklmnopqrstuvwxyz"
#print(len(alphabets))
#a = len(alphabets)
#print(a)
x = ''
while True:
try:
x += input().lower()
except EOFError:
break
for i in range(len(alphabets)):
print("{0} : {1}".format(alphabets[i], int(x.count(alphabets[i]))))
|
d8a5fc6b82b44a8fa362b461748909da75bbbf97
|
jaeyoung-cho/TIL_Python
|
/Basic/pdb/src/example.py
| 342 | 4.125 | 4 |
import pdb
def calc(operator, num1, num2):
pdb.set_trace()
if operator is '+':
return num1 + num2
elif operator is '-':
return num1 - num2
elif operator is '*':
return num1 * num2
else:
return num1 / num2
pdb.set_trace()
num1 = 100
num2 = 5
result = calc('*', num1, num2)
print result
|
54946fd6aeb9d615641b6543f52a9cc8e0bca09d
|
thegabriele97/python-lab2
|
/ex3.py
| 1,982 | 3.828125 | 4 |
import sys
def main(argv):
lst = []
print("Welcome to note 3000 revolution!")
if len(argv) > 1:
print("Loading from %s.." % argv[1])
load_file(lst, argv[1])
print("Done!")
while True:
print()
selected_int = int(show_prompt())
selected_int -= 1
if selected_int == 0:
note = input("Note: ")
if note == "":
print("Error: insert a name.\n")
continue
lst.append(note)
elif selected_int == 1:
sub_str = input("Substring: ")
if sub_str == "":
print("Error: it can't be void!\n")
continue
for note in lst:
if sub_str in note:
lst.remove(note)
print(" - '%s' removed.\n" % note)
elif selected_int == 2:
lst.sort()
print()
print(*map(lambda e: "%d) %s" % (lst.index(e) + 1, e), lst), sep=";\n", end=".\n")
elif selected_int == 3:
if len(argv) > 1:
print("Saving to %s.." % argv[1])
save_file(lst, argv[1])
print("Done!")
break
def show_prompt():
entries = [
"insert a new task (a string of text)",
"remove a task (by typing a substring)",
"show all existing tasks, sorted in alphabetic order",
"close the program"]
print(*map(lambda e: "%d. %s" % (entries.index(e) + 1, e), entries), sep=";\n", end=".\n")
return input(" > ")
def load_file(list_obj, file_name):
file_in = open(file_name, "r")
for line in file_in.readlines():
list_obj.append(line[0:len(line) - 1])
def save_file(list_obj, file_name):
file_out = open(file_name, "w")
for note in list_obj:
file_out.write(note + "\n")
if __name__ == "__main__":
main(sys.argv)
|
5d12616f8ceff0ba0ad40a464612932b95bb8a94
|
lokeshlk368/Python-Programming
|
/TableOfNumber.py
| 93 | 3.9375 | 4 |
num=int(input("Enter a number"))
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i))
|
6065f3a83a2b8a40e7860b4032402930dff7fce1
|
PedroRamos360/PythonCourseUdemy
|
/kivy/aulas/Seção 15 - Funções/Exercicios/Ex14.py
| 155 | 3.734375 | 4 |
def fatorial(numero):
index = numero
while index > 1:
index -= 1
numero *= index
return numero
print(fatorial(int(input())))
|
59a8707da56060407a32ad9590848232bc305aa3
|
Camicam311/Educational-Projects
|
/Survey of Programming Paradigms /Brute Force Password Cracker/crack.py
| 3,092 | 3.84375 | 4 |
from misc import *
import crypt
def load_words(filename,regexp):
"""Load the words from the file filename that match the regular
expression regexp. Returns a list of matching words in the order
they are in the file."""
list = []
with open(filename) as f:
for line in f:
words = line.split()
for word in words:
if(re.match(regexp, word)):
list.append(word)
return list
def transform_reverse(str):
return [str, str[::-1]]
def transform_capitalize(str):
def helper(str):
if not str:
yield ""
else:
char = str[:1]
if char.lower() == char.upper():
for cur_case in transform_capitalize(str[1:]):
yield char + cur_case
else:
for cur_case in transform_capitalize(str[1:]):
yield char.lower() + cur_case
yield char.upper() + cur_case
return list(helper(str))
def transform_digits(str):
dict = {'o':['o', '0'], 'z':['z', '2'], 'a':['a', '4'],
'b':['b', '6', '8'], 'i':['i', '1'], 'l':['l', '1'],
'e':['e', '3'], 's':['s', '5'], 't':['t', '7'],
'g':['g', '9'], 'q':['q', '9']}
def helper(str, list):
if not str:
return list
first = str[:1]
if dict.has_key(first.lower()):
mapping = dict[first.lower()]
else:
mapping = [first.lower()]
new_list = []
if not list:
return helper(str[1:], mapping)
else:
for substr in list:
for new_char in mapping:
new_list.append(substr + new_char)
return helper(str[1:], new_list)
return helper(str, [])
def check_pass(plain,enc):
"""Check to see if the plaintext plain encrypts to the encrypted
text enc"""
salt = enc[:2]
cryptedplain = crypt.crypt(plain, salt)
if cryptedplain == enc: return True
else: return False
def load_passwd(filename):
"""Load the password file filename and returns a list of
dictionaries with fields "account", "password", "UID", "GID",
"GECOS", "directory", and "shell", each mapping to the
corresponding field of the file."""
listdict = []
with open(filename) as f:
for line in f:
values = line.split(":")
record = {'account': values[0], 'shell': re.sub('[\r\n]+','',values[6]), 'UID': values[2], 'GID': values[3], 'GECOS': values[4], 'directory': values[5], 'password': values[1]}
listdict.append(record)
return listdict
def crack_pass_file(fn_pass,words,out):
"""Crack as many passwords in file fn_pass as possible using words
in the file words"""
accountDict = load_passwd(fn_pass)
wordDict = load_words(words, '[a-z]{6,8}')
print str(len(wordDict)) + " words loaded... \n"
outfile = open(out, 'w+')
for record in accountDict:
for word in wordDict:
if check_pass(word.lower(),record['password']) == True:
outfile.write(record['account'] + '=' + word + "\n")
continue
outfile.close()
|
f9be7658465680386db6e86093e7ea8ee1d47b00
|
abu6912/codewars
|
/code/pyscripts/simple_pig_latin.py
| 326 | 3.8125 | 4 |
text = 'Pig latin is cool'
def pig_it(text):
text = text.split(' ')
out = ''
for word in text:
if word.isalpha():
init = word[0]
rest = word[1:]
out += ' {0}{1}ay'.format(rest, init)
else:
out += ' ' + word
return out.strip()
print pig_it(text)
|
af2c458ba8c7437c3531923c1f008d53d7704864
|
ThomasSelvig/MazeAlgo
|
/dfsmazegen.py
| 1,604 | 3.53125 | 4 |
from PIL import Image
import random, sys
def availNodes(x, y, visited, pixels, size):
w, h = size
nodes = [] # ((x, y), (x1, y1)) where x,y is the "destination node" (the one checked) and x1,y1 is the "road node" bridging the dest node and "parameter given" node
# up
if y-2 >= 0 and y-2 < h and pixels[x, y-2] == (0xff, 0xff, 0xff):
nodes.append(((x, y - 2), (x, y - 1)))
# left
if x-2 >= 0 and x-2 < w and pixels[x-2, y] == (0xff, 0xff, 0xff):
nodes.append(((x - 2, y), (x - 1, y)))
# down
if y+2 >= 0 and y+2 < h and pixels[x, y+2] == (0xff, 0xff, 0xff):
nodes.append(((x, y + 2), (x, y + 1)))
# right
if x+2 >= 0 and x+2 < w and pixels[x+2, y] == (0xff, 0xff, 0xff):
nodes.append(((x + 2, y), (x + 1, y)))
return [node for node in nodes if node[0] not in visited]
def nodeAction(x, y, maze, pixels, visited=None):
if visited is None:
visited = []
while nodes := availNodes(x, y, visited, pixels, maze.size):
node, middleNode = random.choice(nodes)
# draw a road
pixels[node] = 0, 0, 0
pixels[middleNode] = 0, 0, 0
# do it again
nodeAction(*node, maze, pixels, visited=visited+[(x, y)])
if len(nodes) == 1:
return x, y
def main():
sys.setrecursionlimit(round(1e6))
rootSize = 151
maze = Image.new(size=(rootSize, rootSize), mode="RGB", color=(0xff, 0xff, 0xff))
pixels = maze.load()
pixels[rootSize // 2, rootSize // 2] = 0, 0, 0xff
nodeAction(rootSize // 2, rootSize // 2, maze, pixels)
pixels[rootSize - 2, 1] = 0xff, 0, 0
maze.save("maze.png")
if __name__ == '__main__':
main()
|
700a747086036c6cea939e6735930c2393040fdb
|
liupy525/LeetCode-OJ
|
/46_Permutations.py
| 779 | 4.09375 | 4 |
#!/usr/local/env python
# -*- coding: utf-8 -*-
'''
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
'''
class Solution:
# @param num, a list of integer
# @return a list of lists of integers
def permute(self, num):
if not num:
return []
if len(num)==1:
return [num]
if len(num)==2:
return [num, num[::-1]]
result = []
for i in range(len(num)):
temp = num[:]
temp.pop(i)
l = self.permute(temp)
result.extend([ [num[i]]+t for t in l ])
return result
num = [1,2,3,4]
t = Solution()
print t.permute(num)
|
b352f0f6f1a1c6f403354b2d5b781cd6c9c2c3f4
|
s2e-lab/SecurityEval
|
/Testcases_Copilot/CWE-117/author_1.py
| 400 | 4.21875 | 4 |
import logging
def inputConversion():
'''
take a string input from the user
convert it to an integer within try-except block and log the error
return the user input after converting it to an integer
'''
try:
user_input = input("Enter a number: ")
user_input = int(user_input)
except ValueError:
logging.error("Invalid input")
return user_input
|
598abfb0336a6ed3702817684de046affbd4c32f
|
shnu2018/python
|
/第8章/教学案例代码/单元测试.py
| 806 | 3.765625 | 4 |
import unittest
class HelloWorldTestCase(unittest.TestCase):
"""测试类必须继承自TestCase, 要测试的函数也必须以test开头"""
def setUp(self):
"""每执行一个测试函数之前,都会首先调用这个setUp()方法"""
print('setUp() method will run first!\n')
def test_hello_world(self):
a = 100
self.assertEqual(100, a)
def test_nihao(self):
a = 10
self.assertEqual(100, a)
def test_shijie(self):
a = 10
self.assertEqual(100, a)
def hello_world(self):
"""这个函数不是test开头的,所以将不会被当做测试函数"""
a = 100
self.assertEqual(100, a)
# 调用main()会自动进行测试工作
unittest.main()
|
54b4a59cbbe29bb18492c86e2ac53aed6c6877f4
|
casperolesen/my_notebooks
|
/my_modules/Week_3/Course.py
| 477 | 3.65625 | 4 |
class Course():
def __init__(self, name, classroom, teacher, ETCS, grade=None):
self.name = name
self.classroom = classroom
self.teacher = teacher
self.ETCS = ETCS
self.grade = grade
def __str__(self):
return 'Name: {name}, Classroom: {classroom}, Teacher: {teacher}, ETCS: {ETCS}, Grade: {grade}'.format(
name=self.name, classroom=self.classroom, teacher=self.teacher, ETCS=self.ETCS, grade=self.grade)
|
32386ed1883f53d2a3928d1660c7a5832e14bd6d
|
RashlyEndemic/ItalianDay
|
/ItalianDay.py
| 1,530 | 3.859375 | 4 |
#shot = 10
#beer = 5
#wine = 1
def drinking_game():
print("Welcome to Italian Day!")
user = input("What is your name? ")
print("The rules are simple. Don't drink too much.")
import random
sobriety = 0
shot = 0
beer = 0
wine = 0
while sobriety < random.randint(89,121):
drink = input("Choose a (s)hot, a (b)eer, or a glass of (w)ine: ")
if drink == "s":
sobriety += 10
shot += 1
print("Your alcohol content is now",sobriety,user)
if drink == "b":
sobriety += 5
beer += 1
print("Your alcohol content is now",sobriety,user)
if drink == "w":
sobriety += 3
wine += 1
print("Your alcohol content is now",sobriety,user)
food = input("Choose to eat (m)eat and cheeses, (c)heese cake, or (s)alad: ")
if food == "m":
sobriety -= 7
print("Your alcohol content is now",sobriety,user)
if food == "c":
sobriety += 100
print("Your alcohol content is now",sobriety,user)
if food == "s":
sobriety -= 2
print("Your alcohol content is now",sobriety,user)
print("//////////////////////////////////////////////////////////////////////////////")
print("You're shit faced",user,"and made a mess of the bathroom!")
print("You had",shot,"shots,",beer,"beers, and",wine,"glasses of wine!")
print("GAME OVER MAN GAME OVER")
drinking_game()
|
3747b4d8a5d6ced465b4d59758948ca20de51be2
|
OOOIOOOIO/Basic_study_for_Machine_Learning
|
/BeautifulSoupBasic/CSS03.py
| 848 | 3.640625 | 4 |
# 스타일시트 연습
from bs4 import BeautifulSoup
# html 파일 열기
fp = open(r"C:\Users\polit\python_MachineLearning\BS\book.html", "r", encoding = "utf-8")
soup = BeautifulSoup(fp, "html.parser")
# 똑같은 표현
print(soup.select_one("ul#itBook > li#DataScience").string) # ul의 id가 idBook이고 그 l 밑에 li id가 DataSciende 인 요소
print(soup.select_one("ul > li#DataScience").string) # ul 밑에 li의 id가 DataSciende 인 요소
print(soup.select_one("#itBook > #DataScience").string)
print(soup.select_one("#itBook #DataScience").string) # ">" 생략 가능
print(soup.select_one("#DataScience").string)
print(soup.select_one("li[id='DataScience']").string)
print(soup.select_one("li:nth-of-type(3)").string)
print(soup.select("li")[3].string) # 4번째 li 선택
print(soup.find_all("li")[3].string) # 똑같음
|
adec90e1bcd2ef78cd772b602c1e316d2a295e83
|
Guilherme2020/ADS
|
/Algoritmos 2016-1/1-lista(professor_fabio)/6.py
| 292 | 3.90625 | 4 |
#Leia uma velocidade em km/h,
#calcule e escreva esta velocidade em m/s. (Vm/s = Vkm/h / 3.6)
velocidade_kmh = float(input("Insira a velocidade em km/h"))
velocidade_metros_segundo = velocidade_kmh/3.6
print(" %.2fKm/h equivale a %.2f m/s "%(velocidade_kmh,velocidade_metros_segundo))
|
8c9509866193b9315726ebad1c90883335db789b
|
brendo61-byte/pythonOnBoarding
|
/old_Learning_Sets/Learning_Set_1:Entry_Level/3_varbles_basics_pt_2.py
| 1,072 | 4.09375 | 4 |
"""
What you will learn:
- How to add, subtract, multiply divide numbers
- Float division and integer division
- Modulus (finding the remainder)
- Dealing with exponents
- Python will crash on errors (like divide by 0)
Okay now lets do more cool things with variables. Like making python do math for us!
What you need to do:
Pt 1
- solve x = 45 + 4(4/6+2)^5 --- should = 584.391
- solve x = (4/5*5+1)^.5 --- should = 2.23607
Pt 2
- understand why divide0 and divide1 have different results
- what is mod0 and mod1
- write code to determine if 39879827239498734985798 is divisible by 3 without a remainder
Pt 3
- divide a number by 0. Watch what happens. Note the type of error it is
Pt 4
- try to add an int and string together. What happens?
"""
x = 6
y = 2
adder = x + y # some simple addition
suber = x - y # some simple subtraction
multr = x * y # some simple multiplication
divide0 = x / y
divide1 = x // y
mod0 = x % y
mod1 = y % x
power = x ** 6 # the "**" means to the power of
p0 = "Hi "
P1 = " My Name IS"
P2 = " Slime Shady"
P = p0 + P1 + P2
print(P)
|
a2283804176ca7940e72d21d0e249a02c81be3fb
|
christopherchoe/holbertonschool-higher_level_programming
|
/0x0A-python-inheritance/100-my_int.py
| 372 | 3.640625 | 4 |
#!/usr/bin/python3
class MyInt(int):
"""
rebel class with reversed == and !=
"""
def __eq__(self, other):
"""
inverted eq method
"""
if isinstance(other, int):
return not super().__eq__(other)
def __ne__(self, other):
"""
inverted ne method
"""
return not self.__eq__(other)
|
bfe1664ff66966824f2b9462097fd48aafae7bcd
|
jelimy/Practicing-CodingTest
|
/프로그래머스 Python/0717(level1).py
| 781 | 3.65625 | 4 |
# 출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges
# 코딩테스트 연습 > 연습문제 > x만큼 간격이 있는 n개의 숫자
# 사용언어 Python3
#내 답안
def solution(x, n):
return [i*x for i in range(1,n+1)]
# 코딩테스트 연습 > 연습문제 > 정수 제곱근 판별
# 사용언어 Python3
#내 답안
def solution(n):
a = n**(1/2)
if a == int(a):
return (a+1)**2
else:
return -1
# 코딩테스트 연습 > 연습문제 > 콜라츠 추측
# 사용언어 Python3
#내 답안
def solution(num):
cnt = 0
while num != 1:
if num % 2 == 0:
num = num / 2
else:
num = num * 3 + 1
cnt += 1
return cnt if cnt <= 500 else -1
|
0b4c258f0d0d001fa056138b45f81a1bf1136514
|
lov2cod/my_playground
|
/Coding_int/venv/replace.py
| 966 | 4.0625 | 4 |
#Python challenge #1 Everybody thinks twice before solving this
message = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj. "
def replaceChars(input, c1, c2):
# create lambda to replace c1 with c2, c2
# with c1 and other will remain same
# expression will be like "lambda x:
# x if (x!=c1 and x!=c2) else c1 if (x==c2) else c2"
# and map it onto each character of string
newChars = map(lambda x: x if (x != c1 and x != c2) else \
c1 if (x == c2) else c2, input)
# now join each character without space
# to print resultant string
print(''.join(newChars))
# Driver program
if __name__ == "__main__":
print(message)
input = message
replaceChars(input, 'k', 'm')
replaceChars(input, 'o', 'q')
replaceChars(input, 'e', 'g')
print(input)
|
7c5b45713694013b8af8670a46428faeb9694dca
|
SimmyZhong/leetCode
|
/dataStructure/listNode.py
| 734 | 3.515625 | 4 |
import random
class ListNode:
"""
链表
"""
def __init__(self, v):
self.val = v
self.next = None
@staticmethod
def getListNode(NodeLen):
"""
获取长度为NodeLen的随机链表
"""
TestListNode, ListNodeLen = ListNode(0), 0
curNode = TestListNode
while ListNodeLen < NodeLen:
ListNodeLen += 1
curNode.next = ListNode(random.choice(range(-10000, 10000)))
curNode = curNode.next
return TestListNode.next
def listNodeToList(headNode):
"""
链表转为数组
"""
result = []
while headNode:
result.append(headNode.val)
headNode = headNode.next
return result
|
2334e384ac7dbb1ec983f7f5e6e0725de680734e
|
guijavax/algoritmos
|
/algoritmo-luhn/main.py
| 1,222 | 4.09375 | 4 |
# This is a sample Python script.
import array
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def reverseNumbers(number):
leng = len(number)
numbers = []
j = leng - 1
for i in range(leng):
numbers.append(int(number[j]))
j = j - 1
return numbers
def sumNumbersImp(numbers):
leng = len(numbers)
for i in range(1, leng, 2):
numbers[i] = numbers[i] * 2
return numbers
def sumPairs(numbers):
leng = len(numbers)
for i in range(leng):
if(numbers[i] > 9):
numbers[i] = int(str(numbers[i])[0]) + int(str(numbers[i])[1])
return numbers
def sumNumbers(numbers):
res = 0
leng = len(numbers)
for i in range(leng):
res = res + numbers[i]
return res
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
number = input('Number\n')
numbers = sumPairs(sumNumbersImp(reverseNumbers(number)))
res = sumNumbers(numbers)
if res % 10 == 0:
print('valido')
else :
print('invalido')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
016429c3eaefdc7d9a230def65086507db1b7d79
|
ujwalkpl/5thSem_SL_Lab
|
/SEE/5/A/5a.py
| 1,430 | 3.859375 | 4 |
import sys
result = []
def celtofah():
cel = int(input("Enter temperature in celcius"))
fah = 9/5*cel+32
result.append((cel,fah))
print(fah)
def fahtocel():
fah = int(input("Enter temperature in fahrenheit"))
cel = 5/9*(fah-32)
result.append((fah,cel))
print(cel)
def keltocel():
kel = int(input("Enter temperature in fahrenheit"))
cel = kel-273
result.append((kel,cel))
print(cel)
def celtokel():
cel = int(input("Enter temperature in fahrenheit"))
kel = cel + 273
result.append((cel,kel))
print(cel)
def fahtokel():
fah = int(input("Enter temperature in fahrenheit"))
kel = 5/9*(fah-32)
result.append((fah,kel))
print(kel)
def keltofah():
fah = int(input("Enter temperature in fahrenheit"))
cel = 5/9*(fah-32)
result.append((fah,cel))
print(cel)
while True:
print("1.Celcius to Fahrenheit\n")
print("2.Fahrenheit to Celcius\n")
print("3.Kelvin to Celcius")
print("4.Celcius to Kelvin" )
print("5.Fahrenheit to Kelvin\n")
print("6.Kelvin to Fahrenheit\n")
print("8.history")
i = int(input())
if(i==1):
celtofah()
elif(i==2):
fahtocel()
elif(i==3):
keltocel()
elif(i==4):
celtokel()
elif(i==5):
fahtokel()
elif(i==6):
keltofah()
elif(i==7):
print("Thank you")
sys.exit()
elif(i==8):
print(result)
|
253b5d947331fc670aaeb404c1e2213581f27646
|
rv404674/Learn-Python3-the-Hard-Way
|
/ch15.py
| 335 | 3.71875 | 4 |
#import argv module from sys
from sys import argv
#load script name in argv and filename in filename
script, filename = argv
#open the file
txt = open(filename)
print(f"Here's your file {filename};")
print(txt.read())
print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
print(txt._again.read())
|
a5fc6ecca491828a5596ea51b470c9f0b66ed9a8
|
qamarilyas/Demo
|
/bubbleSort.py
| 365 | 4.125 | 4 |
def bubbleSort(lst):
for i in range(len(lst)-1): # outer loop run from index 0 to len(lst)
for j in range((len(lst)-i)-1): # inner loop run from index 0 to omitting i values
if(lst[j]>lst[j+1]):
lst[j],lst[j+1]=lst[j+1],lst[j] # swap each time if second value is greater
print(lst)
lst=[5,7,3,11,9,2]
bubbleSort(lst)
|
7ae3adfff82624c85807a12ce0be0f345f36a36c
|
joowoonk/Python-Intro
|
/Datastructure Note/binary search tree.py
| 1,172 | 4.34375 | 4 |
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
# compare the value to the root's value to determine which direction
# we're gonna go in
# if the value < root's value
if value < self.value:
# go left
# how do we go left?
# we have to check if there is another node on the left side
if self.left:
# then self.left is a Node
# now what?
self.left.insert(value)
else:
# then we can park the value here
self.left = BSTNode(value)
# else the value >= root's value
else:
# go right
# how do we go right?
# we have to check if there is another node on the right side
if self.right:
# then self.right is a Node
self.right.insert(value)
else:
self.right = BSTNode(value)
|
9d66b8cdb8a2a92db20d4ea7b2de72799f9a2b76
|
das-jishu/data-structures-basics-leetcode
|
/Leetcode/medium/preorder-traversal.py
| 1,154 | 4.0625 | 4 |
"""
# PREORDER TRAVERSAL
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [1,2]
Example 5:
Input: root = [1,null,2]
Output: [1,2]
Constraints:
The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
Follow up:
Recursive solution is trivial, could you do it iteratively?
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def preorderTraversal(self, root: TreeNode):
stack = []
res = []
head = root
while True:
if head:
res.append(head.val)
stack.append(head)
head = head.left
else:
if len(stack) == 0:
return res
t = stack.pop()
head = t.right
|
9ca6689084d09d1d20d028c252c1bf3509f75cc7
|
Kjew/Final-Project
|
/testspace2.py
| 331 | 3.875 | 4 |
word = "tallie"
#removes letter from alphabet once guessed
def remove_guessed_letter(word): #remove letter once guessed
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for charactors in list(alphabet):
if charactors in word:
alphabet = alphabet.replace(charactors," ")
return alphabet
guess1 = "t"
print remove_guessed_letter()
|
62ad4f883f66ecee265c6d391f168a85dadf990f
|
zhangting2/gitp1804
|
/p10/dengLu.py
| 173 | 3.671875 | 4 |
user=123
for i in range(1,5):
passwd=input('请输入 密码')
if user==passwd:
print('登录成功')
break
else:
print('登录失败')
|
8cbd92125880eb6f31ed399ebbe0db96b2d0fa3b
|
reniass/PythonRecursion
|
/sum_until.py
| 112 | 3.546875 | 4 |
def sumUntil(n):
if n == 0:
return 0
else:
return n + sumUntil(n-2)
print(sumUntil(6))
|
f2ecdfb5a6840cc2a10e06073dfdf5799a2881ab
|
saryamane/python_learnings
|
/functions.py
| 1,817 | 4.375 | 4 |
#!/usr/bin/python
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_one(arg1):
print "arg1: %r" % arg1
def print_none():
print "I got nothing!"
"""The variables in your function are not connected
to the variables in your script.
"""
print_two("Samir","Aryamane")
print_two_again("Awesome", "Wave")
print_one("VizCloud")
print_none()
print
print "Moving to the exercise where we are looking at functions and variables together"
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" % cheese_count
print "You have %d boxes of crackers" % boxes_of_crackers
print "Man that's enough for a party!"
print "Get a blanket.\n"
print "We can just give the function numbers directly:"
cheese_and_crackers(20,30)
print "OR, we can use the variables from our script"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print "We can even do math inside it too"
cheese_and_crackers(10 + 20, 5 + 6)
print "And we can combine the two, variables and math together:"
cheese_and_crackers(amount_of_cheese + 50, amount_of_crackers + 1000)
no_of_cheese_boxes=int(raw_input("Now give me the number of cheese boxes, will you? > "))
no_of_cracker_boxes=int(raw_input("Now give me the number of cracker boxes, will you? > "))
cheese_and_crackers(no_of_cheese_boxes,no_of_cracker_boxes)
def print_names(*args):
arg1 = args
print "And I see that you're name is: %r" % arg1
return arg1
abc = "Dhanu"
print_names("Samir")
print_names(abc)
print_names("Samir"+abc)
print_names("Samir"+"\n"+abc)
""" You can also call the function within a function.
"""
print "Your name is so awesome: %r" %print_names("Samir")
|
232b034eb60701112528ed7f60c35a4c1eee8202
|
ibikimam/py4e
|
/search1.py
| 140 | 3.921875 | 4 |
print('Before')
for value in [9,41,12,3,74,15] :
if value > 20 :
print(value ,'number is larger than 20')
print('After')
|
b02998609aa884a632235d05f4639cb0db58329f
|
Beardocracy/holbertonschool-interview
|
/0x0C-nqueens/0-nqueens.py
| 2,175 | 4.1875 | 4 |
#!/usr/bin/python3
'''
This program show all solutions the N queens problem,
for any given N.
'''
import sys
def print_board(board, n):
'''
Prints the locations of 1s in a n by n matrix
'''
print("[", end="")
for row in range(n):
for col in range(n):
if board[row][col]:
print("[{}, {}]".format(row, col), end="")
if row < n - 1:
print(", ", end="")
print("]")
def attack_check(board, row, col, n):
'''
Checks if there is a queen on the board this spot can attack.
Since we are filling the board from 0x0 to NxN, we only need to
look left, up, and in the upwards diagonals for existing Queens.
'''
if row == n or col == n:
return False
for x in range(col):
if (board[row][x]):
return False
for y in range(row):
if (board[y][col]):
return False
i = row - 1
j = col - 1
while i >= 0 and j >= 0:
if board[i][j]:
return False
i -= 1
j -= 1
i = row - 1
j = col + 1
while i >= 0 and j < n:
if board[i][j]:
return False
i -= 1
j += 1
return True
def solveNQUtil(board, row, n):
'''
Places queens on the board recursively by row
'''
if row == n:
print_board(board, n)
# return True
for col in range(n):
if attack_check(board, row, col, n):
board[row][col] = 1
solveNQUtil(board, row + 1, n)
board[row][col] = 0
# return False
def create_boards(n):
'''
Creates board and sends to recursive func
'''
board = [[0 for col in range(n)] for row in range(n)]
solved = solveNQUtil(board, 0, n)
def main():
'''
Entry point for program
'''
if len(sys.argv) != 2:
print("Usage: nqueens N")
sys.exit(1)
n = sys.argv[1]
try:
n = int(n)
except ValueError:
print("N must be a number")
sys.exit(1)
if n < 4:
print("N must be at least 4")
sys.exit(1)
create_boards(n)
if __name__ == "__main__":
main()
|
90b1237786315f3922f191e3cc76e88c2d23e884
|
anajulianunes/aprendendo-python
|
/Curso-python-iniciante/Projetos do Curso em Vídeo/aula9/9b - analisador de texto.py
| 402 | 3.90625 | 4 |
nome = input('Digite seu nome: ').strip()
print('Seu nome em maiúculo é {}'.format(nome.upper()))
print('Seu nome em minúsculo é {}'.format(nome.lower()))
print('Seu nome tem ao todo {} letras'.format(len(nome) - nome.count(' ')))
#print('Seu primeiro nome tem {} letras'.format(nome.find(' ')))
div = nome.split()
print('Seu primeiro nome é {} e ele tem {} letras'.format(div[0], len(div[0])))
|
8ce65b73a94fa8047edc183e2e9d8c8162a1e017
|
danielchk/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/100-matrix_mul.py
| 1,427 | 3.84375 | 4 |
#!/usr/bin/python3
"""
module 100-matrix_mul
"""
def matrix_mul(m_a, m_b):
"""
multiplies m_a and m_b
"""
if type(m_a) is not list:
raise TypeError('m_a must be a list')
if type(m_b) is not list:
raise TypeError('m_b must be a list')
lens = len(m_a)
len1 = len(m_a[0])
len2 = len(m_b[0])
if lens == 0 or len1 == 0:
raise ValueError('m_a can\'t be empty')
if len(m_b) == 0 or len2 == 0:
raise ValueError('m_b can\'t be empty')
for walk in m_a:
if len(walk) != len1:
raise TypeError('each row of m_a must should be of the same size')
for i in walk:
if type(i) is not int and type(i) is not float:
raise TypeError('m_a should contain only integers or floats')
for walk in m_b:
if len(walk) != len2:
raise TypeError('each row of m_b must should be of the same size')
for i in walk:
if type(i) is not int and type(i) is not float:
raise TypeError('m_b should contain only integers or floats')
if len1 != len2:
raise ValueError('m_a and m_b can\'t be multiplied')
result = []
for a in range(lens):
row2 = []
for b in range(len2):
num = 0
for c in range(len1):
num += m_a[a][c] * m_b[c][b]
row2.append(num)
result.append(row2)
return result
|
d8780b2ae68f465c3a17ebc30e3bbc94e02ec206
|
liamcarroll/python-programming-2
|
/Exam_papers/marks.py
| 636 | 3.71875 | 4 |
#!/usr/bin/env python3
import sys
def main():
try:
with open(sys.argv[1], 'r') as f:
for l in f:
l = l.strip()
name, mark = ' '.join(l.split()[1:-1]), l.split()[-1]
if int(mark) >= 40:
print('{:s} passed with a mark of {:d}'.format(
name, int(mark)))
else:
print('{:s} failed with a mark of {:d}'.format(
name, int(mark)))
except ValueError:
print('Invalid mark encountered: {:s}. Exiting.'.format(mark))
if __name__ == '__main__':
main()
|
f7176e985dd59a288065ef9250215640f2c9d7eb
|
jeffaustin32/CSC421-A2
|
/monopoly/space.py
| 3,653 | 4.03125 | 4 |
import random
from spaceType import SpaceType
'Represents a space on a Monopoly game'
'https://en.wikipedia.org/wiki/Template:Monopoly_board_layout'
class Space:
def __init__(self, id, color, name, cost, rent, spaceType):
self.id = id
self.color = color
self.name = name
self.cost = cost
self.rent = rent
self.visited = 0
self.spaceType = spaceType
self.owner = None
'This space was landed on'
def visit(self, player, roll, spaces, chance, communityChest):
# Player did not move (in jail)
if roll == 0:
return
self.visited += 1
# Perform action depending on space type
if self.spaceType == SpaceType.GO:
player.money += 200
return
elif self.spaceType == SpaceType.CHANCE:
# No more chance cards
if len(chance) == 0:
return
# Draw and play a chance card
card = chance.pop()
card.play(player)
return
elif self.spaceType == SpaceType.COMMUNITY_CHEST:
# No more community chest cards
if len(communityChest) == 0:
return
# Draw and play a community chest card
card = communityChest.pop()
card.play(player)
return
elif self.spaceType == SpaceType.TAX:
player.money -= self.cost
return
elif self.spaceType == SpaceType.GO_TO_JAIL:
player.goToJail()
return
# Pay rent or attempt to buy property
self.payRent(roll, player)
def payRent(self, roll, player):
# If space is not owned, let player try to buy
if not self.owner:
self.buy(player)
return
# Space is owned, pay rent to owner
if self.spaceType == SpaceType.RAILROAD:
# Determine how many railroads are owned
railroadsOwned = 0
for property in self.owner.properties:
if property.spaceType == SpaceType.RAILROAD:
railroadsOwned += 1
# They must own one utility
rentDue = 25
# If more are owned, increase rent
if railroadsOwned == 2:
rentDue = 50
elif railroadsOwned == 3:
rentDue = 100
elif railroadsOwned == 4:
rentDue = 200
player.money -= rentDue
self.owner.money += rentDue
elif self.spaceType == SpaceType.UTILITY:
# Determine how many utilities are owned
utilitiesOwned = 0
for property in self.owner.properties:
if property.spaceType == SpaceType.UTILITY:
utilitiesOwned += 1
# They must own one utility
rentDue = 4 * roll
# If they own both, increase rent
if utilitiesOwned == 2:
rentDue = 10 * roll
player.money -= rentDue
self.owner.money += rentDue
else:
player.money -= self.rent
self.owner.money += self.rent
'Give the player an opportunity to buy the property'
def buy(self, player):
# Check that player has enough money to buy the property
if player.money < self.cost:
return
# 50% chance to buy the property
if random.random() > 0.5:
player.money -= self.cost
self.owner = player
player.properties.append(self)
|
860ea45620d64d4b22e0b8bca5aefa5a3ba1b67d
|
elafleur3/ENG-122-Intro-to-Programming
|
/ECE 122/Project 3/bank-app3.py
| 3,327 | 4.21875 | 4 |
from Bank import BankAccount #imports BankAccount class
def app3(): #defines app3
print("Welcome to App3") #prints intro to app3
print("===============")
print( )
mortgage, rate, monthly = input("Enter amount to borrow, rate, and monthly payment: ").split() #takes user inputs and assigns them to correct variables
mortgage, rate, monthly = float(mortgage), float(rate), float(monthly) #changes inputs to numbers to be acted on
mortgageacc = BankAccount("Mortgage", mortgage, rate)#initializes mortgage account of class BankAccount
print(mortgageacc) #prints balance of mortgage acount
running = True #initializes varibales tto be used in loops
month = 1
year = 0
while running==True: #while loop
if mortgageacc.balance>0: #if the balance of mortgage account is greateer than 0
if month==1: #if statement for first month of loop
mortgageacc.withdraw(monthly-(mortgageacc.rate/12)*mortgageacc.balance) #withdraws amount from motgage account
initprincipal = mortgage-mortgageacc.balance #defines initial principal variable
initinterest = monthly-initprincipal #defines initial interest variable
mort = open("Amortization.txt", "w") #creates new file Amortizaion.txt for wrtiting
mort.write("Month--Principal paid--Interest paid") #writes in new file the correct format for the rest of the writing process
mort.write("\n") #skips line in new file
mort.write(str(month)) #writes the month
mort.write("--")
mort.write(str(initprincipal)) #writes the principal paid
mort.write("--")
mort.write(str(initinterest)) #writes the interst paid
mort.close() #closes file opened earlier
month += 1 #adds 1 to month variable
else: #for rest of months in loop
mortgageacc.withdraw(monthly-(mortgageacc.rate/12)*mortgageacc.balance) #withdraws amount from mortgage account
principal = (mortgage-mortgageacc.balance) #initializes new principle tobe paid
interest = (month*monthly)-principal #initializes new interest to be paid
mort = open("Amortization.txt", "a") #opens file again for appending
mort.write("\n")
mort.write(str(month)) #writes the month
mort.write("--")
mort.write(str(principal))#writes principal paid
mort.write("--")
mort.write(str(interest)) #writes interest paid
mort.close() #closes file
month += 1 #adds 1 to month
if (month % 12 == 0): #checks if a year has passed by using remainder of month divided by 12
year += 1 #adds 1 to year
else:
month -= 1 #gets rid of extra month added in loop
running = False #stops loop
print("You will be paying your loan after ", month, " month! (or ", float(year), " years!)") #prints how long it will take to pay off loan
total = month*monthly #gets total paid by user
print("You borrowed $%s but paid $%s in total (with interests)"%(mortgage,total)) #prints totals
app3()
|
dd51f2036ffc93f78f6ec2b979b3951a1eca664a
|
mukhamedzarifovakf/mukhamedzarifova
|
/Prac11/CW11.5.py
| 1,367 | 3.734375 | 4 |
class Point:
def __init__(self, parametrs = ('0;0')):
a, b = parametrs.split(';')
self.x = float(a)
self.y = float(b)
def Distance(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
def DistanceTo(self, point):
return ((self.x - point.x) ** 2 + (self.y - point.y) ** 2) ** 0.5
def __str__(self):
return str(self.x) + ',' + str(self.y)
def __add__ (self, other):
return Point(str(self.x + other.x) + ';' + str(self.y + other. y))
def __sub__ (self, other):
return Point(str(self.x - other.x) + ';' + str(self.y - other. y))
def __eq__ (self, other):
return self. x == other. x and other. y == other.y
def Perimetr (self, point2, point3):
return (self.DistanceTo(point2) + point2.DistanceTo(point3) + point3.DistanceTo(self))
def Square(self, point2, point3):
p = self.Perimetr(point2, point3) / 2
a = self.DistanceTo(point2)
b = point2.DistanceTo(point3)
c = point3.DistanceTo(self)
return (p * (p - a) * (p - b) * (p - c)) ** 0.5
N = int(input())
Points = []
for i in range(N):
Points.append(Point(input()))
max_s = 0
for i in Points:
for j in Points:
for k in Points:
if i.Square(k, j) > max_s:
print(i.Square(k, j))
max_s = i.Square(k, j)
print(max_s)
|
e817dfe9d19b3aeedfb4c804d6e8f3e9c3dea72b
|
laughtLOOL/grok-learning-answers
|
/introduction to programming (python)/4/ShortLong names.py
| 255 | 4.25 | 4 |
name = input('Enter your name: ')
if len(name) <= 3:
print('Hi ' + name + ', you have a short name.')
elif len(name) >= 4 and len(name) <= 8:
print('Hi ' + name + ', nice to meet you.')
else:
print('Hi ' + name + ', you have a long name.')
|
26e0d865d649d7c3fa3029760e38c4454a4d2f90
|
brijsavla/Project2
|
/Part2/Question 5/weightedGraph.py
| 705 | 3.546875 | 4 |
# Prijesh Dholaria
# CS 435 Section 6
# Question 5
class Node:
def _init_(self, val):
self.nodeValue = val
self.adjacentList = {}
class WeightedGraph:
def _init_(self):
self.nodeList = []
def addNode(self, value):
node = Node(value)
self.nodeList.append(node)
def addWeightedEdge(self, first, second, weight):
if first in self.nodeList or second in self.nodeList:
first.adjacentList[second] = weight
def removeWeightedEdge(self, first, second):
try:
del first.adjacentList[second]
except:
return
def getAllNodes(self):
return self.nodeList
|
7b5ff1cd65a26df4bc67d3e5ec8d9d26226334b9
|
yoshimura19/samples
|
/python/kisoen/kisoen/day4/test60b.py
| 676 | 3.5625 | 4 |
#coding:utf-8
#正規表現でくっつける 最初が"なら or 文字列の終端で終わる。
import re
pat1 = re.compile('^"(.*)",(.*)$')
pat2 = re.compile('(.*),"(.*)"')
rows = []
try:
while True:
s = raw_input()
rows.append(s)
except EOFError, e:
pass
#print(rows)
for i in range(0, len(rows)):
resultpat1 = pat1.search(rows[i])
resultpat2 = pat2.search(rows[i])
if resultpat1 != None:
print "%s\t%s" % (resultpat1.group(1), resultpat1.group(2))
elif resultpat2 != None:
print "%s\t%s" % (resultpat2.group(1), resultpat2.group(2))
else:
temp = rows[i].replace(",","\t")
print temp
|
59e1945a28b49c7557af9d98a3c8cc304f60e993
|
Anshu-Singh1998/python-tutorial
|
/twelve.py
| 450 | 4.21875 | 4 |
# let us c
# Write a program to print out a armstrong number between 1 to 500.
a = int(input("Enter 1st number print armstrong number between two numbers: "))
b = int(input("Enter 2nd number to print armstrong number between two numbers: "))
for num in range(a, b + 1):
s = 0
temporary = num
while temporary > 0:
digit = temporary % 10
s += digit ** 3
temporary //= 10
if num == s:
print(num)
|
ee7fdd5e260c37987c2f81f02c6e013474516989
|
mayankkagrawal/machine-learning
|
/class1.py
| 129 | 3.625 | 4 |
class Calculator():
def add(self,a,b):
return a+b
def subtraction(self,a,b):
return a-b
s=Calculator().add(2,3)
print(s)
|
c9f3cf9371dd31ab107d830b6280bc89249000c0
|
israelbyrd/pdsnd_github
|
/loadandfilterdata.py
| 2,555 | 4.65625 | 5 |
#!python
#This is a bit of a bigger task, which involves choosing a dataset to load and
#filtering it based on a specified month and day. In the quiz below,
#you'll implement the load_data() function, which you can use directly in your
#project. There are four steps:
# Load the dataset for the specified city. Index the global CITY_DATA
# dictionary object to get the corresponding filename for the given city name.
# Create month and day_of_week columns. Convert the "Start Time" column to
# datetime and extract the month number and weekday name into separate
# columns using the datetime module.
# Filter by month. Since the month parameter is given as the name of the month,
# you'll need to first convert this to the corresponding month number.
# Then, select rows of the dataframe that have the specified month and
# reassign this as the new dataframe.
# Filter by day of week. Select rows of the dataframe that have the specified
# day of week and reassign this as the new dataframe.
# (Note: Capitalize the day parameter with the title() method to match the
# title case used in the day_of_week column!)
import pandas as pd
citydata={'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
def loaddata(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - pandas DataFrame containing city data filtered by month and day
"""
#load data into data frame.
df=pd.read_csv(citydata[city])
#convert the start time column to datetime
df['Start Time']=pd.to_datetime(df['Start Time'])
#extract month and day of week from start time to create new columns
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
#filter by month if applicable
if month != 'all':
#use the index of the months list to get the corresponding int
months=['january','february','march','april','may','june','july','august','september','october','november','december']
month = months.index(month)+1
#filter dataframe by month
df=df[df['month']==month]
#filter by day if applicable
if day != 'all':
df=df[df['day_of_week']==day.title()]
return df
df=loaddata('chicago','march','friday')
print('filtered df:\n{}'.format(df))
|
62388ea8fe272a00539f528fb7cd6f62d47f75c5
|
viniciusriosfuck/time-calculator
|
/time_calculator.py
| 4,576 | 4.0625 | 4 |
def add_time(start, duration, start_day_of_week=False):
def hours2minutes(hours):
minutes_per_hour = 60
minutes = hours * minutes_per_hour
return minutes
def am_pm2hours(am_pm):
if am_pm == 'AM':
hours = 0
elif am_pm == 'PM':
# add up mid day
hours = 12
else:
raise ValueError('Invalid time')
return hours
def hhmm2minutes(hhmm):
""" convert time hh:mm format to minutes
Args:
hhmm (str): time hh:mm
Returns:
int: minutes
"""
time_hour = int(hhmm.split(':')[0])
time_minute = int(hhmm.split(':')[1])
minutes = hours2minutes(time_hour) + time_minute
return minutes
def time2minutes(time):
""" Convert time to minutes
Args:
time (string): HH:MM AM (or PM)
Raises:
ValueError: if time not in the correct format
Returns:
minutes (int): number of minutes from the provided time
"""
hhmm = time.split(' ')[0]
am_pm = time.split(' ')[1]
minutes = hhmm2minutes(hhmm) + hours2minutes(am_pm2hours(am_pm))
return minutes
def days2hours(days):
hours_per_day = 24
hours = days * hours_per_day
return hours
def minutes2days(minutes):
minutes_per_hour = 60
hours_per_day = 24
minutes_per_day = minutes_per_hour * hours_per_day
# 24 [h/day] * 60 [min/h] = 1440 [min/day]
days = minutes // minutes_per_day
return days
def minutes2hhmm(minutes):
""" convert minutes to time hh:mm format
Args:
int: minutes
Returns:
hhmm (str): time hh:mm
"""
hours_mid_day = 12
minutes_per_hour = 60
hours_per_day = 24
minutes_per_day = minutes_per_hour * hours_per_day
# 24 [h/day] * 60 [min/h] = 1440 [min/day]
if minutes > minutes_per_day:
days = minutes2days(minutes)
minutes -= days * minutes_per_day
hours = minutes // minutes_per_hour
time_minute = minutes % minutes_per_hour
if (hours <= 23) and (hours > hours_mid_day):
time_hour = hours - hours_mid_day
am_pm = 'PM'
elif (hours == hours_mid_day): # mid_day
time_hour = hours_mid_day
am_pm = 'PM'
elif (hours > 0) and (hours < hours_mid_day):
time_hour = hours
am_pm = 'AM'
elif (hours == 0): # midnight
time_hour = hours_mid_day
am_pm = 'AM'
else:
raise ValueError('hours must be between 0 and 23 inclusive')
time = f'{time_hour}:{time_minute:02d} {am_pm}'
return time
def get_add_days_str(add_days):
if add_days == 0:
add_days_str = ''
elif add_days == 1:
add_days_str = ' (next day)'
elif add_days > 1:
add_days_str = f' ({add_days} days later)'
else:
raise ValueError('add_days not valid')
return add_days_str
def get_key_from_val(dct, search_val):
return {v:k for k, v in dct.items()}[search_val]
def get_end_day_of_week(start_day_of_week, add_days):
dct_day_of_week = {
"Sunday": 0,
"Monday": 1,
"Tuesday": 2,
"Wednesday": 3,
"Thursday": 4,
"Friday": 5,
"Saturday": 6
}
if start_day_of_week:
start_day_of_week = start_day_of_week.title()
start_day_of_week_id = dct_day_of_week[start_day_of_week]
days_per_week = len(dct_day_of_week) # 7
end_day_of_week_id = (start_day_of_week_id + add_days) % days_per_week
end_day_of_week = get_key_from_val(dct_day_of_week, end_day_of_week_id)
end_day_of_week = f', {end_day_of_week}'
else:
end_day_of_week = ''
return end_day_of_week
start_minutes = time2minutes(start)
duration_minutes = hhmm2minutes(duration)
end_minutes = start_minutes + duration_minutes
end_hhmm = minutes2hhmm(end_minutes)
add_days = minutes2days(end_minutes)
add_days_str = get_add_days_str(add_days)
end_day_of_week = get_end_day_of_week(start_day_of_week, add_days)
new_time = end_hhmm + end_day_of_week + add_days_str
return new_time
|
96e59d76bbe24d7aaa8e04153b73de11b1536b47
|
GitPistachio/Competitive-programming
|
/HackerRank/Print Function/Print Function.py
| 435 | 3.546875 | 4 |
# Project name : HackerRank: Print Function
# Link : https://www.hackerrank.com/challenges/python-print/problem
# Try it on :
# Author : Wojciech Raszka
# E-mail : [email protected]
# Date created : 2020-07-15
# Description :
# Status : Accepted (169096236)
# Tags : python
# Comment :
if __name__ == '__main__':
n = int(input())
for i in range(1, n + 1):
print(i, end='')
print('')
|
3b810eac8491b51fc9411c1a645470cee83c5441
|
JaysonSunshine/Portfolio
|
/Software_Engineering/Python/primes.py
| 343 | 4.09375 | 4 |
import sys
def isPrime(N):
for i in range(2, N / 2 + 1):
if N % i == 0:
return False
return True
def primes(N):
if N == 1:
return 0
if N == 2:
return 1
count = 1
for i in range(3, N + 1):
if isPrime(i):
count += 1
return count
def main(args):
print primes(int(sys.argv[1]))
if __name__ == "__main__":
main(sys.argv)
|
87e256dcc1df83cdd27cdea54762809a6df0c758
|
Casmali/inputs
|
/webapp.py
| 2,076 | 3.640625 | 4 |
from flask import Flask, url_for, render_template, request
app = Flask(__name__) #__name__ = "__main__" if this is the file that was run. Otherwise, it is the name of the file (ex. webapp)
@app.route("/")
def render_main():
return render_template('index.html')
@app.route("/fir")
def render_page1():
return render_template('first.html')
@app.route("/sec")
def render_page2():
return render_template('second.html')
@app.route("/thi")
def render_page3():
return render_template('third.html')
@app.route("/response")
def render_response():
ins = float(request.args['inches'])
#The request object stores information that was sent by the client to the server.
#the args is a multidict
#the way we get info from args is that it is visible in a url. - the information in args is visible in the url for hte page being requested(ex. .../response?color=blue)
res = str(ins*2.54)
return render_template('response.html', their = request.args['inches'], response = res)
@app.route("/responsetwo")
def render_responsetwo():
ins = float(request.args['inches'])
#The request object stores information that was sent by the client to the server.
#the args is a multidict
#the way we get info from args is that it is visible in a url. - the information in args is visible in the url for hte page being requested(ex. .../response?color=blue)
res = str(ins/12)
return render_template('responsetwo.html', their = request.args['inches'], response = res)
@app.route("/responsethree")
def render_responsethree():
ins = float(request.args['miles'])
#The request object stores information that was sent by the client to the server.
#the args is a multidict
#the way we get info from args is that it is visible in a url. - the information in args is visible in the url for hte page being requested(ex. .../response?color=blue)
res = str(ins*63360)
return render_template('responsethree.html', their = request.args['miles'], response = res)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.