blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
e38e2d771340ac0843aef8cb25dd0b6fa960755b
pascee/physics_learning_app
/velocity/calculations.py
1,239
3.71875
4
from sympy import * x = Symbol('x') #takes in an equation for displacement as a string and derives it to find velocity def differentiate(your_equation): your_equation = your_equation.replace("^", "**") f_prime = diff(your_equation) f_prime = str(f_prime) if "x" not in f_prime: f_prime = 'y=' + f_prime f_prime = f_prime.replace("**", "^") return f_prime #takes in an equation for displacement as a string and double derives it to find acceleration def doubleDifferentiate(your_equation): your_equation = your_equation.replace("^", "**") f_double_prime = diff(your_equation, x, x) f_double_prime = str(f_double_prime) if "x" not in f_double_prime: f_double_prime = 'y=' + f_double_prime f_double_prime = f_double_prime.replace("**", "^") return f_double_prime def integ(your_equation): your_equation = your_equation.replace("^", "**") integral = integrate(your_equation, x) integral = str(integral) if "x" not in integral: integral = 'y=' + integral integral = integral.replace("**", "^") return integral def doubleInteg(your_equation): integral = integ(your_equation) double_integral = integ(integral) return double_integral
025e4b39d4981efa90b2414fa3a5e59276d83012
crunchypi/Sudoku-Solver
/sudoku_helper_GUI.py
8,717
3.765625
4
import tkinter as tk from tkinter.ttk import Separator, Style import sudoku_tools class GUIInterface(): """ A GUI interface for a Sudoku solver. Requires: - Tkinter. - Sudoku loader and solver. Has two main views/frames: - Top for loading a Sudoku board. - Bottom for displaying a Sudoku grid. """ __sudoku = None __window = None __frame_top = None __frame_grid = None __path_entry = None __subgrid_row_entry = None __subgrid_column_entry = None __grid_var = None __grid_box = None def __init__(self): """ Setup for a Sudoku module and TKinter grids. Initiates a Tkinter main loop. """ self.__sudoku = sudoku_tools.Sudoku() self.__window = tk.Tk() self.__window.title("Sudoku Solver") self.__frame_top = tk.Frame(self.__window, borderwidth=0, relief="solid") self.__frame_top.pack() self.__frame_grid = tk.Frame(self.__window, borderwidth=0, relief="solid") self.__frame_grid.pack() self.__setup_top_interface() self.__window.mainloop() def __setup_top_interface(self): """ Fills the top frame with labels, input fiels and buttons necessary for loading a Sudoku board. """ const_width = 20 const_text_size = 10 # // For path. path_label = tk.Label(self.__frame_top, text="Path to CSV") path_label.config(font=("Courier", const_text_size)) path_label.config(width=const_width) path_label.grid(row=0, column=0) path_entry = tk.Entry(self.__frame_top, width=const_width) path_entry.grid(row=1,column=0) self.__path_entry = path_entry # // For subgrid row specification. subgrid_row_label = tk.Label(self.__frame_top, text="Subgrid row count") subgrid_row_label.config(font=("Courier", const_text_size)) subgrid_row_label.config(width=const_width) subgrid_row_label.grid(row=0, column=1) subgrid_row_entry = tk.Entry(self.__frame_top, width=const_width) subgrid_row_entry.grid(row=1,column=1) self.__subgrid_row_entry = subgrid_row_entry # // For subgrid column specification. subgrid_column_label = tk.Label(self.__frame_top, text="Subgrid column count") subgrid_column_label.config(font=("Courier", const_text_size)) subgrid_column_label.config(width=const_width) subgrid_column_label.grid(row=0, column=2) subgrid_column_entry = tk.Entry(self.__frame_top, width=const_width) subgrid_column_entry.grid(row=1,column=2) self.__subgrid_column_entry = subgrid_column_entry # // Submit button. path_btn = tk.Button(self.__frame_top, text="Load") path_btn.config(highlightbackground="#000000") path_btn.config(font=("Courier", const_text_size)) path_btn.config(width=int(const_width/3)) path_btn.config(command=self.__load_board) path_btn.grid(row=1, column=5) path_btn.update() def __load_board(self): """ Uses input data from top fram to load a Sudoku game. Sudoku game solver is called from here (GUI grid creation is called on success). """ # // Value access. path: str = self.__path_entry.get() subgrid_rows: str = self.__subgrid_row_entry.get() subgrid_cols: str = self.__subgrid_column_entry.get() safe_pass = True # // Error logic. if subgrid_rows.isdigit(): subgrid_rows = int(subgrid_rows) else: self.__subgrid_row_entry.delete(0, tk.END) self.__subgrid_row_entry.insert(0,"Invalid") safe_pass = False if subgrid_cols.isdigit(): subgrid_cols = int(subgrid_cols) else: self.__subgrid_column_entry.delete(0, tk.END) self.__subgrid_column_entry.insert(0,"Invalid") safe_pass = False # // Board creation. if safe_pass: loaded: bool = self.__sudoku.load_board_csv(path, subgrid_rows, subgrid_cols) if loaded: solved: bool = self.__sudoku.backtrack() if solved: self.__frame_grid.destroy() self.__frame_grid = tk.Frame(self.__window, borderwidth=0, relief="solid") self.__frame_grid.pack() self.__setup_grid() self.__setup_separators() else: self.__path_entry.delete(0, tk.END) self.__path_entry.insert(0,"Unsolvable") else: self.__path_entry.delete(0, tk.END) self.__path_entry.insert(0,"Loading failure") def __on_cell_input(self, cell_id: str, unused_1: str, unused_2: str): """ Callback for tracked cells in the GUI grid. Compares GUI cell values against pre-solved Sudoku grid values and does appropriate colorisation of GUI cells. """ # // Value access. coord: list = self.__get_coord_from_var(cell_id) box: tkinter.Entry = self.__grid_box[coord[0]][coord[1]] game_board: list = self.__sudoku.get_board() game_board_result: int = game_board[coord[0]][coord[1]] user_input: str = self.__grid_var[coord[0]][coord[1]].get() # // Colorisation logic. bg = "red" if user_input == "": bg = "white" if user_input.isdigit(): user_input = int(user_input) if user_input == game_board_result: bg = "green" box.config(bg=bg) def __get_coord_from_var(self, cell_id: str): """ Finds the coordinate (in a matrix) where a Tkinter cell is cached, based on tags. """ for i in range(len(self.__grid_var)): for j in range(len(self.__grid_var)): if str(self.__grid_var[i][j]) == str(cell_id): # // Compare tags. return [i,j] def __setup_grid(self): """ Duplicates a Sudoku game-board onto a GUI grid. Cells consist of Tkinter values (StringVar) and entries (Entry). Cells are stored in a matrix for later retrieval (to check if a user enters a correct value, according to a pre-solved Sudoku board). """ board: list = self.__sudoku.get_board() grid_var = [] grid_box = [] temp_var = [] temp_box = [] for i in range(len(board)): for j in range(len(board)): new_var = tk.StringVar() new_box = tk.Entry(self.__frame_grid, textvariable=new_var, width=4) new_box.grid(row=i,column=j) if [i,j] in self.__sudoku.get_protected_coordinates(): new_var.set(board[i][j]) new_box.config(bg="gray") new_box.config(state="disabled") else: new_var.set("") new_var.trace("w", self.__on_cell_input) temp_var.append(new_var) temp_box.append(new_box) grid_var.append(temp_var.copy()) grid_box.append(temp_box.copy()) temp_var.clear() temp_box.clear() self.__grid_var: list = grid_var self.__grid_box: list = grid_box def __setup_separators(self): """ Draws separator lines to visualise subgrids """ self.__frame_grid.update() # // Value access. height: int = self.__frame_grid.winfo_height() width: int = self.__frame_grid.winfo_width() row_count: int = self.__frame_grid.size()[0] # // Draw subgrid. for x in range(row_count): if x % self.__sudoku.get_subgrid_row_count() == 0: line = tk.ttk.Separator(self.__frame_grid, orient=tk.HORIZONTAL) line.place(width=width, height=1, x=0, y=height / row_count * x ) if x % self.__sudoku.get_subgrid_column_count( )== 0: line = line = tk.ttk.Separator(self.__frame_grid, orient=tk.VERTICAL) line.place(width=1, height=height, x=width / row_count * x , y=0 ) # // Finishing edges. line = tk.ttk.Separator(self.__frame_grid, orient=tk.HORIZONTAL) line.place(width=width, height=1, x=0, y=height - 1 ) line = line = tk.ttk.Separator(self.__frame_grid, orient=tk.VERTICAL) line.place(width=1, height=height, x=width - 1 , y=0 ) start = GUIInterface()
cb77261c3c3db53f0a7067e749f1b10a06fbeb63
DandyCV/SoftServeITAcademy
/L07/L07_HW1_4.py
306
4.0625
4
def season(month): """Returns - string (season of year). Argument - integer from 1 to 12 (number of month).""" if 0 < month < 3 or month == 12: return "Winter" if 2 < month < 6: return "Spring" if 5 < month < 9: return "Summer" if 8 < month < 12: return "Autumn" print(season(7))
3a6fa89d2f42f9b264fc509e02c13c8222e8d76c
DandyCV/SoftServeITAcademy
/L07/L07_HW1_3.py
321
4.15625
4
def square(size): """Function returns tuple with float {[perimeter], [area], [diagonal]} Argument - integer/float (side of square)""" perimeter = 4 * size area = size ** 2 diagonal = round((2 * area) ** 0.5, 2) square_tuple = (perimeter, area, diagonal) return square_tuple print(square(3))
97d0ccc3d5c0bd1f9d84c1201695309d49c09fb9
DandyCV/SoftServeITAcademy
/L07/L07_HW1_1.py
473
4.5
4
def arithmetic(value_1, value_2, operation): """Function makes mathematical operations with 2 numbers. First and second arguments - int/float numbers Third argument - string operator(+, -, *, /)""" if operation == "+": return value_1 + value_2 if operation == "-": return value_1 - value_2 if operation == "*": return value_1 * value_2 if operation == "/": return value_1 / value_2 return "Unknown operation" print(arithmetic(12, 3, "*"))
80c45c7f70d8f318b41146d4d8ec521cff44b331
DandyCV/SoftServeITAcademy
/L08/L08_HW2_4.py
1,302
3.578125
4
#Задано символьний рядок,. Розробити програму, яка знаходить групи цифр, записаних підряд, і вилучає із них всі # початкові нулі, крім останнього, якщо за ним знаходиться крапка. Друкує модифікований масив по сорок символів у рядку. from random import randint random_string = "000.001jh000.550opk00023.000dfe70000.0001" for symbol in range(160): random_string += (chr(randint(46, 64))) random_string += "ip001k0101.k001" print("Random string:", random_string) edited_list = [] random_list = list(random_string) prev_elem = " " for i in random_string: if random_list[0] == "0" and prev_elem not in ".0123456789" and len(random_list) == 1: random_list.pop(0) elif random_list[0] == "0" and prev_elem not in ".0123456789" and random_list[1] != ".": random_list.pop(0) else: prev_elem = random_list.pop(0) edited_list.append(prev_elem) edited_string = "".join(edited_list) strings = len(edited_string) / 40 if strings % 1: strings += 1 strings = int(strings) print("Edited string:") for line in range(strings): print(edited_string[line * 40:(line + 1) * 40])
cf22428c9b7c74168b938c045c472490fcdd777e
DandyCV/SoftServeITAcademy
/L06/L06_HW1_8.py
394
3.640625
4
from random import randint random_list = [] for number in range(10): random_list.append(randint(-100, 100)) print("Random list 1:", random_list) index_max = random_list.index(max(random_list)) index_min = random_list.index(min(random_list)) temp = random_list[index_min] random_list[index_min] = random_list[index_max] random_list[index_max] = temp print("Random list 2:", random_list)
5a3e85770875b03396a7a0f19fcd53dfdab290df
devangi2000/HacktoberFest2020-1
/Interview Based/Anagram.py
1,315
4.09375
4
""" Given two strings a and b consisting of lowercase characters. The task is to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “act” and “tac” are anagram of each other. Input: The first line of input contains an integer T denoting the number of test cases. Each test case consist of two strings in 'lowercase' only, in a single line. Output: Print "YES" without quotes if the two strings are anagram else print "NO". Constraints: 1 ≤ T ≤ 300 1 ≤ |s| ≤ 106 Example: Input: 2 geeksforgeeks forgeeksgeeks allergy allergic Output: YES NO Explanation: Testcase 1: Both the string have same characters with same frequency. So, both are anagrams. Testcase 2: Characters in both the strings are not same, so they are not anagrams. """ # T = int(input()) def Anogram_check(string1, string2): # Strings are sorted and verified if(sorted(string1) == sorted(string2)): print("Both strings form a Anogram.") else: print("Both strings do not form as a Anogram.") # driver code string1 ="EARTH" string2 ="HEART" print( "String value1 : ", string1 ) print( "String value2 : ", string2 ) Anogram_check(string1, string2)
4aea4fa53d3b15c6535d109b58eaa36840778e95
devangi2000/HacktoberFest2020-1
/Interview Based/Longest Palindrome in a String.py
805
3.984375
4
""" Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of conflict, return the substring which occurs first ( with the least starting index ). NOTE: Required Time Complexity O(n2). Input: The first line of input consists number of the testcases. The following T lines consist of a string each. Output: In each separate line print the longest palindrome of the string given in the respective test case. Constraints: 1 ≤ T ≤ 100 1 ≤ Str Length ≤ 104 Example: Input: 1 aaaabbaa Output: aabbaa Explanation: Testcase 1: The longest palindrome string present in the given string is "aabbaa". """
c5c25d3d8be7abf375018cdfa1e6a75ac48438e1
devangi2000/HacktoberFest2020-1
/Interview Based/Missing number in array.py
763
3.796875
4
""" Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found. Input: The first line of input contains an integer T denoting the number of test cases. For each test case first line contains N(size of array). The subsequent line contains N-1 array elements. Output: Print the missing number in array. Constraints: 1 ≤ T ≤ 200 1 ≤ N ≤ 107 1 ≤ C[i] ≤ 107 Example: Input: 2 5 1 2 3 5 10 1 2 3 4 5 6 7 8 10 Output: 4 9 Explanation: Testcase 1: Given array : 1 2 3 5. Missing element is 4. """ N = int(input()) lst = [int(item) for item in input().split()] for i in range(0,N-2): if lst[i+1]-lst[i] == 1: count = lst[i+1] print(count+1)
3de63dc10bf4adab4fca2f8da4704652a2e1a3cf
jasonjiang001/LeetCode
/1TwoSum.py
780
3.734375
4
""" 1.两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] """ def getTowSum(nums, target): sum = [] for i in range(len(nums)): for j in range(len(nums)-1, -1, -1): if i >= j: continue if nums[i] + nums[j] == target: sum.append([i, j]) return sum print(getTowSum([1, 5, 7, 3, 2, 3, 4, -1], 6)) """ 返回结果: [[0, 1], [2, 7], [3, 5], [4, 6]] """
aa33cf7e6eca200e41c461c00a48a7f3bafde728
aaherrera3/Lab-3-
/Binary_Tree.py
3,838
4.09375
4
# Code to implement a binary search tree # Programmed by Olac Fuentes # Last modified February 27, 2019 class BST(object): # Constructor def __init__(self, item, left=None, right=None): self.item = item self.left = left self.right = right def Insert(T, newItem): if T == None: T = BST(newItem) elif T.item > newItem: T.left = Insert(T.left, newItem) else: T.right = Insert(T.right, newItem) return T def Delete(T, del_item): if T is not None: if del_item < T.item: T.left = Delete(T.left, del_item) elif del_item > T.item: T.right = Delete(T.right, del_item) else: # del_item == T.item if T.left is None and T.right is None: # T is a leaf, just remove it T = None elif T.left is None: # T has one child, replace it by existing child T = T.right elif T.right is None: T = T.left else: # T has two chldren. Replace T by its successor, delete successor m = Smallest(T.right) T.item = m.item T.right = Delete(T.right, m.item) return T def InOrder(T): # Prints items in BST in ascending order if T is not None: InOrder(T.left) print(T.item, end=' ') InOrder(T.right) def InOrderD(T, space): # Prints items and structure of BST if T is not None: InOrderD(T.right, space + ' ') print(space, T.item) InOrderD(T.left, space + ' ') def SmallestL(T): # Returns smallest item in BST. Returns None if T is None if T is None: return None while T.left is not None: T = T.left return T def Smallest(T): # Returns smallest item in BST. Error if T is None if T.left is None: return T else: return Smallest(T.left) def Largest(T): if T.right is None: return T else: return Largest(T.right) def Find(T, k): # Returns the address of k in BST, or None if k is not in the tree if T is None or T.item == k: return T if T.item < k: return Find(T.right, k) return Find(T.left, k) def FindAndPrint(T, k): f = Find(T, k) if f is not None: print(f.item, 'found') else: print(k, 'not found') def PrintDepth(T,k): if T is None: return if k == 0: print(T.item) else: PrintDepth(T.left,k-1) PrintDepth(T.right,k-1) def Search(T,t): temp = T while temp != None and t != temp.item: if t < temp.item: temp = temp.left if t > temp.item: temp = temp.right if temp == None: return None return temp.item def BinaryTreeToSortedList(T,L): if T is not None: BinaryTreeToSortedList(T.left,L) L.append(T.item) BinaryTreeToSortedList(T.right,L) return L def SortedListToBinaryTree(L): if not L: return None mid = (len(L))//2 root = BST(L[mid]) root.left = (SortedListToBinaryTree(L[:mid])) root.right = SortedListToBinaryTree(L[mid+1:]) return root # Code to test the functions above T = None A = [70, 50, 90, 130, 150, 40, 10, 30, 100, 180, 45, 60, 140, 42] for a in A: T = Insert(T, a) print('Number 5') InOrderD(T,'') print('###################################') for x in range(5): print('Depth at ', x) PrintDepth(T,x) print('Number 2') print(Search(T,140)) print('Number 4') L = [] L = BinaryTreeToSortedList(T,L) print(L) print('Number 3') L = [1,2,3,4,5,6,7] T = SortedListToBinaryTree(L) InOrderD(T,'')
8a05ce56e01f8c822283574871f22ec5ea5fe1dc
chengyaojun/FindDuplicateFile
/find_duplicate_file.py
1,498
3.8125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- """ find duplicate file """ import os from collections import Counter import sys def get_all_files(abspath): """ @abspath: get all files from path of 'abspath' @return: get list of all files """ all_files = [] for _, _, files in os.walk(abspath): for file in files: all_files.append(file) return all_files def find_duplicate_file(abspath): """ @path: Direct path """ __all_files__ = dict(Counter(get_all_files(abspath))) for key in __all_files__: if __all_files__[key] > 1: file_abspaths = find_file_abspath(abspath, key) print('Duplicate times:\t'+ str(__all_files__[key])) print("Duplicate file name:\t" + key) print("Duplicate file path:") for file_abspath in file_abspaths: print(" " + file_abspath) print('\n') print("-" * 100) def find_file_abspath(direct_path, direct_file): """find_file_abspath""" result = [] for dirpath, _, allfiles in os.walk(direct_path): separator = "" if dirpath[len(dirpath) - 1] == "/" else "/" for file in allfiles: if file == direct_file: result.append(dirpath + separator + file) return result # get path from command __relpath__ = os.getcwd() if len(sys.argv) > 1: __relpath__ = sys.argv[1] __abspath__ = os.path.abspath(__relpath__) find_duplicate_file(__abspath__)
9fe71b923d902d03dab882fe161d38d3bd122d81
albornoz440/trabajo-informatica
/programacion 2/punto 3.py
117
3.828125
4
name = input("¿Cómo te llamas?: ") num = input("Introduce un número entero: ") print((name + "\n") * int(num))
97a4605437a98334fb3b356944b504f2ca457588
natemago/advent-of-code-2019
/day-2-program-alarm/solution.py
1,331
3.5625
4
def exec(program): pc = 0 while True: if pc < 0 or pc >= len(program): print('PC outside range') break instr = program[pc] if instr == 99: print('Normal HALT') break a = program[pc + 1] b = program[pc + 2] dest = program[pc + 3] if instr == 1: program[dest] = program[a] + program[b] elif instr == 2: program[dest] = program[a] * program[b] else: raise Exception('Invalid instruction ', instr, ' at postition: ', pc) pc += 4 def load_prog(inpf): with open(inpf) as f: return [int(p.strip()) for p in f.read().strip().split(',')] def test_exec(prg): exec(prg) print(prg) def part1(): program = load_prog('input') program[1] = 12 program[2] = 2 exec(program) return program[0] def part2(): program = load_prog('input') for noun in range(0, 100): for verb in range(0, 100): p = [k for k in program] p[1] = noun p[2] = verb exec(p) if p[0] == 19690720: return noun * 100 + verb raise Exception('None found?') #test_exec([1,9,10,3,2,3,11,0,99,30,40,50]) print('Part 1: ', part1()) print('Part 2: ', part2())
bc23a915700dd7c8f593f9e27e17035e59987e7b
Percy-Cucumber/IND3156
/homework_7/parabola.py
314
3.5625
4
#import import random #code random.seed(42) total=1000000*1000 out = 0 for i in range(total): x = random.random() y = random.random() if ((-x)*x) + x > 1: out = out + 1 #print print( 4.0*(1.0-float(out)/float(total))) #referenced https://pythonprogramming.net/monte-carlo-simulator-python/
b7f773a51b49ad7512c4dee4a860c49d2e600ba7
ramalho/modernoopy
/examples/tombola/ibingo.py
814
4.34375
4
""" Class ``IBingo`` is an iterable that yields items at random from a collection of items, like to a bingo cage. To create an ``IBingo`` instance, provide an iterable with the items:: >>> balls = set(range(3)) >>> cage = IBingo(balls) The instance is iterable:: >>> results = [item for item in cage] >>> sorted(results) [0, 1, 2] Iterating over an instance does not change the instance. Each iterator has its own copy of the items. If ``IBingo`` instances were changed on iteration, the value of this expression would be 0 (zero):: >>> len([item for item in cage]) 3 """ import bingo class IBingo(bingo.Bingo): def __iter__(self): """return generator to yield items one by one""" items = self._items[:] while items: yield items.pop()
d77391b2a500f484e0438d722b683f76077610e5
ramalho/modernoopy
/examples/countries/countries.py
287
3.859375
4
import dataclasses @dataclasses.dataclass class Country: """Represents a country with some metadata""" name: str population: float area: float def density(self) -> float: """population density in persons/km²""" return self.population / self.area
3a8597f3280a8a10dff9731e090596fc79e0b67c
SLongofono/Python-Misc
/multiprocessing/multiprocessing_pools.py
2,446
3.640625
4
""" This demonstrates the use of asynchronous pools of workers using the multiprocessing module. Due to some unfortunate choices on the back end, anonymous functions and closures will not work. Similar constraints apply to the pool.map() construct. Things like logging and shared queues are built in to the module, but trying to use decorators for timing or tracking is out. Here, I hack together a workaround to time and track the PID for some simple worker processes. Another note of interest is that multiprocessing may create a new process, or not. Per the documentation, we can't assume a unique process for each. """ import multiprocessing import time import os # Costly function for each process to compute def dowork(num): if num < 0: raise if num <= 1: return 1 return dowork(num-1) + dowork(num-2) # Multiprocessing uses pickling to pass around functions, which # presents a problem: the built-in pickle module will not support # anonymous functions (lambda f) or closures (functions bound at # runtime using decorators or other attributes). To get extra # functionality, we need to nest a series of functions which # do not depend on out of context values def pidwrapper(num): print("Process {} starting".format(os.getpid())) result = dowork(num) print("Process {} ending".format(os.getpid())) return result if __name__ == "__main__": # Sequential list for generating fibbonacci sequence myList = range(30) # Generates a pool of 30 workers myPool = multiprocessing.Pool(processes=30) # sets up and automatically starts a worker for each number #output = pool.map(dowork, myList) # sets up an automatically starts a worker for each number, returning results # as they arrive results = [myPool.apply_async(pidwrapper, (num,)) for num in myList] # The get will raise an exception if the result is not ready. We can use # this to check it and move on if the result is not ready. done = False visited = [0 for x in myList] finalList = [0 for x in myList] start = time.time() while not done: try: for i in range(len(visited)): if not visited[i]: print("Fibonacci number: {}\n\tfinished in: {} seconds\n\tResult: {}".format(i, time.time()-start, results[i].get(timeout=1))) visited[i] = 1 finalList[i] = results[i].get() done = True except multiprocessing.TimeoutError: pass # The result is still being computed, move on to something else. print(finalList)
53bd12eb151b9514575a8958560352ddb44bd941
SLongofono/Python-Misc
/python2/properties.py
1,250
4.125
4
""" This demonstrates the use of object properties as a way to give the illusion of private members and getters/setters per object oriented programming. Variables prefixed by underscore are a signal to other programmers that they should be changing them directly, but there really isn't any enforcement. There are still ways around it, but this makes it harder to change members that shouldn't change. """ class myThing(object): def __init__(self, foo=None): self._foo = foo # This decorator acts as a getter, accessed with "myFoo.foo" @property def foo(self): return self._foo # This decorator acts as a setter, but only once @foo.setter def foo(self, newFoo): if self._foo is None: self._foo = newFoo else: raise Exception("Immutable member foo has already been assigned...") # This decorator protects against inadvertent deletion via "del myFoo.foo" @foo.deleter def foo(self): raise Exception("Cannot remove immutable member foo") if __name__ == "__main__": myFoo = myThing() print(myFoo.foo) myFoo.foo = "bar" print(myFoo.foo) try: myFoo.foo = "baz" except Exception as e: print(e) print(myFoo.foo) try: del myFoo.foo except Exception as e: print(e)
ab4a89539958603ec6a8b0586b1218ca6602b60c
marcimarc1/Pydoku
/Interface/classes.py
3,525
3.6875
4
import pygame import time pygame.font.init() class Sudoku: def __init__(self, board, width, height): self.board = board self.rows = 9 self.cols = 9 self.cubes = [[Cube(self.board[i][j], width, height) for j in range(self.cols)] for i in range(self.rows)] self.width = width self.height = height self.model = None self.selected = None def update_model(self): self.model = [[self.cubes[i][j].value for j in range(self.cols)] for i in range(self.rows)] def place(self, val): row, col = self.selected if self.cubes[row][col].value == 0: self.cubes[row][col].set(val) self.update_model() if valid(self.model, val, (row, col)) and solve(self.model): return True else: self.cubes[row][col].set(0) self.cubes[row][col].set_temp(0) self.update_model() return False def sketch(self, val): row, col = self.selected self.cubes[row][col].set_temp(val) def draw(self, win): # Draw Grid Lines gap = self.width / 9 for i in range(self.rows + 1): if i % 3 == 0 and i != 0: thick = 4 else: thick = 1 pygame.draw.line(win, (0, 0, 0), (0, i * gap), (self.width, i * gap), thick) pygame.draw.line(win, (0, 0, 0), (i * gap, 0), (i * gap, self.height), thick) # Draw Cubes for i in range(self.rows): for j in range(self.cols): self.cubes[i][j].draw(win) def select(self, row, col): # Reset all other for i in range(self.rows): for j in range(self.cols): self.cubes[i][j].selected = False self.cubes[row][col].selected = True self.selected = (row, col) def clear(self): row, col = self.selected if self.cubes[row][col].value == 0: self.cubes[row][col].set_temp(0) def click(self, pos): """ :param: pos :return: (row, col) """ if pos[0] < self.width and pos[1] < self.height: gap = self.width / 9 x = pos[0] // gap y = pos[1] // gap return (int(y), int(x)) else: return None def is_finished(self): for i in range(self.rows): for j in range(self.cols): if self.cubes[i][j].value == 0: return False return True class Cube: def __init__(self,value, width, height): self.value = value self.temp = 0 self.row = 9 self.col = 9 self.width = width self.height = height self.selected = False def draw(self, win): fnt = pygame.font.SysFont("ubuntu", 40) gap = self.width / 9 x = self.col * gap y = self.row * gap if self.temp != 0 and self.value == 0: text = fnt.render(str(self.temp), 1, (128, 128, 128)) win.blit(text, (x + 5, y + 5)) elif not (self.value == 0): text = fnt.render(str(self.value), 1, (0, 0, 0)) win.blit(text, (x + (gap / 2 - text.get_width() / 2), y + (gap / 2 - text.get_height() / 2))) if self.selected: pygame.draw.rect(win, (255, 0, 0), (x, y, gap, gap), 3) def set(self, val): self.value = val def set_temp(self, val): self.temp = val
3aa2076bc76d17d5cb2c903e5089f9dc6c913a13
acemourya/D_S
/C_1/Chatper-01 DataScience Modules-stats-Example/Module-numpy-example.py
1,100
4.15625
4
#numpy: numerical python which provides function to manage multiple dimenssion array #array : collection of similar type data or values import numpy as np #create array from given range x = np.arange(1,10) print(x) y = x*2 print(y) #show data type print(type(x)) print(type(y)) #convert list to array d = [11,22,4,45,3,3,555,44] n = np.array(d) print(n) print(type(n)) print(n*2) ##change data type n = np.array(d,dtype=float) print(n) #show shpae print(n.shape) #change demenssion n = np.array(d).reshape(-1,2) #read from 1st element , 2 two dimenssion print(n) d = [11,22,4,45,3,3,555,44,3] n = np.array(d).reshape(-1,3) #read from 1st element , 3 dimenssion print(n) #generate the array of zeors print(np.zeros(10)) #generate the array of ones print(np.ones(10)) #matrix or two dimession array and operation x = [[1,2,3],[5,6,7],[66,77,88]] #list y = [[11,20,3],[15,26,70],[166,707,88]] #list #convert to array x = np.array(x) y = np.array(y) print(x) print(y) #addition print(np.add(x,y)) print(np.subtract(x,y)) print(np.divide(x,y)) print(np.multiply(x,y))
803761ecc916ed783192a842385ff34d1fffce5c
vibhor-vibhav-au6/CVRaman-solutions
/week04/day03.py
1,153
4.09375
4
# Q1. # Write a Python program to round the numbers of a given list, print the minimum # and maximum numbers and multiply the numbers by 5. Print the unique numbers # in ascending order separated by space. # Original list: [22.4, 4.0, 16.22, 9.1, 11.0, 12.22, 14.2, 5.2, 17.5] # Minimum value: 4 # Maximum value: 22 # Result: # 20 25 45 55 60 70 80 90 110 def multiTasks(array): array.sort() temp = list(map(round, array)) print ('max is: '+ str(max(temp)) + '\n' + 'min is: '+ str(min(temp))) # def f(a): # return a*5 # this is equivalant to the lambda function below return(list(map(lambda a : a*5,temp))) # driver l = [22.4, 4.0, 16.22, 9.1, 11.0, 12.22, 14.2, 5.2, 17.5] print(multiTasks(l)) # Q2. Write a Python program to create a list by concatenating a given list which # range goes from 1 to n. # Sample list : ['p', 'q'] # n =5 # Sample Output : ['p1', 'q1', 'p2', 'q2', 'p3', 'q3', 'p4', 'q4', 'p5', 'q5' def concatList(n, string): # return [c+str(i) for i in range(1,n+1) for c in string] # or return ['{}{}'.format(i, j) for j in range(1, n+1) for i in string] # driver n = 5 s = ['p', 'q'] print(concatList(n,s))
bfa28ab12a8a5da15f46ea7daf625b9d26d75757
sam98na/consolidatedCollegeWork
/cs188/python_basics/listcomp.py
229
3.75
4
nums = [1, 2, 3, 4, 5, 6] oddNums = [x for x in nums if x % 2 == 1] print(oddNums) oddNumsPlusOne = [x + 1 for x in nums if x % 2 == 1] print(oddNumsPlusOne) def listcomp(lst): return [i.lower() for i in lst if len(i) >= 5]
ae0009a76b00c9000d4cf023b55461676b6706b8
cakmakaf/Project_Euler_Challenges
/sum_of_multiplies_3_or_5.py
140
3.75
4
total_sum = 0 for i in range(1000): if (i % 3 == 0 or i % 5 ==0): total_sum = total_sum + i print(total_sum)
b9b836dffee50eea89374a9978eeb48a86431187
vladosed/PY_LABS_1
/3-4/3-4.py
730
4.3125
4
#create random string with lower and upper case and with numbers str_var = "asdjhJVYGHV42315gvghvHGV214HVhjjJK" print(str_var) #find first symbol of string first_symbol = str_var[0] print(first_symbol) #find the last symbol of string last_symbol = str_var[-1] print(last_symbol) #slice first 8 symbols print(str_var[slice(8)]) #print only symbols with index which divides on 3 without remaining list_of_str_var = list(str_var.strip(" ")) every_third_elem = list_of_str_var[::3] list_to_str = ''.join(str(x) for x in every_third_elem) print(list_to_str) #print the symbol of the middle of the string text middle = str_var[int(len(str_var) / 2)] #len(str_var) / 2 print(middle) #reverse text using slice print(str_var [::-1])
46710e021657795e54522f6820ae99429b93b0bb
DinoSubbu/SmartEnergyManagementSystem
/backend/gasBoiler/hot_water_demand_api.py
3,911
3.65625
4
from datetime import datetime import config import csv import os ############################################### Formula Explanation ############################################## # Formula to calculate Heat Energy required : # Heat Energy (Joule) = Density_Water (kg/l) * Specific_Heat_water (J/Kg/degree Celsius) * Water_Demand (l) * # Temp_Desired - Temp_Current (deg Celsius) # Formula to convert from Heat energy to Power : # Power (Watt) = Heat Energy (Joule) / Time (s) # Example : # Heat Energy required to achieve hot water demand in a hour = 3600 Joule # Power required = No of Joules per second # Assuming time frame of 1 hour = 3600 s # Power = 3600/3600 = 1 J/s = 1 W # (i.e) 1 Joule of energy has to be supplied per second for a duration of 1 hr to meet the demand ################################################################################################################## ############################# Mathematical Constants ################################### DENSITY_WATER = 1 # 1 kg/l SPECIFIC_HEAT_CAPACITY_WATER = 4200 # 4.2KJ/Kg/degree Celsius --> 4200 J/Kg/deg Celsius ######################################################################################## class HotWaterAPI: """ API to calculate power required for meeting hot water demand. Requires hot water demand profile in the form of csv. Attributes ---------- buildingName : string name of the building where gas boiler is installed and hot water has to be supplied noOfOccupants : int number of occupants in a building desiredTempWater : float desired temperature of hot water. Reads from global config file currentTempWater : float current temperature of tap water. Reads from global config file demandProfile : dictionary hourly demand profile for a building hotWaterDemand : float amount of hot water (in litres) needed at the current hour of the day ThermalPowerDHW : float power (in Watts) needed to meet the hot water demand at the current hour of the day Methods ------- getHotWaterProfile() based on the building name and no of occupants, selects the hot water demand profile for the entire day getCurrentHotWaterDemand() returns the hot water demand (in litres) for the current hour getThermalPowerDHW(buildingName) returns power required (in Watt) for hot water demand """ def __init__(self, noOfOccupants = 4): self.noOfOccupants = noOfOccupants self.desiredTempWater = config.DESIRED_TEMPERATURE_WATER self.currentTempWater = config.CURRENT_TEMPERATURE_WATER self.hotWaterDemand = 0 def getHotWaterProfile(self): currentDirectory = os.path.abspath(os.path.dirname(__file__)) pathCsv = os.path.join(currentDirectory, "dhw_demand_profiles/" + self.buildingName + ".csv") with open(pathCsv) as hotWaterProfilecsv: hotWaterCsvReader = csv.reader(hotWaterProfilecsv) demandProfile = [row for idx, row in enumerate(hotWaterCsvReader) if idx==self.noOfOccupants-1] demandProfile = demandProfile[0] demandProfile = {i:float(demandProfile[i]) for i in range(24)} return demandProfile def getCurrentHotWaterDemand(self): currentHour = datetime.now().hour return(self.demandProfile[currentHour]) def getThermalPowerDHW(self, buildingName): self.buildingName = buildingName self.demandProfile = self.getHotWaterProfile() self.hotWaterDemand = self.getCurrentHotWaterDemand() heatEnergy = DENSITY_WATER * SPECIFIC_HEAT_CAPACITY_WATER * self.hotWaterDemand * \ (self.desiredTempWater - self.currentTempWater) self.ThermalPowerDHW = heatEnergy / 3600 return(self.ThermalPowerDHW)
4b96b2b9227aa69affad957b559437872e1ed3ff
SpencerOfwiti/machine-learning-algorithms
/Neural Networks/image_classifier.py
1,850
3.796875
4
# import libraries import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt # load dataset data = keras.datasets.fashion_mnist # splitting data into training and testing data (train_images, train_labels), (test_images, test_labels) = data.load_data() # defining a list of class names class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # pre-processing images # scaling the pixel values down to make computations easier train_images = train_images/255.0 test_images = test_images/255.0 # creating our model # a sequential model with 3 layers from input to output layer # input layer of 784 neurons representing the 28*28 pixels in a picture # hidden layer of 128 neurons # output layer of 10 neurons for each of the 10 classes model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation='relu'), keras.layers.Dense(10, activation='softmax') ]) # compiling and training the model # compiling is picking the optimizer, loss function and metrics to keep track of model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(train_images, train_labels, epochs=5) # testing the accuracy of our model test_loss, test_acc = model.evaluate(test_images, test_labels) print('\nTest accuracy:', test_acc) # using the model to make predictions predictions = model.predict(test_images) # displaying first 5 images and their predictions plt.figure(figsize=(5, 5)) for i in range(5): plt.grid(False) # plotting an image plt.imshow(test_images[i], cmap=plt.cm.binary) plt.xlabel('Actual: ' + class_names[test_labels[i]]) plt.title('Prediction: ' + class_names[np.argmax(predictions[i])]) plt.show()
092484419e6ca5d7ea8c70c89c183c74cfffa743
jisheng1997/pythontest
/main/list.py
2,549
3.890625
4
#!/usr/bin/python3 # -*- encoding: utf-8 -*- """ @File : list.py @Time : 2020/8/6 22:53 @Author : jisheng """ #列表索引从0开始。列表可以进行截取、组合 #列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。 #列表的数据项不需要具有相同的类型 #变量表 list1 = ['Google', 'python', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"] list5 = ['b','a','h','d','y'] tuple1 = ('I','love','python') print('------------以下是列表的获取,修改,删除-------------') print ("list1[0]: ", list1[0]) print ("list1[-2]: ", list1[-2]) print ("list2[1:5]: ", list2[1:5]) print ("list3[1:]: ", list3[1:]) #你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项 print ("第三个元素为 : ", list1[2]) list1[2] = 2001 print ("更新后的第三个元素为 : ", list1[2]) print ("原始列表 : ", list1) del list1[3] print ("删除第三个元素 : ", list1) print('-----------------以下是列表脚本操作符-------------------') #1.长度 2.组合 3.重复 4.元素是否存在于列表中 print(len(list2),list2+list3,list1*4,3 in list2) #5.迭代 for x in list1: print(x,end=' ') print('') print('-------------------以下是嵌套列表--------------------') list4 = [list1,list2,list3] print("list4: ",list4) print("list4[1]: ",list4[1]) print("list4[2][3]: ",list4[2][3]) print('-------------------以下是列表函数&方法---------------------') #列表元素个数/返回列表元素最大值/返回列表元素最小值 print(len(list2),max(list2),min(list2)) #将元组转换为列表 print(list(tuple1)) #在列表末尾添加新的对象 list1.append('baidu') print(list1) #统计某个元素在列表中出现的次数 print(list1.count('Google')) #在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) list1.extend(list2) print(list1) #从列表中找出某个值第一个匹配项的索引位置 print(list1.index("Google")) #将对象插入列表 list1.insert(len(list1),'nihao') print(list1) #移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 print(list1.pop()) #移除列表中某个值的第一个匹配项 list1.remove("Google") print(list1) #反向列表中元素 list1.reverse() print(list1) #对原列表进行排序 True升序 list5.sort(reverse=True) print(list5) #复制列表 listlist = list1.copy() print(listlist) #清空列表 list1.clear() print(list1)
5af8ab9e91bc331bd64ac43aaaf6be59ac95c949
divij-pherwani/Algorithms
/Corona Tracking App/Code.py
1,189
3.5625
4
import sys def trackerApp(n, d, event): ret = [""] * n position = dict() pairs = 0 for k, i in enumerate(event): if i[0] == 1: # Adding element position[i[1]] = "Value" # Adding number of pairs formed using the element pairs = pairs + int((i[1] + d) in position) + int((i[1] - d) in position) elif i[0] == -1: # Removing element del position[i[1]] # Removing number of pairs formed using the element pairs = pairs - int((i[1] + d) in position) - int((i[1] - d) in position) # Final events if pairs >= 1: ret[k] = "red" else: ret[k] = "yellow" del position del pairs return ret # Reads the input astr = sys.stdin.readline().split() n = int(astr[0]) d = int(astr[1]) event = [[0 for _ in range(2)] for _ in range(n)] # Read event for i in range(0, n): astr = sys.stdin.readline().split() event[i] = [int(s) for s in astr[0:2]] # Calls your function ret = trackerApp(n, d, event) # Writes the output for i in range(0, n): print(ret[i])
078677cc461c3047153af9b95bf1f94280fa2855
wayhive/python_course
/python_course/demo1.py
553
3.859375
4
def print_name(): print("My name is Sey") print_name()#calling a function def print_country(country_name): print("My country is " + country_name) print_country("Kenya") developer = "William and Sey" def get_dev(The_string): for x in The_string: print(x) get_dev(developer) stuff = ["hospitals","schools","offices","houses","cars"] def get_dev(a_list): for x in a_list: print(x) get_dev(stuff) def say_name(name = "Developer"): return "My name is " + name say_name("Sey") get_tosh = say_name("Sey") print(get_tosh)
b07283832e229a7e1b45f59784c7abc499dd8fce
davidwrpayne/PythonScripting
/postmasscustomers.py
1,521
3.515625
4
import urllib2 import json import sys import random import base64 def main(): if len(sys.argv) == 1 : print "Usage:" print "Please provide an api host, for example 'https://s1409077295.bcapp.dev'" print "create a legacy api user and token" print sys.argv[0] + " <API_Host> <API_UserName> <APIToken>" sys.exit(0) url = str(sys.argv[1]) url = url + '/api/v2/customers' user = str(sys.argv[2]) token = str(sys.argv[3]) count = 30 if len(sys.argv) == 3 : count = int(sys.argv[2]) for i in range(count): randomint = random.randint(0, sys.maxint) jsondata = createRandomCustomer() createConnection(url, user, token, jsondata) def createRandomCustomer() : firstName = randomString() lastName = randomString() customer = { "first_name":firstName, "last_name":lastName, "email": firstName + "." + lastName + "@example.com" } jsondata = json.dumps(customer) return jsondata def createConnection(url , user, token, data) : request = urllib2.Request(url) # You need the replace to handle encodestring adding a trailing newline # (https://docs.python.org/2/library/base64.html#base64.encodestring) base64string = base64.encodestring('%s:%s' % (user, token)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) request.add_header("Content-Type","application/json") result = urllib2.urlopen(request,data) def randomString() : return ''.join(random.choice('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') for i in range(8)) main()
06368e81ea8b2e85b99fba1d001d6509eeec6a2c
cohn-julian/algorithms
/insertionSort.py
372
3.515625
4
#Insertion Sort. Best O(n) (nearly sorted) - worts/avg O(n^2) import random def sort(arr): for i in range(1, len(arr) ): val = arr[i] j = i - 1 while (j >= 0) and (arr[j] > val): arr[j+1] = arr[j] j = j - 1 arr[j+1] = val a = [] for i in range(50): a.append(random.randint(1,100)) print a sort(a) print a
39c9a51126bf6a3a8fe5d69b7ab180d279c647b3
willyii/CS235-New-York-Airbnb
/Util/FillNa.py
1,509
3.671875
4
import pandas as pd class FillNa: def __init__(self): self.fill_value = 0 def fit(self, data: pd.DataFrame, column_name: str, method ="mean" ): """ Fill the missing value, default use mean to fill :param data: Dataset with missing value. Dataframe format :param column_name: The name of column. String format :param method: filling method, default "mean", also has [mean, median, mode, max, min] or specific value :return the dataframe column with filled value """ filling_name = ["mean", "median", "mode", "max", "min"] if method in filling_name: if method == "mean": self.fill_value = data[column_name].mean() elif method == "median": self.fill_value = data[column_name].median() elif method == "mode": self.fill_value = data[column_name].mode() elif method == "max": self.fill_value = data[column_name].max() elif method == "min": self.fill_value = data[column_name].min() else: self.fill_value = method def transform(self, data: pd.DataFrame, column_name: str): return data[[column_name]].fillna(self.fill_value).to_numpy() if __name__ == '__main__': test = pd.read_csv("AB_NYC_2019.csv") print(test.columns) test_encoder = FillNa() test["reviews_per_month"] = test_encoder.fill(test, "reviews_per_month") print(test)
dcc1cb77098649757c8bc62c5820b002cde8a3b0
Celia-xy/AIPathPlaning
/A_star.py
11,435
4.25
4
# The A* algorithm is for shortest path from start to goal in a grid maze # The algorithm has many different choices: # choose large or small g when f values are equal; forward or backward; adaptive or not from GridWorlds import create_maze_dfs, set_state, get_grid_size, draw_grid from classes import Heap, State import Tkinter # ------------------------------ initialization ------------------------------ # # create original grid of state of size (col, row) def create_state(col=100, row=100): # create grid state_grid = [[State() for i in range(col)] for i in range(row)] # change values in state for i in range(col): for j in range(row): # correct position state_grid[j][i].position = (i, j) # correct movement # if the first column, remove left if i == 0: state_grid[j][i].actions[0] = 0 # if the first row, remove up if j == 0: state_grid[j][i].actions[2] = 0 # if the last column, remove right if i == col-1: state_grid[j][i].actions[1] = 0 # if the last row, remove down if j == col-1: state_grid[j][i].actions[3] = 0 return state_grid # ------------------------------- start A* ------------------------------------ # # global movement [[0, 0, up, down], [left, right, 0, 0]] move = [[0, 0, -1, 1], [-1, 1, 0, 0]] # action is int from 0 to 3, represents left, right, up, down; position is (c, r); state is the state grid def get_succ(states, position, action): # movement [[0, 0, up, down], [left, right, 0, 0]] global move (c, r) = position if states[r][c].action_exist(action): # get next position r_new = r + move[0][action] c_new = c + move[1][action] succ = states[r_new][c_new] return succ # if action is available, cost is 1, otherwise cost is 0 def cost(state, position, action): # movement [[0, 0, up, down], [left, right, 0, 0]] global move (c, r) = position # if the action is available if state[r][c].action_exist(action): cost = 1 else: cost = 1000 # --------------------------------------------- # # search for a new path when original one blocked def compute_path(states, goal, open_list, close_list, counter, expanded, large_g, adaptive): global move (cg, rg) = goal while states[rg][cg].g > open_list.heap[-1][1].f: # open_list is binary heap while each item contains two value: f, state # remove the smallest f value item from open_list heap last_item = open_list.pop() # add the state with smallest f value into close_list close_list.append(last_item[1]) (c, r) = last_item[1].position for i in range(4): if states[r][c].action_exist(i): # get the successor of last item when action is i pos = (c, r) successor = get_succ(states, pos, i) # the position of successor r_succ = r + move[0][i] c_succ = c + move[1][i] try: close_list.index((c_succ, r_succ)) except ValueError: if successor.search < counter: # the successor state in state_grid states[r_succ][c_succ].g = 10000 states[r_succ][c_succ].renew_hf(goal) states[r_succ][c_succ].search = counter if successor.g > states[r][c].g + states[r][c].cost(i): states[r_succ][c_succ].g = states[r][c].g + states[r][c].cost(i) states[r_succ][c_succ].renew_hf(goal) states[r_succ][c_succ].tree = states[r][c] succ_state = states[r_succ][c_succ] # choose favor of large g or small g when f is equal if large_g == "large": succ_favor = states[r_succ][c_succ].f * 10000 - states[r_succ][c_succ].g else: succ_favor = states[r_succ][c_succ].f * 10000 + states[r_succ][c_succ].g i = 0 while i < len(open_list.heap) and len(open_list.heap) > 0: # if successor is in open list if succ_state.position == open_list.heap[i][1].position: # renew the g value in the corresponding open list item and renew heap open_list.remove(i) i += 1 # insert the successor into open list open_list.insert([succ_favor, succ_state]) expanded += 1 else: continue if len(open_list.heap) == 0: break return states, open_list, close_list, expanded # --------------------------------------- A* search ---------------------------------------- # # (path, exist) = A_star_forward(start, goal, maze_grid, large_g="large", forward="forward", adaptive="adaptive" # # input: start, goal: the coordinates (x, y) of start and goal # maze_grid: a grid maze created by create_maze_dfs() function in GridWorlds # large_g: "large" to choose large g when f are same, otherwise choose small g # forward: "forward" to choose forward A*, otherwise choose backward A* # adaptive: "adaptive" to choose adaptive A*, otherwise choose A* # # output: path: array of coordinates (x, y) of path nodes from start to goal # exist: boolean, "True" if path exists, "False" otherwise def A_star_forward(start, goal, maze_grid, large_g="large", adaptive="adaptive"): # initial state grid states = create_state(len(maze_grid), len(maze_grid[0])) # decide if goal is reached reach_goal = False counter = 0 expanded = 0 current = start (cg, rg) = goal path = [] path2 = [] # the current position while reach_goal == False: counter += 1 (cs, rs) = current states[rs][cs].g = 0 states[rs][cs].renew_hf(goal) states[rs][cs].search = counter states[rg][cg].g = 10000 states[rg][cg].renew_hf(goal) states[rg][cg].search = counter # open_list is binary heap while each item contains two value: f, state open_list = Heap() # close_list only store state close_list = [] open_state = states[rs][cs] # choose favor of large g or small g when f is equal if large_g == "large": open_favor = states[rs][cs].f * 1000 - states[rs][cs].g else: open_favor = states[rs][cs].f * 1000 + states[rs][cs].g # insert s_start into open list open_list.insert([open_favor, open_state]) # compute path (states, open_list, close_list, expanded) = compute_path(states, goal, open_list, close_list, counter, expanded, large_g, adaptive) if len(open_list.heap) == 0: print "I cannot reach the target." break # get the path from goal to start by tree-pointer (cc, rc) = goal path = [(cc, rc)] while (cc, rc) != (cs, rs): (cc, rc) = states[rc][cc].tree.position path.append((cc, rc)) # follow the path (c_0, r_0) = path[-1] while states[r_0][c_0].position != (cg, rg): # (c, r) = successor.position (c, r) = path.pop() try: index = path2.index((c, r)) except ValueError: path2.append((c, r)) else: for i in range(index+1, len(path2)): path2.pop() try: index = path2.index((c, r)) except ValueError: path2.append((c, r)) else: for i in range(index+1, len(path2)): path2.pop() if len(path2) > 4: (c1, r1) = path2[-4] (c2, r2) = path2[-1] if abs(c1-c2) + abs(r1-r2) == 1: path2.pop(-3) path2.pop(-2) # if blocked, stop and renew cost of all successors if maze_grid[r][c] == 1: states[r][c].g = 10000 states[r][c].renew_hf(goal) # set action cost if c - c_0 == 0: # cannot move down if r - r_0 == 1: states[r_0][c_0].actions[3] = 0 # cannot move up else: states[r_0][c_0].actions[2] = 0 else: # cannot move right if c - c_0 == 1: states[r_0][c_0].actions[1] = 0 # cannot move left else: states[r_0][c_0].actions[0] = 0 break (c_0, r_0) = (c, r) # set start to current position current = (c_0, r_0) if states[r_0][c_0].position == (cg, rg): reach_goal = True # if path from start to goal exists if reach_goal: # (cc, rc) = start # path = [] # # while (cc, rc) != (cs, rs): # # path.append((cc, rc)) # (cc, rc) = states[rc][cc].tree.position # # while len(path2) > 0: # path.append(path2.pop()) print "I reached the target" print path2 return path2, reach_goal, expanded # draw the path from start to goal def draw_path(maze_grid, path): # get size (col, row) = get_grid_size(maze_grid) screen = Tkinter.Tk() canvas = Tkinter.Canvas(screen, width=(col+2)*5, height=(row+2)*5) canvas.pack() # create initial grid world for c in range(1, col+2): canvas.create_line(c*5, 5, c*5, (row+1)*5, width=1) for r in range(1, row+2): canvas.create_line(5, r*5, (col+1)*5, r*5+1, width=1) # mark blocked grid as black, start state as red, goal as green for c in range(0, col): for r in range(0, row): # if blocked if maze_grid[r][c] == 1: canvas.create_rectangle((c+1)*5+1, (r+1)*5+1, (c+2)*5, (r+2)*5, fill="black") # if the path if (c, r) in path: # mark path as blue canvas.create_rectangle((c+1)*5+1, (r+1)*5+1, (c+2)*5, (r+2)*5, fill="blue") # if start if maze_grid[r][c] == "A": canvas.create_rectangle((c+1)*5+1, (r+1)*5+1, (c+2)*5, (r+2)*5, fill="red") # if goal if maze_grid[r][c] == "T": canvas.create_rectangle((c+1)*5+1, (r+1)*5+1, (c+2)*5, (r+2)*5, fill="green") screen.mainloop() # test my_maze = create_maze_dfs(101, 101) (start, goal, my_maze) = set_state(my_maze) draw_grid(my_maze) # get path by A* search (PATH, reach_goal, expanded) = A_star_forward(start, goal, my_maze, "large", "forward") # if path exist, draw maze and path if reach_goal: draw_path(my_maze, PATH) print expanded else: print "Path doesn't exist"
1cab18caa6822e5a164a198ec77b243086b6a840
phoenix1796/algorithms-practice
/mergeSort.py
783
4.03125
4
def merge(l1,l2): ind1 = ind2 = 0 list = [] while ind1<len(l1) and ind2<len(l2): if l1[ind1]<l2[ind2]: list.append(l1[ind1]) ind1+=1 else: list.append(l2[ind2]) ind2+=1 while ind1<len(l1): list.append(l1[ind1]) ind1+=1 while ind2<len(l2): list.append(l2[ind2]) ind2+=1 # print(list) # lists when bubbling up return list def mergeSort(list): # print(list) # lists when dividing if len(list) <= 1: return list pivot = int((len(list))/2) l1=mergeSort(list[:pivot]) l2=mergeSort(list[pivot:]) return merge(l1,l2) test_list = [21,4,1,3,9,20,25] print(mergeSort(test_list)) # test_list = [0,1,2,3,4] # print(mergeSort(test_list))
1874acb1d4c7dc6c1d0e3e90df8f303698e6bb20
ssong319/Dicts-word-count
/wordcount.py
924
3.765625
4
# put your code here. import sys def count_words(filename): the_file = open(filename) word_counts = {} for line in the_file: #line = line.rstrip('?') list_per_line = line.rstrip().lower().split(" ") # out = [c for c in list_per_line if c not in ('!','.',':', '?')] # print out for word in list_per_line: word = word.rstrip('?') word = word.rstrip('!') word = word.rstrip('.') word = word.rstrip(',') word_counts[word] = word_counts.get(word, 0) + 1 the_file.close() word_counts = word_counts.items() count = 0 for tpl in word_counts: word_counts[count] = list(tpl) word_counts[count].reverse() count += 1 word_counts.sort() word_counts.reverse() for count, word in word_counts: print "{}: {}".format(word, count) count_words(sys.argv[1])
8e668075fd8ddc7f0209e8fcb24689eb2c3af0da
Noahprog/DataProcessing
/Homework/Week_3/convertCSV2JSON.py
557
3.578125
4
# Noah van Grinsven # 10501916 # week 3 # convert csv to json format import csv import json # specific values def csv2json(filename): csvfilename = filename jsonfilename = csvfilename.split('.')[0] + '.json' delimiter = "," # open and read csv file with open(filename, 'r') as csvfile: reader = csv.DictReader(csvfile, delimiter = delimiter) data = list(reader) # open and write to json with open(jsonfilename, 'w') as jsonfile: json.dump(data, jsonfile) # convert csv file csv2json('MaandregenDeBilt2015.csv')
bc21452d6fe5e22f5580c172737d2cecea07dee5
DimaLevchenko/intro_python
/homework_5/task_7.py
739
4.15625
4
# Написать функцию `is_date`, принимающую 3 аргумента — день, месяц и год. # Вернуть `True`, если дата корректная (надо учитывать число месяца. Например 30.02 - дата не корректная, # так же 31.06 или 32.07 и т.д.), и `False` иначе. # (можно использовать модуль calendar или datetime) from datetime import datetime d = int(input('Enter day: ')) m = int(input('Enter month: ')) y = int(input('Enter year: ')) def is_date(a, b, c): try: datetime(day=a, month=b, year=c) return True except ValueError: return False print(is_date(d, m, y))
09a6e8d8e627becba4124c4fe37bbcc94020da82
DimaLevchenko/intro_python
/homework_5/task_4.py
763
3.875
4
# Дан список случайных целых чисел. Замените все нечетные числа списка нулями. И выведете их количество. import random def randomspis(): list = [] c = 0 while c < 10: i = random.randint(0, 100) list.append(i) c += 1 print('Список случайных чисел: ', list) return list spis = randomspis() def newspis(lis): lis2 = [] c = 0 for i in lis: if i % 2 != 0: lis2.append(0) c += 1 else: lis2.append(i) return lis2, c spis2 = newspis(spis) print('Новый список: ', spis2[0]) print('Количество нечетных чисел: ', spis2[1])
0e68170f1d26748450f78365d974c7d052f67d52
DimaLevchenko/intro_python
/homework_15/task_3.py
1,288
4.0625
4
# Вводимый пользователем пароль должен соответсвовать требованиям, # 1. Как минимум 1 символ от a-z # 2. Как минимум 1 символ от A-Z # 3. Как минимум 1 символ от 0-9 # 4. Как минимум 1 символ из $#@-+= # 5. Минимальная длина пароля 8 символов. # Программа принимает на ввод строку, в случае если пароль не верный - # пишет какому требованию не соответствует и спрашивает снова, # в случае если верный - пишет 'Password is correct'. import re password = input('Enter your password - ') def check(pw): if not re.search(r'[a-z]', pw): return 'At least 1 symbol from a-z is required' if not re.search(r'[A-Z]', pw): return 'At least 1 symbol from A-Z is required' if not re.search(r'\d', pw): return 'At least 1 symbol from 0-9 is required' if not re.search(r'[$#@+=\-]', pw): return 'At least 1 symbol of $#@-+= is required' if len(pw) < 8: return 'At least 8 symbol is required' return 'Password is correct' print(check(password))
46c58187e7ad3f322958c60ba51f4332cb0eaea9
DimaLevchenko/intro_python
/homework_4/task_4.py
353
4.03125
4
# По данному натуральному `n ≤ 9` выведите лесенку из `n` ступенек, # `i`-я ступенька состоит из чисел от 1 до `i` без пробелов. n = int(input('Введите число: ')) for i in range(1, n+1): for x in range(1, i+1): print(x, end='') print()
50b6fdeb9324f95234d1d15d3345e728f0c2d5d5
goldiekapur/algorithm-snacks
/leetcode_python/22.Generate_Parentheses.py
1,683
3.546875
4
# https://leetcode.com/problems/generate-parentheses/ # 回溯. 逐个字符添加, 生成每一种组合. # 一个状态需要记录的有: 当前字符串本身, 左括号数量, 右括号数量. # 递归过程中解决: # 如果当前右括号数量等于括号对数 n, 那么当前字符串即是一种组合, 放入解中. # 如果当前左括号数量等于括号对数 n, 那么当前字符串后续填充满右括号, 即是一种组合. # 如果当前左括号数量未超过 n: # 如果左括号多于右括号, 那么此时可以添加一个左括号或右括号, 递归进入下一层 # 如果左括号不多于右括号, 那么此时只能添加一个左括号, 递归进入下一层 class Solution: def generateParenthesis(self, n: int): if n == 0: return '' res = [] self.helper(n, n, '', res) return res def helper(self, l, r, string, res): if l > r: return if l == 0 and r == 0: res.append(string) if l > 0: self.helper(l - 1, r, string + '(', res) if r > 0: self.helper(l, r - 1, string + ')', res) # https://www.youtube.com/watch?v=PCb1Ca_j6OU class Solution: def generateParenthesis(self, n: int) -> List[str]: res = [] if n == 0: return res self.helper(n, 0, 0, res, '') return res def helper(self, k, left, right, res, temp): if right == k: res.append(temp) return if left < k: self.helper(k, left + 1, right, res, temp + '(') if right < left: self.helper(k, left, right + 1, res, temp + ')')
5e39352eeb9519b9b17408456592cd4fc585473f
goldiekapur/algorithm-snacks
/leetcode_python/528.RandomPick_with_Weight.py
792
3.65625
4
#!/usr/bin/env python3 # coding: utf-8 # Time complexity: O() # Space complexity: O() # https://leetcode.com/problems/random-pick-with-weight/ class Solution: # 1 8 9 3 6 # 1 9 18 21 27 # 20 def __init__(self, w: List[int]): for i in range(1, len(w)): w[i] += w[i - 1] self.s = w[-1] self.w = w def pickIndex(self) -> int: seed = random.randint(1, self.s) l = 0 r = len(self.w) - 1 while l < r: # 注意边界 mid = (l + r) // 2 if self.w[mid] < seed: l = mid + 1 # 注意边界 else: r = mid return l # Your Solution object will be instantiated and called as such: # obj = Solution(w) # param_1 = obj.pickIndex()
1d7e96d1abce1a5f23c20b18890761cabd363df0
goldiekapur/algorithm-snacks
/leetcode_python/480.Sliding_Window_Median.py
743
3.625
4
#!/usr/bin/env python3 # coding: utf-8 # https://leetcode.com/problems/sliding-window-median/ import bisect class Solution: def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]: heap = nums[:k] heap.sort() mid = k // 2 if k % 2 == 0: res = [(heap[mid] + heap[mid - 1]) / 2] else: res = [heap[mid]] for i, n in enumerate(nums[k:]): # print(heap) idx = bisect.bisect(heap, nums[i]) # print(idx) heap[idx - 1] = n heap.sort() if k % 2 == 0: res.append((heap[mid] + heap[mid - 1]) / 2) else: res.append(heap[mid]) return res
1e03ddfbc1e14e81606b805b55234686b2ccadd1
goldiekapur/algorithm-snacks
/leetcode_python/417.Pacific_Atlantic_Water_Flow.py
3,364
3.765625
4
#!/usr/bin/env python3 # coding: utf-8 # https://leetcode.com/problems/pacific-atlantic-water-flow/ # 这道题的意思是说让找到所有点既可以走到左面,上面(pacific)又可以走到右面,下面(atlantic) # dfs的思路就是,逆向思维,找到从左边,上面(就是第一列&第一排,已经是pacific的点)出发,能到的地方都记录下来. # 同时右面,下面(就是最后一列,最后一排,已经是Atlantic的点)出发,能到的地方记录下来。 # 综合两个visited矩阵,两个True,证明反过来这个点可以到两个海洋。 # Time complexity: O(MN) # Space complexity: O(MN) class Solution: def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]: if not matrix: return [] m = len(matrix) n = len(matrix[0]) pacific_m = [[False for _ in range(n)] for _ in range(m)] atlantic_m = [[False for _ in range(n)] for _ in range(m)] for i in range(m): # 从第一列(pacific)到对面atlantic self.dfs(matrix, i, 0, pacific_m) # 从最后一列(atlantic)到对面pacific self.dfs(matrix, i, n - 1, atlantic_m) for i in range(n): # 从第一行(pacific)到最后一行atlantic self.dfs(matrix, 0, i, pacific_m) # 从最后一行(atlantic)到第一行pacific self.dfs(matrix, m - 1, i, atlantic_m) res = [] for i in range(m): for j in range(n): if pacific_m[i][j] and atlantic_m[i][j]: res.append([i, j]) return res def dfs(self, matrix, x, y, visited): visited[x][y] = True # 存放一个四个方位的var方便计算左右上下 for i, j in [(0, -1), (0, 1), (-1, 0), (1, 0)]: nx, ny = x + i, y + j if 0 <= nx < len(matrix) and 0 <= ny < len(matrix[0]) and not visited[nx][ny] and matrix[nx][ny] >= \ matrix[x][y]: self.dfs(matrix, nx, ny, visited) # 第二种方法是bfs,使用一个queue去记录可以到达的点,最后同样是合并来给你个能到达的列表的重合返回。 class Solution2: def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]: if not matrix: return [] # 存放一个四个方位的var方便计算左右上下 self.direction = [(0, -1), (0, 1), (-1, 0), (1, 0)] m = len(matrix) n = len(matrix[0]) pacific_set = set([(i, 0) for i in range(m)] + [(0, j) for j in range(n)]) atlantic_set = set([(m - 1, i) for i in range(n)] + [(j, n - 1) for j in range(m)]) def bfs(reachable_point): queue = collections.deque(reachable_point) while queue: x, y = queue.popleft() for i, j in [(0, -1), (0, 1), (-1, 0), (1, 0)]: nx, ny = x + i, y + j if 0 <= nx < len(matrix) and 0 <= ny < len(matrix[0]) and (nx, ny) not in reachable_point and \ matrix[nx][ny] >= matrix[x][y]: reachable_point.add((nx, ny)) queue.append((nx, ny)) return reachable_point return list(bfs(pacific_set) & bfs(atlantic_set))
b9bd0caf3cb168ad51c9f36ab8390890ad50d9d4
goldiekapur/algorithm-snacks
/leetcode_python/410.Split_Array_Largest_Sum.py
940
3.625
4
#!/usr/bin/env python3 # coding: utf-8 # Time complexity: O() # Space complexity: O() class Solution: def splitArray(self, nums: List[int], m: int) -> int: def valid(mid): count = 1 total = 0 for num in nums: total += num if total > mid: total = num count += 1 if count > m: return False return True low = max(nums) high = sum(nums) while low <= high: mid = (low + high) // 2 if valid(mid): high = mid - 1 else: low = mid + 1 return low # https://leetcode.com/problems/split-array-largest-sum/discuss/141497/AC-Java-DFS-%2B-memorization # dp 做法 # https://leetcode.com/problems/split-array-largest-sum/discuss/89821/Python-solution-dp-and-binary-search
74cb46e1099bbcd6f6c8a5c2be93829e6207fa14
vnikhila/PythonClass
/operators.py
606
4.0625
4
a = int(input('Enter value for a\n')) b = int(input('Enter value for b\n')) print('\n') print('Arithmetic Operators') print('Sum: ',a+b) print('Diff: ',a-b) print('Prod: ',a*b) print('Quot: ',b/a) print('Remnder: ',b%a) print('Floor Divisn: ',b//a) print('Exponent: ',a**b) print('\n') print('Relational Operators') print('a == b:', a == b) print('a != b:', a != b) print('a >= b:', a >= b) print('a <= b:', a <= b) print('a > b:', a > b) print('a < b:', a < b) print('\n') print('Logical Operators') print('a or b:', a or b) print('a and b:', a and b) print('\n') print('Assignment Operators') print()
3d773a08b8a163465cc06cfccb597a47e809a17d
vnikhila/PythonClass
/listexamples.py
1,797
4.1875
4
# --------Basic Addition of two matrices------- a = [[1,2],[3,4]] b = [[5,6],[7,8]] c= [[0,0],[0,0]] for i in range(len(a)): for j in range(len(a[0])): c[i][j] = a[i][j]+b[i][j] print(c) # -------Taking values of nested lists from user-------- n = int(input('Enter no of row and column: ')) a = [[0 for i in range(n)] for j in range(n)] #to create a nested list of desired size b = [[0 for i in range(n)] for j in range(n)] c = [[0 for i in range(n)] for j in range(n)] print('Enter the elements: ') for i in range(n): for j in range(n): a[i][j] = int(input('Enter val for list a: ')) b[i][j] = int(input('Enter val for list b: ')) for i in range(n): for j in range(n): c[i][j] = a[i][j] + b[i][j] print('List a: ',a) print('List b: ',b) print('a + b:',c) # -------Values from user method2 (Using While loop)-------- n = int(input('Enter no of rows and col: ')) a,b,rowa,rowb = [],[],[],[] c = [[0 for i in range(n)] for j in range(n)] j = 0 print('Enter values for a') while(j < n): for i in range(n): rowa.append(int(input('Enter value for a: '))) rowb.append(int(input('Enter value for b: '))) a.append(rowa) b.append(rowb) rowa,rowb = [],[] j += 1 for i in range(n): for j in range(n): c[i][j] = a[i][j] + b[i][j] print('a: ',a) print('b: ',b) print('a + b: ',c) # -------Matrix Multiplication---------- n = int(input('Enter no of rows and col: ')) a,b,rowa,rowb = [],[],[],[] c = [[0 for i in range(n)] for j in range(n)] j = 0 print('Enter values for a') while(j < n): for i in range(n): rowa.append(int(input('Enter value for a: '))) rowb.append(int(input('Enter value for b: '))) a.append(rowa) b.append(rowb) rowa,rowb = [],[] j += 1 for i in range(n): for j in range(n): c[i][j] = a[i][j] * b[j][i] print('a: ',a) print('b: ',b) print('a * b: ',c)
9a0ceda7765af0638ec2a3c31f2665b7b7d7075a
vnikhila/PythonClass
/conditional.py
207
4.34375
4
#if else ODD EVEN EXAMPLE a = int(input('Enter a number\n')) if a%2==0: print('Even') else: print('Odd') # if elif else example if a>0: print('Positive') elif a<0: print('Negative') else: print('Zero')
fe7c10f251dc3f5c806709a006ed1e853fffe240
tarah-tamayo/aoc-2020
/day20/20a.py
11,881
3.5
4
import sys import re from copy import deepcopy class monster: monster = None def __init__(self): self.monster = [] lines = [" # ", "# ## ## ###", " # # # # # # "] for line in lines: print(line) m = ['1' if x == "#" else '0' for x in line] self.monster.append(int('0b' + ''.join(m), 2)) def find_monsters(self, t) -> int: c = 0 #for i in range(len(t.grid)-len(self.monster)): for i in range(1, len(t.grid)-1): for j in range(len(t.grid[i]) - 20): key = int('0b' + ''.join(t.bingrid[i][j:j+20]), 2) if (key & self.monster[1]) == self.monster[1]: print(f"OwO? [{i}][{j}]") print(''.join(t.grid[i-1][j:j+20])) print(''.join(t.grid[i][j:j+20])) print(''.join(t.grid[i+1][j:j+20])) print() key = int('0b' + ''.join(t.bingrid[i+1][j:j+20]), 2) if (key & self.monster[2]) == self.monster[2]: print(f"OwO? What's this? [{ i }][{ j }]") c += 1 else: print(f"no wo :'( ") #grid = [] #for k in range(len(self.monster)): # g = [True if x == '#' else False for x in t.grid[i+k][j:j+20]] # grid.append(g) #grid.append(int('0b'+''.join(g), 2)) #grid[k] = grid[k] & self.monster[k] #if self.check_grid(grid): # print("OwO!") # c += 1 #if grid == self.monster: # c += 1 return c def check_grid(self, grid: list) -> bool: for i in range(len(grid)): for j in range(len(grid[i])): grid[i][j] = grid[i][j] and self.monster[i][j] return grid == self.monster class tile: tid = 0 grid = None bingrid = None edges = None neighbors = None def __init__(self, lines, img=False): """ tile(lines, img) - Constructor. Boolean img defaults to False. If True this is a tile holding a full, stitched image. Edge detection is not required. """ self.grid = [] self.bingrid = [] self.edges = [] self.neighbors = [] self.parse(lines) if not img: self.find_edges() def parse(self, lines): for line in lines: match = re.match(r"Tile ([0-9]+):", line) if match: self.tid = int(match.groups()[0]) else: self.grid.append([x for x in line]) def create_bingrid(self): self.bingrid = [] for i in range(len(self.grid)): binstr = ['1' if x == '#' else '0' for x in self.grid[i]] self.bingrid.append(binstr) def find_edges(self): """ find_edges() - Finds the edges of the tile grid convention is that top and bottom edges are --> and left and right edges are top-down In order, edges are defined as: [0] - TOP [1] - RIGHT [2] - BOTTOM [3] - LEFT """ self.edges = [deepcopy(self.grid[0]), [], deepcopy(self.grid[-1]), []] for g in self.grid: self.edges[3].append(g[0]) self.edges[1].append(g[-1]) self.edges[2] self.edges[3] def lr_flip(self): """ lr_flip() - Flips grid Left / Right """ for g in self.grid: g.reverse() def td_flip(self): """ td_flip() - Flips grid Top / Down """ self.cw_rotate() self.cw_rotate() self.lr_flip() self.find_edges() def cw_rotate(self): """ cw_rotate() - Rotates grid clockwise 90 deg """ self.grid = [list(x) for x in zip(*self.grid[::-1])] self.find_edges() def orient(self, t2, left=False): """ orient(t2, left) - reorients this tile to match t2. Left defaults to False and, if true, indicates that t2 is to the left of this tile. Otherwise it assumes t2 is above this tile. """ # In order, edges are defined as: # [0] - TOP # [1] - RIGHT # [2] - BOTTOM # [3] - LEFT edge_i = self.get_edge(t2) if left: edge_t = 3 target = 1 else: edge_t = 2 target = 0 while edge_i != edge_t: self.cw_rotate() edge_i = self.get_edge(t2) if list(reversed(self.edges[edge_t])) == t2.edges[target]: if left: self.td_flip() else: self.lr_flip() def get_edge(self, t2) -> int: """ get_edge(t2) -> int - Returns the edge index of this tile that matches t2. If there is no common edge returns -1. """ for i in range(len(self.edges)): e = self.edges[i] for e2 in t2.edges: if e == e2: if t2 not in self.neighbors: self.neighbors.append(t2) if self not in t2.neighbors: t2.neighbors.append(self) return i if list(reversed(e)) == e2: if t2 not in self.neighbors: self.neighbors.append(t2) if self not in t2.neighbors: t2.neighbors.append(self) return i return -1 def compare(self, t2) -> bool: """ compare(t2) - Finds whether a common edge with tile t2 is present """ return True if self.get_edge(t2) >= 0 else False def find_common_neighbors(self, t2) -> list: """ find_common_neighbors(t) - Returns a list of common neighbors """ neighs = [] for n in self.neighbors: if n in t2.neighbors: neighs.append(n) return neighs def remove_edges(self): self.grid = self.grid[1:-1] for g in self.grid: g = g[1:-1] def __len__(self): self.create_bingrid() c = 0 for bg in self.bingrid: g = [1 if x == '1' else 0 for x in bg] c += sum(g) return c def __str__(self): s = f"\n ----- Tile { self.tid } -----" for g in self.grid: s += "\n" + ''.join(g) return s class image: # Dict of tiles by id tiles = None # 2d grid of tile IDs and rotations grid = None # Found corners corners = None # image stitched together image = None def __init__(self, lines): """ image() - Constructor Takes ALL tile lines and parses them to make a dictionary of tiles """ self.tiles = {} self.parse(lines) self.find_neighbors() self.find_corners() self.build_grid_top() self.build_grid_left() self.fill_grid() self.stitch_image() def parse(self, lines): tile_lines = [] for line in lines: if 'Tile' in line: if len(tile_lines): t = tile(tile_lines) self.tiles[t.tid] = t tile_lines = [line] elif len(line): tile_lines.append(line) t = tile(tile_lines) self.tiles[t.tid] = t def find_neighbors(self): for i in range(len(self.tiles.keys())): t1 = self.tiles[list(self.tiles.keys())[i]] for j in range(0, len(self.tiles.keys())): t2 = self.tiles[list(self.tiles.keys())[j]] if t1 != t2: t1.compare(t2) def find_corners(self): self.corners = [] for tile in self.tiles.values(): if len(tile.neighbors) == 2: self.corners.append(tile) s = "" for t in self.corners: s += f" { t.tid }" print(s) def build_grid_top(self): c = self.corners[0] t = c.neighbors[0] # orient to right side neighbor as top c.orient(t) # rotate clockwise to change top to right side c.cw_rotate() self.grid = [[c, t]] n = len(t.neighbors) while n == 3: for nbr in t.neighbors: if len(nbr.neighbors) == 3 and nbr not in self.grid[0]: t = nbr elif len(nbr.neighbors) == 2 and nbr not in self.grid[0]: t = nbr self.grid[0].append(t) n = len(t.neighbors) def build_grid_left(self): c = self.corners[0] t = c.neighbors[1] left = [c, t] n = len(t.neighbors) while n == 3: for nbr in t.neighbors: if len(nbr.neighbors) == 3 and nbr not in left: t = nbr elif len(nbr.neighbors) == 2 and nbr not in left: t = nbr left.append(t) n = len(t.neighbors) for i in range(1, len(left)): self.grid.append([None for _ in range(len(self.grid[0]))]) self.grid[i][0] = left[i] def fill_grid(self): for i in range(1,len(self.grid[0])): self.grid[0][i].orient(self.grid[0][i-1], left=True) for i in range(1,len(self.grid)): for j in range(1,len(self.grid[i])): neighs = self.grid[i][j-1].find_common_neighbors(self.grid[i-1][j]) for n in neighs: if n not in self.grid[i-1]: self.grid[i][j] = n self.grid[i][j].orient(self.grid[i-1][j]) for t in self.tiles.values(): t.remove_edges() def print_grid_ids(self): for g in self.grid: s = "" for t in g: if t is None: s += " None -" else: s += f" { t.tid } -" print(s) def stitch_image(self): # Create an empty tile object for the full image tile_lines = ["Tile 1:"] self.image = tile(tile_lines, img=True) line = 0 for g in self.grid: self.image.grid.extend([[] for _ in range(len(g[0].grid))]) for t in g: for i in range(len(t.grid)): self.image.grid[line+i].extend(t.grid[i]) line += len(g[0].grid) self.image.create_bingrid() if __name__ == '__main__': if len(sys.argv) > 1: file = sys.argv[1] else: file = 'day20/day20.in' with open(file) as f: lines = f.read().splitlines() img = image(lines) mult = 1 for t in img.corners: mult *= t.tid print(f"Day 20 Part 1: { mult }") m = monster() c = m.find_monsters(img.image) i = 0 while c == 0 and i < 4: print("...rotating...") img.image.cw_rotate() img.image.create_bingrid() i += 1 if c == 0: print("...flipping...") img.image.lr_flip img.image.create_bingrid() c = m.find_monsters(img.image) i = 0 while c == 0 and i < 4: print("...rotating...") img.image.cw_rotate() i += 1 print(img.image) print(c) print(f"Day 20 Part 2: { len(img.image) }") #lines = ['Tile 99:', '#...#', '.#...', '..#..', '...#.', '....#'] #t = tile(lines) #print(t) #t.td_flip() #print(t)
b5418dbfb626ef9a83a73a5de00da17e8e3822b5
Kristjamar/Verklegt-namskei-
/Breki/Add_to_dict.py
233
4.1875
4
x = {} def add_to_dict(x): key = input("Key: ") value = input("Value: ") if key in x: print("Error. Key already exists.") return x else: x[key] = value return x add_to_dict(x) print(x)
2f6070d909963b329e87f5a220c3c9b65c4e9a24
diksha-zodape/Miniproject
/generatePassword.py
361
3.640625
4
import random import string def generatePassword(stringLength=10): password_characters = string.ascii_letters + string.digits + string.punctuation return ''.join(random.choice(password_characters) for i in range(stringLength)) print("Random String password is generating...\n", generatePassword()) print ("\nPassword generated successfully!")
6c3ef65cf9d656edcec4dc65982a7fcc8c1527fb
codewithpom/Factor-finder
/main.py
171
3.90625
4
factors = [] i = 0 number = int(input("Enter the number")) while i <= number: i = i+1 if number % i == 0: factors.append(i) print(factors)
130f575d861172289c27e110441b5719a1adda61
kwax21/secu
/petite.py
983
3.671875
4
def premier(a): if a == 1: return False for i in range(a - 1, 1, -1): if a % i == 0: return False return True def findEverythingForTheWin(a): p = 2 q = 2 while 1 == 1: if premier(p) and (n % p == 0): q = int(n/p) print("P : ", p) print("Q : ",q) break else: p += 1 phiN = (p-1) * (q-1) print("phiN : ", phiN) if p < q: d = q else: d = p while 1 == 1: if((e * d % phiN == 1)): print("d : ", d) break d = d + 1 print("\nCle privee : (",d,",",phiN,")") print("\nDecryptage du message") ligne = pow(this,d)%n print("Fin : ", ligne) a = "o" e = int(input("entrez e : ")) n = int(input("entrez n : ")) while a == "o": print("\n") this = int(input("entrez le message a decrypter : ")) findEverythingForTheWin(n) a = input("\nEncore ? o/n : ")
2cbf2c0fc7ba8e74f40c1bcf6c1e9fbaf50af798
Talalkanjo01/GlobalAIHubPythonCourse
/Homeworks/HW2.py
528
4.03125
4
#Explain your work first i took value from user then i used for loop to check numbers between 0 and number user has entered if are odd or even then i printed to screen #Question 1 n = int(input("Entre single digit integer: ")) for number in range(1, int(n+1)): if (number%2==0): print(number) #Question 2 my_list = [1, 2 , 3 , 4, 5, 6, 7, 8, 9, 10] my_list[0:round(len(my_list)/2)] , my_list[round(len(my_list)/2):len(my_list)] = my_list[round(len(my_list)/2):len(my_list)] , my_list[0:round(len(my_list)/2)] print(my_list)
b7da43bd8f29aab4f61c7a9d4e6e918ce606eef0
gachiemchiep/source_code
/courses/problem_solving_with_algorithm_and_data_structures_using_python/4.5.stack.py
2,590
3.90625
4
class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) # Write a function revstring(mystr) that uses a stack to reverse the characters in a string. def revstring(mystr:str) -> str: s = Stack() # put into stack for char in mystr: s.push(char) # pop again to form a reverse string new_string = "" while not s.isEmpty(): new_string+= s.pop() return new_string # Simple Balanced Parentheses : def parChecker(symbolString:str) -> bool: s = Stack() is_balanced = True index = 0 while (index < len(symbolString)) and is_balanced: char = symbolString[index] if char == "(": s.push(char) elif char == ")": if s.isEmpty(): is_balanced = False else: s.pop() index += 1 return is_balanced # Simple Balanced Parentheses : [{()}] def parChecker2(symbolString): s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol in "([{": s.push(symbol) else: if s.isEmpty(): balanced = False else: top = s.pop() if not matches(top,symbol): balanced = False index = index + 1 if balanced and s.isEmpty(): return True else: return False def matches(open,close): opens = "([{" closers = ")]}" return opens.index(open) == closers.index(close) # Converting Decimal Numbers to Binary Numbers def baseConverter(decNumber, base=2): digits = "0123456789ABCDEF" remstack = Stack() while decNumber > 0: rem = decNumber % base remstack.push(rem) decNumber = decNumber // base binString = "" while not remstack.isEmpty(): binString = binString + digits[remstack.pop()] return binString if __name__ == '__main__': s=Stack() print(s.isEmpty()) s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.isEmpty()) s.push(8.4) print(s.pop()) print(s.pop()) print(s.size()) print(parChecker('((()))')) print(parChecker('(()')) print(baseConverter(256, 16))
a1a96cb2f60c516e63b861e96479ae5c9937f857
ritopa08/30-Days-Coding-Challenge
/day_26.py
556
4.0625
4
#-----Day 25: Running Time and Complexity-------# import math def isprime(data): x=int(math.ceil(math.sqrt(data))) if data==1: return "Not prime" elif data==2: return"Prime" else: for i in range(2,x+1): if data%i==0: return "Not prime" #break else: return "Prime" return "-1" s=int(input()) while s: d=int(input()) v=isprime(d) print(v)
95d846c051abad8b7a718db79dd33c5f5e308923
sabian2008/speciation_patterns
/analyze_interactive.py
3,852
3.765625
4
import numpy as np import pickle import matplotlib.pyplot as plt from matplotlib.widgets import Slider def gen_dist(genes): """Computes the genetic distance between individuals. Inputs: - genes: NxB matrix with the genome of each individual. Output: - out: NxN symmetric matrix with (out_ij) the genetic distance from individual N_i to individual N_j. """ # First generate an NxNxB matrix that has False where # i and j individuals have the same kth gene and True # otherwise (XOR operation). Then sum along # the genome axis to get distance return np.sum(genes[:,None,:] ^ genes, axis=-1) def classify(genes, G): """Classifies a series of individuals in isolated groups, using transitive genetic distance as the metric. If individual 1 is related to invidual 2, and 2 with 3, then 1 is related to 3 (independently of their genetic distance). Based on: https://stackoverflow.com/questions/41332988 and https://stackoverflow.com/questions/53886120 Inputs: - genes: NxB matrix with the genome of each individual. - G: Integer denoting the maximum genetic distance. Output: - out: list of lists. The parent lists contains as many elements as species. The child lists contains the indices of the individuals corresponding to that species. """ import networkx as nx # Calculate distance gendist = gen_dist(genes) N = gendist.shape[0] # Make the distance with comparison "upper triangular" by # setting lower diagonal of matrix extremely large gendist[np.arange(N)[:,None] >= np.arange(N)] = 999999 # Get a list of pairs of indices (i,j) satisfying distance(i,j) < G indices = np.where(gendist <= G) indices = list(zip(indices[0], indices[1])) # Now is the tricky part. I want to combine all the (i,j) indices # that share at least either i or j. This non-trivial problem can be # modeled as a graph problem (stackoverflow link). The solution is G = nx.Graph() G.add_edges_from(indices) return list(nx.connected_components(G)) # Load simulation S = 5 G = 20 target = "S{}-G{}.npz".format(S,G) data = np.load(target, allow_pickle=True) genes, pos, params = data['genes'], data['pos'], data['params'][()] G = params['G'] # Max. genetic distance tsave = params["tsave"] # Saves cadency # Load classification. If missing, perform it try: with open("S{}-G{}.class".format(S,G), 'rb') as fp: species = pickle.load(fp) except: print("Classification not found. Classyfing...") species = [] for t in range(0, genes.shape[0]): print("{} of {}".format(t, genes.shape[0]), end="\r") species.append(classify(genes[t], G)) with open("S{}-G{}.class".format(S,G), 'wb') as fp: pickle.dump(species, fp) # Create figure, axes and slider fig, ax = plt.subplots(1,1) axtime = plt.axes([0.25, 0.01, 0.5, 0.03], facecolor="lightblue") stime = Slider(axtime, 'Generation', 0, len(species), valfmt='%0.0f', valinit=0) fig.tight_layout(rect=[0, 0.03, 1, 0.95]) # Initial condition for s in species[0]: ax.scatter(pos[0,list(s),0], pos[0,list(s),1], s=5) # Function to update plots def update(val): i = int(round(val)) # Update plots ax.clear() for s in species[i]: ax.scatter(pos[i,list(s),0], pos[i,list(s),1], s=5) stime.valtext.set_text(tsave*i) # Update label # Draw fig.canvas.draw_idle() # Link them stime.on_changed(update) # Function to change slider using arrows def arrow_key_control(event): curr = stime.val if event.key == 'left': stime.set_val(curr-1) if event.key == 'right': stime.set_val(curr+1) fig.canvas.mpl_connect('key_release_event', arrow_key_control) plt.show()
935a2a6d789116d14739fc3572f1c283b0ea020d
akshatfulfagar12345/EDUYEAR-PYTHON-20
/day 3.py
176
3.8125
4
int=a,b,c b = int(input('enter the year for which you want to calculate')) print(b) c = int(input('enter your birth year')) a = int((b-c)) print('your current age is',a)
58a8258c74f852fb7d0e44c79827ea23cd25bbbd
akshatfulfagar12345/EDUYEAR-PYTHON-20
/day 6( Remove duplicate elements ).py
266
3.609375
4
data = [10,20,30,30,40,50,50,60,60,70,40,80,90] def remove_duplicates(duplist): noduplist = [] for element in duplist: if element not in noduplist: noduplist.append(element) return noduplist print(remove_duplicates(data))
32caa7eb3f40feade5b973c7b3f3c0b1b5650ca1
Jordan71214/PythonPractice
/0425/pyPrac0425_02.py
263
3.890625
4
a = range(10) print(a) for i in a: print(i) name = (1, 2, 3, 5, 4, 6) for i in range(len(name)): print('第%s個資料是:%s' % (i, name[i])) for i in range(1, 10, 2): print(i) b = list(range(10)) print(b) print(type(b)) c = [1, 2] print(type(c))
3141cca11b98778e6a419ec614939839ef906b3e
Jordan71214/PythonPractice
/0419/hello.py
372
3.5
4
import math r = 15 print('半徑 %.0f 的圓面積= %.4f' % (r, r * r * math.pi)) print('半徑15的圓面積=', math.ceil(15 * 15 * math.pi)) print('半徑15的圓面積=', math.floor(15 * 15 * math.pi)) #math.ceil() -> 向上取整 換言之 >= 的最小整數 print(math.ceil(10.5)) #math.floor() -> 向下取整 換言之 <= 的最大整數 print(math.floor(10.5))
a181420a345cd7cb8a9d8ec6cc8a9fbd5624492c
RoncoGit/Uniquindio
/CondicionalesAnidadas.py
1,434
4.03125
4
print("================") print("Conversor") print("================ \n") print("Menú de opciones: \n") print("Presiona 1 para convertir de número a palabra.") print("Presiona 2 para convertir de palabra a número. \n") conversor = int(input("¿Cuál es tu opción deseada?:")) if conversor == 1: print("Conversor de Número a palabras. \n") num = int(input("¿Cual es el número que deseas convertir?:")) if num == 1: print("el número es 'uno'") elif num == 2: print("el número es 'dos'") elif num == 3: print("el número es 'tres'") elif num == 4: print("el número es 'cuatro'") elif num == 5: print("el número es 'cinco'") else: print("el número máximo de conversion es 5.") elif conversor == 2: print("Conversor de palabras a números. \n") tex = input("¿Cual es la palabra que deseas convertir?:") tex = tex.lower() if tex == "uno" : print("el número es '1'") elif tex == "dos" : print("el número es '2'") elif tex == "tres" : print("el número es '3'") elif tex == "cuatro" : print("el número es '4'") elif tex == "cinco" : print("el número es '5'") else: print("el número máximo de conversion es cinco.") else: print("Respuesta no válida. Intentalo de nuevo.") print("Fin.")
bdc16e91fac7d1045b84f248b0fbb929e44bff0e
RoncoGit/Uniquindio
/CondicionalesMultiples.py
571
4.1875
4
print("===================================") print("¡¡Convertidor de números a letras!!") print("===================================") num = int(input("Cuál es el número que deseas convertit?:")) if num == 4 : print("El número es 'Cuatro'") elif num == 1 : print("El número es 'Cinco'") elif num == 2 : print("El número es 'Cinco'") elif num == 3 : print("El número es 'Cinco'") elif num == 5 : print("El número es 'Cinco'") else: print("Este programa solo puede convertir hasta el número 5") print("Fin.")
0d2653d959843341a061b39ae6150472d43297dd
PWalis/Graphs
/projects/ancestor/ancestor.py
1,915
3.90625
4
from graph import Graph from util import Queue def bfs(graph, starting_vertex): """ Return a list containing the longest path from starting_vertex """ earliest_an = None # Create an empty queue and enqueue A PATH TO the starting vertex ID q = Queue() initial_path = [starting_vertex] q.enqueue(initial_path) # Create a Set to store visited vertices visited = set() # While the queue is not empty... while q.size() > 0: # Dequeue the first PATH path = q.dequeue() # save the length of the path path_length = len(path) # Grab the last vertex from the PATH last_vert = path[-1] # If that vertex has not been visited... if last_vert not in visited: # Mark it as visited... visited.add(last_vert) # Then add A PATH TO its neighbors to the back of the for v in graph.vertices[last_vert]: # COPY THE PATH path_copy = path[:] # APPEND THE NEIGHOR TO THE BACK path_copy.append(v) q.enqueue(path_copy) # If the new path is longer than previous path # Save the longer path as earliest_ancestor if len(path_copy) > path_length: earliest_an = path_copy if earliest_an: return earliest_an[-1] return -1 def earliest_ancestor(ancestors, starting_node): graph = Graph() for a in ancestors: # Add all vertices to graph graph.add_vertex(a[0]) graph.add_vertex(a[1]) for a in ancestors: # Create child to parent relationship graph.add_edge(a[1], a[0]) return bfs(graph, starting_node) test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 1)] print(earliest_ancestor(test_ancestors, 1))
68683ee483f4bf0d25de8e9c6d8ae3d89c057be3
syamms/Deep-Learning-Projects
/Deep Learning A-Z/Volume 1 - Supervised Deep Learning/Part 3 - Recurrent Neural Networks (RNN)/Recurrent_Neural_Networks/rnn_pratice.py
2,416
4
4
# -*- coding: utf-8 -*- """ 08:08:21 2017 @author: SHRADDHA """ #Recurrent Neural Network #PART 1 DATA PREPROCESSING #importing libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing training set training_set = pd.read_csv('Google_Stock_Price_Train.csv') training_set = training_set.iloc[:,1:2].values #Feature Scaling #Normalization used here where only min and max values are needed #Once known min and max they are transformed #Not Standardization from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler() training_set = sc.fit_transform(training_set) #Getting Input and Output #In RNNs, here we take the input as the current price of Stocks today #Using the current, we predict the next day's value #That is the what happens, and hence we divide the ds into two parts X_train = training_set[0:1257] y_train = training_set[1:1258] #Reshaping #It's used by RNN X_train = np.reshape(X_train,(1257,1,1)) #PART 2 BUILDING THE RNNs #Importing the libraries from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM #Initializing the RNNs regressor = Sequential() #Adding the LSTM Layer and input layer regressor.add(LSTM(units = 4, activation = 'sigmoid', input_shape = (None,1))) regressor.add(Dense(units = 1)) #Compile the Regressor, compile method used regressor.compile(optimizer = 'adam', loss = 'mean_squared_error') #Fitting the training set regressor.fit(X_train, y_train, batch_size = 32, epochs = 200) #PART 3 PREDICTING AND VISUALIZING THE TEST SET #Importing the test_Set test_set= pd.read_csv('Google_Stock_Price_Test.csv') real_stock_price = test_set.iloc[:,1:2].values #Getting the predicted Stock Prices of 2017 inputs = real_stock_price inputs = sc.transform(inputs) inputs = np.reshape(inputs, (20,1,1)) predicted_stock_price = regressor.predict(inputs) predicted_stock_price = sc.inverse_transform(predicted_stock_price) #Visualizing the Stock Prices plt.plot(real_stock_price, color = 'red', label = 'Real Stock Price') plt.plot(predicted_stock_price , color = 'blue', label = 'Predicted Stock Price') plt.title('Google Stock Price Predictions') plt.xlabel('Time') plt.ylabel('Google Stock Price') plt.legend() plt.show() #PART 4 EVALUATING THE RNN import math from sklearn.metrics import mean_squared_error rmse = math.sqrt(mean_squared_error(real_stock_price, predicted_stock_price))
d199f3982f11b3c74a62f2ae3184acf486f990db
arren1234/Turtle-Race-Ultimate
/turtle race ultimate.py
2,403
3.75
4
import turtle #adds turtle functions import random #adds random functions t3 = turtle.Turtle() t1 = turtle.Turtle() t4 = turtle.Turtle() #adds turtles 3,1,4,6,7 t6 = turtle.Turtle() t7 = turtle.Turtle() wn = turtle.Screen() #adds screen t1.shape("turtle") t1.color("green") #colors and shapes bg and t1 wn.bgcolor("tan") t2 = turtle.Turtle() t2.shape("turtle")#adds shapes and colors turtle 2 t2.color("blue") t4.shape("turtle")#shapes and colors turtle 4 t4.color("yellow") t4.up() t1.up()#raises pen of turtle 1,2,6 and 4 t2.up() t6.up() t5 = turtle.Turtle() #adds shapes colors and lifts pen of turtle 5 t5.color("purple") t5.shape("turtle") t5.up() t6.color("black")#colors and shapes turtle 6 t6.shape("turtle") t7.color("orange")#colors shape a lifts pen of turtle 7 t7.shape("turtle") t7.up() t8 = turtle.Turtle() t8.color("grey")#adds colors shape a lifts pen of turtle 8 t8.shape("arrow") t8.up() t9 = turtle.Turtle() t9.shape("turtle")#adds colors shape a lifts pen of turtle 9 t9.color("pink") t9.up() t3.pensize(15) t3.color("red") t3.up() t3.goto(350,-500)#makes finish line using turtle 3 t3.lt(90) t3.down() t3.fd(1100) t1.goto(-350,20) t2.goto(-350,-20) t4.goto(-350,-60) t5.goto(-350, 60)#puts racers in starting position t6.goto(-350, 100) t7.goto(-350,-100) t8.goto(-1400,140) t9.goto(-350,-140) t1.speed(1) t2.speed(1) t4.speed(1)#sets racer speed t5.speed(1) t6.speed(1) t7.speed(1) t8.speed(1) t9.speed(1) for size in range(1000):#functions as endless loop t1.fd(random.randrange(30,70)) #t1 is a green turtle with the very consistent movement t2.fd(random.randrange(-20,120)) #t2 is a blue turtle with a slightly higher max but lower min t4.fd(random.randrange(10,90))#t4 is a a yellow turtle with a very slightly lower max and higher min t5.fd(random.randrange(0,100))#t5 is a purple turtle with standard stats t6.fd(random.randrange(-100,200))#t6 is a black turtle with a very high max and low min t7.rt(random.randrange(0,360))#t7 is an orange turtle with high max and normal low but random turns t7.fd(random.randrange(200,300)) t8.fd(150)#t8 is a grey space ship with a non random movement of a high 150 but starts much farther back t9.fd(random.randrange(-1000,1000))#t9 is a pink turtle with the most random movement with a max of 1000 and min of -1000
683d036de36a774b4c26ff328c0ab1c6aa722bbb
houjf/PycharmProjects
/进阶/字典.py
664
3.828125
4
# class Student(object): # def __init__(self, name, score): # self.__name = name # self.__score = score # # def print_score(self): # print('%s, %s'%(self.__name, self.__score)) # # def get_grade(self): # if self.__score > 90: # return print('A') # elif 90 > self.__score > 80: # return print('B') # elif 80 > self.__score > 60: # return print('C') # else: # print('C') # # student = Student('hello', 60) # student.print_score() # student.get_grade() # print(student.__name) # n = student.__score # print(n) add = lambda x,y:x*y b=add(2,6) print(b)
956d9f7797c6c5294ea475fc30cf8fec65ef0c3c
Vitoria0/Notepad
/Observações-07.py
440
3.921875
4
#Tratamento de Erros e Exceções try: #-------tente a = int(input('Numerador: ')) b = int(input('Dennominador: ')) r = a / b except ZeroDivisionError: print('Não se pode dividir por zero') except Exception as erro: print(f'O erro encontrado foi {erro.__cause__}') else: #------Se não der erro: print(f'O resultado é {r:.1f}') finally: #-------Finaliza com: print('Volte sempre!')
df86c8f38f511f08aa08938abba0c79875727eb9
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/conditionals/odd_even.py
234
4.46875
4
# Write a program that reads a number from the standard input, # then prints "Odd" if the number is odd, or "Even" if it is even. number = int(input("enter an integer: ")) if number % 2 == 0: print("Even") else: print("Odd")
39147e634f16988b71a0aee7d825d8e93def5359
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/user_input/average_of_input.py
316
4.34375
4
# Write a program that asks for 5 integers in a row, # then it should print the sum and the average of these numbers like: # # Sum: 22, Average: 4.4 sum = 0 number_of_numbers = 5 for x in range(number_of_numbers): sum += int(input("enter an integer: ")) print("sum:", sum, "average:", sum / number_of_numbers)
a314a1eef3981612f213986b9d261adaf2ff85ce
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_02/arrays/reverse_list.py
327
4.46875
4
# - Create a variable named `numbers` # with the following content: `[3, 4, 5, 6, 7]` # - Reverse the order of the elements of `numbers` # - Print the elements of the reversed `numbers` numbers = [3, 4, 5, 6, 7] temp = [] for i in range(len(numbers)): temp.append(numbers[len(numbers)-i-1]) numbers = temp print(numbers)
31170eab6926b9a475fe8fb1b7258571d762b96e
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_02/data_structures/list_introduction_1.py
1,247
4.78125
5
# # List introduction 1 # # We are going to play with lists. Feel free to use the built-in methods where # possible. # # - Create an empty list which will contain names (strings) # - Print out the number of elements in the list # - Add William to the list # - Print out whether the list is empty or not # - Add John to the list # - Add Amanda to the list # - Print out the number of elements in the list # - Print out the 3rd element # - Iterate through the list and print out each name # ```text # William # John # Amanda # ``` # - Iterate through the list and print # ```text # 1. William # 2. John # 3. Amanda # ``` # - Remove the 2nd element # - Iterate through the list in a reversed order and print out each name # ```text # Amanda # William # ``` # - Remove all elements names = [] print(len(names)) print() names.append("William") print(len(names)) print() print(len(names) == 0) print() names.append("John") names.append("Amanda") print(len(names)) print() print(names[2]) print() for name in names: print(name) print() for i in range(len(names)): print(i + 1, ".", names[i]) print() names.remove(names[1]) i = len(names) - 1 while i >= 0: print(names[i]) i -= 1 print() names[:] = []
e5da5de6c4ab02f17214140dfff12d23b5d9d4ba
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_03/oop/blog_post/blog_post.py
1,713
3.890625
4
# # BlogPost # # - Create a `BlogPost` class that has # - an `authorName` # - a `title` # - a `text` # - a `publicationDate` class BlogPost: def __init__(self, author_name, title, text, publication_date): self.author_name = author_name self.title = title self.text = text self.publication_date = publication_date # - Create a few blog post objects: # - "Lorem Ipsum" titled by John Doe posted at "2000.05.04." # - Lorem ipsum dolor sit amet. post1_text = "Lorem ipsum dolor sit amet." post1 = BlogPost("John Doe", "Lorem Ipsum", post1_text, "2000.05.04.") # - "Wait but why" titled by Tim Urban posted at "2010.10.10." # - A popular long-form, stick-figure-illustrated blog about almost # everything. post2_text = "A popular long-form, stick-figure-illustrated blog about almost everything." post2 = BlogPost("Tim Urban", "Wait but why", post2_text, "2010.10.10.") # - "One Engineer Is Trying to Get IBM to Reckon With Trump" titled by William # Turton at "2017.03.28." # - Daniel Hanley, a cybersecurity engineer at IBM, doesn’t want to be the # center of attention. When I asked to take his picture outside one of IBM’s # New York City offices, he told me that he wasn’t really into the whole # organizer profile thing. post3_text = "Daniel Hanley, a cybersecurity engineer at IBM, doesn’t want to be the center of attention. When I " \ "asked to take his picture outside one of IBM’sNew York City offices, he told me that he wasn’t really " \ "into the wholeorganizer profile thing. " post3 = BlogPost("William Turton", "One Engineer Is Trying to Get IBM to Reckon With Trump", post3_text, "2017.03.28.")
e10add30914bc94d9ce15807c45746ad49175d5b
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_03/oop/pokemon/pokemon.py
1,164
4
4
class Pokemon(object): def __init__(self, name, type, effective_against): self.name = name self.type = type self.effectiveAgainst = effective_against def is_effective_against(self, another_pokemon): return self.effectiveAgainst == another_pokemon.type def initialize_pokemons(): pokemon = [] pokemon.append(Pokemon("Bulbasaur", "grass", "water")) pokemon.append(Pokemon("Pikachu", "electric", "water")) pokemon.append(Pokemon("Charizard", "fire", "grass")) pokemon.append(Pokemon("Pidgeot", "flying", "fighting")) pokemon.append(Pokemon("Kingler", "water", "fire")) return pokemon pokemons = initialize_pokemons() # Every pokemon has a name and a type. # Certain types are effective against others, e.g. water is effective against fire. def choose(pokemon_list, opponent): for pokemon in pokemon_list: if pokemon.is_effective_against(opponent): return pokemon.name # Ash has a few pokemon. # A wild pokemon appeared! wild_pokemon = Pokemon("Oddish", "grass", "water") # Which pokemon should Ash use? print("I choose you, " + choose(pokemons, wild_pokemon))
238f272124f13645a7e58e8de1aaee8d9a433967
green-fox-academy/hanzs_solo
/Foundation/week_02-week_04/PythonBasicsProject/week_02/expressions_and_control_flow/loops/count_from_to.py
634
4.28125
4
# Create a program that asks for two numbers # If the second number is not bigger than the first one it should print: # "The second number should be bigger" # # If it is bigger it should count from the first number to the second by one # # example: # # first number: 3, second number: 6, should print: # # 3 # 4 # 5 a = -999 b = -1999 while a > b: if a != -999: print("\nthe second number should be bigger") a = int(input("gimme a number to count from: ")) b = int(input("gimme a number to count to: ")) while a < b: print(a) a += 1 # for x in range(b): # if x < a: # continue # print(x)
ca2c31265c491c989bdd6b34fb2e66f05614750f
ec36339/evescripts
/evepraisal.py
2,223
4.03125
4
""" Convert JSON output from https://evepraisal.com/ into CSV data that can be pasted into Excel. The script arranges the output in the same order as the input list of items, so the price data can be easily combined with existing data already in the spreadsheet (such as average prices, market volume, etc.) It requires two input files: - items.txt: List of items (one item name per line) - prices.json: JSON output from https://evepraisal.com/ Usage: 1. Copy the item list from your spreadsheet (usually a column containing item names) 2. Paste the item list into items.txt 3. Paste the item list into https://evepraisal.com/ 4. Export the data from https://evepraisal.com/ as JSON and paste it into prices.json 5. Run this script 6. Paste the output into your spreadsheet. Note: If you misspelled an item name, then its buy and sell price will be listed as zero. """ import json def make_price(price): """ Convert an ISK price (float) to a format acceptable by Excel :param price: Float ISK price :return: ISK price as Excel string """ return ('%s' % price).replace('.', ',') def print_csv(name, buy, sell): """ Print a row for an Excel sheet :param name: Name of item :param buy: Float buy order ISK price :param sell: Float sell order ISK price :return: ISK price as tab-separated Excel row """ print("%s\t%s\t%s" % (name, make_price(buy), make_price(sell))) def main(): # Load list of items (copy column from Excel sheet) with open('items.txt') as f: items = [l.split('\n')[0] for l in f.readlines()] # Load price data (export JSON from evepraisal.com after pasting same item list) with open('prices.json') as f: j = json.load(f) # Arrange prices in lookup table by item name item_db = {i['name']: i['prices'] for i in j['items']} # Print item data as Excel row with items in same order as original item list. for i in items: found = item_db.get(i) if found is not None: print_csv(i, found['buy']['max'], found['sell']['min']) else: print_csv(i, 0, 0) if __name__ == '__main__': main()
eacc98d8a0ccf38be757c6693c93ebdaf33848c1
carrillobenjamin/Carrillo_B_Dataviz
/data/medalprogress.py
484
3.5
4
import matplotlib.pyplot as plt years = [1924, 1928, 1932, 1936, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1994, 1998, 2002, 2006, 2010, 2014] medals = [9, 12, 20, 13, 20, 17, 20, 21, 7, 20, 1, 3, 2, 4, 6, 37, 40, 49, 75, 68, 91, 90] plt.plot(years, medals, color=(255/255, 100/255, 100/255), linewidth=5.0) plt.ylabel("Medals Won") plt.xlabel("Competition Year") plt.title("Canada's Medal Progression 1924-2014", pad=20) # show the chart plt.show()
598836e5e5920d1ba4c73c4e4b9e143690a0af95
Lord-Chronos/DoorBellBotPlus
/tictactoe.py
970
3.953125
4
def game(player1, player2): turn = 1 game_over = False start_board = ('```' ' 1 | 2 | 3 \n' ' - + - + - \n' ' 4 | 5 | 6 \n' ' - + - + - \n' ' 7 | 8 | 9 ' '```') while not game_over: current_board = '' if turn == 1: current_board = start_board print_game(current_board, turn) if turn % 2 == 0: print('hello player2') else: print('hello player1') board_update(current_board, next_move) print(board) def print_game(current_board, turn): print('Turn: ' + turn + '\n\n' + current_board) def board_update(current_board, next_move): new_board = '' return new_board def print_board(): return ('``` | | \n' ' - + - + - \n' ' | | \n' ' - + - + - \n' ' | | \n```')
99dc9f1f0571c4511567a1d5e6bd83d2e7ab2a96
Vitor-Aguiar/TheTools
/Wordlist-Gen.py
1,436
3.796875
4
import os import sys # -t @,%^ # Specifies a pattern, eg: @@god@@@@ where the only the @'s, ,'s, # %'s, and ^'s will change. # @ will insert lower case characters # , will insert upper case characters # % will insert numbers # ^ will insert symbols if len(sys.argv) != 3: print "Usage: python gen.py word wordlist.txt" sys.exit() word = sys.argv[1] wordlist = sys.argv[2] masks = [word+"^%" , word+"^%%" , word+"^%%%" , word+"^%%%%" , #word+"^%%%%%" , word+"^%%%%%%" , word+"%^" , word+"%%^" , word+"%%%^" , word+"%%%%^" , #word+"%%%%%^" , word+"%%%%%%^" , "^%"+word , "^%%"+word , "^%%%"+word , "^%%%%"+word , #"^%%%%%"+word , "^%%%%%%"+word , "%^"+word , "%%^"+word , "%%%^"+word , "%%%%^"+word , #"%%%%%^"+word , "%%%%%%^"+word "^"+word , word+"^" , "^"+word+"%" , "^"+word+"%%" , "^"+word+"%%%" , "^"+word+"%%%%" , # "^"+word+"%%%%%" , "%"+word+"^" , "%%"+word+"^" , "%%%"+word+"^" , "%%%%"+word+"^" , # "%%%%%"+word+"^" , word , word+"%" , word+"%%" , word+"%%%" , word+"%%%%" , "%"+word , "%%"+word , "%%%"+word , "%%%%"+word ] for n,mask in enumerate(masks): tamanho = str(len(mask)) comando = "crunch "+tamanho+" "+tamanho+" -t "+mask+" -o "+str(n)+wordlist+".txt" print "Comando: ",comando os.system(comando) os.system('cat *'+wordlist+'.txt >> '+wordlist+'_wordlist.txt') os.system('rm *'+wordlist+'.txt')
27a458c5355a32cf2bc9eb53cef586a8120e9e36
hr4official/python-basic
/td.py
840
4.53125
5
# nested list #my_list = ["mouse", [8, 4, 6], ['a']] #print(my_list[1]) # empty list my_list1 = [] # list of integers my_list2 = [1, 2, 3] # list with mixed datatypes my_list3 = [1, "Hello", 3.4] #slice lists my_list = ['p','r','o','g','r','a','m','i','z'] # elements 3rd to 5th print(my_list[2:5]) # elements beginning to 4th print(my_list[:-5]) # elements 6th to end print(my_list[5:]) # elements beginning to end print(my_list[:]) #We can add one item to a list using append() method or add several items using extend() method. #Here is an example to make a list with each item being increasing power of 2. pow2 = [2 ** x for x in range(10)] # Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] print(pow2) #This code is equivalent to pow2 = [] for x in range(10): pow2.append(2 ** x)
38277e97e74594103b4eb709affdbfb99d3c3457
hr4official/python-basic
/dict.py
544
4.09375
4
# empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'apple', 2: 'ball'} # dictionary with mixed keys my_dict = {'name': 'John', 1: [2, 4, 3]} # using dict() my_dict = dict({1:'apple', 2:'ball'}) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')]) """ marks = {}.fromkeys(['Math','English','Science'], 0) # Output: {'English': 0, 'Math': 0, 'Science': 0} print(marks) for item in marks.items(): print(item) # Output: ['English', 'Math', 'Science'] list(sorted(marks.keys())) """
8971b06f5b722e21f4f48faf778e4ffa758146a4
CircuitLaunch/colab_reachy_ros
/src/head_motor_control.py
4,983
3.6875
4
#!/usr/bin/env python3 # creates a ros node that controls two servo motors # on a arduino running ros serial # this node accepts JointState which is # --------------- # would the datastructure look like # jointStateObj.name = ["neck_yaw", "neck_tilt"] # jointStateObj.position = [180,0] # jointStateObj.velocity# unused # jointStateObj.effort#unused # --------------- # by oran collins # github.com/wisehackermonkey # [email protected] # 20210307 import rospy import math from std_msgs.msg import UInt16 # from sensor_msgs.msg import JointState from trajectory_msgs.msg import JointTrajectory from trajectory_msgs.msg import JointTrajectoryPoint global yaw_servo global tilt_servo global sub global yaw_servo_position global tilt_servo_position # standard delay between moving the joints DELAY = 1.0 # setting up interger variables # the arduino only accepts integers yaw_servo_position = UInt16() tilt_servo_position = UInt16() yaw_min = 0 # in degrees from x to y angles are accepted positions yaw_max = 360 tilt_min = 75 tilt_max = 115 # helper function # keeps the input number between a high and alow def constrain(input: float, low: float, high: float) -> float: """ input: radian float an number to be constrained to a range low<-> high low: radian float minimum value the input can be high: radian float maximum value the input can be """ return max(min(input, high), low) def move_servos(msg: JointTrajectoryPoint) -> None: print(msg) print(msg.positions[0]) print(msg.positions[1]) yaw_degrees = constrain(math.degrees(msg.positions[0]), yaw_min, yaw_max) tilt_degrees = constrain(math.degrees(msg.positions[1]), tilt_min, tilt_max) print("Yaw: ", yaw_degrees, "tilt: ", tilt_degrees) # convert float angle radians -pi/2 to pi/2 to integer degrees 0-180 yaw_servo_position.data = int(yaw_degrees) tilt_servo_position.data = int(tilt_degrees) # send an int angle to move the servo position to 0-180 yaw_servo.publish(yaw_servo_position) tilt_servo.publish(tilt_servo_position) # im only dulpicating this one betcause i cant think in radians and its a identical function to the one above # exept i dont convert to degrees from radians def move_servos_degrees_debug(msg: JointTrajectoryPoint) -> None: print(msg) print(msg.positions[0]) print(msg.positions[1]) yaw_degrees = constrain((msg.positions[0]), yaw_min, yaw_max) tilt_degrees = constrain((msg.positions[1]), tilt_min, tilt_max) print("Yaw: ", yaw_degrees, "tilt: ", tilt_degrees) # convert float angle radians -pi/2 to pi/2 to integer degrees 0-180 yaw_servo_position.data = int(yaw_degrees) tilt_servo_position.data = int(tilt_degrees) # send an int angle to move the servo position to 0-180 yaw_servo.publish(yaw_servo_position) tilt_servo.publish(tilt_servo_position) # runs though all the JointTrajectoryPoint's inside a JointTrajectory # which basically runs though an array of angles for each of the joints in this case # a joint is a servo motor (and a diamixel motor for the antenna) # and waits `DELAY` time before setting the motors to go to the next position def process_positions(msg: JointTrajectory) -> None: print(msg) for joint_point in msg.points: print("Here") move_servos(joint_point) rospy.sleep(DELAY) def process_positions_debug_degrees(msg: JointTrajectory) -> None: print(msg) for joint_point in msg.points: print("Here") move_servos_degrees_debug(joint_point) rospy.sleep(DELAY) if __name__ == "__main__": rospy.init_node("position_animator_node") # setup topics to control into arduino servo angles # publishing a integer between angle 0-180 /servo1 or /servo2 yaw_servo = rospy.Publisher("/head/neck_pan_goal", UInt16, queue_size=1) tilt_servo = rospy.Publisher("/head/neck_tilt_goal", UInt16, queue_size=1) # waiting for a JointState data on the topic "/move_head" # example data # DOCS for joint state # http://wiki.ros.org/joint_state_publisher # Data format # http://docs.ros.org/en/api/sensor_msgs/html/msg/JointState.html # Header headerx # string[] name <- optional # float64[] position # float64[] velocity # float64[] effort # rostopic pub /move_head "/{header:{}, name: ['servo1', 'servo2'], position: [0.5, 0.5], velocity:[], effort:[]}"" sub = rospy.Subscriber("/head/position_animator", JointTrajectory, process_positions) sub = rospy.Subscriber("/head/position_animator_debug_degrees", JointTrajectory, process_positions_debug_degrees) sub = rospy.Subscriber("/head/position_animator/debug_point", JointTrajectoryPoint, move_servos) sub = rospy.Subscriber( "/head/position_animator/debug_point_degrees", JointTrajectoryPoint, move_servos_degrees_debug ) rate = rospy.Rate(10) print("servo_mover: Running") while not rospy.is_shutdown(): rate.sleep()
03ffdbf920e309ebb68d396e033b44d8848a6952
bk2coady/ProjectEuler
/ProjectEulerS1.py
499
4.03125
4
#Problem1 #Find sum of all numbers which are multiples of more than one value (ie 3 and 5) #remember to not double-count numbers that are multiples of both 3 and 5 (ie multiples of 15) def sumofmultiples(value, max_value): total = 0 for i in range(1,max_value): if i % value == 0: #print(i) total = total+i #print(total) return total upto = 1000 cumulative_total = sumofmultiples(3,upto) + sumofmultiples(5,upto) - sumofmultiples(15,upto) print(cumulative_total)
6d09a3651b149aad6a6d4c96626062b969ca88db
bk2coady/ProjectEuler
/ProjectEulerS9.py
444
3.890625
4
#Problem9 #find pythagorean triplet where a + b + c = 1000 def pythag_check(a, b): c = (a*a + b*b) ** 0.5 #print(c) if c == int(c): return True return False def pythag_triplet(k): for i in range(1,k-1): for j in range(1,k-i): if pythag_check(i,j): c = int((i*i + j*j) ** 0.5) if i + j + c == k: return i+j+c, i, j, c, i*j*c return False print(pythag_check(3, 4)) print(pythag_triplet(1_000))
c0355b2269c01bed993270e4472d1771ffab9527
sharikgrg/week3.Python-Theory
/104_data_type_casting.py
316
4.25
4
# casting # casting is when you change an object data type to a specific data type #string to integer my_var = '10' print(type(my_var)) my_casted_var = int(my_var) print(type(my_casted_var)) # Integer/Floats to string my_int_vaar = 14 my_casted_str = str(my_int_vaar) print('my_casted_str:', type(my_casted_str))
cff7d4a762f14e761f3c3c46c2e656f74cb19403
sharikgrg/week3.Python-Theory
/exercises/exercise1.py
745
4.375
4
# Define the following variable # name, last name, age, eye_colour, hair_colour # Prompt user for input and reassign these # Print them back to the user as conversation # Eg: Hello Jack! Welcome, your age is 26, you eyes are green and your hair_colour are grey name = input('What is your name?') last_name = input('What is your surname?') age = int(input('What is your age?')) eye_colour = input('What is the colour of your eye?') hair_colour = input('What is the colour of your hair?') print('Hello',name.capitalize(), f'{last_name.capitalize()}!', 'Welcome, your age is', f'{age},', 'your eyes are', eye_colour, 'and your hair is', hair_colour) print(f'Hello {name} {last_name}, Welcome!, your age is') print('You were born in', 2019 - age)
cda99da103298b6c26c29b9083038a732826be11
sharikgrg/week3.Python-Theory
/102_data_types.py
1,736
4.5
4
# Numerical Data Types # - Int, long, float, complex # These are numerical data types which we can use numerical operators. # Complex and long we don't use as much # complex brings an imaginary type of number # long - are integers of unlimited size # Floats # int - stmads for integers # Whole numbers my_int = 20 print(my_int) print(type(my_int)) # Operator - Add, Subtract, multiply and devide print(4+3) print(4-3) print(4/2) # decimals get automatically converted to float print(4//2) # keeps it as integer/ drops the decimal print(4*2) print(3**2) # square # Modules looks for the number of remainder # % # print(10%3) ## --> 3*3 =9, so 1 is the remainder # Comparison Operators ## --> boolean value # < / > - Bigger and Smaller than # <= - Smaller than or equal # >= Bigger than or equal # != Not equal # is and is not my_variable1 = 10 my_variable2 = 13 # example of using operators print(my_variable1== my_variable2) # output is false print(my_variable1 > my_variable2) print(my_variable1 < my_variable2) print(my_variable1 >= my_variable2) print(my_variable1 != my_variable2) print(my_variable1 is my_variable2) print(my_variable1 is not my_variable2) # Boolean Values # Define by either True or False print(type(True)) print(type(False)) print (0 == False) print(1 == True) ## None print(None) print(type(None)) print(bool(None)) #Logical And & Or a = True b = False print('Logical and & or -------') # Using *and* both sides have to be true for it to result in true print(a and True) print((1==1) and (True)) print((1==1) and False) #Use or only one side needs to be true print('this will print true-----') print(True or False) print(True or 1==2) print('this will print false -----------') print(False or 1==2)
d42b8c1bfab1011862b843d6166ee0bb41f857b8
pranjay04/algorithms-and-data-structures
/search/python/binarysearch_rec.py
393
3.796875
4
def binarysearch_rec(array, key): l = 0 h = len(array) - 1 def search(array, l, h, key): if l > h: return False mid = (l + h)//2 if array[mid] == key: return mid if key < array[mid]: h = mid - 1 else: l = mid + 1 return search(array, l, h, key) return search(array, l, h, key)
f56178664ed321ef7b8ad9a3696f5fe7cf0cee10
clarkmyfancy/Hangman
/Console.py
1,033
3.703125
4
class Console: def printStartupSequence(self): print("Let's play Hangman!") def printScoreboardFor(self, game): word = game.secretWord isLetterRevealed = game.lettersRevealed outputString = "" for x in range(0, len(word)): outputString += word[x] if isLetterRevealed[x] == True else "_" outputString += ' ' print(outputString) print("\n") def printGuessedLettersFor(self, game): for i, x in enumerate(game.guessedLetters): if i == len(game.guessedLetters) - 1: print(x) print() else: print(x + " ", end="") def retrieveGuessFrom(self, player): print(player.name + ", enter guess: ") def printGuessFor(self, player): print(str(player.name) + " guessed: " + player.currentGuess) def printStatusFor(self, player, game): context = "Incorrect guesses left for " print(context + player.name + ": " + str(game.wrongGuessesLeft)) def printGameOverMessageFor(self, player): print("And that's it, \'" + player.name + "\' is out of guesses.") print(player.name + ", Game Over")
a826b8384e312b2ccfdeb01f0d84446870734b5c
knutss/PyWake
/py_wake/deflection_models/deflection_model.py
1,068
3.5
4
from abc import ABC, abstractmethod class DeflectionModel(ABC): args4deflection = ["ct_ilk"] @abstractmethod def calc_deflection(self, dw_ijl, hcw_ijl, dh_ijl, **kwargs): """Calculate deflection This method must be overridden by subclass Arguments required by this method must be added to the class list args4deflection See documentation of EngineeringWindFarmModel for a list of available input arguments Returns ------- dw_ijlk : array_like downwind distance from source wind turbine(i) to destination wind turbine/site (j) for all wind direction (l) and wind speed (k) hcw_ijlk : array_like horizontal crosswind distance from source wind turbine(i) to destination wind turbine/site (j) for all wind direction (l) and wind speed (k) dh_ijlk : array_like vertical distance from source wind turbine(i) to destination wind turbine/site (j) for all wind direction (l) and wind speed (k) """
4173a8b376cb1c007c103999e1f352299bb8f810
TeresaRem/CodingDojo
/Python/selectionSort.py
829
3.84375
4
## selectionSort.py import random, datetime def selectionSort(arr): a = datetime.datetime.now() min = arr[0] start = 0 for i in range(0,len(arr)-1): for j in range(start,len(arr)): if arr[j] < min: min = arr[j] index = j # print "current minimum is {} at index {}".format(min,index) if arr[start] > min: temp = arr[start] arr[start] = arr[index] arr[index] = temp # print "swap {} and {}".format(arr[index],arr[start]) # print "array is:" # print arr start+=1 min = arr[start] b = datetime.datetime.now() time = b - a print "{} seconds".format(time.total_seconds()) return arr # selectionSort([6,5,3,1,8,7,2,4]) def randomArr(): # create random array arr = [] for i in range(1000): arr.append(random.randint(0,10000)) return arr hundred = randomArr() selectionSort(hundred)
54ce45e8ca61bcdbe1df2a33b3abf1250dac665a
TeresaRem/CodingDojo
/Python/animal.py
1,006
3.890625
4
# animal.py class Animal(object): def __init__(self,name): self.name = name self.health = 100 def walk(self): self.health -= 1 return self def run(self): self.health -= 5 return self def displayHealth(self): print "name is {}".format(self.name) print "health is {}".format(self.health) return self animal = Animal('animal').walk().walk().walk().run().run().displayHealth() class Dog(Animal): def __init__(self,name): super(Dog,self).__init__(self) self.health = 150 self.name = name def pet(self): self.health += 5 return self dog = Dog('dog').walk().walk().walk().run().run().pet().displayHealth() class Dragon(Animal): def __init__(self,name): super(Dragon,self).__init__(self) self.health = 170 self.name = name def fly(self): self.health -= 10 return self def displayHealth(self): print "this is a dragon!" super(Dragon,self).displayHealth() return self dragon = Dragon('dragon').walk().walk().walk().run().run().fly().fly().displayHealth()
a0cd809b0d43cbb95f2e80b7459959e23c76d4c2
TeresaRem/CodingDojo
/pylot/restful_routes/app/models/Product.py
1,414
3.703125
4
from system.core.model import Model class Product(Model): def __init__(self): super(Product, self).__init__() """ Below is an example of a model method that queries the database for all users in a fictitious application Every model has access to the "self.db.query_db" method which allows you to interact with the database """ def get_products(self): query = "SELECT * from products" return self.db.query_db(query) def get_product(self, id): query = "SELECT * from products where id = :id" data = {'id': id} return self.db.get_one(query, data) def add_product(self, data): if data['price'].isdecimal(): sql = "INSERT into products (name, description, price) values(:name, :description, :price)" self.db.query_db(sql, data) return True else: return False def update_product(self, data): if data['price'].isdecimal(): query = '''UPDATE products SET name=:name, description=:description, price=:price WHERE id = :id''' self.db.query_db(query, data) return True else: return False def destroy_product(self, id): query = "DELETE FROM products WHERE id = :id" data = {'id' : id} return self.db.query_db(query, data)
e9d15c1e46656bbed8240b591c5c848d6bc13dcf
TeresaRem/CodingDojo
/pylot/login/app/controllers/Users.py
3,002
4.125
4
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from system.core.controller import * class Users(Controller): def __init__(self, action): super(Users, self).__init__(action) """ This is an example of loading a model. Every controller has access to the load_model method. """ self.load_model('User') self.db = self._app.db """ This is an example of a controller method that will load a view for the client """ def index(self): """ A loaded model is accessible through the models attribute self.models['WelcomeModel'].get_users() self.models['WelcomeModel'].add_message() # messages = self.models['WelcomeModel'].grab_messages() # user = self.models['WelcomeModel'].get_user() # to pass information on to a view it's the same as it was with Flask # return self.load_view('index.html', messages=messages, user=user) """ return self.load_view('index.html') def success(self): return self.load_view('success.html') def register(self): data = { "first_name" : request.form['first_name'], "last_name" : request.form['last_name'], "email" : request.form['email'], "password" : request.form['password'], "confirm" : request.form['confirm'] } # call create_user method from model and write some logic based on the returned value # notice how we passed the user_info to our model method create_status = self.models['User'].create_user(data) if create_status['status'] == True: # the user should have been created in the model # we can set the newly-created users id and name to session session['id'] = create_status['user']['id'] session['first_name'] = create_status['user']['first_name'] # we can redirect to the users profile page here return redirect('/success') else: # set flashed error messages here from the error messages we returned from the Model for message in create_status['errors']: flash(message, 'regis_errors') # redirect to the method that renders the form return redirect('/') def login(self): data = request.form user = self.models['User'].login_user(data) if not user: flash("Your login information is incorrect. Please try again.") return redirect('/') session['id'] = user['id'] session['first_name'] = user['first_name'] return redirect('/success') def logout(self): session.clear() return redirect('/')
5cba492f9034b07ca9bc7d266dca716ea684ba3c
sdhanendra/coding_practice
/DataStructures/linkedlist/linkedlist_classtest.py
1,647
4.5
4
# This program is to test the LinkedList class from DataStructures.linkedlist.linkedlist_class import LinkedList def main(): ll = LinkedList() # Insert 10 nodes in linked list print('linked list with 10 elements') for i in range(10): ll.insert_node_at_end(i) ll.print_list() # delete three nodes at the end in the linked list print('\ndelete last three elements') for i in range(3): ll.delete_node_at_end() ll.print_list() # insert a node at the Head print('\ninsert a node at head') ll.insert_node_at_head(10) ll.print_list() # delete a node at the Head print('\ndelete a node from head') ll.delete_node_at_head() ll.print_list() # Insert a node 20 after node 2 print('\ninsert a node after a given node') ll.insert_node_after_give_node(20, 2) ll.print_list() # delete the node 20 print('\ndelete a given node') ll.delete_given_node(20) ll.print_list() # search for node 4 in the linked list print('\nsearch for a node in linked list') ll.search_node(4) # sum all elements of the linked list print('\nsum all elements of a linked list') elem_sum = ll.sum_all_elements() print('Sum of the linked list: {}'.format(elem_sum)) # count the number of nodes in the linked list print('\ncount the number of elements of a linked list') num_nodes = ll.count_nodes() print('Total number of nodes in linked list: {}'.format(num_nodes)) # reverse a linked list print('\nreverse a linked list') ll.reverse_list() ll.print_list() if __name__ == '__main__': main()
518b0d4700b932388532ed42c21614a78006015c
jaxmandev/Python_OOP
/python.py
815
4.09375
4
# Creating a python class as child class of our Snake class from snake import Snake class Python(Snake): def __init__(self): super().__init__() self.large = True self.two_lungs = True self.venom = False # creating functions for our python class def digest_large_prey(self): return " Yum Yummyyy...." def clim(self): return "up we go....." def shed_skin(self): return "time to grow up.... fast......myself!" python_object = Python() # creating an object of our python class print(python_object.breathe()) # function from our Animal class print(python_object.hunt()) # function from our Reptile class print(python_object.use_venum())# fucntion from our Snake class print(python_object.shed_skin()) # function from our python class
058dc3932000b0d290652ff758d3d8653ac1c5f5
GIS-PuppetMaster/EVO-TSP
/Selection.py
2,796
3.78125
4
from math import * import random import copy def fitnessProportional(problem, population): """ # because our fitness is the distance of the traveling salesman # so we need to replace 'fitness' with '1/fitness' to make sure the better individual # get greater chance to be selected :param problem: the problem to be solved :param population: the population :return: new population after selection """ sum = 0 new_population = [] for i in population: sum += 1 / fitness(problem, i) for i in population: pro = (1 / fitness(problem, i)) / sum flag = random.uniform(0, 1) if flag <= pro: new_population.append(i) return new_population def fitness(problem, individual): """ calculate fitness :param problem: problem graph :param individuals: an individual :return: fitness """ graph = problem.getGraph() last_city = None dis = 0 for city in individual.solution: if last_city is not None: cor1 = graph[city] cor2 = graph[last_city] dis += sqrt(pow((cor1[0] - cor2[0]), 2) + pow((cor1[1] - cor2[1]), 2)) last_city = city # calculate go back distance cor1 = graph[last_city] cor2 = graph[individual.solution[0]] dis += sqrt(pow((cor1[0] - cor2[0]), 2) + pow((cor1[1] - cor2[1]), 2)) return dis def tournamentSelection(problem, population, unit, number): """ :param problem: the problem to solve :param population: the population for selection ,[Individuals] :param unit: how many individuals to sample at once :param number: how many individuals to return :return: new population """ new_population = [] i = 1 while i < number: samples = random.sample(population, unit) min_fitness = 1e20 best_sample = None for sample in samples: f = fitness(problem, sample) if f < min_fitness: min_fitness = f best_sample = sample if best_sample not in new_population: new_population.append(best_sample) else: # prevent repeat reference new_population.append(copy.deepcopy(best_sample)) i += 1 return new_population def elitismSelection(problem, population): """ return the best fitness individual, which won't mutate and cross :param problem: the problem to solve :param population: the population for selection ,[Individuals] :return: the best fitness individual """ best = None min_fitness = 1e20 for individual in population: f = fitness(problem, individual) if f <= min_fitness: min_fitness = f best = individual return best
804ebb78ded35b6817a5a1a32b15f8bfa7b0605a
tonimk/testi
/myscript.py
814
3.8125
4
# Kommentti esimerkin vuoksi tähän def inputNumber(message): while True: try: userInput = int(input(message)) except ValueError: print("Anna ikä kokonaislukuna, kiitos!") continue else: return userInput break i = 0 while i < 3: nimi = input("Anna nimesi: ") print("Sinä olet " + nimi) ikä = inputNumber("Anna ikäsi: ") print("Ikäsi on:",ikä) kaverikä = inputNumber("Kuinka vanha mielikuvituskaverisi on? ") if ikä > kaverikä: print("Sinä olet vanhempi") elif ikä < kaverikä: print("Kaveri on vanhempi") else: print("Olette yhtä vanhoja") i = i + 1 if i < 3: print("Tämä käydään vielä", 3 - i,"kertaa") else: print("Tämä\nohjelma\non\nnyt\nloppu")