blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
bc9d30b6e09e31792b8db87ab3599a0f41baa81d
sonymoon/algorithm
/src/main/python/geeksforgeeks/graph/floyd-warshall-shortest-path.py
1,532
3.71875
4
# Input: # graph[][] = { {0, 5, INF, 10}, # {INF, 0, 3, INF}, # {INF, INF, 0, 1}, # {INF, INF, INF, 0} } # which represents the following graph # 10 # (0)------->(3) # | /|\ # 5 | | # | | 1 # \|/ | # (1)------->(2) # 3 # Note that the value of graph[i][j] is 0 if i is equal to j # And graph[i][j] is INF (infinite) if there is no edge from vertex i to j. # # Output: # Shortest distance matrix # 0 5 8 9 # INF 0 3 4 # INF INF 0 1 # INF INF INF 0 # A utility function to print the solution def printSolution(dist): print "Following matrix shows the shortest distances\ between every pair of vertices" for i in range(V): for j in range(V): if(dist[i][j] == INF): print "%7s" %("INF"), else: print "%7d\t" %(dist[i][j]), if j == V-1: print "" V = 4 INF = 999999 graph = [[0,5,INF,10], [INF,0,3,INF], [INF, INF, 0, 1], [INF, INF, INF, 0] ] dist = map(lambda row:map(lambda column:column, row), graph) for k in range(V): for i in range(V): for j in range(V): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j] ) printSolution(dist) print(dist[0][3])
8c5f62408cd00e029468b4c39b70b22aa6d61991
moneyDboat/offer_code
/25_复杂链表的复制.py
1,153
3.671875
4
# -*- coding: utf-8 -*- """ # @Author : captain # @Time : 2018/10/28 3:00 # @Ide : PyCharm """ # class RandomListNode: # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution: # 返回 RandomListNode def Clone(self, pHead): # write code here if not pHead: return None tmpNode = pHead while tmpNode: copyNode = RandomListNode(tmpNode.label) copyNode.next = tmpNode.next forNode = tmpNode tmpNode = tmpNode.next forNode.next = copyNode tmpNode = pHead while tmpNode: if tmpNode.random: tmpNode.next.random = tmpNode.random.next tmpNode = tmpNode.next.next copyHead = pHead.next tmpNode = pHead while tmpNode: copyNode = tmpNode.next tmpNode.next = copyNode.next if tmpNode.next: copyNode.next = tmpNode.next.next else: copyNode.next = None tmpNode = tmpNode.next return copyHead
20f1285b5d94d9c314fe0316e2fa4a7a7b92024f
raberin/Sprint-Challenge--Computer-Architecture
/ls8/simple.py
1,903
3.90625
4
import sys PRINT_BEEJ = 1 HALT = 2 PRINT_NUM = 3 SAVE = 4 # Save a value to a register PRINT_REGISTER = 5 # Print the value in a register ADD = 6 # ADD 2 registers, store the result in 1st reg memory = [0] * 256 register = [0] * 8 pc = 0 # Program counter def load_memory(filename): try: address = 0 # Open the file with open(filename) as f: # Read all the lines for line in f: # Parse out comments comment_split = line.strip().split("#") # Cast the numbers from strings to ints value = comment_split[0].strip() # Ignore blank lines if value == "": continue num = int(value) memory[address] = num address += 1 except FileNotFoundError: print("File not found") sys.exit(2) if len(sys.argv) != 2: print("ERROR: Must have file name") sys.exit(1) load_memory(sys.argv[1]) print(memory) while True: command = memory[pc] if command == PRINT_BEEJ: print("Beej!") pc += 1 elif command == PRINT_NUM: num = memory[pc + 1] print(num) pc += 2 elif command == SAVE: # Save a value to a register num = memory[pc + 1] reg = memory[pc + 2] register[reg] = num pc += 3 elif command == PRINT_REGISTER: # Print the value in a register reg = memory[pc + 1] print(register[reg]) pc += 2 elif command == ADD: # ADD 2 registers, store the result in 1st reg reg_a = memory[pc + 1] reg_b = memory[pc + 2] register[reg_a] += register[reg_b] pc += 3 elif command == HALT: sys.exit(0) else: print(f"I did not understand that command: {command}") sys.exit(1)
81171cbfc61a46f8aa1a3a4a708c6b21c1eac30d
aaralh/AdventOfCode
/utils.py
233
3.796875
4
def readFile(fileName: str) -> str: ''' Return contents of file with given name. Arguments: fileName -- Name of the file. ''' with open(fileName, 'r', newline='') as inputFile: return inputFile.read()
6102f1fdb3bde9fcce0310f744726eba24ea1c83
wyb2333/Computer-Vision-and-Pattern-Recognition
/Homework 3/test.py
201
3.6875
4
import numpy as np a = range(27) a = np.array(a) a = a.reshape([3, 3, 3]) b = range(9) b = np.array(b) b = b.reshape([1, 3, 3]) print(a) # print(a[0, :, :]) # print(np.sum(a, 0)) print(b) print(a*b)
e715336b8fcc784c6d7a0b030ca9cf8be67a0bd2
SudiLillian/Test-App
/questions.py
951
4.25
4
class Question(object): """This class models question objects.""" def __init__(self, question_text, answer, choices): """ Create a new Question object. The method accepts: question_text: The question itself answer: The answer to the question choices: A list containing the various choices """ self.question_text = question_text self.answer = answer self.choices = choices def grade(self, user_answer): """Check whether answer provided is correct.""" if self.answer.lower() == user_answer.lower(): return True return False def to_string(self): """Return a string containing the question and its choices.""" final_string = self.question_text + "\n" for key in sorted(self.choices.keys()): final_string += key + ". " + self.choices[key] + "\n" return final_string
91b54249d1afa6f77a1af371997d3e00aaaae34b
Nishith170217/Coursera-Python-3-Programming-Specialization
/num_chars.py
309
4.15625
4
# Write code to count the number of characters in original_str using the accumulation pattern and assign # the answer to a variable num_chars original_str = "The quick brown rhino jumped over the extremely lazy fox." num_chars=0 for i in range(len(original_str)): num_chars=num_chars+1 print(num_chars)
5df28ae56a8aeb4a588f348cd0ac0ecd3790c404
dhbandler/Unit2
/movie.py
557
4
4
#Daniel #1/29/18 #movie.py prints most scandalous movie legal per age age=float(input("What is your age? ")) if age<13: print("You can watch either G or PG movies. The MPAA doesn't discriminate due to age in this category.") elif 13<=age<17: print("Watch PG-13 movies! The MPAA says you can watch this category when you are younger as long as you exercize caution. The MPAA also says you can watch R rated movies with parental guidance") else: print("YOu can now watch NC-17 movies and R rated movies alone in theaters. Congrats?")
550ced8d8369a8cfdc71ea01cb018b9fe973a4ff
enolan26/EGN3124
/8-4.py
236
3.6875
4
import pandas as pd url=r'https://thermo.pressbooks.com/chapter/saturation-properties-temperature-table/' t_table = pd.read_html(url, header=0) print(t_table) userInput = str(input('Enter temperature in degrees C:').upper())
9560e49468398604596f2bfc1cb6653a78282cd0
banashish/DS-Algo
/coding Ninjas/DS/LinkedList/basicCreation.py
464
3.953125
4
class Node: def __init__(self,val = 0,next = None): self.val = val self.next = next class LinkedList: def __init__(self): self.head = None def printList(head): while head != None: print(head.val,end = "\n") head = head.next ll = LinkedList() node1 = Node(5) node2 = Node(6) node3 = Node(40) ll.head = node1 node1.next = node2 node2.next = node3 printList(ll.head) printList(ll.head)
905121ed02664705aae6ee1eaf67e644334af252
cjj1024/Mario
/sprite/coin.py
981
3.5625
4
import pygame from tool.init import * # 硬币类 # 当Mario撞击有硬币的砖块时, 出现在砖块的上方 # 硬币出现后, 旋转一定时间后消失 class Coin(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = coin_img[1] self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.rect.y -= self.rect.height # 表示硬币剩余的时间, 为0时消失 self.life = 9 self.animationNum = 0 self.init_animation() def update(self): if self.life == 0: self.kill() if self.animationNum < len(self.coin_rotate) - 1: self.animationNum += 1 else: self.animationNum = 0 self.image = self.coin_rotate[self.animationNum] self.life -= 1 def init_animation(self): self.coin_rotate = [coin_img[0], coin_img[1], coin_img[2], coin_img[3]]
71d36931d95c0ff17cb42b9884d931786e44dba8
jhonnymonte/python-unsam
/Clase02/ejercicio 2.13.py
538
3.59375
4
import csv with open('C:/Users/User2021/Documents/python/unsam/ejercicios python/clase 2/archivos/camion.csv', 'rt') as f: filas= csv.reader(f) next(filas) fila=next(filas) d={ 'nombre' : fila[0], 'cajones' : int(fila[1]), 'precio' : float(fila[2]) } print(d) d['fecha'] =(14,8,2020) d['cuenta'] = (12345) print (d) for k in d: print('k=',k) for k in d: print(k, '=', d[k]) claves = d.keys() claves = d.values() print (claves)
17131147034f426721ada562c1e8194e2a0fe25c
shiveshsky/datastructures
/linked_list/merge_sort_linked_list.py
1,091
3.828125
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def sortList(self, head): pass def merge(self, l, r): if l is None: return r if r is None: return l result = None if l.val < r.val: result = l result.next = self.merge(l.next, r) else: result = r result.next = self.merge(l, r.next) return result def merge_sort(self, head): if head is None: return if head.next is None: return head mid = self.get_mid(head) mid_next = mid.next mid.next = None l = self.merge_sort(head) r = self.merge_sort(mid_next) sort_ll = self.merge(l, r) return sort_ll def get_mid(self, head): tortoise = head hare = head if head is None: return None while hare and hare.next: hare = hare.next.next tortoise = tortoise.next return tortoise
729f480605ecb385433ae6f3435e5f7276220133
rrude/Exercise09
/recursion.py
3,187
3.875
4
l = [1, 3, 2, 9, 17] # Multiply all the elements in a list def multiply_list(l): if len(l) == 1: return l[0] else: return l[0] * multiply_list(l[1:]) # Return the factorial of n def factorial(n): total = 1 if n == 1: return 1 else: total = factorial(n-1) * n return total # Count the number of elements in the list l def count_list(l): if len(l) == 1: return 1 else: return 1 + count_list(l[1:]) # Sum all of the elements in a list def sum_list(l): if len(l) == 1: return l[0] else: return l[0] + sum_list(l[1:]) # Reverse a list without slicing or loops def reverse(l): if len(l) == 1: return l else: x = l.pop() return [x] + reverse(l) # Fibonacci returns the nth fibonacci number. The nth fibonacci number is # defined as fib(n) = fib(n-1) + fib(n-2) def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) # Finds the item i in the list l.... RECURSIVELY def find(l, i): if l[0] == i: return True else: return find(l[1:], i) # Determines if a string is a palindrome def palindrome(some_string): #compare first item with last if true run function again if false return false if len(some_string) <= 1: return True elif some_string[0] != some_string[-1]: return False else: new_string = some_string[1:-1] return palindrome(new_string) # Given the width and height of a sheet of paper, and the number of times to fold it, return the final dimensions of the sheet as a tuple. Assume that you always fold in half along the longest edge of the sheet. def fold_paper(width, height, folds): if folds == 0: return width, height #next line checks if user entered width and height incorrectly, ensures paper always folded lengthwise elif width >= height: return fold_paper( height / 2, width, folds - 1 ) else: return fold_paper( width / 2, height, folds - 1 ) # Count up # Print all the numbers from 0 to target # we need to use a list to append items from recursion, but the function requires a single int # this solution assumes that n will represent 0, in order to count up from 0 def count_up(target, n): #this is our base case we are increasing n by 1 until it is equal to target if n == target: return [target] #I'm returning target because this will complete the count since range is exclusive else: #here I'm creating a list so I can reference the first item, which will change with each loop listy = range(n, target) # I'm assigning the fist value in the range to x our range gets smaller each time because the starting #point of n increases each time getting closer to target x = listy[0] # need to return x as a list so that it can be appended rather than calculating a sum return [x] + count_up(target, n + 1) #zero was specified in question five is a random choice for target print count_up(5, 0)
747707c028e314a5eff983e4a9e35bede5aae0c0
eklitzke/algorithms
/combinatorics/permutations.py
621
4.09375
4
"""Implementation of permutations. This uses the "interleaving" technique, which I find the most intuitive. It's not the most efficient algorithm. """ def interleave(x, xs): """Interleave x into xs.""" for pos in range(len(xs) + 1): yield xs[:pos] + [x] + xs[pos:] def permutations(xs): """Generate the permuations of xs.""" if len(xs) == 0: yield [] else: for subperm in permutations(xs[1:]): for inter in interleave(xs[0], subperm): yield inter def list_permutations(xs): """Permutations as a list.""" return list(permutations(xs))
3838debe3c9ec2384e132d46a409ae5564b08d1c
itsjw/python_exercise
/python_book_exercise/exercise_two.py
115
3.953125
4
length = 5 breadth = 2 area = length*breadth print('Area is',area) print('Perimeter is', 2*(length + breadth))
11f3ca77adca9bee093fc89f0109e80051f6933c
AlessandroCorradini/MIT-6.00.2x-Introduction-to-Computational-Thinking-and-Data-Science
/5 - Stocastic Thinking/Exercise 3.py
521
4.3125
4
# Write a deterministic program, deterministicNumber, that returns an even number between 9 and 21. # def deterministicNumber(): # ''' # Deterministically generates and returns an even number between 9 and 21 # ''' # # Your code here import random def deterministicNumber(): ''' Deterministically generates and returns an even number between 9 and 21 ''' # Your code here random.seed(0) # This will be discussed in the video "Drunken Simulations" return 2 * random.randint(5, 10)
474fe5aaf257910296f2789aa7805b8724a7e8c6
ai-nakamura/adventofcode2020
/day6.py
2,109
3.609375
4
# * * * * * * * * * * * * # Setup # * * * * * * * * * * * * f = open("day6test.txt", "r") test = f.read().split('\n\n') """ * * * * * * * * * Part 1 * * * * * * * * * def process_one_yes(group): yeses = [0 for _ in range(26)] for respondent in group.split(): answers = respondent.split() for a in answers[0]: yeses[ord(a) - 97] = 1 return yeses def main(): total = 0 for groups in test: one_group = process_one_yes(groups) total += sum(one_group) return total """ """ * * * * * * * * * Part 2 * * * * * * * * * """ def everyone_yes(str_group): """ takes in one group (not a list of them) and finds the responses that everyone answered yes to :param str_group: string representation of one group :return: number of answers everyone said yes to """ respondent = str_group.split() # print(respondent) if len(respondent) < 1: print("that didn't have anything") return 0 yeses = [0 for _ in range(26)] # do the first person for a in respondent[0]: yeses[ord(a) - 97] = 1 # do the rest if not len(respondent) == 1: for resp in respondent[1:]: this_one = [0 for _ in range(26)] for a in resp: this_one[ord(a) - 97] = 1 yeses = [a and b for a, b in zip(yeses, this_one)] print(yeses) return yeses def main(): total = 0 for groups in test: one_group = everyone_yes(groups) total += sum(one_group) return total """ * * * * * * * * * Testing * * * * * * * * * """ g = "a\ bz\ cd" g2 = "ab\ ac" # break down of test[-1] a = [ch for ch in 'nlczsygmdabuorweqjhxfitv'] a.sort() b = [ch for ch in 'nmuvojghteyaxibwldsqrzfc'] b.sort() c = [ch for ch in 'mihetjnswbyzdvufcogxaqrl'] c.sort() d = [c for c in 'iulxgqfoctnjhvrawbzemsdy'] d.sort() e = [c for c in 'exugdvclmqfzsojiwnbarhty'] e.sort() # part 1 # print(sum(process_one_yes(g))) # print(main()) # part 2 # print(everyone_yes("abc")) print(everyone_yes(g2)) print(main())
d36c3d26a1d9fbff45c8e8adca94f9e25be56a48
DonaldMcC/Kite_ROS
/scripts/file_csv_out.py
1,642
3.546875
4
#!/usr/bin/env python import os import csv class CSVDataWrite: """ For logging CSV files to disk for further analysis """ def __init__(self): self.file_ref = None self.csvwriter = None def open_output(self, file_name='testoutput.csv', path='', reset_file=True): """ Opens a file for CSV data ouptut. If path is not specified (an empty string is given as the path) then the file will be opened in the current execution directory. If the reset_file parameter is False then file will be opened in append mode. If True then file will be opened in write mode and any existing data will be deleted if the file already exists. """ # create the fully qualified path name file_path = os.path.join(path, file_name) fmode = "w" if reset_file else "a" try: self.file_ref = open(file_path, fmode) self.csvwriter = csv.writer(self.file_ref) except Exception as e: print("%s" % str(e)) return def close_output(self): self.file_ref.close() return def write_data(self, datavals): self.csvwriter.writerow(datavals) return def test_file(): # this should create an output file out = CSVDataWrite() out.open_output() myheaders = ('One', 'Two', 'Three', 'Four') out.write_data(myheaders) for x in range(10): mydata = (1, 2, 3, 4) out.write_data(mydata) out.close_output() print('File output completed') if __name__ == '__main__': test_file()
2ed93fbd60480382bf2d2d698e5fd4e108cf21e5
PervykhDarya/laba4
/hardlevel1.py
205
3.890625
4
a2 = int(input("Enter a2: ")) a1 = int(input("Enter a1: ")) b = int(input("Enter b: ")) c1 = (a1+b)%10 c2 = a2+(a1+b)/10 print("result number of tens %.f" %c2) print("result number of units %.f" %c1)
25c50d242171b364ec66b323f32e07eee6cb5acb
PaulinaSurazynska/Movie-Trailer-Website
/media.py
873
3.71875
4
"""module with allows to open URLs in interactive browser applications.""" import webbrowser class Movie(): """class with defines variables: title, storyline, poster and youtube_trailer with will be used by instances (objects) of this class created in marvel_best_movies.py """ def __init__( """ constructor method initializing all the data associated with the instances of movie class """ self, movie_title, movie_storyline, poster_image, trailer_youtube ): self.title = movie_title self.storyline = movie_storyline self.poster_image_url = poster_image self.trailer_youtube_url = trailer_youtube def show_trailer(self): """method to show movie's trailer""" webbrowser.open(self.trailer_youtube_url)
33a118086b3d9c2a8f0ffce343ec3c7ef384f768
ermkv98/Algorithms
/app/array/arrayDefs.py
401
3.71875
4
def average_value(array): average = 0.0 for i in range(len(array)): average += array[i] return average/len(array) def dispersion(array, average_vaue): sqr_diff = 0.0 for i in range(len(array)): sqr_diff += pow((float(array[i])-average_vaue), 2) return sqr_diff/len(array) def deviation(dispersion): deviation = pow(dispersion, 0.5) return deviation
a09a808c6860c9718f8cd28e5d53ae3df5952ab2
jack-robs/OOPatterns
/strategyPattern/pyStratPattern/message.py
475
3.578125
4
# class that holds the message uses to encrypt/decrypt class Message: def __init__(self, message, strategy): self.message = message self.strategy = strategy #confirm I can access strategy class def getStrat(self): return self.strategy def getMessage(self): return self.message def changeStrat(self, strategy): self.strategy = strategy def encrypt(self): return self.strategy.encrypt(self)
81ee62cf84ed95ffd6ae78a2eb8c62d013da32f8
ihommani/code-elevator-webpy
/Elevator_prober.py
4,044
3.703125
4
#! /usr/bin/env python import unittest from Elevator import elevator class TestElevator(unittest.TestCase): def setUp(self): self.elevator = elevator() def test_elevator_should_be_closed(self): self.assertTrue(self.elevator.isClosed()) def test_elevator_should_be_opened(self): self.elevator.openDoor() self.assertTrue(self.elevator.isOpen()) def test_elevator_should_be_at_ground_zero(self): self.assertEqual(self.elevator.getCurrentFloor(), 0) def test_elevator_should_go_to_floor_x(self): self.elevator.call(5) self.assertEqual(self.elevator.getCurrentFloor(), 5) def test_elevator_should_be_empty(self): self.assertEqual(self.elevator.userExit(), 0) def test_elevator_should_contain_one_more_user(self): first = self.elevator.userEntrance() second = self.elevator.userEntrance() self.assertEqual(second, first + 1) def test_elevator_should_contain_one_less_user(self): first = self.elevator.userEntrance() second = self.elevator.userEntrance() third = self.elevator.userExit() self.assertEqual(third, second - 1) def test_elevator_cannot_go_below_0(self): self.assertEqual(self.elevator.call(-6), 0) return def test_elevator_cannot_go_below_0(self): #self.assertEqual(self.elevator.call(-6), 0) return def test_should_return_NOTHING(self): self.assertEqual(self.elevator.getNextMove(), "NOTHING") def test_elevator_should_compute_next_command(self): self.elevator.call(5) self.elevator.call(3) self.elevator.call(3) self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "OPEN") self.assertEqual(self.elevator.getNextMove(), "CLOSE") self.assertEqual(self.elevator.getNextMove(), "DOWN") self.assertEqual(self.elevator.getNextMove(), "DOWN") self.assertEqual(self.elevator.getNextMove(), "OPEN") self.assertEqual(self.elevator.getNextMove(), "NOTHING") def test_should_compute_go_command(self): self.elevator.call(5) self.elevator.go(3) self.elevator.call(4) self.elevator.go(1) self.elevator.go(5) self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "OPEN") self.assertEqual(self.elevator.getNextMove(), "CLOSE") self.assertEqual(self.elevator.getNextMove(), "DOWN") self.assertEqual(self.elevator.getNextMove(), "DOWN") self.assertEqual(self.elevator.getNextMove(), "OPEN") self.assertEqual(self.elevator.getNextMove(), "CLOSE") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "OPEN") self.assertEqual(self.elevator.getNextMove(), "CLOSE") self.assertEqual(self.elevator.getNextMove(), "DOWN") self.assertEqual(self.elevator.getNextMove(), "DOWN") self.assertEqual(self.elevator.getNextMove(), "DOWN") self.assertEqual(self.elevator.getNextMove(), "OPEN") self.assertEqual(self.elevator.getNextMove(), "CLOSE") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") self.assertEqual(self.elevator.getNextMove(), "UP") if __name__ == '__main__': unittest.main()
ac5573705fda6daf26a00c81ff81082d38fff4ff
songokunr1/Learning
/sortowanie/sortowanie_numpy.py
393
3.734375
4
import numpy as np dtype = [('name', 'S10'), ('height', float), ('age', int)] values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38), ('Galahad', 1.7, 38)] a = np.array(values, dtype=dtype) # create a structured array np.sort(a, order='height') np.sort(a, order=['age', 'height']) #https://thispointer.com/delete-elements-from-a-numpy-array-by-value-or-conditions-in-python/
0ef11fe30fd087f558f74c2b8bf6fc90216eaddb
henrique-voni/genetic-tsp
/genetic.py
6,806
3.78125
4
# -*- coding: utf-8 -*- """ Spyder Editor Algoritmo Genético - Henrique Voni """ import numpy as np, random, operator, pandas as pd, matplotlib.pyplot as plt ## Classe de cidade class City: ## Inicializa classe def __init__(self, x, y): self.x = x self.y = y ## Calcula distância euclidiana def distance(self, city): xDis = abs(self.x - city.x) yDis = abs(self.y - city.y) distance = np.sqrt((xDis ** 2) + (yDis ** 2)) return distance ## Coordenadas da cidade def __repr__(self): return "(" + str(self.x) + "," + str(self.y) + ")" ## Classe de fitness class Fitness: def __init__(self, route): self.route = route self.distance = 0 self.fitness = 0.0 def routeDistance(self): if self.distance == 0: pathDistance = 0 ## Percorre as cidades for i in range(0, len(self.route)): fromCity = self.route[i] toCity = None ## Se não tem cidade na rota, adiciona if i+1 < len(self.route): toCity = self.route[i+1] else: toCity = self.route[0] ## acrescenta distancia do caminho pathDistance += fromCity.distance(toCity) self.distance = pathDistance return self.distance def routeFitness(self): if self.fitness == 0: self.fitness = 1 / float(self.routeDistance()) print("Fitness: ", self.fitness) return self.fitness ## Criar população de rotas def createRoute(cityList): route = random.sample(cityList, len(cityList)) return route ## Criar uma população def initialPopulation(popSize, cityList): population = [] for i in range(0, popSize): population.append(createRoute(cityList)) return population ## Ranquear o fitness de cada rota def rankRoutes(population): fitnessResults = {} ## loop para calcular cada fitness for i in range(0, len(population)): fitnessResults[i] = Fitness(population[i]).routeFitness() ## retorna ordenado os fitness return sorted(fitnessResults.items(), key = operator.itemgetter(1), reverse=True) ## Seleção dos indivíduos def selection(popRanked, eliteSize): selectionResults = [] df = pd.DataFrame(np.array(popRanked), columns=["Index", "Fitness"]) ## Método da roleta ## Soma acumulativa dos fitness df['cum_sum'] = df.Fitness.cumsum() ## Define porcentagem de cada rota dividindo pelo total df['cum_perc'] = 100 * df.cum_sum / df.Fitness.sum() ## Seleciona elite for i in range(0, eliteSize): selectionResults.append(popRanked[i][0]) ## Seleciona demais indivíduos pelo metodo da roleta for i in range(0, len(popRanked) - eliteSize): ## Chance de seleção pick = 100 * random.random() for i in range(0, len(popRanked)): if pick <= df.iat[i, 3]: selectionResults.append(popRanked[i][0]) break return selectionResults ## Mating Pool def matingPool(population, selectionResults): matingpool = [] for i in range(0, len(selectionResults)): index = selectionResults[i] matingpool.append(population[index]) return matingpool ## Cruzamento def breed(parent1, parent2): child = [] childP1 = [] childP2 = [] geneA = int(random.random() * len(parent1)) geneB = int(random.random() * len(parent1)) ## Inicio e fim do corte de cruzamento startGene = min(geneA, geneB) endGene = max(geneA, geneB) for i in range(startGene, endGene): childP1.append(parent1[i]) childP2 = [item for item in parent2 if item not in childP1] child = childP1 + childP2 return child ## Nova populacao def breedPopulation(matingPool, eliteSize): children = [] length = len(matingPool) - eliteSize pool = random.sample(matingPool, len(matingPool)) for i in range(0, eliteSize): children.append(matingPool[i]) for i in range(0, length): child = breed(pool[i], pool[len(matingPool) - i - 1]) children.append(child) return children ## mutação def mutate(individual, mutationRate): for swapped in range(len(individual)): # SE aleatorio menor que taxa de mutacão, troca if(random.random() < mutationRate): #seleciona indice swapWith = int(random.random() * len(individual)) #permuta 2 cidades no individuo city1 = individual[swapped] city2 = individual[swapWith] individual[swapped] = city2 individual[swapWith] = city1 return individual ## Gera mutação na população def mutatePopulation(population, mutationRate): mutatedPop = [] ## aplica a mutação em cada individuo da população for ind in range(0, len(population)): mutatedInd = mutate(population[ind], mutationRate) mutatedPop.append(mutatedInd) return mutatedPop ## Define nova geração def nextGeneration(currentGen, eliteSize, mutationRate): popRanked = rankRoutes(currentGen) selectionResults = selection(popRanked, eliteSize) matingpool = matingPool(currentGen, selectionResults) children = breedPopulation(matingpool, eliteSize) nextGeneration = mutatePopulation(children, mutationRate) return nextGeneration ## algoritmo genetico def ga(population, popSize, eliteSize, mutationRate, generations): pop = initialPopulation(popSize, population) print("Initial distance: " + str(1 / rankRoutes(pop)[0][1])) for i in range(0, generations): pop = nextGeneration(pop, eliteSize, mutationRate) print("Final distance: " + str(1 / rankRoutes(pop)[0][1])) bestRouteIndex = rankRoutes(pop)[0][0] bestRoute = pop[bestRouteIndex] return bestRoute ## Exemplo cityList = [] ## criar 25 cidades aleatórias for i in range(0, 25): cityList.append(City(x=int(random.random() * 200), y=int(random.random() * 200))) oneRoute = ga(population=cityList, popSize=100, eliteSize=20, mutationRate = 0.01, generations=500) def showMap(cityList): print(cityList) prev=City(0,0) for i in cityList: plt.plot(i.x, i.y,'ro') plt.plot(prev.x,prev.y, 'k-') if(prev.x == 0 and prev.y == 0): prev=i continue; else: plt.plot([prev.x,i.x],[prev.y, i.y],'k-') prev=i plt.show() showMap(oneRoute)
021995fbba11c5c7a36dbc72dc3dad138963b248
zhouwy1994/Notes
/yisiderui/study on python.py
15,877
3.8125
4
#=========================================python2.x================================================================= #usr/bin/python #coding=utf-8#֧ı,pythonĬֻ֧ASCII pythonԲͬľ{}࣬ԼһЩ߼ж pythonʹʾΣͬһȱҪͬ if True: print "true" else: print "flase" Ȳһ»ʹõһܱIndentationError// Ծʹͬոtab if else: 󲿷ͬpythonʹ\Ϊдһ а() {} []ͲûзҲdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; pythonַ('')˫("")(''' '''or """ """) ſɰУҲע string = """This is a segment frist line secend line""" """ This is a Multi-line comment function: name: argment: """ \nת廻 #Pythonͬһʹö䣬֮ʹ÷ֺ(;)ָ import sys//sys using namespace stdͬ str = "Hello Python"; sys.stdout.write(str + '\n'); print ĬǻеģҪʵֲҪڱĩβ϶ print string, #ͬһ乹һ飬dz֮顣 #ifwhiledefclassĸ䣬Թؼֿʼð( : )֮һлд빹ɴ顣 #ǽмĴΪһӾ(clause) python test.py arg1 arg2 arg3 Python Ҳ sys sys.argv ȡв sys.argv вб len(sys.argv) в #в,pythonв,sys.argv׽ for i in range(len(sys.argv)): print sys.argv[i]; #в #˵:ú len() range(), len() бijȣԪصĸ rangeһе for IJбֻ[1, 2, 3, 4]ʽshellͬ pythonִshellַ 1.os.system('cat /proc/cpuinfo')#ֻ᷵0and1ִгɹ 2.output = os.popen('cat /proc/cpuinfo');print output.read()'''popenֻoutputĶҪͨread()ȡ Ҳֱcmd = os.popen('shell cmd').read();''' 3.(status, output) = commands.getstatusoutput('cat /proc/cpuinfo');print status, output#'''ȿԵõֵҲܵõ #Ҳֱʹcommands.output('shell cmd')ȡcommandsҪimport commands Python׼ͣ 1.Numbers֣#intfloat,long,complexDzı,ζı Number ͵ֵ·ڴռ䡣 a = 20; b = 20;#abĵַһģCܴ 2.Stringַ#±ȡֵstr = "Hello World",str[1:6] = ello W str*2 = Hello World Hello World str[1] = e 3.Listб#飬ַ֣бǶlist = ['string1', string2, string3]; 4.TupleԪ飩#ֻ飬,ŷָ(),ҲɲãlistǼ[] 5.Dictionaryֵ䣩#бֻͨ±ƫƴȡֵüȡ(key)shellĹ{} б Ԫ ֵ [],ɶдͨ±ƫƴȡ ()or','ֻͨ±ƫƴȡ {},ɶдͨȡ shellһ鳤Ȳǰ ͵תֻҪΪɡint('string') pythonC + - * / % **()a**b(abη) //̵ Ƚһ<> ֵCͬ λCͬ ߼and or notʾ python Աin not in#ҳԱǷб list = [1, 2, 3, 4, 5];a = 4; if (a in list)#4Ƿб is not is жǷͬһ is == is жöǷΪͬһ == жñֵǷȡid(var)ӡidڴֵ ȼҲCͬ 305995 python:if a == b: handel; if (a == b): handel; pythonûswitchֻelif棬break˳ ߼ҲDzö· бջlist.pop();бջlist.append(var); pythonѭ while for while (true):handel; ⣺elseʹ while (False): handel; else: handel 2; break continueCһ pass䣬Cе; pythonʱ䴦ҲC ȡʱtime.time();ظͣ1970-01-01 pythonһרתʱĽṹ(Ԫ) struct_timeԪ struct_time = (tm_year,tm_mon,tm_mday,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst); ȡʱ亯ʱ pythonṩ2Ҫʽre.match re.search match ַֻĿʼʽƥ䣬ƥɹmatchobject򷵻none search ִַʽƥ䣬еִûƥɹnone򷵻matchobjectre.search൱perlеĬΪ match:ȷƥ re.match(Hello,Hello) = matchobject re.match(Hello,He) = none search:ģƥ re.match(Hello,Hello) = matchobject re.match(Hello,He) = matchobject # -*- coding: utf-8 -*- ʽĬΪASCII佫ʽijuft-8,֧ import from...import python import from...import Ӧģ顣 ģ(somemodule)룬ʽΪ import somemodule ijģеij,ʽΪ from somemodule import somefunction ijģе,ʽΪ from somemodule import firstfunc, secondfunc, thirdfunc ijģеȫ룬ʽΪ from somemodule import * #=========================================python3.x================================================================= python : 1.ֵ 1.1:int 1.2float 1.3:complex #type(var): isinstance(var, int):жݵͣTrue or False 2.ַ(string) str = 'Hello' 3.б(list) list = ["ds", "ds", "dsa"] 4.Ԫ(tuple) Ԫ飨tupleбƣ֮ͬԪԪز޸ġԪдС(())Ԫ֮öŸ tup = ("ds", "ds", "dsd") 5.(set) ϣsetһظԪصС ǽгԱϵԺɾظԪ ʹô { } set() ϣע⣺һռϱ set() { }Ϊ { } һֵ䡣 a = {"adds", "ada"} b = set('asdfd') if ('s' in b):#ж"s"ǷڼȺb 6.Dictionaryֵ䣩 ֵһӳֵͣ"{ }"ʶһļ(key) : ֵ(value)Լϡ (key)ʹòɱ͡ dic = {'one':'frist',"two":"secend"} 2.Python߼ and x and y "" - x Ϊ Falsex and y False y ļֵ (a and b) 20 or x or y "" - x True x ֵ y ļֵ (a or b) 10 not not x "" - x Ϊ True False x Ϊ False True not(a and b) False 3.PythonԱ ϵһЩ֮⣬Pythonֳ֧ԱʵаһϵеijԱַбԪ顣 ʵ in ָҵֵ True򷵻 False x y , x y з True not in ָûҵֵ True򷵻 False x y , x y з True ʵʾPythonгԱIJ 4.Python ڱȽĴ洢Ԫ ʵ is is жʶDzһ x is y, id(x) == id(y) , õͬһ򷵻 True򷵻 False is not is not жʶDzԲͬ x is not y id(a) != id(b)õIJͬһ򷵻ؽ True򷵻 False id()رĵַ pythonǶ̬ģʱ s == is жöǷΪͬһ == жñֵǷȡ б: list = [i for i in range(0,14)] while elseʹ shellʹseq pythonʹrange Python3 PythonǿĹ֮һǷʼԪصһַʽ һԼסλõĶ ӼϵĵһԪؿʼʣֱеԪرֻǰˡ ķiter() next() ַбԪ󶼿ڴ list=[1,2,3,4] it = iter(list) # print (next(it)) # һԪ Python Уʹ yield ĺΪgenerator ͨͬǣһصĺֻڵ򵥵һ ڵеĹУÿ yield ʱͣ浱ǰеϢyieldֵһִ next()ʱӵǰλüС ʵʹ yield ʵ쳲У ɸ(mutable)벻ɸ(immutable) python Уstrings, tuples, numbers DzɸĵĶ󣬶 list,dict ǿ޸ĵĶ ɱֵͣ a=5 ٸֵ a=10ʵһ int ֵ 10 a ָ 5 Ǹıaֵ൱a ɱֵͣ la=[1,2,3,4] ٸֵ la[2]=5 ǽ list la ĵԪֵģlaûжֻڲһֵ޸ˡ python IJݣ ɱͣ c++ ֵݣ ַԪ顣funaݵֻaֵûӰa funaڲ޸ a ֵֻ޸һƵĶ󣬲Ӱ a ɱͣ c++ ôݣ бֵ䡣 funlaǽ la Ĵȥ޸ĺfunⲿlaҲӰ python һжǶϸDz˵ֵݻôݣӦ˵ɱʹɱ úʱûдݲʹĬϲʵûд age ʹĬֵ #!/usr/bin/python3 #д˵ def printinfo( name, age = 35 ): python ɱʽ def func (argv, *args): print (argv) for var in args: print (var) lambda бƵʽ >>> vec = [2, 4, 6] >>> [3*x for x in vec] [6, 12, 18] >>> [[x, x**2] for x in vec] [[2, 4], [4, 16], [6, 36]] Python3 쳣 1﷨ SyntaxError: invalid syntax 2쳣 NameError: TypeError: SyntaxError:Ĵ󲿷־쳣 쳣 УûһϷûжʹ Control-C ߲ϵͳṩķûжϵϢһ KeyboardInterrupt 쳣 >>> while True: try: x = int(input("Please enter a number: ")) break except ValueError: print("Oops! That was no valid number. Try again ") try䰴·ʽ ȣִtryӾ䣨ڹؼtry͹ؼexcept֮䣩 û쳣exceptӾ䣬tryӾִк ִtryӾĹз쳣ôtryӾµIJֽԡ쳣ͺ except ֮ôӦexceptӾ佫ִСִ try ֮Ĵ롣 һ쳣ûκεexceptƥ䣬ô쳣ᴫݸϲtryС һ try ܰexceptӾ䣬ֱͬض쳣ֻһ֧ᱻִС ֻԶӦtryӾе쳣д try Ĵе쳣 һexceptӾͬʱ쳣Щ쳣һΪһԪ飬: except (RuntimeError, TypeError, NameError): pass selfʵ ķͨĺֻһر𡪡DZһĵһ, չ self C++thisָ python ı洦洦ʹ ִнԺԵĿself ʵǰĵַ self.class ָࡣ self python ؼ֣ǰ runoob Ҳǿִе:ֻҪǵһ #˽,˽ⲿ޷ֱӽз __weight = 0 ˽ֻķ ̳ Python ֧ͬļ̳УһԲּ֧̳Уûʲô塣Ķʾ: class DerivedClassName(BaseClassName1): <statement-1> . . . <statement-N> ҪעԲл˳ǻͬķʹʱδָpython δҵʱҲһǷ BaseClassNameʾеĻඨһڡ࣬ñʽඨһģʱһdz: class DerivedClassName(modname.BaseClassName): 뷽 ˽ __private_attrs»߿ͷΪ˽Уⲿʹûֱӷʡڲķʹʱ self.__private_attrs ķ ڲʹ def ؼһһ㺯岻ͬ෽ selfΪһself ʵ self ֲǹ涨ģҲʹ thisûǰԼ self ˽з __private_method»߿ͷ÷Ϊ˽зֻڲ ⲿáself.__private_methods ʵ רз __init__ : 캯ɶʱ __del__ : ͷŶʱʹ __repr__ : ӡת __setitem__ : ֵ __getitem__: ȡֵ __len__: ó __cmp__: Ƚ __call__: __add__: __sub__: __mul__: __div__: __mod__: __pow__: ˷
967be7d4e6ec559afa37a0e1265471c91324c900
v-erse/pythonreference
/Science Libraries/Matplotlib/Object Oriented Matplotlib/animationexample.py
732
3.71875
4
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation # Create figure with black background colour fig = plt.figure(facecolor="black") # Create ax with no frame, add to figure ax = plt.axes(xlim=(0, 2), ylim=(-2, 2), frameon=False) fig.add_axes(ax) # and no ticks ax.set_xticks([]) ax.set_yticks([]) # Create line line, = ax.plot([], [], lw=2, color="white") def init(): line.set_data([], []) return line, def animate(framenumber): x = np.linspace(0, 2, 1000) y = np.sin(2*np.pi*(x-0.01*framenumber)) line.set_data(x, y) return line, anim = FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=True) plt.show()
b7a9fd5df201d510c5c6af3d1f9ae8ea9f75b731
conalryan/python-notes
/classes/inheritance.py
1,861
4.53125
5
#!/usr/bin/env python """ Inheritance Specify base class in class definition Call base class constructor explicitly One or more base classes can be specified as part of the class definition Default base class is object Base class must already be imported Classes may override methods of their base classes (for Java and C++ programmers: all methods in Python are effectively virutal) To extend rather than simply replace a base class method, call the base class method directly: BaseClassName.methodname(self, args) Super You can also use super() function which stands in for the base class class Foo(Bar): def __init(self): super().__init__() # same as Bar.__init__(self) The advantage of super() is that you don't have to specify the base class explicitly, so if you change the base class, it automatically does the right thing Follows MRO (method resolution order) to find function Great for single inheritance tree Use explicit base class names for multiple inheritance Syntax super().method() Use in a class to invoke methods in base classes Searches the base classes and their bases, recursively, from left to right until the method is found If classes have a diamond shaped inheritance tree, super() may not do what you expect, in that case use the base class name explicitly """ class Base(object): def some_method(self): print('--> Base.some_method()') class Inheritance(Base): def another_method(self): print('--> Inhertianc.another_method()') class OverrideBase(Base): def some_method(self): super().some_method() print('--> OverrideBase.some_method()') i = Inheritance() i.some_method() i.another_method() o = OverrideBase() o.some_method()
d8ebfc53bcccd66e971b4ffbf49c2ba11800df52
itamar19-meet/meet2017y1mini-proj
/snake.py
4,376
3.59375
4
import turtle import random turtle.tracer(1,0) #map size SIZE_X=1000 SIZE_Y=700 turtle.setup(SIZE_X,SIZE_Y) turtle.penup() turtle.speed(0.5) sq_size = 20 start_len = 7 #intialize lists pos_list = [] stamp_list = [] food_pos = [] food_stamps = [] snake = turtle.clone() snake.shape("circle") turtle.hideturtle() snake.color("red") for i in range(start_len): x_pos = snake.pos()[0] y_pos = snake.pos()[-1] x_pos = x_pos + sq_size my_pos = (x_pos , y_pos) snake.goto(x_pos , y_pos) pos_list.append(snake.pos) stamp_ID = snake.stamp() stamp_list.append(stamp_ID) #directions UP_ARROW = "Up" DOWN_ARROW = "Down" LEFT_ARROW = "Left" RIGHT_ARROW = "Right" TIME_STEP = 100 UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 direction = UP UP_EDGE = SIZE_Y/2 DOWN_EDGE = -SIZE_Y/2 RIGHT_EDGE = SIZE_X/2 LEFT_EDGE = -SIZE_X/2 def up(): global direction direction = UP print("you pressed up key") def down(): global direction direction = DOWN print("you pressed down key") def left(): global direction direction = LEFT print("you pressed left key") def right(): global direction direction = RIGHT print("you pressed right key") turtle.onkeypress(up , UP_ARROW) turtle.listen() turtle.onkeypress(down , DOWN_ARROW) turtle.listen() turtle.onkeypress(left , LEFT_ARROW) turtle.listen() turtle.onkeypress(right , RIGHT_ARROW) turtle.listen() #fjdjiokbuyfgyuiokjihugyuojihuhhhhhhhhhhhhhhhh----------------------------------------------- def move_snake(): my_pos = snake.pos() x_pos = my_pos[0] y_pos = my_pos[1] if direction == RIGHT: snake.goto(x_pos + sq_size,y_pos) elif direction == LEFT: snake.goto(x_pos - sq_size , y_pos) if direction == UP: snake.goto(x_pos , y_pos + sq_size) elif direction == DOWN: snake.goto(x_pos , y_pos - sq_size) my_pos = snake.pos() pos_list.append(my_pos) new_stamp = snake.stamp() stamp_list.append(new_stamp) old_stamp = stamp_list.pop(0) snake.clearstamp(old_stamp) pos_list.pop(0) new_pos = snake.pos() new_x_pos = new_pos[0] new_y_pos = new_pos[1] if new_x_pos >= RIGHT_EDGE: print("you lose :(") quit() if new_x_pos <= LEFT_EDGE: print("you lose :(") quit() if new_y_pos >= UP_EDGE: print("you lose :(") quit() if new_y_pos <= DOWN_EDGE: print("you lose :(") quit() if pos_list[-1] in pos_list[0:-1]: print("dont hit yourself!!!!") quit() ################################################################################################1 #specialllll!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! global food_stamps , food_pos if snake.pos() in food_pos: food_ind = food_pos.index(snake.pos()) food.clearstamp(food_stamps[food_ind]) food_pos.pop(food_ind) food_stamps.pop(food_ind) print("you ate a turtle!!!!") makefood() turtle.ontimer(move_snake,TIME_STEP) move_snake() #food count = 0 food = turtle.clone() food.color("green") food.shape("turtle") food_pos = [(100,100) , (-100,100) , (-100, -100) , (100,-100)] for this_food_pos in food_pos: food.goto(this_food_pos[0], this_food_pos[1]) stamp_number = food.stamp() food_stamps.append(stamp_number) def snake_grow(): stamp_list.append(snake.stamp()) pos_list.append(snake.pos()) count = 0 def counter(): turtle.goto(280,270) turtle.clear() turtle.write("score: " + str(count) , font =( "Arial" , 16 , "normal")) turtle.ontimer(counter,1000) turtle.color("white") def makefood(): global count min_x = -int(SIZE_X/2/sq_size)+1 max_x = int(SIZE_X/2/sq_size)-1 min_y = -int(SIZE_Y/2/sq_size)+1 max_y = int(SIZE_Y/2/sq_size)-1 food_x = random.randint(min_x,max_x)*sq_size food_y = random.randint(min_y,max_y)*sq_size food.goto(food_x,food_y) stood = food.stamp() food_stamps.append(stood) food_pos.append(food.pos()) snake_grow() count = count + 1 print(count) counter() turtle.bgcolor("black") #if #int(count) == 50: #print("omg you are so goooooood!!!!!!!!") # good = turtle.write("omg you are so goof!!" , font =( "Arial" , 16 , "normal")) #good.clear()
ea9c26a98ab7d67ff4c11a95b2675bd7a2409293
torch-msdi/SWMM
/section_feature.py
5,660
3.640625
4
import math class SectionFeature(object): """ 单个断面计算方法 """ def __init__(self, data, depth): """ :param data: 断面数据 e.g {'data':1, 'type': 'circle'} """ self.data = data self.depth = max(0, depth) def section_area(self): """ 返回指定水深下的过水断面面积 :return: """ if self.data['type'] == 'circle': """定积分求圆面积""" r = self.data['data'] / 2 # r为圆半径 # 水深大于管径时,调整为管径 if self.depth > 2 * r: self.depth = 2 * r width = 2 * (r ** 2 - (r - self.depth) ** 2) ** 0.5 # 勾股定理 cos_degree = 1 - width ** 2 / (2 * r ** 2) # 余弦定理 angle = math.acos(cos_degree) if self.depth < r: total_area = math.pi * r**2 * angle / (2 * math.pi) triangle_area = width * (r - self.depth) / 2 return total_area - triangle_area else: total_area = math.pi * r ** 2 * angle / (2 * math.pi) triangle_area = width * (r - self.depth) / 2 return math.pi * r**2 - total_area + triangle_area elif self.data['type'] == 'rectangle': """矩形断面面积求法""" return abs(self.depth) * self.data['data']['width'] elif self.data['type'] == 'irregular': """非规则断面面积求法""" area = 0 x_list, z_list = self.data['data'][0], self.data['data'][1] minor_z = min(z_list) z_list = [i-minor_z for i in z_list] for delta_index in range(len(x_list) - 1): x = [x_list[delta_index], x_list[delta_index + 1]] z = [z_list[delta_index], z_list[delta_index + 1]] delta_area = abs(x[0] - x[1]) * abs(z[0] - z[1]) / 2 if self.depth >= max(z): area += delta_area + abs(x[0] - x[1])*abs(self.depth-max(z)) elif self.depth <= min(z): pass else: ratio = self.depth / abs(z[0] - z[1]) area += ratio**2 * delta_area return area def avg_water_depth(self): """ 计算给定水深下的断面平均水深 :return: """ area = self.section_area() try: return area/self.water_width() except ZeroDivisionError: return 0 def water_width(self): """ 返回指定水深下的水面宽度 :return: """ if self.data['type'] == 'circle': r = self.data['data'] / 2 if self.depth > r: return 2 * r else: return 2 * (r**2 - (r - self.depth)**2)**0.5 elif self.data['type'] == 'rectangle': return self.data['data']['width'] elif self.data['type'] == 'irregular': width = 0 x_list, z_list = self.data['data'][0], self.data['data'][1] minor_z = min(z_list) z_list = [i-minor_z for i in z_list] for delta_index in range(len(x_list) - 1): x = [x_list[delta_index], x_list[delta_index + 1]] z = [z_list[delta_index], z_list[delta_index + 1]] delta_with = abs(x[0] - x[1]) if self.depth >= max(z): width += delta_with elif self.depth <= min(z): pass else: ratio = self.depth / abs(z[0] - z[1]) width += ratio * delta_with return width def wet_circle(self): """ 返回指定水深下的湿周 :return: """ if self.data['type'] == 'circle': r = self.data['data'] / 2 if self.depth < r: width = 2 * (r**2 - (r - self.depth)**2)**0.5 # 勾股定理 cos_degree = 1 - width**2 / (2 * r**2) # 余弦定理 angle = math.acos(cos_degree) wet_circle = angle * r return wet_circle elif self.depth > 2 * r: return 2 * math.pi * r else: width = 2 * (r ** 2 - (r - self.depth) ** 2) ** 0.5 # 勾股定理 cos_degree = 1 - width ** 2 / (2 * r ** 2) angle = 2 * math.pi - math.acos(cos_degree) wet_circle = angle * r return wet_circle elif self.data['type'] == 'rectangle': return 2 * self.depth + self.data['data']['width'] elif self.data['type'] == 'irregular': width = 0 x_list, z_list = self.data['data'][0], self.data['data'][1] minor_z = min(z_list) z_list = [i-minor_z for i in z_list] for delta_index in range(len(x_list) - 1): x = [x_list[delta_index], x_list[delta_index + 1]] z = [z_list[delta_index], z_list[delta_index + 1]] delta_wet = ((x[0] - x[1])**2 + (z[0] - z[1])**2)**0.5 if self.depth >= max(z): width += delta_wet elif self.depth <= min(z): pass else: ratio = self.depth / abs(z[0] - z[1]) width += ratio * delta_wet return width
2df2a888c6d8b77b37132925f204c981c32281f7
licup/interview-problem-solving
/Module 3/singleNum.py
505
3.921875
4
def single_number(integers): integers.sort() #sorts all of the numbers in array i = 0 while i < len(integers) - 1: if integers[i] == integers[i+1]: #if first instance of number is equal to the next one it is not a single num i += 2 else: return integers[i] return integers[-1] #returns last number in array if while loop finishes without it hitting the else #Test Cases print(single_number([4,1,2,1,2])) #returns 4 print(single_number([3,2,2,5,6,1,3,1,5]) #returns 5
4eff0acc1f2f8e75a0ece1c17c65631d2bbfa4ac
bdrummo6/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
3,176
4.1875
4
class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList: def __init__(self): self.head = None def add_to_head(self, value): node = Node(value) if self.head is not None: node.set_next(self.head) self.head = node def contains(self, value): if not self.head: return False current = self.head while current: if current.get_value() == value: return True current = current.get_next() return False # Function using iteration reverses node order in a singly linked list def reverse_list(self, node, prev): if node: current = self.head # Set current to head for iterating through the linked list # Loop while current is not None while current: next = current.get_next() # Store a reference to the second node in the list in a variable next current.set_next(prev) # Store the current's next reverence to prev prev = current # Set prev with the reference to current current = next # Set the node referenced by next to current self.head = prev # This sets the last node to of the non-reversed list to the head of the new reversed list """ # Function reverses item order in a singly linked list def reverse_list(self, node, prev): # if node is not none proceed with reversing the list if node: # Retrieve the initial value of the second node in the list current = self.head.get_next() # set the next reference of head to prev self.head.set_next(prev) # store the head reference in prev prev = self.head # if the next reference for head is None then return the new head of the reversed list if not current: return self.head # if the next reference is not None, keep moving through the list else: self.head = current # if the list reversal is not complete then recursively call reverse_list return self.reverse_list(node, prev) """ def print_list(self): current = self.head while current: print(current.get_value()) current = current.get_next() # Created Linked list to run my own tests on the reverse_list function ll = LinkedList() ll.add_to_head(5) # 5 ll.add_to_head(8) # 8 5 ll.add_to_head(17) # 17 8 5 ll.add_to_head(25) # 25 17 8 5 ll.add_to_head(13) # 13 25 17 8 5 ll.add_to_head(14) # 14 13 25 17 8 5 print('\nNon-reversed List: ') ll.print_list() # Linked List should be: 14 13 25 17 8 5 ll.reverse_list(Node(), None) # Call reverse list with an Empty Node and prev set as None print('\nReversed List: ') ll.print_list() # Linked List should be: 5 8 17 25 13 24
f0915014aaed09a8b7b937f39501caafde5b8218
1790113591/study
/python/20201022:Python第2天课后资料包/课堂示例代码/deffunc/prime/prt_prime.py
238
3.671875
4
# 组员A: from deffunc.prime.util import isprime print("=============== 打印500到800之间的素数 ==================\n") for n in range(500, 801): if isprime(n): print(n, end=" ") print("\n谢谢使用!")
16f43100e6b91757365690443007b373f80d54a9
nervaishere/DashTeam
/python/HOMEWORK/6th_Session/Answers/Class/2/T2.py
258
4.125
4
a=int(input("Enter number of hour:")) b=int(input("Enter number of minute:")) if( b>=60 or a>24): print("The number of hour or minute is nit valid") else: if a>12: a=a-12 print(format(a, "0<2d"),":",format(b, "0<2d"))
397e742b1ddd0a151085b9436083a2588ea4d4d5
fabriciovale20/AulasExercicios-CursoEmVideoPython
/Exercícios Mundo 3 ( 72 à 115 )/ex085.py
575
4.1875
4
""" Exercício 85 Crie um programa onde o usuário possa digitar sete valores numéricos e cadastre-os em uma lista única que mantenha separados os valores pares e ímpares. No final, mostre os valores pares e ímpares em ordem crescente. """ numeros = [[], []] for c in range(0, 7): n = int(input(f'Digite o {c+1}º valor: ')) if n % 2 == 0: numeros[0].append(n) else: numeros[1].append(n) print('=-'*30) print(f'''Os valores pares digitados foram: {sorted(numeros[0])} Os valores ímpares digitados foram: {sorted(numeros[1])}''')
748e4ed6103eed08699f86d1a9744fb9213c6bec
inlike/Python-algorithm
/希尔排序.py
521
3.9375
4
# -*- coding:utf-8 -*- def shell_sort(alist): """希尔排序""" n = len(alist) gap = n // 2 i = 1 while gap > 0: for j in range(gap, n): i = j while i > 0: if alist[i] < alist[i - gap]: alist[i], alist[i - gap] = alist[i - gap], alist[i] i -= gap else: break gap //= 2 if __name__ == '__main__': list = [3, 6, 2, 8, 6, 9, 1] shell_sort(list) print(list)
d59bc12d7e649b4d3f962718bc10ce93dc86e26c
cccccyclone/Maleapy
/src/ex3/pictrans.py
1,875
4.1875
4
#!/usr/bin/python from PIL import Image import numpy as np import matplotlib.pyplot as plt def imageToMatrix(filename): im = Image.open(filename) # im.show() width,height = im.size # L model means the picture will be convert to grayscale picture. And the following formula is used to convert RGB color picture to grayscal picture. # L = R * 299/1000 + G * 587/1000+ B * 114/1000 im = im.convert("L") data = im.getdata() data = np.matrix(data) new_data = np.reshape(data,(width,height)) return new_data def matrixToImage(data): return Image.fromarray(data.astype(np.uint8)) def showImage(data): """To show a grayscale picture with it's relative matrix """ # use matplotlib to show image directly plt.imshow(data, cmap=plt.cm.gray, interpolation='nearest') plt.show() """ img = matrixToImage(data) img.show() """ def randomShow(): # x.txt stores 5000 training examples of handwritten digits, each digits has 400(20*20) pixels data data = np.loadtxt('x.txt') num = 25 row = col = int(np.sqrt(num)) fig,ax = plt.subplots(row,col) # random select num digits rnd = np.random.randint(1,5000,num) sels = data[rnd,:] for i in np.arange(0,num): r = i / row c = i % row pic = sels[i,:].reshape((20,20)) ax[r,c].imshow(pic, cmap=plt.cm.gray, interpolation='nearest') # do not show any ticks ax[r,c].set_xticks([]) ax[r,c].set_yticks([]) # adjust the space between pictues to 0 plt.subplots_adjust(wspace=0,hspace=0) plt.show() if __name__ == '__main__': filename = './digit/10.png' image = plt.imread(filename) plt.imshow(image) plt.axis('off') plt.show() #data = imageToMatrix(filename) #showImage(data) #img.save('lena_1.bmp') #randomShow()
54fa64f4b5ed2c223c5e76a5ffab9eec517fecc0
pengwa1234/unbuntuCode
/thread/08锁的方式解决共享变量的问题.py
574
3.796875
4
from threading import Thread,Lock import time def main(): t1=Thread(target=test1) t1.start() t2=Thread(target=test2) t2.start() print("main----%s"%g_num) mutex=Lock() g_num=0 def test1(): global g_num if mutex.acquire(): for i in range(1000000): g_num+=1 mutex.release() print("test1----%s"%g_num) def test2(): global g_num if mutex.acquire(): for i in range(1000000): g_num+=1 mutex.release() print("test2----%s"%g_num) if __name__=="__main__": main()
d3df6a9dfdf79fc9139878f23fbe84eb798f5c35
spring-2018-csc-226/a03
/a03_Horinet.py
2,721
4.46875
4
####################################################### # Author: Tayttum Horine # Purpose: To better understand turtles and incorporate new ideas ####################################################### import turtle def make_square (t): # creates bottom of house """ The function creates the base of the house. :param t: turtle class :return: none """ t.color("#DC143C") t.pensize(3) t.penup() t.goto(-50,0) t.pendown() t.begin_fill() for i in range (4): t.fd(100) t.rt(90) t.end_fill() def make_door (t): """ This function creates the door of the house. :param t: turtle :return: none """ t.penup() t.color("blue") t.goto(-10,-100) t.pendown() t.begin_fill() for i in range (2): t.fd(20) t.lt(90) t.fd(40) t.lt(90) t.end_fill() def make_roof (t): # creates roof """ This function creates the roof of the house. :param t: turtle :return: none """ t.color('#DC130C') t.pensize(3) t.begin_fill() t.bk(25) t.goto(0,50) t.goto(75,0) t.bk(125) t.end_fill() def make_sun (t): """ This function creates a sun in the sky. :param t: turtle :return: none """ t.color("#ffff00") t.penup() t.goto (220,170) t.pendown() t.begin_fill() t.circle(45) t.end_fill() def make_window1 (t): """ This function creates the first window :param t: turtle :return: none """ t.color("black") t.penup() t.goto(-30,-5) t.pendown() t.speed(2) t.fillcolor("white") t.begin_fill() for i in range (8): t.fd(6) t.rt(45) t.fd(6) t.end_fill() def make_window2 (t): """ This function creates the second window :param t: turtle :return: none """ t.color("black") t.penup() t.goto(30,-5) t.pendown() t.speed(2) t.fillcolor("white") t.begin_fill() for i in range (8): t.fd(6) t.rt(45) t.fd(6) t.end_fill() def make_cloud(t): t.color("white") t.penup() t.goto(-190,160) t.pendown() for i in range (3): t.begin_fill() t.circle(30) t.end_fill() t.penup() t.fd(30) t.pendown() def main(): t = turtle.Turtle() wn = turtle.Screen() wn.bgcolor("#87ceeb") make_square(t) make_roof(t) make_sun(t) make_cloud(t) make_door(t) make_window1(t) make_window2(t) t.color("#FF1493") t.penup() t.setpos(0, 90) t.pendown() t.write("Tayttums Smol Home", align='center', font=("Times New Roman", 20 )) wn.exitonclick() main()
515e1a116e38030f0911e56b2d53afde97e89466
znelson/advent-of-code
/2015/day14.py
3,080
3.71875
4
#!/usr/bin/env python data = """ Rudolph can fly 22 km/s for 8 seconds, but then must rest for 165 seconds. Cupid can fly 8 km/s for 17 seconds, but then must rest for 114 seconds. Prancer can fly 18 km/s for 6 seconds, but then must rest for 103 seconds. Donner can fly 25 km/s for 6 seconds, but then must rest for 145 seconds. Dasher can fly 11 km/s for 12 seconds, but then must rest for 125 seconds. Comet can fly 21 km/s for 6 seconds, but then must rest for 121 seconds. Blitzen can fly 18 km/s for 3 seconds, but then must rest for 50 seconds. Vixen can fly 20 km/s for 4 seconds, but then must rest for 75 seconds. Dancer can fly 7 km/s for 20 seconds, but then must rest for 119 seconds. """ class Reindeer: def __init__(self, name, speed, fly_time, rest_time): self.name = name self.speed = speed self.fly_time = fly_time self.rest_time = rest_time self.time = 0 self.is_flying = True self.time_since_takeoff = 0 self.distance = 0 self.score = 0 def __repr__(self): return '<{0} - {1} km - {2} pts>'.format(self.name, self.distance, self.score) def pass_one_second(self): if self.is_flying: self.distance = self.distance + self.speed self.time = self.time + 1 self.time_since_takeoff = self.time_since_takeoff + 1 if self.is_flying: if self.time_since_takeoff == self.fly_time: self.is_flying = False self.time_since_takeoff = 0 elif not self.is_flying: if self.time_since_takeoff == self.rest_time: self.is_flying = True self.time_since_takeoff = 0 class ReindeerHolder(): def __init__(self, reindeer): self.reindeer = reindeer def _pass_one_second(self): furthest = [] for r in self.reindeer: r.pass_one_second() if len(furthest) == 0: furthest.append(r) elif r.distance == furthest[0].distance: furthest.append(r) elif r.distance > furthest[0].distance: furthest = [r] for r in furthest: r.score = r.score + 1 def pass_seconds(self, count): for seconds in range(count): self._pass_one_second() def get_reindeer_with_highest_score(self): scoriest = self.reindeer[0] for r in self.reindeer: if r.score > scoriest.score: scoriest = r return scoriest def get_furthest_reindeer(self): furthest = self.reindeer[0] for r in self.reindeer: if r.distance > furthest.distance: furthest = r return furthest def load_reindeer(reindeer_data): lines = reindeer_data.strip().split('\n') reindeer = [] for line in lines: words = line.split(' ') name = words[0] speed = int(words[3]) fly_time = int(words[6]) rest_time = int(words[13]) r = Reindeer(name, speed, fly_time, rest_time) reindeer.append(r) return reindeer def solve_part_1(): reindeer = load_reindeer(data) rh = ReindeerHolder(reindeer) rh.pass_seconds(2503) furthest = rh.get_furthest_reindeer() print(furthest) # should be Cupid at 2696 km def solve_part_2(): reindeer = load_reindeer(data) rh = ReindeerHolder(reindeer) rh.pass_seconds(2503) best = rh.get_reindeer_with_highest_score() print(best) solve_part_1() solve_part_2()
60f2897f3a07d8de9b6e96d896ba54e62c5772d6
yuriy-lishchynskyy/NBANetworkAnalysis
/nba_network_draw_graph.py
2,256
3.5
4
import networkx as nx import os.path import matplotlib.pyplot as plt # INPUT ANALYSIS YEAR year = input("Please enter year (minimum 2013-14): \n") team = input("Please enter team (e.g. GSW): \n") game_type = input("Please enter game type (1 = regular season, 2 = playoffs): \n") if game_type == "1": game_s = "Regular Season" file_s = "" else: game_s = "Playoffs" file_s = " playoffs" edgelist_path = os.path.join(year + file_s, "edge_list_" + team + ".txt") # READ TEAM EDGELIST file = open(edgelist_path, 'r') G_team = nx.read_weighted_edgelist(file, nodetype=str, create_using=nx.DiGraph()) file.close() # DRAW GRAPH plt.figure(figsize=(8, 8)) pos = nx.circular_layout(G_team) # prepare circular arrangement of nodes nx.draw_circular(G_team, with_labels=False, connectionstyle='arc3, rad = 0.03', node_size=25, node_color="black", arrowsize=6) label_ratio = 1.0 / 10.0 pos_labels = {} for aNode in G_team.nodes(): # shift node labels outwards so dont overlap with nodes/edges x, y = pos[aNode] # Get the node's position from the layout N = G_team[aNode] # Get the node's neighbourhood # Find the centroid of the neighbourhood. The centroid is the average of the Neighbourhood's node's x and y coordinates respectively. cx = sum(map(lambda x: pos[x][0], N)) / len(pos) cy = sum(map(lambda x: pos[x][1], N)) / len(pos) # Get the centroid's 'direction' or 'slope'. That is, the direction TOWARDS the centroid FROM aNode. slopeY = (y - cy) slopeX = (x - cx) # Position the label at some distance along this line. Here, the label is positioned at about 1/10th of the distance. pos_labels[aNode] = (x + slopeX * label_ratio, y + slopeY * label_ratio) nx.draw_networkx_labels(G_team, pos=pos_labels, font_size=10, font_color='red') # redraw the labels at their new position. edge_labels = dict([((u, v,), int(d['weight'])) for u, v, d in G_team.edges(data=True)]) # set edge labels as weights nx.draw_networkx_edge_labels(G_team, pos, edge_labels=edge_labels, label_pos=0.125, font_size=8, font_color='blue') # draw edge weights plt.text(-1.0, 1.0, "TEAM: {0}\nYEAR: {1}".format(team, year)) plt.text(-1.0, -1.05, "Value adjacent to node = \nNo. of passes received from teammate") plt.show()
7dff8f54ba315b3fc408d409bb271b21e4b2380f
mtz99/GHDevOpsSurvey
/survey1.py
513
3.65625
4
fname = input(str("Enter your first name:")) lname = input(str("Enter your last name:")) dob = input("Enter your date of birth:") email = input(str("Enter your email:")) zcode = input("Enter your zip code:") city = input(str("Enter your city:")) state = input(str("Enter your state:")) race = input(str("Enter your race:")) age = input("Enter your age:") sex = input(str("Enter your sex:")) print(fname) print(lname) print(dob) print(email) print(zcode) print(city) print(state) print(race) print(age) print(sex)
4b686c6105f5cb212ff278dc10698033bb848898
LeoVilelaRibeiro/opfython
/opfython/math/distribution.py
834
3.890625
4
import numpy as np from opfython.math.random import generate_uniform_random_number def bernoulli_distribution(prob=0.0, size=1): """ Generates a bernoulli distribution based on an input probability. Args: prob (float): probability of distribution. size (int): size of array. Returns: A Bernoulli distribution array. """ # Creating bernoulli array bernoulli_array = np.zeros(size) # Generating random number r = generate_uniform_random_number(0, 1, size) # For each dimension for i in range(size): # If random generated number if smaller than probability if (r[i] < prob): # Mark as one bernoulli_array[i] = 1 else: # If not, mark as zero bernoulli_array[i] = 0 return bernoulli_array
ec7b5f363f3d0914136ec07f794f97b171d1fdec
underseatravel/AlgorithmQIUZHAO
/Week_06/438_find_all_anagram_in_a_string.py
609
3.65625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/8/22 12:12 # @Author : weiyu # @File : 438_find_all_anagram_in_a_string.py import collections class Solution: def findAnagrams(self, s, p): res = [] pdic = collections.Counter(p) sdic = collections.Counter(s[:len(p) - 1]) for i in range(len(p) - 1, len(s)): sdic[s[i]] += 1 if sdic == pdic: res.append(i - len(p) + 1) sdic[s[i - len(p) + 1]] -= 1 if sdic[s[i - len(p) + 1]] == 0: del sdic[s[i - len(p) + 1]] return res
dac705193706434becc7c8bf9f8c719618d34f65
PravallikaJuturu/Assignment3
/starttomiddle.py
247
3.875
4
print('Enter list of elements') list=input() newList=list.split(' ') midIndex=int(len(newList)/2) print('all elements from the middle to end in list',newList[midIndex:]) print('all elements from the start till middle in list',newList[:midIndex])
4fbbbeeb2689ef76ec53d707af9ca39a8c85f383
alexxa/Python_Google_course
/03_wordcount.py
3,248
4.46875
4
#!/usr/bin/python #PERFORMED BY: alexxa #DATE: 19.12.2013 #SOURCE: Google Python course # https://developers.google.com/edu/python/ #PURPOSE: Basics. # The original course and exercises are in Python 2.4 # But I performed them in Python 3 # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Wordcount exercise Google's Python class The main() below is already defined and complete. It calls print_words() and print_top() functions which you write. 1. For the --count flag, implement a print_words(filename) function that counts how often each word appears in the text and prints: word1 count1 word2 count2 ... Print the above list in order sorted by word (python will sort punctuation to come before letters -- that's fine). Store all the words as lowercase, so 'The' and 'the' count as the same word. 2. For the --topcount flag, implement a print_top(filename) which is similar to print_words() but which prints just the top 20 most common words sorted so the most common word is first, then the next most common, and so on. Use str.split() (no arguments) to split on all whitespace. Workflow: don't build the whole program at once. Get it to an intermediate milestone and print your data structure and sys.exit(0). When that's working, try for the next milestone. Optional: define a helper function to avoid code duplication inside print_words() and print_top(). """ import sys, string # +++your code here+++ # Define print_words(filename) and print_top(filename) functions. # You could write a helper utility function that reads a file # and builds and returns a word/count dict for it. # Then print_words() and print_top() can just call the utility function. ### # This basic command line argument parsing code is provided and # calls the print_words() and print_top() functions which you must define. def del_punctuation(item): ''' This function deletes punctuation from a word. ''' punctuation = string.punctuation for c in item: if c in punctuation: item = item.replace(c, '') return item def dictionary(words_list): d = dict() for c in words_list: d[c] = d.get(c, words_list.count(c)) print(c, d[c]) d.pop('', None) return d def break_into_words(filename): ''' This function reads file, breaks it into a list of used words in lower case. ''' book = open(filename) words_list = [] for line in book: for item in line.split(): item = del_punctuation(item) item = item.lower() words_list.append(item) return words_list def print_top(filename): ''' This function returns the 20 most frequently-used words in the book ''' words_list = break_into_words(filename) d = dictionary(words_list) print(d) dict_copy = d counter = 0 while counter < 20 : popular_word = max(dict_copy, key=dict_copy.get) print(popular_word, dict_copy[popular_word]) dict_copy.pop(popular_word, None) counter += 1 print_top('alice.txt')
477aca3a366ff7509d6341c4a3179e7feb47d413
prstcsnpr/Algorithm
/src/srm/598/ErasingCharacters.py
994
3.734375
4
import unittest class ErasingCharacters(object): def simulate(self, s): while True: result = s for i in range(len(s) - 1): if s[i] == s[i + 1]: result = s[0:i] + s[i+2:] if result == s: return result else: s = result class ErasingCharactersTestCase(unittest.TestCase): def setUp(self): self.ec = ErasingCharacters() def test_0(self): self.assertEqual(self.ec.simulate('cieeilll'), 'cl') def test_1(self): self.assertEqual(self.ec.simulate('topcoder'), 'topcoder') def test_2(self): self.assertEqual(self.ec.simulate('abcdefghijklmnopqrstuvwxyyxwvutsrqponmlkjihgfedcba'), '') def test_3(self): self.assertEqual(self.ec.simulate('bacaabaccbaaccabbcabbacabcbba'), 'bacbaca') def test_4(self): self.assertEqual(self.ec.simulate('eel'), 'l') if __name__ == '__main__': unittest.main()
515457751bf900c44ff0f925bff390ee768577f9
dankarthik25/python_Tutorial
/UdemyTutorials/s05_01_input.py
114
3.859375
4
name = input("Give Input to python ") print("Given input is : " + name) for num in [1, 2, 3, 4]: print(num)
ccdf2b64d909bb91839eff3d3940e2330144dd87
billm79/COOP2018
/Chapter07/U07_Ex11_LeapYear.py
1,860
4.4375
4
# U07_Ex11_LeapYear.py # # Author: Bill Montana # Course: Coding for OOP # Section: A3 # Date: 24 Oct 2017 # IDE: PyCharm Community Edition # # Assignment Info # Exercise: 11 # Source: Python Programming # Chapter: 7 # # Program Description # Function that calculates if a given year is a leap year. Returns boolean. # # Algorithm (pseudocode) # introduce program # create a list with sample data with which to test # for each element in list call isLeapYear() with element as parameter # print results # # isLeapYear(): # y is argument # if y is divisible by 4 and not century year divisble by 400, return true # otherwise, return false def main(): # introduce program print('This program contains the function isLeapYear() which determines if a given year is a leap year.') # create a list with sample data with which to test years = [1800, 1900, 2000, 2001, 2002, 2003, 2004] # for each element in list call isLeapYear() with element as parameter for year in years: # print results print('{0} {1} a leap year'.format(year, 'is' if isLeapYear(year) else 'is not')) # isLeapYear(): # y is argument def isLeapYear(y): # if y is divisible by 4 and not century year divisble by 400, return true if y % 4 == 0 and not (y % 100 == 0 and not y % 400 == 0): return True # otherwise, return false return False if __name__ == '__main__': main() ''' RESULTS: ======== isLeapYear(1800) --> 0 | 0 | [ Pass ] isLeapYear(1900) --> 0 | 0 | [ Pass ] isLeapYear(2000) --> 1 | 1 | [ Pass ] isLeapYear(2001) --> 0 | 0 | [ Pass ] isLeapYear(2002) --> 0 | 0 | [ Pass ] isLeapYear(2003) --> 0 | 0 | [ Pass ] isLeapYear(2004) --> 1 | 1 | [ Pass ] ======== '''
ba4ec9be19e027c6da1cd86921597862874d8d7e
enzoyoshio/Problemas
/problema1.py
645
4.1875
4
# lista de dicionario dado listDict = [ {1 : 1, 2 : "oi", "nome" : "obrigado"}, {"Bolo" : "Cenoura", "Camarão" : "Verde", "nome" : "Sagrado"}, {1 : 10, "nome" : "oi", "caracol" : "obrigado"}, {"nome":"obrigado"} ] # a chave que será procurada nome = "nome" # inicializando a lista vazia lista = [] # verifico para cada nome se ele está ou não no dicionário for dict1 in listDict: # se a chave nome estiver no dicionário # e o valor dela não tiver sido adicionado a lista, só adicionar na lista if nome in dict1 and dict1[nome] not in lista: lista.append(dict1[nome]) # printa a lista print(lista)
ada748d900dda911919cd47340b0a0515df65490
mrhoran54/basic_csv_splitter
/csv_splitter.py
1,669
3.828125
4
import os def make_new_filename(row): output_name='output_%s.csv' x = './' + (output_name % row) return(x) def split(filehandler, num_of_rows, keep_headers): """ Splits a CSV file into x number of rows """ import csv index = 1 #can specify the delimiter here delimiter=',' #defining the reader reader = csv.reader(filehandler, delimiter=delimiter) #making the first file current_out_path = make_new_filename(1) print(current_out_path) current_writer = csv.writer(open(current_out_path, 'w'), delimiter=delimiter) current_limit = num_of_rows ## if keep_headers: #for the first row keep the headers headers = reader.next() current_writer.writerow(headers) for i, row in enumerate(reader): # if you're at the Size limit time to output all you've read if i + 1 > current_limit: index += 1 current_out_path = make_new_filename(index) current_writer = csv.writer(open(current_out_path, 'w'), delimiter=delimiter) if keep_headers: current_writer.writerow(headers) #otherwise just keep writing current_writer.writerow(row) ## def main(): num_rows = input('Enter number of rows: ') keep_headers = raw_input('Keep headers? (yes/no) :') file_name = raw_input('Enter the file name:') if keep_headers == 'yes': keep_headers = True else: keep_headers= False split(open(file_name, 'r'),num_rows, keep_headers) print('now go make megan a coffee') main()
0532a7f6077472c878e362508256222175d549da
sapscode/Code-Files
/Python test files/CSV/csv_parse.py
1,813
4.4375
4
import csv ### READING FORM A CSV """ with open('names.csv','r') as csv_file: csv_reader = csv.reader(csv_file) #creating a reader to read from the files for line in csv_reader: print(line) #will give a list of all the values print(line[2]) #to print the email column """ ### WRITING TO A CSV """ with open('names.csv','r') as csv_file: csv_reader = csv.reader(csv_file) with open('new.csv','w') as new_file: #csv_writer = csv.writer(new_file, delimiter='-') #delimiter, so they are seperated by '-' instead of ',' csv_writer = csv.writer(new_file, delimiter= '\t') for line in csv_reader: csv_writer.writerow(line) """ ## But when you open that file, ERROR """ with open ('new.csv','r') as new_file: #csv_reader = csv.reader(new_file) #This will print it out with the '\t' in place as a text, #to change this we will have to explicitely state it in # the reader csv_reader = csv.reader(new_file,delimiter='\t') for line in csv_reader: print(line) """ ## READING THE CSV AS A DICTIONARY ## this will make the column name as keys, and hence easy to access """ with open('names.csv', 'r') as csv_file: csv_reader = csv.DictReader(csv_file) for line in csv_reader: #print(line) print(line['email']) #to print just the email column """ ## To write csv files as dictionary with open('names.csv', 'r') as csv_file: csv_reader = csv.DictReader(csv_file) with open('new_names.csv', 'w') as new_file: fieldnames = ['first_name', 'last_name'] csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter='\t') csv_writer.writeheader() for line in csv_reader: del line['email'] csv_writer.writerow(line)
fa4b4776ca8e329698a58f3e4cb5d1cbba78ca45
daniel-reich/ubiquitous-fiesta
/CzrTZKEdfHTvhRphg_20.py
589
3.6875
4
def pgcd(num1, num2): for val in range(min(num1, num2), 0, -1): if num2%val == 0 and num1%val == 0 : return val ​ def mixed_number(frac): up, down = list(map(lambda elm: int(elm), frac.split('/'))) if up == 0: return '0' up = abs(up) div = pgcd(up, down) up, down = up//div, down//div num = up//down result = '-' if frac[0] == '-' else '' if num == up/down: return result + str(num) result += str(num)+' ' if num != 0 else '' result += str(up - num*down) + '/' + str(down) if num != up/down else str(num) return result
c788c0621364acf2c4bd9be2693c1f534d5d2a10
JMBoter/Euler-Problems
/5_SmallestMultiple.py
336
3.546875
4
import util i = 11 found = False while (found == False): found = True for j in range(1,11): if i %j != 0: found = False break i += 1 #print (i-1) def smallest_multiple_upto(x): n = 1 for i in range(1,x+1): n = util.lcm(n,i) return (n) print (smallest_multiple_upto(20))
f81126eac13f27633c0b7708db39b6c75fc683a3
hiroshi415/pythonweek2
/test/1_rpswith2players.py
4,272
4.03125
4
def rsp(): player1 = input('What is your name? ') player2 = input('What is your opponent name? ') player1choice = input(player1 + '! Rock, Scissors, or Paper? ').lower() player2choice = input(player2 + '! Rock, Scissors, or Paper? ').lower() if(player1choice == player2choice): print("It's a tie") elif (player1choice == 'rock' and player2choice == 'scissors'): print('Rock wins') elif (player1choice == 'rock' and player2choice == 'paper'): print('Paper wins') elif (player1choice == 'scissors' and player2choice == 'paper'): print('Scissors wins') elif (player1choice == 'scissors' and player2choice == 'rock'): print('Rock wins') elif (player1choice == 'paper' and player2choice == 'rock'): print('Paper wins!') elif (player1choice == 'paper' and player2choice == 'scissors'): print('Scissors wins!') def hangman(): x = input('Enter a word: ').lower() ans = ['-']*len(x) while '-' in ans: letter = input('Guess a letter: ').lower() for i in range(len(x)): if x[i] == letter: print(letter, 'is in index of', i) ans[i] = letter.upper() print(ans) print('Congrats!') def num_guess(): import random # generate random number randnum = random.randint(0, 9) count = 1 # start guessing until guess is the same value of random number guess = int(input('guess a number from 0-9: ')) while guess != randnum: if guess > randnum: print('guess too big') guess = int(input('guess a number: ')) count += 1 else: print('guess too small') guess = int(input('guess a number: ')) count += 1 # only finish when guess is correct else: print('Number was', randnum) print('Correct! You have guess in ', count, 'time(s)!') # # id name salary department position hire date # import sqlite3 # mydb = sqlite3.connect('TEST.db') # mycursor = mydb.cursor() # mycursor.execute('CREATE TABLE IF NOT EXISTS teachers (id INT AUTO_INCREMENT, name VARCHAR(255), salary INT(255), department VARCHAR(255), position VARCHAR(255), hire_date VARCHAR(255))') # mycursor.execute("INSERT INTO teachers(id, name, salary, department, position, hire_date) VALUES (10, 'hiroshi10', 10000, 'school', 'student', '2019-10-05')") # mydb.commit() # # find birthdays # def find_birth(): # li = {'hiroshi':'1001/9/4','rekha':'2005/10/01','kotaro':'1999/09/29', 'seiya':'2000/01/01'} # print('Whose birthday do you want to find?') # for x in li.keys(): # print(x) # name = input('Enter a name: ') # print(name,'was born on',li[name.lower()]) # find_birth() # # Find Even numbers # def find_even(): # li = [1,2,3,4,5,6,10,9,54,31] # ans=[] # for i in range(len(li)): # if(li[i]%2==0): # ans.append(li[i]) # print(li) # print(ans) # find_even() # # sum of all nums # def sum_all(): # li = [1,2,3,4,5,6,7,8,9,10] # ans = 0 # for i in range(len(li)): # ans += li[i] # print(ans) # sum_all() # # find from list # def find_in_list(a,b): # li = [2,4,6,8,10] # guess = [a,b] # print('From list', li) # print('Finding...', guess) # if(guess[0] in li and guess[1] in li): # print(True) # else: # print(False) # find_in_list(1,10) # # compare lists # def copm_list(): # a = [1,2,3,4,5,6,7,8,9,10, 15] # b = [1,4,8,11,15, 9, 3] # print(a) # print(b) # ans = [] # for i in range(len(a)): # for j in range(len(b)): # if b[j] == a[i]: # ans.append(b[j]) # print(ans) # copm_list() # # remove duplicates(two lines) # def remove_dup(): from tkinter import * root=Tk() root.geometry('300x300') # radiobutton first = Radiobutton(root) first.grid(row=3, column=0) firstLabel = Label(text='First') firstLabel.grid(row=3, column=1) second = Radiobutton(root) second.grid(row=3, column=2) secondLabel = Label(text='Second') secondLabel.grid(row=3, column=3) third = Radiobutton(root) third.grid(row=3, column=4) thirdLabel = Label(text='Third') thirdLabel.grid(row=3, column=5) root.mainloop()
93eac8614c32ce9eb442fbab1169088b83f3d963
liyunkuo/python
/0312-3.py
358
3.5
4
# -*- coding: utf-8 -*- """ 1100312 作業三 一個整數:它加上100後是一個完全平方數, 再加上168又是一個完成平方數,請問它是多少? """ import math for num in range(1,1001) : n = math.sqrt(num + 100) m = math.sqrt(num + 268) if n == int(n) and m == int(m) : print(num)
58ab7f4892dfff52a4988928dda61eae8eca2629
ililiiilil/Algorithms-Python-
/BaekJoon/BOJ2751-1.py
697
3.625
4
import sys n = int(sys.stdin.readline()) arr = [] for _ in range(n): arr.append(int(sys.stdin.readline())) def merge_sort(arr): if len(arr) < 2: return arr mid = len(arr) // 2 low_arr = merge_sort(arr[:mid]) high_arr = merge_sort(arr[mid:]) merged_arr = [] l = h = 0 while l < len(low_arr) and h < len(high_arr): if low_arr[l] < high_arr[h]: merged_arr.append(low_arr[l]) l += 1 else: merged_arr.append(high_arr[h]) h += 1 merged_arr += low_arr[l:] merged_arr += high_arr[h:] return merged_arr merged_arr = merge_sort(arr) for i in merged_arr: print(i)
0daf019552713456251ab569f4206d8536e97bcd
pauloALuis/LP
/SeriesDeProblemas2/pb4.py
1,408
4.5625
5
#!/usr/bin/env python3 """ pb1.py 18/08/2021 """ import random import math #4.a) def generate_list(n: int = 10): """ function that generates a list @param n : length of the list @return list with pair numbers between 0 and 50 """ l=[] [l.append(random.randint(0,25) * 2) for _ in range(0, n)] return l #4.b) def square_root_list(l: list): """ method that returns a square root list of an list @param l: the list @return a square root list of "l" """ l2 = [] [l2.append(math.sqrt(i)) if i > 0 else l2.append(0.0) for i in l] return l2 l = generate_list(10) print(l) print(square_root_list(l)) #4.c) def multiply_list(l: list, n: int = 3): """ method that returns a list multiplied by "n" @param list: list to multiply @param n : number of multiplicity @return the list with elements multiplies by "n" """ return list(map(lambda x: x*n, l)) print(multiply_list(l)) #4.d) def remove_pair_numbers(l: list): """ removes even numbers of a list @param l : the list @return the list l without even numbers """ return list(filter(check_even, l )) def check_even(n: int): """ method that checks if a number is even or odd @param n : the number @return true if is evend and false if is odd number """ return True if n % 2 == 0 else False print(remove_pair_numbers(l))
d4a2dcff93d43bcfa30f41dc8f76d9ff4fecaa3f
justyna-eevee/codecool_week_pair2_homework
/hello_world/helloinput.py
327
3.546875
4
def get_user_name(): name = input('What is your name? ') return name.upper() def get_hello_message(): name = get_user_name() if name: return f'Hello, {name}!' else: return 'Hello World!' def say_hello(): print(get_hello_message()) if __name__ == "__main__": say_hello()
990b1068c0d749c9ed29bcec9d29907f23318045
richardcinca/CursuriPY
/Functions/ex1.py
388
3.578125
4
lista=[] count=0 while count<5: number=input('>>') lista.append(int(number)) count+=1 # print(lista) #VARIANTA PRIN ACCESARE ELEMENTE LISTA suma=0 for i in range(0,len(lista)): suma=suma+lista[i] print(f' Total = {suma}') #VARIANTA PRIN ITERARE SI ADUNARE # def sum(lista): # suma=0 # for i in lista: # suma=suma+i # print(suma) # sum(lista)
0656314b2fa7826f4cc2f3ddad88598eb253f217
fmojica30/leetcode_practice
/sliding_puzzle_2.py
1,379
3.8125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from copy import deepcopy class Queue(object): def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) return def dequeue(self): return self.queue.pop(0) class Solution(): def slidingPuzzles(self, board): valid_puzzle = [[1,2,3],[4,5,0]] todo = Queue() done = [] x = None y = None num_moves = 0 for i in range(len(board)): for j in range(len(board[i])): if (board[i][j] == 0): x = i y = j xMoves = [1,-1,0,0] yMoves = [0,0,1,-1] todo.enqueue(board) while len(todo.queue > 0): check = todo.dequeue() if check == valid_puzzle: return True for i in range(4): new_x = x + xMoves[i] new_y = y + yMoves[i] if (self.valid_move(new_x, new_y)): moved = deepcopy(check) moved[y][x], moved[new_y][new_x] = moved[new_y][new_x], moved[y][x] todo.enqueue(moved) return -1 def valid_move(self, x, y): return (x <= 2 and x >= 0 and y <= 1 and y >= 0) def main(): x = Solution() main()
c62e4e3bdd7032ea780bd5cf9604c6fe44c5b1ec
Exia01/Python
/Self-Learning/iterators_and_generators/generators.py
914
4.3125
4
# generators are iterators # example: # def count_up(max): # count = 1 # while count <= max: # yield count # yield has a next stores the most recent cycle # count += 1 # total_count = count_up(20) # print(list(total_count)) # print(help(count_up)) # counter = count_up(20) # print([x for x in counter]) from math import sqrt def next_prime(): candidate = 2 while True: for divisor in range(2, round(sqrt(candidate))+1): yield f" Candidate:\t{candidate}" yield f" Divisor:\t{divisor}" yield f" Modulo:\t{candidate%divisor}" if candidate%divisor == 0 and divisor != 1: yield f"Not a prime....\n" break else: yield f"\t\t{candidate} ← ← ← ← ← ← ← ← ← ← PRIME\n" # yield candidate candidate += 1 primes = next_prime() for thing in [next(primes) for i in range(100)]: print(thing)
a5b809d24686527234468793fdeeb6e09cbe0bd7
PawarKishori/QSE
/two_relations.py
1,039
3.65625
4
import sqlite3 conn=sqlite3.connect('Treebank_English.db') def rel2(conn): cursor=conn.cursor() cursor2=conn.cursor() x=input("enter the first relation\n:") y=input("enter the second relation\n:") x="'"+x+"'" y="'"+y+"'" cursor.execute('SELECT p.rel, c.rel, count(1) FROM Tword p INNER JOIN Tword c ON p.wid = c.parent AND p.sid = c.sid WHERE p.rel='+x+' AND c.rel='+y+' GROUP BY p.rel, c.rel') cursor2.execute('SELECT p.rel, c.rel, count(1) FROM Tword p INNER JOIN Tword c ON p.wid = c.parent AND p.sid = c.sid WHERE p.rel='+y+' AND c.rel='+x+' GROUP BY p.rel, c.rel') myresult1=cursor2.fetchall() myresult=cursor.fetchall() #print(myresult1) n = len(myresult) for i in range(n): print('parent_rel: '+myresult[i][0]+'\tchild_relation: '+myresult[i][1]+'\tn_occurances: '+str(myresult[i][2])) m=len(myresult1) for i in range(m): print('child_rel: '+myresult1[i][0]+'\tparent_relation: '+myresult1[i][1]+'\tn_occurances: '+str(myresult1[i][2])) rel2(conn)
13a74e73a06e7a857e173236caf743831548e581
pgenev/Programming101-Tasks-Completion
/Week1/1.Warmups/factorial_digits.py
274
3.8125
4
from factorial import factorial def fact_digits(number): sum = 0 number = abs(number) while(number != 0): sum += factorial(number % 10) number = number // 10 return sum print(fact_digits(111)) print(fact_digits(145)) print(fact_digits(999))
939e9ea2fc1fa96b44832cf07816de6186a0299e
wy/ProjectEuler
/solutions/problem56.py
508
3.515625
4
# coding: utf8 # Author: Wing Yung Chan (~wy) # Date: 2017 # Powerful Digit Sum # maximise the digits sum of a^b for a,b < 100 def digitsum(n:int) -> int: s = str(n) d = 0 for c in s: d += int(c) return d def problem56(): max = 0 for a in range(99,0,-1): for b in range(99,0,-1): n = a ** b d = digitsum(n) if d > max: max = d if 9 * len(str(n)) < max: break return max print(problem56())
673f125787776592babd1e9b450b1416fc118ce7
likesfish/learning
/homework6.py
257
3.984375
4
for i in range(1, 101, 1): if i % 2 == 0 and i % 3 == 0: print (i, "fizzbuzz") elif i % 2 == 0: print (i, "fizz") elif i % 3 == 0: print (i, "buzz") else: print (i, "you're still a number")
b8200fa038012b6c307f7bd22ef65e58ecf730d8
sakumiak/clearcode_tasks
/task2.py
1,859
4.0625
4
#Python intern task - task2 #Function damage # Inputs spell: str # Outputs: dmg: int # This function check if spell is spell and counting damage points. def damage (spell): dmg = 0 subspells_dict = {'fe': 1, 'je': 2, 'jee': 3, 'ain': 3, 'dai': 5, 'ne': 2, 'ai': 2} subspells_list = ['fe','jee','je','ain','dai','ne','ai'] if not(type(spell) is str): return 'Pleas use str to cast your spell' if 'fe' in spell and 'ai' in spell and spell.count('fe') == 1 and spell.index('ai') > spell.index('fe'): spell = spell[spell.index('fe'):] dmg += subspells_dict['fe'] spell = spell.replace('fe','') spell = spell[:spell.rfind('ai')] dmg += subspells_dict['ai'] #In this loop function countin damage points and choose the one with the biggest damage. #Choose the biggest damage: # First function check str with length 3 cause 'jee' is more valuable than 'je'. The same thing is with 'ain' and 'ai'. # 'dai-n' is always more valueable than 'd-ain' and it is always checking first. Look at subspells_dict. # If spell starts with 'ain' we check next character. If it's equal 'e' function use 'ai-ne' subspells cause it's more valuable than 'ain-e' #Damage counting: # Function add to dmg variable value from subspells_dict if str[0:2] or str[0:3] is subspell else it add -1 to dmg variable while len(spell) > 0: if spell[0:3] in subspells_list: if len(spell) > 3 and spell[0:3] == 'ain' and spell[3] == 'e': dmg += subspells_dict['ai'] + subspells_dict['ne'] spell = spell[4:] else: dmg += subspells_dict[spell[0:3]] spell = spell[3:] elif spell[0:2] in subspells_list: dmg += subspells_dict[spell[0:2]] spell = spell[2:] else: dmg -= 1 spell = spell[1:] if dmg < 0: dmg = 0 return dmg if __name__ == '__main__': print(damage('jejejefedaiainanana'))
6ec7185ea8a03d14d4b87468e1882b5e61e25006
rishabkatta/CDSusingPython
/people.py
5,486
4
4
_author = 'sps' """ CSCI-603: String/File/List/Dictionary Lecture (week 5) Author: Sean Strout @ RIT CS This is a demonstration program for strings, files, lists and dictionaries. It takes a comma separated file (CSV) that contains basic information about individuals (one per line): id,first_name,last_name,email,country,ip_address For each individual, it displays formatted information about them: ID: # Name: {FirstInitial} . {LastName} Username: {Username} Domain: {Domain} Country Code: {CountryCode} IP (hex): {IP} This data was generated randomly by the site: https://www.mockaroo.com/ """ import sys # stderr # CONSTANTS # positions of fields in CSV data file ID = 0 FIRST_NAME = 1 LAST_NAME = 2 EMAIL = 3 COUNTRY = 4 IP = 5 # country code mappings where key(str)={Full Country Name} and associated # value(str)= {3 digit ISO} COUNTRY_CODES = { 'Bangladesh' : 'BGD', 'China' : 'CHN', 'Dominican Republic' : 'DOM', 'Greece' : 'GRC', 'Kazakhstan' : 'KAZ', 'Nigeria' : 'NGA', 'Philippines' : 'PHL', 'Portugal' : 'PRT', 'Ukraine' : 'UKR' } def printName(firstName, lastName): """ Print the name of the person in the format <TAB>Name: <first initial>. <last name> :param firstName (str): The first name :param lastName (str): The last name :return: None """ # strip off the first initial firstInitial = firstName[:1] # concatenate together and print name = firstInitial + '. ' + lastName print('\tName:', name) def printEmail(email): """ Print the email information for the person in the format <TAB>Username: <user name> <TAB>Domain: <domain name> :param email (str): The full email address :return: None """ # find the location of the @ symbol atPos = email.index('@') # the username is up to but not including the @ symbol username = email[:atPos] print('\tUsername:', username) # the domain is everything after the @ symbol domain = email[atPos+1:] print('\tDomain:', domain) def printCountryCode(country): """ Print the country code (if found). Format: <TAB>Country Code: <country code> or <TAB>Country Code: **** NOT FOUND **** :param country (str): The full name of the country :return: None """ # if the country is in the dictionary, display the code, otherwise # indicate that it could not be found if country in COUNTRY_CODES: print('\tCountry Code:', COUNTRY_CODES[country]) else: print('\tCountry Code:', '*** NOT FOUND ***') def printIP(ip): """ Print the IP address in hex. :param ip (str): The ip address as '#.#.#.#' where '#' is a decimal number string. Print it in the same form except that the four numbers will be in base 16. :return: None """ # split the 4 bytes (as strings) into a list, e.g.: # ip -> '95.126.14.81' # bytes -> ['95', '126', '14', '81'] bytes = ip.split('.') # build the hex address, starting with the '0x' address = '0x' # loop over the list of byte strings for byte in bytes: # convert the byte string to hex (by first converting # the string byte to an integer), e.g.: # byte -> '95' # int(byte) -> 95 # hex(95) -> '0x5f' hexStr = hex(int(byte)) # strip off the leading '0x' because we are building this into # the address string hexStr = hexStr[2:] # pad string w/ a leading 0 if only 1 digit (a value less than 16), # e.g.: # hexStr -> 'd' -> '0d' if (len(hexStr) != 2): hexStr = '0' + hexStr # concatenate to full address: # address -> '0x' # hexStr -> '0d' # address -> '0x0d' address += hexStr print('\tIP (hex):', address) def processFile(fileName): """ Process the entire CSV file and display each individuals information. :param fileName (str): The file name :exception: FileNotFoundError if fileName does not exist: <TAB>IP (hex): <hex ip addr> :return: None """ # using 'with' means the file handle, f, will be automatically closed # when the region finishes with open(fileName) as f: # discard first line (column labels) f.readline() # process the remainder of the lines for line in f: # strip the newline at the end of the line line = line.strip() # split the line into a list of strings, using the comma delimiter data = line.split(',') # print the ID print('ID:', data[ID]) # print first initial and last name printName(data[FIRST_NAME], data[LAST_NAME]) # print the username and domain for the email address printEmail(data[EMAIL]) # print the country code printCountryCode(data[COUNTRY]) # print IP printIP(data[IP]) def main(): """ The main function. :return: None """ try: fileName = input("Enter filename: ") processFile(fileName) except FileNotFoundError as fnfe: print(fnfe, file=sys.stderr) if __name__ == '__main__': main()
31e4558361382063fa321a39c9f25f210e2085de
arnabs542/Competitive-Programming
/CodeForces/problem/A/996A_HitTheLottery.py
323
3.578125
4
# https://codeforces.com/problemset/problem/996/A money = int(input()) bills = 0 if money>=100: bills += money//100 money -= bills*100 if money>=20: bills += money//20 money -= (money//20)*20 if money>=10: bills += 1 money -= 10 if money>=5: bills += 1 money -= 5 print(bills + money)
ec3988f213783578a6d95d25921099300e6a6421
pauloestrella1994/automate_stuffs_with_python
/regular_expressions/begin_finish_regex.py
1,643
3.90625
4
import re #Match the object only with it's in the begging of the string (^) beginRegex = re.compile(r'^Hello') mo = beginRegex.search('Hello there!') mo2 = beginRegex.search('He said "Hello"') print(mo.group()) if not mo2: print("Can't match object") #find the object in the final of the string ($) endRegex = re.compile('world!$') mo = endRegex.search('Hello world!') print(mo.group()) #find all digits in the regex pattern in a string, beginning with ^, ending with $ alldigitsRegex = re.compile(r'^\d+$') mo = alldigitsRegex.search('7851498645929546') print(mo.group()) #find any caractere plus the pattern with . atRegex = re.compile(r'.at') mo = atRegex.findall('The cat in the hat sat on the flat mat!') print(mo) #find any object after a specify string, using . and * for multiples objects nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)') mo = nameRegex.findall('First Name: Paulo Last Name: Netto') print(mo) #matching in two different ways the pattern between marks serve = '<To serve humans> for dinner>' firstmarkRegex = re.compile(r'<(.*?)>') lastmarkRegex = re.compile(r'<(.*)>') print(firstmarkRegex.findall(serve)) print(lastmarkRegex.findall(serve)) #the expression .* find all objects, except a new line. To find all the strings, even if it has lines, set re.DOTALL in compile phrase = " Hello\n Beautiful\n World" dotAllRegex = re.compile(r'.*', re.DOTALL) mo = dotAllRegex.search(phrase) print(mo.group()) #to match any characteres, upper or lower case, set in compile r.I phrase = 'WhY PROgrAmminG Is so HArD?' lowerupperRegex = re.compile(r'[aeiou]', re.I) print(lowerupperRegex.findall(phrase))
16533f2f86a3481580c1d6fe93e774bfe3b6e231
RDAW1/Programacion
/Practica 1/Exercici_03.py
162
3.953125
4
print 'ACTIVIDAD 3: NUMERO PAR O IMPAR' print 'Escribe el numero' n=input() if n % 2==0: print 'El numero es par' else: print 'El numero es impar'
d742337caf58417de0b4880feb142ca0107415cb
LordGhostX/unittest-intro
/test_calc2.py
718
3.53125
4
import unittest import calc class TestCalc(unittest.TestCase): def setUp(self): self.first_number = 10 self.second_number = 5 def tearDown(self): print("tearDown Class") def test_add(self): self.assertEqual(calc.add(self.first_number, self.second_number), 15) def test_substract(self): self.assertEqual(calc.substract( self.first_number, self.second_number), 5) def test_multiply(self): self.assertEqual(calc.multiply( self.first_number, self.second_number), 50) def test_divide(self): self.assertEqual(calc.divide(self.first_number, self.second_number), 2) if __name__ == "__main__": unittest.main()
5620c9d334d8aa2a72966f870979f1a6eb44b307
ServePeak/proj2-pd6-08-JASE
/stuyteachers.py
11,677
3.5
4
## ACCESS TEACHER LIST: ## getTeachers(SORT) ## available options: ## - first ## - last (DEFAULT if left blank) ## - title ## ## returns dictionary of sorted results import urllib import json import math from bs4 import BeautifulSoup from operator import itemgetter from pymongo import MongoClient # our functions import pFinder # gets addresses and phone numbers import salary # gets salary import ratemt # ratemyteachers.com import zipcode # zipcode information import gimages c = MongoClient() # special cases special = [ # Department to be part of, Title ["Computer Science","Coordinator Comp Sci"] ] def getTeachers(s=None): url = "http://stuy.enschool.org/apps/staff/" result = BeautifulSoup(urllib.urlopen(url)) r = [] for x in result.find("table").find_all("tr"): name = x.find("td").find("a") if name: n = name.get_text().split(". ")[1]#.split(" ") r.append({ "first":n.split(" ")[0], "last":n.replace(n.split(" ")[0]+" ",""), "title":x.find_all("td")[1].get_text() }) if r and s in r[0].keys(): r = sorted(r, key=itemgetter(s)) return r def teachersToDatabase(): c.teachers.Collections.remove() print("Adding in teachers to database...") teachers = getTeachers() for x in range(0,len(teachers)): t = teachers[x] t["id"] = x # add in teacher's salary gs = salary.getSalary(t["first"],t["last"]) t["salary"] = int(gs[0]) t["salary_year"] = int(gs[1]) # array for multiple address results of teachers t["address"] = [] addr = pFinder.pFind(t["first"],t["last"]) if addr: for z in addr: # z["map"] = gmap() --- placeholder for Google Maps function t["address"].append(z) t["rmt_overall"] = -1 t["rmt_easiness"] = -1 t["rmt_helpfulness"] = -1 t["rmt_clarity"] = -1 t["rmt_num_reviews"] = 0 c.teachers.Collections.insert(teachers[x]) # if t["salary"] == -1: # print("[%d] Error %s %s"%(x,t["first"],t["last"])) # else: pr = "[%d]\t{{ %s %s }}\t"%(x,t["first"],t["last"]) if t["salary"] == -1: pr += "Error " else: pr += "$%d"%(t["salary"]) if(len(t["address"]) > 0): pr += "\t%s\t%s"%(t["address"][0]["phoneNum"],t["address"][0]["address"]) else: pr += "No address found" pr += "\n" print(pr) do_ratemyteachers() distance.getTeachs() citibike.updateTeachers() do_zipcode() print("Done.") def fix_address(n): r = [] for x in n: if "(212)" in x["phoneNum"] or "(718)" in x["phoneNum"] or "NeW York" in x["address"] or "Brooklyn" in x["address"]: r.append(x) n.remove(x) if len(r) > 0: return r return n def do_ratemyteachers(): c.ratemt.Collections.remove() # compare ratemyteachers print("Searching up results from ratemyteachers.com:") res = ratemt.getRatings() for x in range(0,len(res)): res[x]["id"] = x res[x]["overall"] = res[x]["overall"] c.ratemt.Collections.insert(res[x]) # pair up with ratemyteachers for x in c.ratemt.Collections.find(): a = x["name"].split(" ") if len(a) > 1: c.ratemt.Collections.update({"id":x["id"]},{"$set":{"matched":False,"first":a[0],"last":a[1]}}) else: c.ratemt.Collections.update({"id":x["id"]},{"$set":{"matched":False,"first":"","last":a[0]}}) perfect = [] # perfect matches (first AND last) close = [] # close matches (last) no = [] # no matches for x in c.teachers.Collections.find(): if "first" in x.keys() and "last" in x.keys(): k = c.ratemt.Collections.find_one({"first":x["first"],"last":x["last"],"matched":False}) if k: perfect.append(k) teacher_update(x,k) else: k = c.ratemt.Collections.find({"last":x["last"],"matched":False}) if k.count() == 1: close.append([x,k]) teacher_update(x,k[0]) else: no.append(x) for x in c.ratemt.Collections.find({"matched":False}): for y in c.teachers.Collections.find({"rmt_overall":-1,"last":{"$regex":x['last']+" "}}): teacher_update(y,x) # print(y['first']+" "+y['last']+" = "+x['first']+" "+x['last']) print("Stuyvesant teachers matched with ratemyteachers.com results:") print("%d perfect matches"%(len(perfect))) print("%d close matches"%(len(close))) print("%d no matches"%(len(no))) def do_zipcode(): for x in c.teachers.Collections.find(): if len(x["address"]) > 0: a = str(x["address"][0]["address"]).split(",")[1].lstrip().split(" ")[1] k = zipcode.zipinfo(a) x["address"][0]["zipinfo"] = k try : print("%s %s Median: $%d, College Graduate Percent: %d, White Percent: %d"%(x['first'],x['last'],k["MedianIncome"],k["CollegeDegreePercent"],k["WhitePercent"])) c.teachers.Collections.update({"id":x['id']},{"$set":{"address":x["address"]}}) except: print("\t%s %s ===== ERROR"%(x['first'],x['last'])) def teacher_update(x,k): c.ratemt.Collections.update({"id":k["id"]},{"$set":{"matched":True}}) c.teachers.Collections.update( {"id":x["id"]}, {"$set":{ "rmt_overall":k["overall"], "rmt_easiness":k["easiness"], "rmt_helpfulness":k["helpfulness"], "rmt_clarity":k["clarity"] } }) def get(a,sort=1,limit=-1,offset=0,teachers=False): # sort: r = [] k = c.teachers.Collections.find({a:{"$ne":-1}}).sort(a,sort)#.skip(offset) if teachers: count = 0 for x in k: if "Teacher" in x['title']: r.append(x) count += 1 if count == limit: break else: # if limit > 0 : # k = k.limit(limit) count = 0 for x in k: if a in x.keys(): r.append(x) count += 1 if count == limit+offset: break for x in range(0,offset): r.remove(r[0]) return r def search(ar,limit,offset=0): r = [] temp = "" m = [] if "name" in ar and ar.get("name") != "": temp = ar.get("name").replace(" ","|").replace("-","|") m.append({"$or":[ {"first":{"$regex":temp,"$options":"-i"}}, {"last":{"$regex":temp,"$options":"-i"}} ] }) if "title" in ar and ar.get("title") != "": k = [{"title":{"$regex":ar.get("title"),"$options":"-i"}}] for x in special: if ar.get("title") == x[0]: k.append({"title":x[1]}) if len(k) > 1: m.append({"$or":k}) else: m.append(k[0]) # k = c.teachers.Collections.find({ # "$or":[ # {"first":{"$regex":temp,"$options":"-i"}}, # {"last":{"$regex":temp,"$options":"-i"}} # ] # }) if len(m) == 0: k = c.teachers.Collections.find() else: k = c.teachers.Collections.find({"$and":m}) for x in k.sort("last",1): r.append(x) return r def get_overpaid(limit): return get_payscale(limit,True,2,.65) def get_underpaid(limit): return get_payscale(limit,False,.65,2) def get_payscale(limit,order,b1,b2): a = [] # salary and overall rating must be there for x in c.teachers.Collections.find({"salary":{"$ne":-1},"rmt_overall":{"$ne":-1}}): if x["rmt_overall"] != 0 and "Teacher" in x["title"]: # ratio = math.sqrt(x["salary"])/(x["rmt_overall"]*x["rmt_overall"]) ratio = math.pow(x["salary"],b1)/math.pow(x["rmt_overall"],b2) a.append([ratio,x]) a = sorted(a, key=itemgetter(0), reverse=order) r = [] for x in range(min(limit,len(a))): r.append(a[x][1]) return r def get_departments(): k = c.teachers.Collections.find({"title":{"$regex":"Teacher"}}).distinct("title") r = [] for x in k: x = x.replace("Teacher ","").split(",")[0].split(" &")[0] spl = x.split("/") if len(spl) > 1: for y in spl: if y not in r: r.append(y) else: if x not in r: r.append(x) return r def get_teachers_in_department(n): r = [] for x in c.teachers.Collections.find({"title":{"$regex":n}}): r.append(x) for x in special: if n == x[0]: for y in c.teachers.Collections.find({"title":x[1]}): r.append(y) return r def get_teacher(n): return c.teachers.Collections.find_one({"id":n}) def num_teachers(a={}): return c.teachers.Collections.find(a).count() def total_salary(): sal = 0 k = c.teachers.Collections.find({"salary":{"$ne":-1}}) for x in k: sal += x['salary'] return sal def average_salary(): sal = [] k = c.teachers.Collections.find({"salary":{"$ne":-1}}) for x in k: sal.append(x['salary']) return sum(sal)/len(sal) def average_rmt(): rmt = [] k = c.teachers.Collections.find({"rmt_overall":{"$ne":-1}}) for x in k: rmt.append(x['rmt_overall']) if len(rmt) > 0: return sum(rmt)/len(rmt) else: return 0 if __name__ == "__main__": do_gimages() # teachersToDatabase() # pass # do_zipcode() # c = MongoClient() # for x in c.teachers.Collections.find(): # if len(x["address"]) > 0: # if "zipinfo" in x["address"][0].keys(): # # ar = {} # # for y in x["address"][0]["zipinfo"].keys(): # ar["zip_"+y] = x["address"][0]["zipinfo"][y] # # c.teachers.Collections.update({"id":x['id']},{"$set":ar},upsert=True) # teachersToDatabase() # c = MongoClient() # c.ratemt.Collections.remove() # print("Searching up results from ratemyteachers.com:") # # res = ratemt.getRatings() # # for x in range(0,len(res)): # res[x]["overall"] = int(res[x]["overall"].replace("%","")) # res[x]["id"] = x # c.ratemt.Collections.insert(res[x]) # teachersToDatabase() # for x in c.teachers.Collections.find(): # c.teachers.Collections.update({"id":x["id"]},{"$set":{"address2":x["address"],"address":None}},upsert=True) # for x in c.teachers.Collections.find(): # c.teachers.Collections.update({"id":x["id"]},{"$set":{"address2":[]}},upsert=True) # for x in c.teachers.Collections.find(): # print("%s %s"%(x['first'],x['last'])) # a = fix_address(pFinder.pFind(x["first"],x["last"])) # if len(a) > 0: # print(a[0]["address"].lstrip()) # c.teachers.Collections.update({"id":x["id"]},{"$set":{"address":a}},upsert=True) # print(str(fix_address(pFinder.pFind("Mark","Halperin")))) # do_ratemyteachers()
c44362d571f8beaa1e5c2ddcdd137249f5460de0
PChalmers/LearnJava
/Python course/src/ProblemSet1_3.py
1,005
3.78125
4
''' Created on Jan 14, 2015 @author: ca0d0340 ''' def main(): s = 'ygcgfislipsdbqggjzkff' resultString = '' tempString = '' previousLetter = '' rIndex = 0 while rIndex < len(s): currentchar = s[rIndex] # print previousLetter, currentchar, tempString, resultString # Check if the current char is greater if currentchar >= previousLetter: # Current char is greater tempString = tempString + currentchar # Current char is not greater if len(tempString) > len(resultString): # Store the New string resultString = tempString else: # Reset the temp string tempString = currentchar # Always update the previous char previousLetter = currentchar rIndex += 1 print "Longest substring in alphabetical order is:", resultString if __name__ == '__main__': main()
3b8953b116afa01d745ead8c3a47cb2019506b10
max-zia/nand2tetris
/assembler/symbol_table.py
1,444
4.03125
4
""" Keeps a correspondence between symbolic labels in a Hack assembly program and numeric addresses. """ def constructor(): """ Creates a new empty symbol table. In this case, the structure used to represent the relationship between symbols in a Hack assembly program and RAM and ROM addresses is a hash table (i.e., a python dictionary). """ return {} def initialise(symbol_table): """ Initialises symbol table with predefined symbols. Note that each one of the top five RAM locations can be referred to using two predefined labels. """ labels = [ 'SP', 'LCL', 'ARG', 'THIS', 'THAT', 'R0', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10', 'R11', 'R12', 'R13', 'R14', 'R15', 'SCREEN', 'KBD' ] addresses = [ 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16384, 24576 ] # Update the symbol table by iterating through two lists simultaneously for label, address in zip(labels, addresses): symbol_table[label] = address return symbol_table def add_entry(symbol, address, symbol_table): """ Adds the pair (symbol, address) to the symbol table. """ symbol_table[symbol] = address def contains(symbol, symbol_table): """ Does the symbol table contain the given symbol? """ if symbol in symbol_table: return True else: return False def get_address(symbol, symbol_table): """ Returns the address associated with a symbol. """ return symbol_table[symbol]
ace23dddc3ad7631687d0908389aee5aefaef734
XavRobo/Pyton_vrac
/test_json/test.py
485
3.53125
4
import json # fix this function, so it adds the given name # and salary pair to salaries_json, and return it def add_employee(salaries_json, name, salary): salaries[name] = salary return json.dumps(salaries) # test code with open('salaries.json', 'r') as f: salaries = json.load(f) new_salaries = add_employee(salaries, "Me", 800) decoded_salaries = json.loads(new_salaries) print(decoded_salaries["Alfred"]) print(decoded_salaries["Jane"]) print(decoded_salaries["Me"])
01d0d828f97f77f1ceb97243f9347cd9678a07e8
Arindaam/Class-work
/Data Structures/Misc/open_ma.py
5,396
3.765625
4
import turtle happy=turtle.Screen() happy.bgcolor("black") turtle=turtle.Turtle() turtle.shape("circle") turtle.color("peru") turtle.width(9) turtle.speed(11) colors=["white","ivory","dark orange","coral","cyan","hot pink","gold","ivory","yellow","red","pink","green","blue","light blue","light green",] def move(x,y): turtle.up() turtle.setposition(0,0) turtle.setheading(90) turtle.rt(90) turtle.fd(x) turtle.lt(90) turtle.fd(y) turtle.pendown() def mov(x,y): turtle.up() turtle.setposition(0,0) turtle.setheading(90) turtle.lt(90) turtle.fd(x) turtle.rt(90) turtle.fd(y) turtle.pendown() def M(): turtle.fd(80) turtle.rt(145) turtle.fd(60) turtle.lt(120) turtle.fd(70) turtle.rt(155) turtle.fd(85) def ballon(size): turtle.color(colors[size%8]) turtle.begin_fill() turtle.circle(size) turtle.end_fill() for i in range(17): turtle.lt(10) turtle.fd(3) turtle.fd(120) def draw_happy(i,x,y): turtle.pencolor("linen") turtle.color(colors[i%7]) turtle.begin_fill() turtle.lt(70) turtle.penup() turtle.goto(x,y) turtle.pendown() turtle.circle(33) turtle.end_fill() def f1(): for i in range(9): turtle.pensize(5) turtle.pencolor('light blue') turtle.color(colors[i%19]) turtle.begin_fill() turtle.left(330) turtle.forward(55) turtle.begin_fill() turtle.rt(110) turtle.circle(33) turtle.end_fill() turtle.rt(11) turtle.backward(33) turtle.end_fill() def cake(x,y): turtle.fd(x) turtle.rt(90) turtle.fd(y) turtle.rt(90) turtle.fd(x) turtle.rt(90) turtle.fd(y) def heart(): for i in range(43): turtle.pencolor(colors[i%9]) turtle.rt(5) turtle.fd(5) turtle.fd(150) turtle.penup() turtle.rt(140) turtle.fd(150) turtle.pendown() for i in range(43): turtle.pencolor(colors[i%9]) turtle.lt(5) turtle.fd(5) turtle.lt(7) turtle.fd(150) def A(size): turtle.rt(16) turtle.forward(size) turtle.rt(150) turtle.fd(size) turtle.backward(size/2) turtle.rt(105) turtle.fd(size/3) def B(): turtle.forward(60) turtle.rt(90) for i in range(18): turtle.rt(9) turtle.fd(3) for i in range(18): turtle.rt(13) turtle.backward(3) def m(): turtle.forward(30) for i in range(20): turtle.rt(9) turtle.fd(3) turtle.forward(5) turtle.backward(5) turtle.lt(180) for i in range(20): turtle.rt(9) turtle.fd(3) turtle.forward(30) def i(size): turtle.fd(size) def t(size): turtle.fd(size) turtle.backward(size/2) turtle.lt(90) turtle.fd(10) turtle.backward(20) def H(): turtle.fd(60) turtle.backward(30) turtle.rt(90) turtle.fd(30) turtle.lt(90) turtle.fd(30) turtle.backward(60) def H1(): turtle.fd(75) turtle.backward(50) turtle.rt(90) turtle.fd(35) turtle.lt(90) turtle.fd(25) turtle.backward(75) def P(): turtle.fd(60) turtle.rt(90) turtle.fd(7) for i in range(8): turtle.rt(20) turtle.fd(5) def Y(): turtle.fd(40) turtle.left(60) turtle.fd(20) turtle.backward(20) turtle.rt(90) turtle.fd(35) def a(): for i in range(18): turtle.rt(20) turtle.fd(9) for i in range(9): turtle.rt(20) turtle.fd(9) turtle.fd(20) for i in range(6): turtle.lt(30) turtle.fd(4) def R(): turtle.fd(60) turtle.rt(90) turtle.fd(7) for i in range(15): turtle.rt(12) turtle.fd(3) turtle.lt(120) turtle.fd(49) def D(): turtle.fd(60) turtle.rt(90) turtle.fd(9) for i in range(13): turtle.rt(13) turtle.fd(7) def brd1(): turtle.lt(90) turtle.forward(100) turtle.lt(90) turtle.forward(1000) turtle.lt(90) turtle.forward(100) def brd2(): turtle.rt(90) turtle.forward(100) turtle.rt(90) turtle.forward(1000) turtle.rt(90) turtle.forward(100) turtle.pencolor("cyan") turtle.width(11) mov(220,300) H() mov(180,300) A(65) mov(135,300) P() mov(100,300) P() mov(52,300) Y() mov(25,300) B() move(12,300) i(60) move(36,300) R() move(80,300) t(100) move(102,300) H() move(150,300) D() move(190,300) A(65) move(250,300) Y() turtle.pencolor("hot pink") turtle.width(15) mov(185,400) M() mov(105,400) A(100) mov(35,415) H1() move(30,400) i(76) move(60,400) turtle.pencolor("white") m() move(160,425) a() turtle.pencolor("hot pink") move(430,400) ballon(69) move(-250,400) ballon(72) turtle.speed(12) mov(90,20) turtle.width(17) turtle.color(colors[8%5]) turtle.begin_fill() cake(40,180) turtle.end_fill() mov(80,55) turtle.color(colors[8%3]) turtle.begin_fill() cake(40,160) turtle.end_fill() mov(70,90) turtle.color("hot pink") turtle.begin_fill() cake(40,133) turtle.end_fill() mov(-10,133) turtle.width(11) turtle.pencolor("red") turtle.circle(7) turtle.pencolor("black") move(-15,90) turtle.write("20" ,font=("Cambria",25,"bold")) for i in range(5): draw_happy(i,-189,200) for i in range(6): draw_happy(i,189,200) for i in range(7): draw_happy(i,123,-100) for i in range(5): draw_happy(i,-123,-100) mov(10,-80) turtle.width(19) heart() mov(10,-400) f1() turtle.pencolor("cyan") move(-350,500) brd1() turtle.pencolor("white") move(360,500) brd2() happy.exitonclick()
a9ce6d71e3d7283c5895936b0d3d22e2bdcf53e5
feadoor/advent-of-code-2018
/13.py
7,250
3.546875
4
TURN_LEFT = 0 TURN_STRAIGHT = 1 TURN_RIGHT = 2 UP = 0 LEFT = 1 DOWN = 2 RIGHT = 3 def replace_cart(track_segment): if track_segment == '<' or track_segment == '>': return '-' elif track_segment == '^' or track_segment == 'v': return '|' else: return track_segment def is_cart(c): return c in ['<', '>', '^', 'v'] def direction_from_cart(cart): if cart == '<': return LEFT elif cart == '>': return RIGHT elif cart == '^': return UP elif cart == 'v': return DOWN def next_direction(direction, turn): if turn == TURN_STRAIGHT: return direction elif turn == TURN_LEFT: return (direction + 1) % 4 else: return (direction - 1) % 4 def get_track_and_carts(): with open('data/13.txt', 'r') as f: lines = f.readlines() track, carts = [[replace_cart(c) for c in line.rstrip()] for line in lines], [] for i, line in enumerate(lines): carts.append([None] * len(line.rstrip())) for j, c in enumerate(line.rstrip()): if is_cart(c): carts[i][j] = (direction_from_cart(c), TURN_LEFT) return track, carts def tick_return_crash(track, carts): ignored_locations = set() for i, row in enumerate(carts): for j, cart in enumerate(row): if cart and not (i, j) in ignored_locations: carts[i][j] = None direction, turn = cart if direction == UP: if carts[i - 1][j]: return i - 1, j elif track[i - 1][j] == '/': carts[i - 1][j] = (RIGHT, turn) elif track[i - 1][j] == '\\': carts[i - 1][j] = (LEFT, turn) elif track[i - 1][j] == '+': carts[i - 1][j] = (next_direction(direction, turn), (turn + 1) % 3) else: carts[i - 1][j] = (direction, turn) elif direction == LEFT: if carts[i][j - 1]: return i, j - 1 elif track[i][j - 1] == '/': carts[i][j - 1] = (DOWN, turn) elif track[i][j - 1] == '\\': carts[i][j - 1] = (UP, turn) elif track[i][j - 1] == '+': carts[i][j - 1] = (next_direction(direction, turn), (turn + 1) % 3) else: carts[i][j - 1] = (direction, turn) if direction == DOWN: if carts[i + 1][j]: return i + 1, j elif track[i + 1][j] == '/': carts[i + 1][j] = (LEFT, turn) elif track[i + 1][j] == '\\': carts[i + 1][j] = (RIGHT, turn) elif track[i + 1][j] == '+': carts[i + 1][j] = (next_direction(direction, turn), (turn + 1) % 3) else: carts[i + 1][j] = (direction, turn) ignored_locations.add((i + 1, j)) if direction == RIGHT: if carts[i][j + 1]: return i, j + 1 elif track[i][j + 1] == '/': carts[i][j + 1] = (UP, turn) elif track[i][j + 1] == '\\': carts[i][j + 1] = (DOWN, turn) elif track[i][j + 1] == '+': carts[i][j + 1] = (next_direction(direction, turn), (turn + 1) % 3) else: carts[i][j + 1] = (direction, turn) ignored_locations.add((i, j + 1)) def tick_remove_crashes_return_count(track, carts): ignored_locations = set() count = 0 for i, row in enumerate(carts): for j, cart in enumerate(row): if cart and not (i, j) in ignored_locations: count += 1 carts[i][j] = None direction, turn = cart if direction == UP: if carts[i - 1][j]: carts[i - 1][j] = None count -= 2 elif track[i - 1][j] == '/': carts[i - 1][j] = (RIGHT, turn) elif track[i - 1][j] == '\\': carts[i - 1][j] = (LEFT, turn) elif track[i - 1][j] == '+': carts[i - 1][j] = (next_direction(direction, turn), (turn + 1) % 3) else: carts[i - 1][j] = (direction, turn) elif direction == LEFT: if carts[i][j - 1]: carts[i][j - 1] = None count -= 2 elif track[i][j - 1] == '/': carts[i][j - 1] = (DOWN, turn) elif track[i][j - 1] == '\\': carts[i][j - 1] = (UP, turn) elif track[i][j - 1] == '+': carts[i][j - 1] = (next_direction(direction, turn), (turn + 1) % 3) else: carts[i][j - 1] = (direction, turn) if direction == DOWN: if carts[i + 1][j]: carts[i + 1][j] = None count -= 2 elif track[i + 1][j] == '/': carts[i + 1][j] = (LEFT, turn) elif track[i + 1][j] == '\\': carts[i + 1][j] = (RIGHT, turn) elif track[i + 1][j] == '+': carts[i + 1][j] = (next_direction(direction, turn), (turn + 1) % 3) else: carts[i + 1][j] = (direction, turn) ignored_locations.add((i + 1, j)) if direction == RIGHT: if carts[i][j + 1]: carts[i][j + 1] = None count -= 2 elif track[i][j + 1] == '/': carts[i][j + 1] = (UP, turn) elif track[i][j + 1] == '\\': carts[i][j + 1] = (DOWN, turn) elif track[i][j + 1] == '+': carts[i][j + 1] = (next_direction(direction, turn), (turn + 1) % 3) else: carts[i][j + 1] = (direction, turn) ignored_locations.add((i, j + 1)) return count def first_collision(): track, carts = get_track_and_carts() collision = None while collision is None: collision = tick_return_crash(track, carts) return (collision[1], collision[0]) def last_cart(): track, carts = get_track_and_carts() count = sum(sum(1 if cart else 0 for cart in row) for row in carts) while count > 1: count = tick_remove_crashes_return_count(track, carts) for i, row in enumerate(carts): for j, cart in enumerate(row): if cart: return j, i print(first_collision()) print(last_cart())
5e1b14e6f2b5b769875111a2f34fe398ae0036c5
aditepDev/python_101
/l07_regular/Exercise/ValidateTel.py
696
3.53125
4
import re # กำหนด แพทเทิล ของ tel # ขึ้นต้อนด้วย 08 ตัวเลข - ตัวเลช 3 ตัว - ตัวเลช 4 ตัว telRE = r'^08\d-\d{3}-\d{4}$' try: # เปิดไฟล์ file = open('/home/aditep/softwares/python/l05_io_FileHandling/io_Exercise/student','r') allStds = file.readlines() for s in allStds: name = s.strip().split(",")[1] tel = s.strip().split(",")[3] try: find = re.match(telRE,tel) print(name, " Valid :", find.group()) except : print(name,"Invalid :",tel) except Exception as e : print("Could not found",e)
3ae2000f2537b5156fe0ea29d52a70bfd89a6deb
yuhsh24/Design-Pattern
/Python/Proxy/Play.py
996
3.75
4
# -*- coding:utf-8 -*- class Play: def Play1(self): pass def Play2(self): pass def Play3(self): pass class Player(Play): def Play1(self): print "战役" def Play2(self): print "军团" def Play3(self): print "神器" class ProxyPlayerVip1(Play): def __init__(self): self.__player = Player() def Play1(self): self.__player.Play1() def Play2(self): self.__player.Play2() def Play3(self): print "没有权限" class ProxyPlayerVip2(Play): def __init__(self): self.__player = Player() def Play1(self): self.__player.Play1() def Play2(self): self.__player.Play2() def Play3(self): self.__player.Play3() if "__main__" == __name__: player1 = ProxyPlayerVip1() player2 = ProxyPlayerVip2() player1.Play1() player1.Play2() player1.Play3() player2.Play1() player2.Play2() player2.Play3()
4481af310834026f36072d4283958c84145c4664
totetmatt/project-euler
/03 - Largest prime factor/main.py
288
3.5
4
number = 600851475143 import math def isPrime(n): for j in range(int(n/2)+1,2,-1): if n % j == 0: return False return True i = int(math.sqrt(number)) while i: if number % i == 0: if isPrime(i): print(i) break i -=1
8d8a81f6a1a75a526b9037ed39036abd856985b7
KshitizS26/computer-vision-programming
/rotation.py
1,382
3.890625
4
import numpy as np import argparse import imutils import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) cv2.waitKey(0) ''' rotating the image around its center OpenCV allows to specify arbitrary point upon which to rotate ''' (h, w) = image.shape[:2] # integer division is used to ensure we receive whole integer numbers center = (w // 2, h //2) ''' defining a matrix to rotate an image by calling getRotationMatrix2D() instead of creating a NumPy array manually center: the point at which we want to rotate theta: the number of degrees to rotate the image scale: 1.0 means the same dimensions of the image are used; a value of 2.0 will double the size of the image; a value of 0.5 will half the image ''' M = cv2.getRotationMatrix2D(center, 45, 1.0) ''' applying rotation image: the image to be rotated M: rotation matrix (w, h): output dimension of the image ''' rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("Rotated by 45 Degrees", rotated) cv2.waitKey(0) M = cv2.getRotationMatrix2D(center, -90, 1.0) rotated = cv2.warpAffine(image, M, (w, h)) cv2.imshow("Rotated by -90 Degrees", rotated) cv2.waitKey(0) rotated = imutils.rotate(image, 180) cv2.imshow("Rotated by 180 Degrees", rotated) cv2.waitKey(0)
948eaf86cb9dfc470f056d4fddc78c6711daee9f
kellyo1/gwcfiles
/Test Folder/listchallenge.py
1,934
4.09375
4
#imports the ability to get a random number from random import * aRandomNumber = randint(0,100) print("This will generate a random number from 0 to 100") print(aRandomNumber) #create the list of wods you want to choose from #this will be a random generator for food (menu) dinnermenu = ["burgers and fries", "pasta", "soup", "rice and sides"] dinnersides = ["side salad", "potato fries", "sweet potato fries", "tortilla chips and sauces"] dessertmenu = ["ice cream", "mochi ice cream", "cake", "nutella crepe"] aRandomNumber = randint(0,len(dinnermenu)-1) print("What are you going to eat for dinner today?") print(dinnermenu[aRandomNumber]) aRandomNumber = randint(0,len(dinnersides)-1) print("What side should go along with that?") print(dinnersides[aRandomNumber]) aRandomNumber = randint(0,len(dessertmenu)-1) print("What dessert are you going to have?") print(dessertmenu[aRandomNumber]) #Generates a random number aList = ["flowers", "cherry", "chamomile", "peach-colored", "blowing", "tearing"] bList = ["begin", "seedling", "flowing", "living", "coffee", "teabag", "latte", "loving", "ending"] cList = ["sun", "bench", "life", "pass", "end", "breeze", "wind", "side", "like", "sing", "out"] print("Let's make a haiku :)") aRandomIndex1 = randint(0, len(aList)-1) aRandomIndex2 = randint(0, len(aList)-1) aRandomIndex3 = randint(0, len(bList)-1) aRandomIndex4 = randint(0, len(bList)-1) aRandomIndex5 = randint(0, len(bList)-1) aRandomIndex6 = randint(0, len(cList)-1) aRandomIndex7 = randint(0, len(cList)-1) aRandomIndex8 = randint(0, len(cList)-1) aRandomIndex9 = randint(0, len(cList)-1) aRandomIndex10 = randint(0, len(cList)-1) print(aList[aRandomIndex1], aList[aRandomIndex2], cList[aRandomIndex6]) print(bList[aRandomIndex3], bList[aRandomIndex4], bList[aRandomIndex5], cList[aRandomIndex6]) print(cList[aRandomIndex6], cList[aRandomIndex7], cList[aRandomIndex8], cList[aRandomIndex9], cList[aRandomIndex10])
37853fc2a44555fdd160ebe39c4cdf5f79f9b7c8
ShitalBorganve/raspberrypi
/projects/image_processing/background_change.py
1,908
3.640625
4
#!/usr/bin/env python ''' This program takes an image and changes the background for a given one. It shows in two windows the original with the background detected and colore d as black and the image with the background changed. The *** USER tag in the comments is to point good places where the user can modify it for his own purpouses. ''' from cv2 import * import cv # Open the webcam cam= VideoCapture(0) # Create two views, one for the original image and another for the image with the background deleted # *** USER: change the names of the windows. namedWindow("Without background", cv.CV_WINDOW_AUTOSIZE) namedWindow("Another background", cv.CV_WINDOW_AUTOSIZE) while True: # grab an image from the camera s, image = cam.read() if s: # *** USER: change name of file imwrite('cam_image.jpg', image) my_image = cv.LoadImage('cam_image.jpg') # Get destiny image # *** USER: change destiny image. destiny = cv.LoadImage("green_wall-wallpaper-320x240.jpg") # iterate over ever pixel in the image by iterating # over each row and each column for x in range(0, my_image.height): for y in range(0, my_image.width): # get the value of the current pixel blue, green, red = my_image[x, y] # check if the intensity is near white # *** USER: change color that will be detected and deleted. if green > 180 and red > 180 and blue > 120: # this pixel is predominantly white let's set it to black # *** USER: change the color that will appear in the removed places. my_image[x, y] = 0, 0, 0 # If it shouldn't be deleted, then copy to the destiny image else: destiny[x,y] = blue,green,red # *** USER: Save destiny image if you desire so cv.SaveImage("Image_background_changed.jpg",destiny) # display the images on the screen cv.ShowImage("Without background", my_image) cv.ShowImage("Another background", destiny) cv.WaitKey(1)
0e6c48c0ee2b28da2014fd9f5ccb21bf1b9f8b96
recooper1066/pythonExercises
/FromBook/Chapter 02/2.4.py
552
4.21875
4
# Exercise 2.4 # Bob Cooper # Exercise 4: Assume that we execute the following assignment statements: width = 17 height = 12.0 # // Floor Division operator - divide and throw away remainder. print(width//2, ' ', type(width//2)) # // Modulus operator - divide and return remainder. # not in exercise, but related to floor division. print(width % 2, ' ', type(width % 2)) print(width/2.0, ' ', type(width/2.0)) print(height/3, ' ', type(height/3)) # print((1 + 2 \* 5), ' ', type(1 + 2 \* 5)) print('Problem with:', '(1 + 2 \* 5), ' ', type(1 + 2 \* 5)')
82eda89e3bc67a9dfbe3ca9e148ca316e6b1e5d1
RJPlog/aoc-2020
/day23/python/asung/solution.py
2,232
3.875
4
#!/usr/bin/env python3 import os from typing import Dict, Iterator, List class Solver: def __init__(self, filepath: str) -> None: with open(filepath, 'r') as text_file: self.cups = [int(label) for label in text_file.read().strip()] @staticmethod def solve(cups: List[int], move_count: int) -> Iterator[int]: # Store the successor cup for each cup. successors = {} # type: Dict[int, int] last_cup = cups[-1] for cup in cups: successors[last_cup] = cup last_cup = cup cup_count = len(cups) # Designate the first cup. current_cup = cups[0] # Do move_count moves. for _ in range(move_count): # Pick up three cups. successor1 = successors[current_cup] successor2 = successors[successor1] successor3 = successors[successor2] successors[current_cup] = successors[successor3] # Select destination cup. destination_cup = (current_cup - 2) % cup_count + 1 while destination_cup in {successor1, successor2, successor3}: # Wrap around. destination_cup = (destination_cup - 2) % cup_count + 1 # Place picked up cups. successors[successor3] = successors[destination_cup] successors[destination_cup] = successor1 # Select new current cup. current_cup = successors[current_cup] # Start after the cup labeled 1. current_cup = 1 # Collect other cups. for _ in range(1, cup_count): current_cup = successors[current_cup] yield current_cup def solve_part1(self) -> int: return int(''.join(str(cup) for cup in self.solve(self.cups, 100))) def solve_part2(self) -> int: cup_count = 1000000 move_count = 10000000 cups = self.cups + list(range(len(self.cups) + 1, cup_count + 1)) results = self.solve(cups, move_count) return next(results) * next(results) if __name__ == "__main__": solver = Solver(os.path.join(os.path.dirname(__file__), "input.txt")) print(solver.solve_part1()) print(solver.solve_part2())
c6529c7e2b78cd6ce44b4dd8aa806d6ea445d722
starmi/python-learning-projects
/Pandas/dataManipulation.py
1,901
3.609375
4
# How to manipulate DataFrames and make transformations # Dataset: https://www.ars.usda.gov/northeast-area/beltsville-md/beltsville-human-nutrition-research-center/nutrient-data-laboratory/docs/sr28-download-files/ import pandas food_info = pandas.read_csv("food_info.csv") #attributes on pandas DataFrame objects: pandas.shape; pandas.columns; pandas.loc[]; pandas.head() #methods: index.tolist() # col_names = food_info.columns.tolist() # print(col_names) # print(food_info.head(3)) ## 2: Transforming a Column # sodium_grams = food_info["Sodium_(mg)"] / 1000 # sugar_milligrams = food_info["Sugar_Tot_(g)"] * 1000 ## 3: Math with multiple columns # grams_of_protein_per_gram_of_water = food_info["Protein_(g)"] / food_info["Water_(g)"] # milligrams_of_calcium_and_iron = food_info["Calcium_(mg)"] + food_info["Iron_(mg)"] ## 4: Nutritional index # score = 2 x (Protein_(g)) - 0.75 x (Lipid_Tot_(g)) # weighted_protein = 2 * food_info["Protein_(g)"] # weighted_fat = -0.75 * food_info["Lipid_Tot_(g)"] # initial_rating = weighted_protein + weighted_fat # print(initial_rating.head(10)) ## 5: Normalizing columns in a Dataset #Series.max() method to get the largest value in the column max_protein = food_info["Protein_(g)"].max() normalized_protein = food_info["Protein_(g)"] / max_protein max_fat = food_info["Lipid_Tot_(g)"].max() normalized_fat = food_info["Lipid_Tot_(g)"] / max_fat ## 6: Creating a new column food_info["Normalized_Protein"] = normalized_protein food_info["Normalized_Fat"] = normalized_fat ## 7: Normalized nutritional index food_info["Norm_Nutr_Index"] = (2 * food_info["Normalized_Protein"]) + (-0.75 * food_info["Normalized_Fat"]) ## 8: Sorting a DataFrame per column. ## http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html food_info.sort_values("Norm_Nutr_Index", ascending = False, inplace = True) print(food_info.head(5))
d2b95ce6c8853c64dc2c70023cd839a41db454cd
freedream520/python_notes
/examples/start/default_arg.py
173
3.703125
4
''' Created on 2013-9-12 @author: Administrator ''' def f(a, L=None): if L == None: L = [] L.append(a) return L print f(1) print f(2) print f(3)
320657bfc81b924c93e0867405297ecfb5cf361c
astroML/astroML
/astroML/stats/_binned_statistic.py
13,324
4.375
4
import numpy as np def binned_statistic(x, values, statistic='mean', bins=10, range=None): """ Compute a binned statistic for a set of data. This is a generalization of a histogram function. A histogram divides the space into bins, and returns the count of the number of points in each bin. This function allows the computation of the sum, mean, median, or other statistic of the values within each bin. Parameters ---------- x : array_like A sequence of values to be binned. values : array_like The values on which the statistic will be computed. This must be the same shape as x. statistic : string or callable, optional The statistic to compute (default is 'mean'). The following statistics are available: * 'mean' : compute the mean of values for points within each bin. Empty bins will be represented by NaN. * 'median' : compute the median of values for points within each bin. Empty bins will be represented by NaN. * 'count' : compute the count of points within each bin. This is identical to an unweighted histogram. `values` array is not referenced. * 'sum' : compute the sum of values for points within each bin. This is identical to a weighted histogram. * function : a user-defined function which takes a 1D array of values, and outputs a single numerical statistic. This function will be called on the values in each bin. Empty bins will be represented by function([]), or NaN if this returns an error. bins : int or sequence of scalars, optional If `bins` is an int, it defines the number of equal-width bins in the given range (10, by default). If `bins` is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths. range : (float, float), optional The lower and upper range of the bins. If not provided, range is simply ``(x.min(), x.max())``. Values outside the range are ignored. Returns ------- statistic : array The values of the selected statistic in each bin. bin_edges : array of dtype float Return the bin edges ``(length(statistic)+1)``. Notes ----- All but the last (righthand-most) bin is half-open. In other words, if `bins` is:: [1, 2, 3, 4] then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which *includes* 4. Examples -------- >>> binned_statistic([1, 2, 1], [2, 5, 3], bins=[0, 1, 2, 3], statistic='count') (array([0., 2., 1.]), array([0., 1., 2., 3.])) See Also -------- np.histogram, binned_statistic_2d, binned_statistic_dd """ try: N = len(bins) except TypeError: N = 1 if N != 1: bins = [np.asarray(bins, float)] medians, edges = binned_statistic_dd([x], values, statistic, bins, range) return medians, edges[0] def binned_statistic_2d(x, y, values, statistic='mean', bins=10, range=None): """ Compute a bidimensional binned statistic for a set of data. This is a generalization of a histogram2d function. A histogram divides the space into bins, and returns the count of the number of points in each bin. This function allows the computation of the sum, mean, median, or other statistic of the values within each bin. Parameters ---------- x : array_like A sequence of values to be binned along the first dimension. y : array_like A sequence of values to be binned along the second dimension. values : array_like The values on which the statistic will be computed. This must be the same shape as x. statistic : string or callable, optional The statistic to compute (default is 'mean'). The following statistics are available: * 'mean' : compute the mean of values for points within each bin. Empty bins will be represented by NaN. * 'median' : compute the median of values for points within each bin. Empty bins will be represented by NaN. * 'count' : compute the count of points within each bin. This is identical to an unweighted histogram. `values` array is not referenced. * 'sum' : compute the sum of values for points within each bin. This is identical to a weighted histogram. * function : a user-defined function which takes a 1D array of values, and outputs a single numerical statistic. This function will be called on the values in each bin. Empty bins will be represented by function([]), or NaN if this returns an error. bins : int or [int, int] or array-like or [array, array], optional The bin specification: * the number of bins for the two dimensions (nx=ny=bins), * the number of bins in each dimension (nx, ny = bins), * the bin edges for the two dimensions (x_edges=y_edges=bins), * the bin edges in each dimension (x_edges, y_edges = bins). range : array_like, shape(2,2), optional The leftmost and rightmost edges of the bins along each dimension (if not specified explicitly in the `bins` parameters): [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be considered outliers and not tallied in the histogram. Returns ------- statistic : ndarray, shape(nx, ny) The values of the selected statistic in each two-dimensional bin xedges : ndarray, shape(nx + 1,) The bin edges along the first dimension. yedges : ndarray, shape(ny + 1,) The bin edges along the second dimension. See Also -------- np.histogram2d, binned_statistic, binned_statistic_dd """ # This code is based on np.histogram2d try: N = len(bins) except TypeError: N = 1 if N != 1 and N != 2: xedges = yedges = np.asarray(bins, float) bins = [xedges, yedges] medians, edges = binned_statistic_dd([x, y], values, statistic, bins, range) return medians, edges[0], edges[1] def binned_statistic_dd(sample, values, statistic='mean', bins=10, range=None): """ Compute a multidimensional binned statistic for a set of data. This is a generalization of a histogramdd function. A histogram divides the space into bins, and returns the count of the number of points in each bin. This function allows the computation of the sum, mean, median, or other statistic of the values within each bin. Parameters ---------- sample : array_like Data to histogram passed as a sequence of D arrays of length N, or as an (N,D) array. values : array_like The values on which the statistic will be computed. This must be the same shape as x. statistic : string or callable, optional The statistic to compute (default is 'mean'). The following statistics are available: * 'mean' : compute the mean of values for points within each bin. Empty bins will be represented by NaN. * 'median' : compute the median of values for points within each bin. Empty bins will be represented by NaN. * 'count' : compute the count of points within each bin. This is identical to an unweighted histogram. `values` array is not referenced. * 'sum' : compute the sum of values for points within each bin. This is identical to a weighted histogram. * function : a user-defined function which takes a 1D array of values, and outputs a single numerical statistic. This function will be called on the values in each bin. Empty bins will be represented by function([]), or NaN if this returns an error. bins : sequence or int, optional The bin specification: * A sequence of arrays describing the bin edges along each dimension. * The number of bins for each dimension (nx, ny, ... =bins) * The number of bins for all dimensions (nx=ny=...=bins). range : sequence, optional A sequence of lower and upper bin edges to be used if the edges are not given explicitely in `bins`. Defaults to the minimum and maximum values along each dimension. Returns ------- statistic : ndarray, shape(nx1, nx2, nx3,...) The values of the selected statistic in each two-dimensional bin edges : list of ndarrays A list of D arrays describing the (nxi + 1) bin edges for each dimension See Also -------- np.histogramdd, binned_statistic, binned_statistic_2d """ if type(statistic) == str: if statistic not in ['mean', 'median', 'count', 'sum']: raise ValueError('unrecognized statistic "%s"' % statistic) elif callable(statistic): pass else: raise ValueError("statistic not understood") # This code is based on np.histogramdd try: # Sample is an ND-array. N, D = sample.shape except (AttributeError, ValueError): # Sample is a sequence of 1D arrays. sample = np.atleast_2d(sample).T N, D = sample.shape nbin = np.empty(D, int) edges = D * [None] dedges = D * [None] try: M = len(bins) if M != D: raise AttributeError('The dimension of bins must be equal ' 'to the dimension of the sample x.') except TypeError: bins = D * [bins] # Select range for each dimension # Used only if number of bins is given. if range is None: smin = np.atleast_1d(np.array(sample.min(0), float)) smax = np.atleast_1d(np.array(sample.max(0), float)) else: smin = np.zeros(D) smax = np.zeros(D) for i in np.arange(D): smin[i], smax[i] = range[i] # Make sure the bins have a finite width. for i in np.arange(len(smin)): if smin[i] == smax[i]: smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 # Create edge arrays for i in np.arange(D): if np.isscalar(bins[i]): nbin[i] = bins[i] + 2 # +2 for outlier bins edges[i] = np.linspace(smin[i], smax[i], nbin[i] - 1) else: edges[i] = np.asarray(bins[i], float) nbin[i] = len(edges[i]) + 1 # +1 for outlier bins dedges[i] = np.diff(edges[i]) nbin = np.asarray(nbin) # Compute the bin number each sample falls into. Ncount = {} for i in np.arange(D): Ncount[i] = np.digitize(sample[:, i], edges[i]) # Using digitize, values that fall on an edge are put in the right bin. # For the rightmost bin, we want values equal to the right # edge to be counted in the last bin, and not as an outlier. for i in np.arange(D): # Rounding precision decimal = int(-np.log10(dedges[i].min())) + 6 # Find which points are on the rightmost edge. on_edge = np.where(np.around(sample[:, i], decimal) == np.around(edges[i][-1], decimal))[0] # Shift these points one bin to the left. Ncount[i][on_edge] -= 1 # Compute the sample indices in the flattened statistic matrix. ni = nbin.argsort() xy = np.zeros(N, int) for i in np.arange(0, D - 1): xy += Ncount[ni[i]] * nbin[ni[i + 1:]].prod() xy += Ncount[ni[-1]] result = np.empty(nbin.prod(), float) if statistic == 'mean': result.fill(np.nan) flatcount = np.bincount(xy, None) flatsum = np.bincount(xy, values) a = np.arange(len(flatcount)) result[a] = flatsum result[a] /= flatcount elif statistic == 'count': result.fill(0) flatcount = np.bincount(xy, None) a = np.arange(len(flatcount)) result[a] = flatcount elif statistic == 'sum': result.fill(0) flatsum = np.bincount(xy, values) a = np.arange(len(flatsum)) result[a] = flatsum elif statistic == 'median': result.fill(np.nan) for i in np.unique(xy): result[i] = np.median(values[xy == i]) elif callable(statistic): try: null = statistic([]) except Exception: null = np.nan result.fill(null) for i in np.unique(xy): result[i] = statistic(values[xy == i]) # Shape into a proper matrix result = result.reshape(np.sort(nbin)) for i in np.arange(nbin.size): j = ni.argsort()[i] result = result.swapaxes(i, j) ni[i], ni[j] = ni[j], ni[i] # Remove outliers (indices 0 and -1 for each dimension). core = D * [slice(1, -1)] result = result[tuple(core)] if (result.shape != nbin - 2).any(): raise RuntimeError('Internal Shape Error') return result, edges
636d2ccf2699b1e2e3f04a394a094d55c0571b2a
Freewin/mclass
/Chapter_2_and_3/mulit_inheritance_depth_first.py
334
3.546875
4
# Example of depth first search presented in class class A(object): def dothis(self): print("Doing this in A") class B(A): pass class C(object): def dothis(self): print("Doing this from C") class D(B, C): pass d_instance = D() d_instance.dothis() # Method Resolution Order print(D.mro())
1bdaf816b75fac3fc43f4d1d40eb0884fe1fd142
DiegoFFreitas7/Teste_IA
/teste_Maximizacao.py
3,575
3.546875
4
from random import randint from algoritmo_Genetico import Individuo, Algoritimo_Genetico ''' PROBLEMA Existe 3 tipos de item para se colocar em uma caixa de capacidade igual a 20Kg A massa, valor e peso de cada item e descrito abaixo Item Quantidade Massa(Kg) Valor(R$) item_A 3 3 40 item_B 2 5 100 item_C 5 2 50 Como se pode colocar os item na caixa de forma a obter o melhor valor? ''' ''' DEFINICAO DA SOLUCAO x1 = quantidade do item_A x2 = quantidade do item_B x3 = quantidade do item_C Funcao objetivo / Desempenho Max_Z = item_A.valor*x1 + item_B.valor*x2 + item_C.valor*x3 Restricoes item_A.massa*x1 + item_B.massa*x2 + item_C.massa*x3 <= 20 item_A.qtde <= 3 item_B.qtde <= 2 item_C.qtde <= 5 item_A.qtde >= 0 item_B.qtde >= 0 item_C.qtde >= 0 ''' # Definicao dos itens do problema class Definicoes: def __init__(self, qtde, massa, valor): self.qtde = qtde self.massa = massa self.valor = valor item_A = Definicoes(3, 3, 40) item_B = Definicoes(2, 5, 100) item_C = Definicoes(5, 2, 50) limite_peso = 20 num_populacao = 10 taxa_mutacao = 10 qtde_genes = 3 # Como sao 3 item, cada gene representa um item min_gene = 0 max_gene = 5 desempenho = lambda genes : item_A.valor*genes[0] + item_B.valor*genes[1] + item_C.valor*genes[2] ''' # ou de forma mais visual def des(genes): soma_dos_valores = item_A.valor*genes[0] + item_B.valor*genes[1] + item_C.valor*genes[2] return soma_dos_valores desempenho = lambda genes : des(genes) ''' restricoes = lambda genes : ((item_A.massa*genes[0] + item_B.massa*genes[1] + item_C.massa*genes[2]) <= limite_peso) and (genes[0] <= item_A.qtde) and (genes[1] <= item_B.qtde) and (genes[2] <= item_C.qtde) and (genes[0] >= 0) and (genes[1] >= 0) and (genes[2] >= 0) ''' # ou de forma mais visual res1 = lambda genes : item_A.massa*genes[0] + item_B.massa*genes[1] + item_C.massa*genes[2]) <= limite_peso res2 = lambda genes : genes[0] <= item_A.qtde res3 = lambda genes : genes[1] <= item_B.qtde res4 = lambda genes : genes[2] <= item_C.qtde res5 = lambda genes : genes[0] >= 0 res6 = lambda genes : genes[1] >= 0 res7 = lambda genes : genes[2] >= 0 def res(gense): if res1 and res2 and res3 and res4 and res5 and res6 and res7: return True else: return False restricoes = lambda genes : res(gense) ''' teste = Algoritimo_Genetico(num_populacao, taxa_mutacao, qtde_genes, min_gene, max_gene, desempenho, restricoes) print('-Populacao inicial---------') for i in teste.populacao: print('Genes: ', i.genes, ' Desempenho: ', i.cal_Desempenho(), ' Kilos: ', (item_A.massa*i.genes[0] + item_B.massa*i.genes[1] + item_C.massa*i.genes[2])) print('Melhor:', teste.melhor.genes, teste.melhor.cal_Desempenho()) print('-Populacao inicial---------') print('') for iteracao in range(100): teste.nova_pop() #print('Melhor_' + str(iteracao) + ': ', 'Genes: ', teste.melhor.genes, ' Desempenho: ', teste.melhor.cal_Desempenho() ) print('-Populacao final-----------') for i in teste.populacao: print('Genes: ', i.genes, ' Desempenho: ', i.cal_Desempenho(), ' Kilos: ', (item_A.massa*i.genes[0] + item_B.massa*i.genes[1] + item_C.massa*i.genes[2])) print('Melhor:', teste.melhor.genes, teste.melhor.cal_Desempenho()) print('-Populacao final-----------') print('')
0c55851543194d3c79a6559a2bcdfbffaf5dc701
DavidMetcalfe/USB-drive-mounted-check
/USB_drive_mounted_check.py
919
3.59375
4
# ------------------------------------ # Loops through available drives and returns # the drive letter if one matches the given # drive name. If none match, return 0. # Ideal for checking if a specific USB # drive is mounted. # # David Metcalfe, January 19, 2020 # ------------------------------------ import win32api def get_drive_by_name(name: str): '''Loop through potential drives on system and return the letter if one matches the provided name.''' drive_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] for i in drive_letters: drive_path = "{}:\\".format(i) # Format drive path so win32api will accept it. try: if win32api.GetVolumeInformation(drive_path)[0] == name: return i except: continue return 0
1f7417c373569e0b62bc56f4a155524b40ae9a5d
vmnchv/PYTHON_ALGORITMS
/Lesson3/DZ3_3.py
293
3.84375
4
#В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. from random import random N = 15 arr = [0]*N for i in range(N): arr[i] = int(random()*100) print(arr[i], end = ' ') print()
0b25194f3dd653e142230ac05a0a3fd21f79889a
LukeBreezy/Python3_Curso_Em_Video
/Aula 14/ex060.py
682
4.1875
4
from math import factorial num = int(input('Digite um número e veja o fatorial: ')) fatorial = factorial(num) print(''' Utilizando módulo factorial() O fatorial de {} é {}'''.format(num, fatorial)) # =========================================== print('=*' * 20) fatorial = num for i in range(num-1, 0, -1): fatorial *= i print(''' Utilizando for(): O fatorial de {} é {}'''.format(num, fatorial)) # =========================================== print('=*' * 20) fatorial = num print('\nUtilizando while:') print('O fatorial de {} é '.format(num), end='') while num > 1: num -= 1 fatorial *= num print(fatorial)
9873594ba403b3dea2f0dd65ddbb289e6c5f5ddb
sedychl2/sr-4-5-6-2
/инд задание в питоне.py
441
4.15625
4
V = 3 A = 1 R = 1 H = 2 if V <= A**3 and V <= 3.14 * R**2 * H: print("Жидкость может заполнить обе ёмкости") elif V <= A**3: print("Жидкость может заполнить первую ёмкость") elif V <= 3.14 * R**2 * H: print("Жидкость может заполнить вторую ёмкость") else: print("Слишком большой объём жидкости")
321a686854f00e2b0dc0c154f028b805362e658b
GGbb2046/ST018
/Exercises/Class03/FutureValueCalc.py
273
3.65625
4
print("Welcome to the calculation of Future Value ") PV= float(input("Please enter the present value ")) R= float(input("Please enter the rate of return in % ")) N= float(input("Please enter the time period ")) FV= PV*(1+(R/100))**N print("The future value", "is ", FV)
a59842935dda5f68d114b28d26fed5a00ccb516e
hackvan/codecademy-examples
/python/bitwise_operator.py
1,638
4.46875
4
print 5 >> 4 # Right Shift print 5 << 1 # Left Shift print 8 & 5 # Bitwise AND print 9 | 4 # Bitwise OR print 12 ^ 42 # Bitwise XOR print ~88 # Bitwise NOT ''' In Python, you can write numbers in binary format by starting the number with 0b. When doing so, the numbers can be operated on like any other number! ''' print 0b1, #1 print 0b10, #2 print 0b11, #3 print 0b100, #4 print 0b101, #5 print 0b110, #6 print 0b111 #7 print "******" print 0b1 + 0b11 print 0b11 * 0b11 one = 0b1 two = 0b10 three = 0b11 four = 0b100 five = 0b101 six = 0b110 seven = 0b111 eight = 0b1000 nine = 0b1001 ten = 0b1010 eleven = 0b1011 twelve = 0b1100 # The bin() function ''' You can also represent numbers in base 8 and base 16 using the oct() and hex() functions. ''' print bin(1) for i in range(2, 6): print bin(i) ''' int()'s Second Parameter When given a string containing a number and the base that number is in, the function will return the value of that number converted to base ten. ''' print int("1",2) print int("10",2) print int("111",2) print int("0b100",2) print int(bin(5),2) # Print out the decimal equivalent of the binary 11001001. print int("11001001", 2) # Slide to the left slide to the right shift_right = 0b1100 shift_left = 0b1 # Your code here! shift_right = shift_right >> 2 shift_left = shift_left << 2 print bin(shift_right) print bin(shift_left) print bin(0b1110 & 0b101) print bin(0b1110 | 0b101) print bin(0b1110 ^ 0b101) # Check bit 4: def check_bit4(bin_number): mask = 0b1000 desired = bin_number & mask if (desired > 0): return "on" else: return "off"
6d4289059dd03ecf766f0020d0b72b863761b04a
hiitiger/cobackup
/py/object.py
511
3.546875
4
class WTF(object): def __init__(self): print("I ") def __del__(self): print("D ") print(WTF() is WTF()) print(id(WTF()) == id(WTF())) l = [1, 2, 3] g = (x for x in l if l.count(x) > 0) l = [1] print(list(g)) array_1 = [1,2,3,4] g1 = (x for x in array_1) l1 = [x for x in array_1] array_1 = [1,2,3,4,5] print(list(g1)) array_2 = [1,2,3,4] g2 = (x for x in array_2) l2 = [x for x in array_2] array_2[:] = [1,2,3,4,5] print(list(g2)) print(list(l2))
9b0bbc5aa8c4ce11df81e3107001bea30c4fc83a
dstch/my_leetcode
/Breadth-first Search/Perfect Squares.py
1,896
3.78125
4
#!/usr/bin/env python # encoding: utf-8 """ @author: dstch @license: (C) Copyright 2013-2019, Regulus Tech. @contact: dstch@163.com @file: Perfect Squares.py @time: 2019/9/19 15:25 @desc: Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. """ class Solution(object): def numSquares(self, n): """ :type n: int :rtype: int """ q = [[n, 0]] visited = [False for _ in range(n + 1)] while any(q): i = 1 num, step = q.pop(0) tnum = num - i ** 2 while tnum >= 0: if tnum == 0: return step + 1 if visited[tnum] == False: visited[tnum] = True q.append([tnum, step + 1]) i += 1 tnum = num - i ** 2 # Lagrange 四平方定理: 任何一个正整数都可以表示成不超过四个整数的平方之和。 # 也就是说,这个题目返回的答案只有1、2、3、4这四种可能。 我们可以将输入的数字除以4来大大减少计算量,并不改变答案 # 一个数除以8的余数,如果余数为7, 则其必然由四个完全平方数组成 # 然后检测是否可以将简化后的数拆分为两个完全平方数,否则一定由三个完全平方数组成。 import math while n % 4 == 0: n = n // 4 if n % 8 == 7: return 4 if int(math.sqrt(n)) ** 2 == n: return 1 i = 1 while i * i <= n: j = math.sqrt(n - i * i) if int(j) == j: return 2 i += 1 return 3 if __name__ == '__main__': s = Solution() s.numSquares(12)