blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
e58eae9f3603be7750ae6d25bd5d48dcd1510c3f
bulongo/Scraper
/deleter.py
1,218
4.1875
4
#This script is written to delete items from a file that are too #random and that would take a lot of time to select one at a time #so it will be fed a list and a target directory to look in. If the files #it is fed are in the directory then it will delete them.Else it will retur #none. #V 0.01 import os,sys one,two,*three = sys.argv target = input("Enter your target folder: ") #three is a list of all the items that you will give as arguments i.e. the items #you want the script to check for in your target folder and deletes #review: make it easier to identify files in later versions e.g. give it a folder #of items it should store and then use the list it stores as arguments for the #removal in the target directory os.chdir(target) #need to add absolute path to this '''for items in three: #the for loop is not finding the items in os.getcwd,think B if items in os.getcwd(): print(items)''' #we will use os.walk for now check = [] def get_items(): for i,j,k in os.walk("./"): for items in k: check.append(items) get_items() for items in check: if two == items: os.remove(two) print(two + " removed") #deletes items. It works....but why?!
7c0d52d8a08f4bf917f654a0f918ae787bc5664b
avallbona/python-crash-course
/comprehension_list.py
1,193
3.890625
4
def is_prime(value): primes = {1, 2, 3, 5, 7} return value in primes print("lista") some_list = [element + 5 for element in range(10) if is_prime(element)] print(some_list) print("diccionario") results = {element: element + 5 for element in range(10) if is_prime(element)} print(results) print("diccionario2 refactored") results2 = {element: element + 5 for element in range(10) if element in (1, 2, 3, 5, 7)} print(results2) print("generador") some_list2 = (element + 5 for element in range(10) if is_prime(element)) print(type(some_list2)) print(some_list2) # print(next(some_list2)) # print(next(some_list2)) # for it in some_list2: # print(it) print(list(some_list2)) print("operaciones") def apply_operation(left_operand, right_operand, operator): import operator as op operator_mapper = {"+": op.add, "-": op.sub, "*": op.mul, "/": op.truediv} try: return operator_mapper[operator](left_operand, right_operand) except KeyError: return "Unrecognized operation" print(apply_operation(2, 3, "+")) print(apply_operation(2, 3, "-")) print(apply_operation(2, 3, "*")) print(apply_operation(2, 3, "/")) print(apply_operation(2, 3, "."))
221bb16f7517aa2c350773f5839d8cce3eceaf88
lightening0907/algorithm
/treeprint.py
1,124
3.65625
4
__author__ = 'ChiYuan' class treenode: def __init__(self,value): self.left = None self.right = None self.value = value def treeprint(root): q_par = [] q_par.append(root) q_child = [] order = 1 while len(q_par)>0: while len(q_par)>0: if order == 1: if q_par[-1].left: q_child.append(q_par[-1].left) if q_par[-1].right: q_child.append(q_par[-1].right) print(q_par[-1].value,end="") del q_par[-1] else: if q_par[-1].right: q_child.append(q_par[-1].right) if q_par[-1].left: q_child.append(q_par[-1].left) print(q_par[-1].value,end="") del q_par[-1] print("\n") order *= -1 q_par, q_child = q_child, q_par tr = treenode(5) tr2 = treenode(7) tr3 = treenode(8) tr4 = treenode(1) tr5 = treenode(10) tr6 = treenode(2) tr7 = treenode(3) tr.left = tr2 tr.right = tr3 tr2.left =tr4 tr3.right = tr5 tr2.right = tr6 tr3.left = tr7 treeprint(tr)
c9d9b87fcd9464fe32f6ced2f0a3281e7ade9d2c
gmlwhd2092/haedal
/a.py
723
3.6875
4
class soccer: soccer_count = 0 def __init__(self, name, position, club, country): self.name = name self.position = position self.club = club self.country = country soccer.soccer_count += 1 def info(self): print(f'축구선수: {self.name}') print(f'포지션: {self.position}') print(f'소속팀: {self.club}') print(f'국: {self.country}') print() soccer1 = soccer("호날두", "공격수", "유벤투스", "포르투칼") soccer2 = soccer("메시", "미드필더", "바르셀로나", "아르헨티나") soccer3 = soccer("반다이크", "수비수", "리버풀", "네덜란드") soccer1.info() soccer2.info() soccer3.info()
107ddc75e1d9ae6838ea5952db496a9c1d67f45e
fitigf15/PYTHON-VICTOR
/Algorismica avançada - UB/Pau/(ALGA)Algorismica avançada/(ALGA)Algorismica avançada/practica11.py
1,294
3.5625
4
import networkx as nx def llegir_graf(): '''lee el grafo de un fichero de texto''' global Grafo Grafo = nx.Graph() nom = raw_input("Doneu el nom del graf: ") Grafo = nx.read_adjlist(nom,create_using=nx.DiGraph(),nodetype = int) def crea_mat_adj(): global mat_adj mat_adj = [] num_nodes = Grafo.number_of_nodes() #mat_adj = [range(number_of_nodes) for i in range(number_of_nodes)] for i in range(num_nodes): mat_adj.append([]) for j in range(num_nodes): mat_adj[i].append(0) def busca_ciclo(origen): mat_adj[origen-1][origen-1] = 1 #Marcamos el nodo origen como visitado #print mat_adj #mat_adj[0][2]= 1 vecinos = Grafo.neighbors(origen) print "Nodo: ",origen,": vecinos: ", vecinos if vecinos != []: for i in range(len(vecinos)): if mat_adj[origen-1][vecinos[i]-1]!=1: print "ESTA VISITADO? : ", origen-1," ", vecinos[i]-1 mat_adj[origen-1][vecinos[i]-1] = 1 print "vecinos[i]-1: ", vecinos[i]-1 return busca_ciclo(vecinos[i]) else: print "Vuelve hacia atras!!" return origen-2 llegir_graf() crea_mat_adj() busca_ciclo(1) print mat_adj #print Grafo.nodes() #print Grafo.edges()
03f45ff2ff6391bd8680cc2d35b6b059cc0d0280
IrtazaChohan/Python_Essentials
/lists2.py
254
3.6875
4
student_grades = [9.1, 8.8, 7.5] dir(list) dir(int) # shows the builtin functions of python..like print etc dir(__builtins__) # find the average using number of items in list mysum = (sum(student_grades)) / len(student_grades) print(mysum) dir(len)
743d45975b5db721890246d70b650620bd9f0869
pazodilei/Smart_Calculator
/Problems/Palindrome/main.py
142
4.0625
4
word = input() if word == ''.join([word[i] for i in range(len(word) - 1, -1, -1)]): print("Palindrome") else: print("Not palindrome")
918f599630a4b3a3caa6278bc8902f1e1942fcf5
parivgabriela/Coursera
/Python-DB/prueba-semana3.py
334
3.984375
4
import sqlite3 conn = sqlite3.connect(':memory:') cursor = conn.cursor() cursor.execute("""CREATE TABLE table_1 (ID integer primary key, name text)""") cursor.execute("INSERT INTO table_1 VALUES (1, 'prueba')") conn.commit() query = "SELECT * FROM table_1" currencies = cursor.execute(query).fetchall() print(currencies) conn.close()
5ab90c5c71ccce403e88c1022a8ced4afb55c2b6
enzodiaz25/Scrabble
/codigo/logica/check_palabra.py
7,190
3.828125
4
''' Versión de check_palabra según última modificación propuesta por la Cátedra. Se mantiene la valuación de palabras con tilde, puesto que es una mejora en las posibilidades del usuario. ''' import pattern.es as pes from pattern.es import verbs, tag, spelling, lexicon import itertools as it def posibles_palabras (palabra): ''' Por cada vocal que tenga la palabra seleccionada se genera una posibilidad con Tilde. Esto permite resolver el problema que, mientras pattern posee palabras con tilde, nuestra aplicación utiliza todas letras sin acentuación. Se genera una lista con posible opciones con tilde para que pattern las encuentre en sus diccionario de palabras. ''' lisPal = [] #siempre la primer palabra será la ingresada por el jugador lisPal.append(palabra) vocales = {'a':'á', 'e':'é', 'i':'í', 'o':'ó', 'u':'ú'} pos = [idx for idx, x in enumerate(palabra) if x in vocales.keys()] #le pongo tilde a esas vocales, y agrego la palabra for it in range(len(pos)): pal_temp = '' for it2 in range(len(palabra)): if it2 != pos[it]: pal_temp += palabra[it2] else: pal_temp += vocales[palabra[pos[it]]] lisPal.append(pal_temp) return lisPal def clasificar(palabra): print(tag(palabra, tokenize=True, encoding='utf-8', tagset='UNIVERSAL')) print() def es_palabra(palabra): ''' Evalua si la palabra recibida existe en los diccionarios de PATTERN.ES ''' ok = True if palabra: if not palabra.lower() in verbs: if not palabra.lower() in spelling: if (not (palabra.lower() in lexicon) and not (palabra.upper() in lexicon) and not ( palabra.capitalize() in lexicon)): ok = False else: print('La encontró en lexicon') clasificar(palabra) else: print('La encontró en spelling') clasificar(palabra) else: print('La encontró en verbs') clasificar(palabra) return ok def check_jugador(palabra, preferencias): ''' Recibe una palabra y verifica que sea un verbo, adjetivo o sustantivo, retorna True si es asi, o False en caso contrario. Este módulo asignará por defecto la dificultad en FÁCIL si no es indicada ''' dificultad = preferencias.getNivel() if len(palabra) >= 2: global TIPO posibles = posibles_palabras(palabra) ok = False cont = 0 #en cuanto encuentre una opcion que de 'True' dejara de comprobar e insertará esa while (not ok) and (cont < len(posibles)): pal = '' #La condición debe mantener este orden porque, de otro modo, es_palabra podría ejecutarse #en el nivel incorrecto. Si el nivel es difícil, es_palabra imprimirá la misma información 3 veces if (dificultad == 'facil') and es_palabra(posibles[cont]): pal = pes.parse(posibles[cont]).split('/') if pal[1] in TIPO['adj']: ok =True elif pal[1] in TIPO['sus']: ok= True elif pal[1] in TIPO['verb']: ok= True elif (dificultad == 'medio' or dificultad == 'dificil') and es_palabra(posibles[cont]): pal = pes.parse(posibles[cont]).split('/') if pal[1] in TIPO['adj']: ok =True elif pal[1] in TIPO['verb']: ok= True elif (dificultad == 'personalizado') and es_palabra(posibles[cont]): pal = pes.parse(posibles[cont]).split('/') for tipo_palabra in preferencias.getCategoriasPersonalizadas(): if pal[1] in TIPO[tipo_palabra]: ok =True break else: ok = False # print("se chequeo {} el contador es {} y ok esta en {}".format(pal,cont,ok)) cont += 1 else: return False return ok def check_compu(atril_pc, tablero, preferencias): dificultad = preferencias.getNivel() fichas_pc = atril_pc.ver_atril() letras = '' for ficha in fichas_pc: letras += list(ficha.keys())[0] palabras = set() for i in range(2, len(letras)+1): palabras.update(map(''.join, it.permutations(letras, i))) posibilidades = {} for pal in palabras: if check_jugador(pal, preferencias): fichas_pal = [] for letra in pal: for ficha in fichas_pc: if list(ficha.keys())[0] == letra: #Notar algo importante: A la primera aparición de una ficha que coincida con la letra que busca, #agrega la ficha a la lista. Esto es correcto; sin embargo es conveniente no olvidar que, #si una letra se repitiese y la bolsa contuviese referencias repetidas, se estaría agregando dos veces #la misma ficha a la lista (el mismo diccionario). En usos futuros, si se modificase una, también cambiaría la otra. #No sucede en la implementación actual, pero es importante tenerlo en cuenta. fichas_pal.append(ficha) break busqueda = tablero.buscarEspacio(fichas_pal, preferencias) if busqueda['coordenada'] != -1: busqueda['fichas'] = fichas_pal posibilidades[pal] = busqueda #En el modo "facil" y "medio", retorna la primer palabra que pueda validar y encontrarle un espacio. #En el modo "personalizado", dependerá de la configuración seleccionada por el usuario. if (dificultad == 'facil') or (dificultad == 'medio') or ((dificultad == 'personalizado') and not (preferencias.getIA()['palabra_inteligente'])): return posibilidades[pal], pal for clave, valor in posibilidades.items(): print(clave, ':', valor['interes']) print('') if len(posibilidades) > 0: mejor_opcion = max(posibilidades, key = lambda d: posibilidades[d]['interes']) print('La mejor opcion es: ' + mejor_opcion + '. En la coordenada ' + str(posibilidades[mejor_opcion]['coordenada'][0]) + ', ' + str(posibilidades[mejor_opcion]['coordenada'][1])) return posibilidades[mejor_opcion], mejor_opcion return posibilidades, letras '''TIPO sera una varible global que nos permite chequear que la palabra a ingresar, este dentro de las clasificaciones permitidas en el juego adj = adjetivo, sus= sustantivo, verb = verbos. Las clasificiaciones estan tomadas del modulo pattern, pero la construcción de este modulo facilita su comprobación. ''' TIPO= {'adj':["AO", "JJ","AQ","DI","DT"], 'sus':["NC", "NN", "NCS","NCP", "NNS","NP", "NNP","W"], 'verb':[ "VAG", "VBG", "VAI","VAN", "MD", "VAS" , "VMG" , "VMI", "VB", "VMM" ,"VMN" , "VMP", "VBN","VMS","VSG", "VSI","VSN", "VSP","VSS" ] }
ca6b42c11324f5d0a6967d5b4554eef518b75ebc
dede1751/tcp_chess
/board_gui.py
5,821
3.625
4
""" This module implements solely the gui elements of the chess game. It does not care for efficiency, implements no logic and simply allows the player to see and interact with the board. The board is a 1D vector, indexed from the top left to bottom right (A8,B8, ... , G1, H1). For more info check engine module. """ import sys import os os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" # avoid pygame prompt import pygame as pg from pygame.sprite import Sprite, Group import numpy as np import engine class Point(Sprite): """Pygame trick for mouse interaction with sprites""" def __init__(self, pos: tuple[int,int]) -> None: super().__init__() self.rect = pg.Rect(pos[0], pos[1], 1, 1) self.rect.center = pos class ChessPiece(Sprite): """ Chess piece sprite with simple tile movement. - ChessPiece.piece 8-bit integer representing the piece - ChessPiece.color 1-bit representing color - ChessPiece.last_tile memory for replacing piece at original pos """ def __init__(self, pos: int, piece: str) -> None: super().__init__() self.piece = piece self.color = piece >> 6 self.image = pg.image.load(f"images/{piece}.png") self.rect = self.image.get_rect() self.move_to_tile(pos) def move_to_tile(self, move: int) -> None: self.rect.center = (move % 8)*62.5 + 31.25, (move // 8)*62.5 + 31.25 self.last_tile = move class PieceGroup(Group): """Sprite group wrapper, avoids passing game instance to all sprites""" def __init__(self, game: 'ChessGame') -> None: super().__init__() self.screen = game.screen def update_sprites(self) -> None: if game.grab: # grabbed piece follows mouse game.grab.rect.center = pg.mouse.get_pos() for p in super().sprites(): self.screen.blit(p.image, p.rect) class ChessGame(): """ Game instance is controlled by main script, hence not much is done at init. - ChessGame.active indicates whether the game instance is running the gui. - start_new_game(side) does what would normally be at init - setup_board() updates the game to the current match attribute everything regarding move checking and board generation should be handled by the engine module, and then the result submitted to this class by updating said match attribute. """ def __init__(self) -> None: self.active = False self.point = Point([0, 0]) def start_new_game(self, side: int) -> None: pg.init() self.image = pg.image.load("images/board.png") self.rect = self.image.get_rect() self.screen = pg.display.set_mode((500, 500)) pg.display.set_caption("Chess") self.side = side # side to display board from self.grab = None # currently grabbed piece self.player_move = None # (start, end) scalar coordinates self.active = True # pygame window activity if side == 0: start = np.copy(engine.start_white) else: start = np.copy(engine.start_black) self.match = [start, np.ones((2,2), dtype=np.uint8), 0] self.setup_board() def setup_board(self) -> None: """Spawns and places pieces based on board input.""" self.turn = self.match[2] self.pieces = PieceGroup(self) for tile in range(64): piece = self.match[0][tile] if piece and not (piece & 0b10000000): # don't spawn en passant self.pieces.add(ChessPiece(tile, piece)) def close_window(self) -> None: # close window without killing class pg.display.quit() pg.quit() self.active = False def check_events(self) -> None: """Event loop. Press Q or exit window to quit current instance""" for event in pg.event.get(): if event.type == pg.QUIT: self.close_window() elif event.type == pg.KEYDOWN : if event.key == pg.K_q: self.close_window() elif event.type == pg.MOUSEBUTTONDOWN: self.grab_piece() elif event.type == pg.MOUSEBUTTONUP and self.grab: self.drop_piece() def grab_piece(self) -> None: """Checks for sprite collisions.""" self.point.rect.center = pg.mouse.get_pos() p = pg.sprite.spritecollide(self.point, self.pieces, False) if p: # in case you don't click any piece piece = p[0] self.grab = piece def drop_piece(self) -> None: """Translates player movement to engine-readable move""" # grabbed piece can't be moved (opponent's piece or opponent's turn) if not (self.grab.color == self.turn and self.turn == self.side): self.grab.move_to_tile(self.grab.last_tile) # reset self.grab = None return start = self.grab.last_tile x, y = pg.mouse.get_pos() end = (int(y // 62.5))*8 + int(x // 62.5) move = [start, end] if start != end and engine.check_legality(self.match, move): engine.update_game(self.match, move) self.setup_board() self.player_move = move # start broadcasting new move else: self.grab.move_to_tile(self.grab.last_tile) self.grab = None def display_frame(self) -> None: """Checks events, blits to surfaces and updates display""" self.check_events() if self.active: # to avoid errors when closing instance self.screen.blit(self.image, self.rect) self.pieces.update_sprites() pg.display.flip() pg.time.wait(3)
48837ba41dd80c5d783e0d20d22890afd8af53f4
ba-talibe/lab_netacad
/the_digit_of_life.py
194
3.5625
4
n = input(">>>") def digit(n): if len(n) == 1: return int(n) sum = 0 for i in range(len(n)): sum += int(n[i]) return digit(str(sum)) print(digit(n))
e98e8a5e4f936f769267764ec05bf0faee78ecfa
pureoym/leetcode
/array/566_Reshape_the_Matrix.py
1,785
3.6875
4
# -*- coding: utf-8 -*- # author: pureoym # time: 2017/12/15 9:59 # Copyright 2017 pureoym. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import numpy as np class Solution(object): def matrixReshape(self, nums, r, c): """ :type nums: List[List[int]] :type r: int :type c: int :rtype: List[List[int]] """ row = len(nums) column = len(nums[0]) if r * c != row * column: return nums else: return np.reshape(nums, (r, c)).tolist() if __name__ == '__main__': """ Example 1: Input: nums = [[1,2],[3,4]], r = 1, c = 4 Output: [[1,2,3,4]] Explanation: The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list. Example 2: Input: nums = [[1,2],[3,4]],r = 2, c = 4 Output:[[1,2],[3,4]] Explanation: There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix. """ s = Solution() nums = [[1, 2], [3, 4]] output = s.matrixReshape(nums, 1, 4) print nums print output
7f91df5090e36ee3c8a64c390abd7698ffdb77db
PyRPy/algorithms_books
/leetcode/add_digits.py
308
3.640625
4
# add_digits.py class Solution: def addDigits(self, num: int) -> int: if num <= 0: return 0 else: result = (num - 1) % 9 + 1 return result num = 383 sol = Solution() print(num) print(sol.addDigits(num)) # think about it again !
4257c2a7532e6ae0f4912bead9e91cf99a024516
wisesky/LeetCode-Practice
/src/206.reverse-linked-list.py
1,381
4.03125
4
# # @lc app=leetcode id=206 lang=python3 # # [206] Reverse Linked List # # https://leetcode.com/problems/reverse-linked-list/description/ # # algorithms # Easy (66.47%) # Likes: 7386 # Dislikes: 138 # Total Accepted: 1.5M # Total Submissions: 2.2M # Testcase Example: '[1,2,3,4,5]' # # Given the head of a singly linked list, reverse the list, and return the # reversed list. # # # Example 1: # # # Input: head = [1,2,3,4,5] # Output: [5,4,3,2,1] # # # Example 2: # # # Input: head = [1,2] # Output: [2,1] # # # Example 3: # # # Input: head = [] # Output: [] # # # # Constraints: # # # The number of nodes in the list is the range [0, 5000]. # -5000 <= Node.val <= 5000 # # # # Follow up: A linked list can be reversed either iteratively or recursively. # Could you implement both? # # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: oldHead = ListNode() oldHead.next = head # cur = oldHead newHead = ListNode() while oldHead.next != None: cur = oldHead.next oldHead.next = cur.next cur.next = newHead.next newHead.next = cur return newHead.next # @lc code=end
4007ae49ed5554864b3d2aceb339db6204a60d3e
sarkarChanchal105/Coding
/HackerRank/python/Easy/ctci-array-left-rotation.py
2,344
4.40625
4
""" https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem A left rotation operation on an array shifts each of the array's elements unit to the left. For example, if left rotations are performed on array , then the array would become . Note that the lowest index item moves to the highest index in a rotation. This is called a circular array. Given an array of integers and a number, , perform left rotations on the array. Return the updated array to be printed as a single line of space-separated integers. Function Description Complete the function rotLeft in the editor below. rotLeft has the following parameter(s): int a[n]: the array to rotate int d: the number of rotations Returns int a'[n]: the rotated array Input Format The first line contains two space-separated integers and , the size of and the number of left rotations. The second line contains space-separated integers, each an . Constraints Sample Input 5 4 1 2 3 4 5 Sample Output 5 1 2 3 4 Explanation When we perform left rotations, the array undergoes the following sequence of changes: """ # !/bin/python3 import math import os import random import re import sys # # Complete the 'rotLeft' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER_ARRAY a # 2. INTEGER d # def rotLeft(a, d): # Write your code here n = len(a) if d > n: d = d % n if d == n: reverseArray(a, start=0, end=n - 1) return a if d == 0: return a ## reverse the subarray 0 to d-1 reverseArray(a, start=0, end=d - 1) ## reverse the subarray d to n-1 reverseArray(a, start=d, end=n - 1) ## revere the whole array now reverseArray(a, start=0, end=n - 1) return a def reverseArray(array, start, end): while start <= end: array[start], array[end] = array[end], array[start] start += 1 end -= 1 if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') first_multiple_input = input().rstrip().split() n = int(first_multiple_input[0]) d = int(first_multiple_input[1]) a = list(map(int, input().rstrip().split())) result = rotLeft(a, d) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
6ce2e593f6f01bd793f14ead1451067f6b93dc76
machukhinktato/test_tasks_python
/task4/SRC/task4.py
1,013
3.875
4
def main(str1=None, str2=None): """ Функция сравнивает два строчных элемента, где в качестве второго элемента, может быть передана строка, внутри которой есть символ '*', заменяющий любое кол-во любых символов. """ if str1 == None or str2 == None: return print('В функцию не были переданы аргументы.\n' 'Принимаются аргументы строчного типа.\n' 'Процесс будет завершен.') is_same = False length = len(str2[0:(str2.index('*'))]) if '*' in str2: is_same = True if str1[0:length] == str2[0:length] else False elif str1 == str2: is_same = True elif "*" == str2[0]: is_same = True return print(['OK' if is_same else 'KO'][0]) if __name__ == '__main__': main()
0387cdec127355d3098d47cb058420ebf0105116
mohan78/PythonProgramming
/advanced/closure.py
3,823
4.5
4
""" A closure is a function object that remembers the data in enclosed scopes. To know more about closure, we need to know about types of scopes in Python. There are 3 types of scopes in python Built-in, Global, Local, Non-Local or Enclosing scope. 1. Built-in scope: This is the widest scope. This consist of all the names that are loaded when we start the interpreter. 2. Global: When a variable are defined in the script not inside any conditional, loops or functional namespace, then it is called to be a Global variable and the namespace is called Global namespace. Global variables can be accessed from anywhere in the script. A global variable can be created using keyword 'global'. 3. Local: When a variable are defined in a loop or condition block or function namespace, then it is called to be local variable and it is called Local namespace. 4. Non-Local or Enclosing: When a variable is defined in a nested function it is called non-local variable and the scope is called enclosing scope. This variable will neither have global or local scope. a Non-Local variable can be created using the keyword 'nonlocal'. """ global_x = 10 # This is a global variable print(f"Value of global variable 'global_x' is {global_x}") # Output: 10 print("\n") def func_1(): # To be able to change the value of a global variable inside a function, we need to declare it as # a global variable. print("-"*30, "In func_1", "-"*30) global global_x print(f"Value of global variable 'global_x' inside func_1 is {global_x}") global_x = 20 print("-"*30, "End of func_1", "-"*30, "\n") def func_2(): # A variable declared inside a function consists of local scope. It will not be available to access # outside this function print("-"*30, "In func_2", "-"*30) local_x = 10 print(f"Value of local variable 'local_x' is {local_x}") # Output: 10 print("-"*30, "End of func_2", "-"*30, "\n") def func_3(): # In this, there is a nested function nested_func defined inside func_3. That nested function also # consists of another local_x which is redefined with value of 30. print("-"*30, "In func_3", "-"*30) local_x = 10 def nested_func(): local_x = 30 print(f"Value of local variable 'local_x' inside nested_func is {local_x}") nested_func() print(f"Value of local variable 'local_x' inside func_3 is {local_x}") print("-"*30, "End of func_3", "-"*30, "\n") def func_4(): print("-"*30, "In func_4", "-"*30) local_x = 10 print(f"Value of local variable 'local_x' inside func_4 is {local_x}") def nested_func(): # Here we defined local_x is defined with nonlocal keyword meaning setting its scope to nonlocal # Hence this variable will same as the local_x variable defined in above func_4. Therefore changing # its value here will reflect in func_4's local_x. nonlocal local_x local_x = 30 nested_func() print(f"Value of local variable 'local_x' inside func_4 after executing nested_func is {local_x}") print("-"*30, "End of func_4", "-"*30, "\n") def func_5(): print("-"*30, "In func_5", "-"*30) local_x = 10 print(f"Value of local variable 'local_x' inside func_5 is {local_x}") def nested_func(): # We can access local variable local_x inside nested_func even though it is not supplied to # nested_func as an argument. This is called 'Closure'. print(f"Value of variable 'local_x' accessed inside nested_func is {local_x}") nested_func() print("-"*30, "End of func_5", "-"*30, "\n") func_1() func_2() func_3() func_4() func_5() print(f"Value of global variable global_x after re-assignment in func_1 is {global_x}") # Output: 20
a950f4779ec053b7004de84f56f9411c4909b4d0
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/mzwrun001/question2.py
366
3.921875
4
"""Program to check for paired letters in a string Runako Muzwidzwa 06/05/2014""" v=input("Enter a message:\n") def pairs(v): if len(v)<2: return 0 #to return number elif v[0] == v[1]: n=v[2:] return 1 + pairs(n) else: return pairs(v[1:])#calls function with the message after slicing print("Number of pairs:",pairs(v))
1d2853474fd5c24f18e9f32b98efcf15fa82b2e1
smartLp/Sort
/Sort_Algorithm.py
5,782
3.828125
4
# coding: utf-8 # # 几种常见的排序算法 # ## 1.插入排序 # In[2]: import time from functools import wraps def fn_timer(function): @wraps(function) def function_timer(*args, **kwargs): t0 = time.time() for i in range(100000): result = function(*args, **kwargs) t1 = time.time() print ("Total time running %s: %s seconds" % (function.func_name, str(t1-t0)) ) return result return function_timer @fn_timer def insertedsort(l): for i in range(1,len(l)): j = i-1 while l[i]<l[j] and j>-1: key = l[i] l[j+1] = l[j] i = j l[i] = key j -= 1 return l if __name__ == "__main__": l = [3,2,5,1,7,9,7,0,10] result = insertedsort(l) print (result) # In[ ]: # In[3]: @fn_timer def insertedsorted(l): for i in range(1,len(l)): for j in range(i-1,-1,-1): while l[i]<l[j]: key = l[i] l[j+1] = l[j] i = j l[i] = key return l if __name__ == "__main__": l = [3,2,5,1,7,9,7,0,10] result = insertedsorted(l) print (result) # In[ ]: # ## 2.冒泡排序 # In[4]: @fn_timer def maopaosort(l): for index in range(len(l)-1): if l[index]>l[index+1]: l[index],l[index+1] = l[index+1],l[index] return l if __name__ == "__main__": l = [3,2,5,1,7,9,7,0,10] result = insertedsort(l) print result # ## 3. 快速排序 # In[1]: ''' def QuickSort(l,front,end): if front < end: pivot_index = Partition(l,front,end) QuickSort(l,front,pivot_index-1) QuickSort(l,pivot_index+1,end) return l def Partition(l,front,end): pivot = l[end] i = front - 1 for j in range(end): if l[j] < pivot: i += 1 l[i],l[j] = l[j],l[i] l[i+1],l[end]=l[end],l[i+1] return i+1 def main(): l = [3,2,5,1,7,9,7,0,6] index = range(len(l)) print index[0],index[-1] result = QuickSort(l,index[0],index[-1]) print result if __name__ == "__main__": main() ''' def QuickSort(Arr): if len(Arr) <= 1: return Arr else: pivot = Arr[-1] LessThan_pivot = [element for element in Arr[:-1] if element <= pivot] GreatThan_pivot = [element for element in Arr[:-1] if element > pivot] return QuickSort(LessThan_pivot) + [pivot] + QuickSort(GreatThan_pivot) if __name__ == "__main__": l = [3,2,5,1,7,9,7,0,10] result = QuickSort(l) print result # ## 4.归并排序 # # In[33]: def Merge(Arr,L,M,R): Left_Size = M - L Right_Size = R - M + 1 Left_Arr = [] Right_Arr = [] # fill in the left sub array for i in range(L,M): Left_Arr.append(Arr[i]) #fill in the right sub array for j in range(M,R+1): Right_Arr.append(Arr[j]) #Merge into the original array i = 0 j = 0 k = L while i<Left_Size and j<Right_Size: if Left_Arr[i] < Right_Arr[j]: Arr[k] = Left_Arr[i] i += 1 k += 1 else: Arr[k] = Right_Arr[j] j += 1 k += 1 while i<Left_Size: Arr[k] = Left_Arr[i] i += 1 k += 1 while j < Right_Size: Arr[k] = Right_Arr[j] j += 1 k += 1 def MergeSort(Arr,L,R): if L==R: return else: M = (L + R) // 2 MergeSort(Arr,L,M) MergeSort(Arr,M+1,R) Merge(Arr,L,M+1,R) if __name__ == "__main__": items = raw_input("Please input the unsorted List separated by commas: ") collection = [int(item) for item in items.strip().split(",")] print collection index = range(len(collection)) L = index[0] R = index[-1] MergeSort(collection,L,R) print collection # In[21]: def merge_sort(collection): """Pure implementation of the merge sort algorithm in Python""" length = len(collection) if length > 1: midpoint = length//2 left_half = merge_sort(collection[:midpoint]) right_half = merge_sort(collection[midpoint:]) i = 0 j = 0 k = 0 left_length = len(left_half) right_length = len(right_half) while i < left_length and j < right_length: if left_half[i] < right_half[j]: collection[k] = left_half[i] i += 1 else: collection[k] = right_half[j] j += 1 k += 1 while i < left_length: collection[k] = left_half[i] i += 1 k += 1 while j < right_length: collection[k] = right_half[j] j += 1 k += 1 return collection if __name__ == "__main__": items = raw_input("Please input the unsorted List separated by commas: ") print items unsorted = [int(item) for item in items.split(",")] sorted_list = merge_sort(unsorted) print sorted_list # ## 5.选择排序 # In[6]: def selection_sort(collection): length = len(collection) if length == 1: pass else: for i in range(length-1): for j in range(i+1,length): if collection[i] > collection[j]: collection[i],collection[j] = collection[j],collection[i] return collection # In[7]: collection = [2,3,2,5,1] result = selection_sort(collection) print result # In[ ]:
e300db0fa9aadd9675ad77d253285ee01bf5357d
faidev/python
/day1/6.guess.py
234
4.09375
4
#!/usr/bin/env python3 age_of_wayne = 28 guess_age = int(input("guess age:")) if guess_age == age_of_wayne: print("yes,you got it.") elif guess_age > age_of_wayne: print("think smaller...") else: print("think bigger!")
a56a8f4ea047b3daed4c8b340e9b1af09d721c87
lukashaverbeck/parknet
/util/concurrent.py
3,878
3.625
4
import math import time from typing import Any, Callable import util def stabilized_concurrent(name: str, min_delay: float, max_delay: float, steps: int, daemon: bool = True) -> Callable: """ Decorator factory for concurrently executing a function with dynamic delays in between. Whenever a function is decorated with ``@stabilized_concurrent(...)``, it will be executed concurrently with dynamically changing delays in between two executions. The longer the execution has been stable, the longer the delay. An execution was stable exactly if the decorated function returned True. Notes: A ``@stabilized_concurrent`` function cannot return Values other than None since it is run in its own thread. Args: name: Name of the thread the function is executed in. min_delay: Lower bound for the dynamic delay. max_delay: Upper bound for the dynamic delay. steps: Number of stable executions to reach the maximum delay. daemon: Boolean whether the thread in which the function is executed is daemonic. Returns: The according decorator function. """ # the minimum delay must be less than the maximum delay assert 0 < min_delay < max_delay, "Minimum delay must be positive and less than max delay." # there must be at least one step from minimum to maximum delay assert steps > 0, "It must take at least one step to reach the maximum delay." def calc_delay(stable_intervals: int) -> float: """ Calculates the delay before the next execution based on the number of consecutive stable executions. The delay d is defined as min_delay * exp(stable_intervals * ln(max_delay / min_delay) / steps) normally but is at maximum ``max_delay``. For 0 stable intervals the delay is ``min_delay``. After ``steps`` stable intervals, the delay is ``max_delay``. Args: stable_intervals: Number of consecutive stable executions. Returns: The delay to wait before the next execution in seconds. """ return min(max_delay, min_delay * math.exp(stable_intervals * math.log(max_delay / min_delay) / steps)) def decorator(function: Callable[[Any], bool]) -> Callable: @util.threaded(name, daemon) def concurrent_execution(*args, **kwargs) -> None: """ Concurrently executes the decorated function with dynamically calculated delays in between. The delay is calculated based on the number of consecutive stable executions of the function. The execution of the decorated function was stable exactly if the function returns ``True``. Args: *args: Arguments, the decorated function is called with. **kwargs: Keyword arguments, the decorated function is called with. """ # initially there have been no stable executions stable_intervals = 0 while True: # execute the decorated function and save the result stable = function(*args, **kwargs) # the decorated function must return a Boolean assert stable is True or stable is False, f"A stabilized concurrent function must return a Boolean " \ f"but {function.__name__}(...) did not." # calculate a dynamic delay and stop the execution for the corresponding duration delay = calc_delay(stable_intervals) time.sleep(delay) # update number of stable executions accordingly to the result of the latest execution stable_intervals = stable_intervals + 1 if stable else 0 return concurrent_execution return decorator
e4733b2b9ef857b4fa3180a72bf6d0f44d9c44cc
kevinelong/AM_2015_04_06
/Week2/bitmask.py
1,458
3.8125
4
class permissions(): READ = 4 WRITE = 2 EXECUTE = 1 def __init__(self): self.permissions = 0 def allow(self, permission): #USE "OR" (vertical bar) to set a bit self.permissions = self.permissions | permission def revoke(self, permission): #USE "AND" (ampersand) and "NOT" (tilde) # to invert input and unset a bit self.permissions = self.permissions & ~permission def can(self, permission): #USE "AND" (ampersand) check a bit # It will be the value of the bit 1,2,4,8 etc if set # compare to zero so as to return true only if the bit is set return (permission & self.permissions) != 0 def __str__(self): #Use format to create padded binary output return format(self.permissions, "#010b") + " --> " + str(self.permissions) # LOGIC TRUTH TABLE # | OR # 0 1 # # 0 0 1 # 1 1 1 # & AND # 0 1 # # 0 0 0 # 1 0 1 # ~ NOT # # 0 1 # 1 0 # 6 3 1 # 4 2 6 8 4 2 1 # ------------- # 0 0 0 0 1 1 1 -> decimal 7 showing 4+2+1 all three set p = permissions() print(p) print("CAN READ? " + str(p.can(p.READ))) p.allow(p.READ) print(p) p.allow(p.WRITE) print(p) p.allow(p.EXECUTE) print(p) p.revoke(p.WRITE) print(p) print("CAN READ? " + str(p.can(p.READ))) # OUTPUTS: # 0b00000000 --> 0 # CAN READ? False # 0b00000100 --> 4 # 0b00000110 --> 6 # 0b00000111 --> 7 # 0b00000101 --> 5 # CAN READ? True
552bef72b059809ae77c2658dcec7f47e76fa136
jiaozhennan/python300
/012-dotProduct.py
406
3.5
4
class Solution: def dotProduct(self, A, B): if len(A) == 0 or len(B) == 0 or len(A) != len(B): return -1 ans = 0 for i in range(len(A)): ans += A[i] * B[i] return ans if __name__ == '__main__': A = [1, 1, 1] B = [2, 2, 2] solution = Solution() print("A与B分别为:", A, B) print("点积为:", solution.dotProduct(A,B))
0c2fcb7529b603ffb5eef3c1de0bd5cea60fac38
rentes/Euler
/problem1.py
577
3.671875
4
"""Project Euler - Problem 1 - http://projecteuler.net/problem=1""" import sys import time import tools.timeutils as timeutils def sum_numbers(): """ Sums all natural numbers below 1000 that are multiples of 3 or 5 Returns: int """ a, b = 1, 0 while a < 1000: if (a % 3 == 0) or (a % 5 == 0): b += a a += 1 return b def main(): """Main entry point for the script""" start = time.time() print(sum_numbers()) timeutils.elapsed_time(time.time() - start) if __name__ == '__main__': sys.exit(main())
41789e171b1594aa69ef8a5447f5c244b3842946
trgreenman88/CS_21
/greenman_archery.py
3,766
4.0625
4
# Trent Greenman # CS 21, Fall 2018 # Program: Archery # Import graphics from graphics import * # This function creates the target def create_target_window(): # Creates the graphics window win = GraphWin() # Set the size of the graph win.setCoords(-6, -6, 6, 6) # Set the color of the background win.setBackground("gray") # Set a point in the center so the circles are all centered p = Point(0, 0) # Create the outer white circle with radius 5 c5 = Circle(p, 5) c5.setFill("white") c5.draw(win) # Create the black circle with radius 4 over the white circle c4 = Circle(p, 4) c4.setFill("black") c4.draw(win) # Create the blue circle with radius 3 over the black circle c3 = Circle(p, 3) c3.setFill("blue") c3.draw(win) # Create the red circle with radius 2 over the blue circle c2 = Circle(p, 2) c2.setFill("red") c2.draw(win) # Create the inside yellow circle with radius 1 over the red circle c1 = Circle(p, 1) c1.setFill("yellow") c1.draw(win) # return the window in which the target is drawn return win # This function gives us the score of each arrow shot def get_score(point): # Initialize the score to be 0 score = 0 # For all of these, if the value of point (given in main()) is # less than the radius ** 2, then add the given point values # If the arrow hits the yellow circle, add 9 points to score if point <= 1: score += 9 # If the arrow hits the red circle, add 7 points to score elif point <= 4: score += 7 # If the arrow hits the blue circle, add 5 points to score elif point <= 9: score += 5 # If the arrow hits the black circle, add 3 points to score elif point <= 16: score += 3 # If the arrow hits the white circle, add 1 point to score elif point <= 25: score += 1 # If the arrow doesn't hit the target, add 0 points to score else: score += 0 # Return the arrow's score as an integer return score # The main function gets the mouse clicks def main(): # Call the first function win = create_target_window() # Initialize the total score to start at 0 total = 0 # Keep taking arrow shots until the player presses "q" while win.checkKey() != "q": # Have the score show up on the graphics window. Center it # at (0, -5.5) so it is right below the target t = Text(Point(0,-5.5), "Current Score: " + str(total)) # Draw the text on the graphics window t.draw(win) # If there is a mouse click, set this point to be p1 p1 = win.checkMouse() # Only execute the following code if there is actually a mouse # click. Without the mouse click, p1 has no value and we cannot # draw the points or get x and y values for a nonexistant point if type(p1) == Point: # Draw the point p1.draw(win) # Call the score function for each arrow and add it to the # total score. We want to have point in get_score(point) be # equal to x**2 + y**2 so we can use pythagorean's theorem # to make sure our point is inside a given radius total += get_score(p1.getX() ** 2 + p1.getY() ** 2) # Create a gray rectangle to cover up the score each time so # that we do not end up with a bunch of overlaped scores and # we can only see the most recent score r = Rectangle(Point(-6,-6),Point(6,-5.1)) r.setFill("gray") r.setOutline("gray") r.draw(win) # If the loop is broken by typint "q", close the window win.close() # Run the main function main()
8464c89eb3726f9c3cd7220785e869cf59d95c6c
jad2192/babys_first_repo
/random/graph_algs.py
5,058
3.796875
4
# Most of these algorithms are derived from psuedocode in Cormen et. al. inf = float('inf') class Vertex(object): """ Adjacent list implementation of a graph. Create a vertex (v) and then its adjacent edges are stored in the list v.edges. A graph will then just be a set of vertex objects. Can use this to implement directed/undirected and weighted/unweighted graphs easily.""" def __init__(self, adj=[]): self.adjacent = adj def get_edges(self, adj_vert): """ Input an array-like object "adj_vert" containing all the vertices directly connected to our current vertex.""" for u in adj_vert: self.adjacent.append(u) def __repr__(self): return str(self) def __str__(self): return str(self) class Priority_Queue_Min(object): """ Heap implementation of priority queue of objects with priorities (keys) stored in a dictionary P.""" def __init__(self, A=[],P={}): self.heap = A self.P = P if len(self.heap) > 0: self.build_min_heap() def min_heapify(self,i): P = self.P l = 2*i + 1 r = 2*i + 2 if l < len(self.heap) and P[self.heap[l]] < P[self.heap[i]]: smallest = l else: smallest = i if r < len(self.heap) and P[self.heap[r]] < P[self.heap[smallest]]: smallest = r if smallest != i: self.heap[i], self.heap[smallest] = self.heap[smallest], self.heap[i] self.min_heapify(smallest) def build_min_heap(self): k = (len(self.heap) // 2) - 1 for i in range(k,-1,-1): self.min_heapify(i) def extract_min(self): if len(self.heap) < 1: print('heap-underflow') return m = self.heap[0] self.heap[0] = self.heap[-1] self.heap = self.heap[:-1] self.min_heapify(1) return m def decrease_key(self,x,key): i = self.heap.get_index(x) if key > self.P[self.heap[i]]: print('Can only decrease key value') return self.P[self.heap[i]] = key while i > 0 and self.P[self.heap[(i-1)//2]] > self.P[self.heap[i]]: self.heap[i], self.heap[(i-1)//2] = self.heap[(i-2)//2], self.heap[i] i = (i-1) // 2 def insert(self,x,key_x): self.heap.append(x) self.P[x] = inf self.decrease_key(len(self.heap),key_x) # Single Shortest Paths def init_single_source(G,s): P = {} pi = {} for v in G: P[v] = inf pi[v] = None P[s] = 0 return P, pi def relax(u,v,P,pi,w): """ Sub routine that will update the distances. Here w is the dictionary encoding the edge weights, i.e. w[(u,v)] = weight of edge from u to v.""" P, pi = P, pi if P[v] > P[u] + w[(u,v)]: P[v] = P[u] + w[(u,v)] pi[v] = u return P, pi def Bellman_Ford(G,w,s): """ Bellman-Ford algorithm for finding a single shortest path from a source, s, to every vertex in the connected component containing s. This algorithm is less efficient than Dijkstra's but can handle the case of negative edge weights. It also has a built in infinite, negative-weight cycle detector.""" P, pi = init_single_source(G,s) for i in range(len(G)-1): for v in G: for u in v.adjacent: # These two lines (100-101) are equivalent to looping over the edges of the graph. P, pi = relax(v,u,P,pi,w) for v in G: # Infinite negative cycle detection. for u in v.adjacent: if P[u] > P[v] + w[(v,u)]: print('Negative weight cycle detected') return False return P, pi def Dijkstra(G,w,s): """ Dijkstra's is faster than Bellman-Ford, but is only valid when the weights are positive.""" P, pi = init_single_source(G,s) S = [] Q = Priority_Queue_min(G,P) while len(Q.heap) > 0: u = Q.extract_min() S.append(u) for v in u.adjacent: sum = Q.P[u] + w[(u,v)] if Q.P[v] > sum: Q.decrease_key(v,sum) pi[v] = u P = Q.P return P, pi def find_shortest_path(G,w,s,t): """ This function will print a shortest path from s to t, as well as its weight. Assumes no negative cycles.""" m = min(list(w.values())) if m >= 0: P, pi = Dijkstra(G,w,s) else: P, pi = Bellman_Ford(G,w,s) if P[t] < inf: path = [] p = t while P[p] != 0: path = [str(p)] + path p = pi[p] print("-->".join(path)) print('Weight = ', P[t]) else: print('They are not connected') # Bredth First Search def BFS(G,s): color = {} P = {} pi = {} for v in G: color[v] = 'white' pi[v] = None P[v] = inf color[s] = 'grey' P[s] = 0 Q = [s] while Q: u = Q.pop(0) for v in u.adjacent: if color[v] == 'white': color[v] = 'grey' P[v] = P[u] + 1 pi[v] = u Q.append(v) color[u] = 'black' return P, pi # Minimum Spanning Tree def Prim(G,w,r): """ Prim's algorithm starting with arbitrary root vertex r. Here we assume G is connected and undirected. This function returns the dictionary 'pi' which keeps track of the parent of a vertex in the MST if the vertex is in the MST and keeps it NIL otherwise. Can easily use this info to print out the tree.""" P, pi = {}, {} for u in G: P[u] = inf pi[u] = None P[r] = 0 Q = Priority_Queue_Min(G,P) while Q.heap: u = Q.extract_min() for v in u.adjacent: if v in Q.heap and w[(u,v)] < Q.P[v]: pi[v] = u Q.decrease_key(v,w[(u,v)]) return pi
de18edf082547b02c9e908203eb93078dfb86dee
thackerdynasty/Guess-the-number-
/main.py
118
3.546875
4
from game import * import random Guesses = 0 name = input("Hello! What is your name? ") number = random.randint(1, 20)
8aa1825e40be87360a91c93838a8a6e7224fca1a
MechaMonst3r/Python-Assignment-1
/Assignment 1/dayoldbread.py
918
3.90625
4
# Name: Luke Bowden # Student Number: t00040951 # Lab Number: 1 # Date: 2020-09-16 # Description: Takes in input from a user who wishes to buy old # bread at a discount price and produces the total. #Defining Constants and variables. BREADCOST = 3.49; DISCOUNT = 0.6; totalBread = 0.0; totalDiscount = 0.0; totalSale = 0.0; #Gets input from user. userInput = float(input("Enter number of loaves of old bread you want to buy:\n")); #Does caluclations to get the total cost of bread, the discount, and applies the proper amount to the sale total. totalBread = userInput * BREADCOST; totalDiscount = totalBread * DISCOUNT; totalSale = totalBread - totalDiscount; #Prints the results to the user and formats it to the second decimal. print("Cost per loaf: $" + "{:.2f}".format(totalBread)); print("Amount you save: $" + "{:.2f}".format(totalDiscount)); print("Total price: $" + "{:.2f}".format(totalSale));
bfa4c8529f95a85f03cd0cce65bd3d03827c369a
SaiHarsh/twitter_anaslysis_Search
/crowd dynamics programs/date_max_min_median.py
2,126
3.5
4
#find median of hours group by date #step one median for a next step of median of median #find the min, max, sum, mean, median values per date and day #change the group by option from date/day or any suitable as needed. import pandas as pd from datetime import datetime import csv cols = ['date', 'startTime', 'endTime', 'day', 'count', 'unique'] df = pd.read_csv('o_1_hour.csv', header=None, names=cols) c_max = df.groupby(['day'])[['count']].max() #max of count day-wise c_min = df.groupby(['day'])[['count']].min() #min of count day-wise u_max = df.groupby(['day'])[['unique']].max() #max of unique day-wise u_min = df.groupby(['day'])[['unique']].min() #min of unique day-wise c_sum = df.groupby(['day'])[['count']].sum() #sum of count day-wise u_sum = df.groupby(['day'])[['unique']].sum() #sum of unique day-wise c_mean = df.groupby(['day'])[['count']].mean().astype(int) #avg of count day-wise u_mean = df.groupby(['day'])[['unique']].mean().astype(int) #avg of unique day-wise c_med = df.groupby(['day'])[['count']].median().astype(int) #median of count day-wise u_med = df.groupby(['day'])[['unique']].median().astype(int) #median of unique day-wise #dictionary created with new data and respective column names data_dictionary = {'day': df['day'].unique(), 'max_count': list(c_max['count']), 'min_count': list(c_min['count']), 'max_unique': list(u_max['unique']), 'min_unique': list(u_min['unique']), 'sum_count': list(c_sum['count']), 'sum_unique': list(u_sum['unique']), 'mean_count': list(c_mean['count']), 'mean_unique': list(u_mean['unique']), 'med_count': list(c_med['count']), 'med_unique': list(u_med['unique'])} #construction of new dataframe with new dictionary formed new_df = pd.DataFrame(data = data_dictionary) #output new_df.to_csv('o_day_min_max.csv', index = False) ''' cols = ['date_count', 'all_hours','c_min', 'c_max', 'c_med', 'c_med_med', 'u_min', 'u_max', 'u_med', 'u_med_med'] stats = pd.DataFrame([[date_count, all_hours, c_min, c_max, c_med, c_med_med, u_min, u_max, u_med, u_med_med]], columns = cols) #print (stats) stats.to_csv('o_stats_by_date.csv', index=False) '''
899c4d0d162f993e54f66f0d390873ac0a7b4d84
lgauing/Guias-dispositivas-y-ejercicios-en-clase_Lady
/condicion.py
846
3.984375
4
# Lady Mishell Gauin Gusñay # 3er semestre de software A1 class condicion: def __init__(self,num1,num2): self.numero1=num1 self.numero2=num2 numeros=self.numero1+self.numero2 self.numero3=numeros def usoIf(self): #if...elif ... else ...: permiten condicionar la ejecucion de uno o varios bloques # de sentencias al cumplimiento de una o varias condiciones. if self.numero1 == self.numero2: print("numero1={}=numero2={} : son iguales".format(self.numero1,self.numero2)) elif self.numero1 == self.numero3: print("numero1 y numero3 son iguales") else: print ("numero diferentes") # print("instancia de la clase # cond2= condicion() # print (cond2.numero3) # cond2.usoIf() cond1= condicion(10,10) cond1.usoIf() print("Gracias por su visita")
041bc3ba085aa319a4bdf8fc4cdb822f35aebc82
tylors1/Leetcode
/Problems/findLargestSum.py
429
4.0625
4
# Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. # For example, [2, 4, 6, 8] should return 12, since we pick 4 and 8. [5, 1, 1, 5] should return 10, since we pick 5 and 5. def findSum(nums): max1 = nums[0] maxi = 0 for i in range(len(nums))[1:]: if max1 < nums[i]: max1 = nums[i] maxi = i nums = [2,4,7,8,9] print findSum(nums)
ab3a82c04326e59c7f2c1b5123640f162b57edf4
XuSShuai/data-structure-and-algorithm
/inverse_pair.py
1,259
3.65625
4
import numpy as np def merge_sort(arr, L, R): if L == R: return 0 mid = (L + R) // 2 return merge_sort(arr, L, mid) + merge_sort(arr, mid + 1, R) + merge(arr, L, mid, R) def merge(arr, L, mid, R): p = L q = mid + 1 res = 0 auxiliary = [] while p <= mid and q <= R: if arr[p] > arr[q]: res += (mid - p + 1) auxiliary.append(arr[q]) q += 1 else: auxiliary.append(arr[p]) p += 1 if p > mid: auxiliary.extend(arr[q:R+1]) if q > R: auxiliary.extend(arr[p:mid+1]) for i in range(len(auxiliary)): arr[L + i] = auxiliary[i] return res def correct_method(arr): res = 0 for i in range(len(arr)): for j in range(i + 1, len(arr)): if arr[j] < arr[i]: res += 1 return res def generate_cases(): for i in range(10000): arr = list(np.random.randint(1, 100, 10)) res_1 = correct_method(arr) res_2 = merge_sort(arr, 0, len(arr) - 1) if res_2 != res_1: print("error") # print("input array: ") # arr = list(map(int, stdin.readline().strip().split(","))) # print(merge_sort(arr, 0, len(arr) - 1)) generate_cases()
288e1ade1b1ef44ec163d087d0d8b009bb5012c0
headend/frontend
/utils/__init__.py
703
4.21875
4
import datetime import time # Python Program to Convert seconds # into hours, minutes and seconds def convert_seconds_to_day(seconds): days = seconds // (24 * 3600) seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 return "%dd %02dh:%02dm:%02ds" % (days, hour, minutes, seconds) def caculate_distance(date_update): now = int(datetime.datetime.now().strftime("%s")) - time.timezone #print("Timezone %d"%(time.timezone)) #print("Db %s"%(str(date_update))) #print("Now %s"%(now)) #print("Db %s"%(date_update.strftime("%s"))) return now - (int(date_update.strftime("%s")) - time.timezone)
c4cd16869254cf214071eb40d6c9966d5d362ce1
VladimirKrgn/triangle_test_task
/triangle.py
815
3.8125
4
class Triangle: def __init__(self, a, b, c): self.a = a self.b = b self.c = c self.ab_length = (pow(a[0] - b[0], 2) + pow(a[1] - b[1], 2)) ** 0.5 self.ac_length = (pow(a[0] - c[0], 2) + pow(a[1] - c[1], 2)) ** 0.5 self.bc_length = (pow(b[0] - c[0], 2) + pow(b[1] - c[1], 2)) ** 0.5 def is_exist(self): f = sorted([self.ab_length, self.ac_length, self.bc_length]) if f[2] < sum([f[0], f[1]]): return True else: return False def get_perimeter(self): return sum([self.ab_length, self.ac_length, self.bc_length]) def get_area(self): # p = half_perimeter p = self.get_perimeter() * 0.5 return (p * (p - self.ab_length) * (p - self.bc_length) * (p - self.ac_length)) ** 0.5
52c224954489725a2530ef63cec51b3cfecd16fc
likaon100/pythonbootcamp
/dzień 2/cwiczenie 3.py
408
3.546875
4
Miasto_A = str(input("Miasto A:")) Miasto_B = str(input("Maisto B:")) Dystans_z_Miasto_A_do_Miasto_B = int(input(f"Dystand {Miasto_A}-{Miasto_B}:")) Cena_paliwa = float(input("podaj cene paliwa:")) spalaniekm = float(input("Spalanie na 100 km:")) koszt = round((Dystans_z_Miasto_A_do_Miasto_B / 100) * spalaniekm * Cena_paliwa,2) # koszt = round(koszt,2) print(f"Koszt przejazdu Warszawa-Gdañsk to {koszt} PLN")
b50cae8c4fb8c80d5e705c3a940f0e6bdf6079bb
vinodrajendran001/python-interview-prep
/array_rotation.py
649
3.75
4
''' Left array rotation d = 4 [1 2 3 4 5] -> [2 3 4 5 1] -> [3 4 5 1 2] -> [4 5 1 2 3] -> [5 1 2 3 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, item): return self.items.pop(item) def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def __str__(self): return str(self.items) def rotation(n, a): s = Stack() count = 0 for i in range(len(a)): s.push(a[i]) while count < n: top = s.pop(0) s.push(top) count = count + 1 return s print rotation(3,'12345')
8f0d39fc984a0a82530f1196170914bad6d68cb9
elikaski/BF-it
/Compiler/Functions.py
1,223
3.59375
4
from copy import deepcopy from Exceptions import BFSemanticError functions = dict() # Global dictionary of function_name --> FunctionCompiler objects def insert_function_object(function): functions[function.name] = function def get_function_object(name): """ must return a copy of the function because we might need to compile function recursively and if we don't work on different copies then we will interfere with the current token pointer etc for example: int increase(int n) { return n+1;} int main() {int x = increase(increase(1));} while compiling the first call, we start a compilation of the same function object in the second call """ return deepcopy(functions[name]) def check_function_exists(function_token, parameters_amount): function_name = function_token.data if function_name not in functions: raise BFSemanticError("Function '%s' is undefined" % str(function_token)) function = functions[function_name] if len(function.parameters) != parameters_amount: raise BFSemanticError("Function '%s' has %s parameters (called it with %s parameters)" % (str(function_token), len(function.parameters), parameters_amount))
f18fc0dd2e198b463a419d0b8c0fba0f426d2c68
cybelewang/leetcode-python
/code726NumberOfAtoms.py
4,089
4.375
4
""" 726 Number of Atoms Given a chemical formula (given as a string), return the count of each atom. An atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name. 1 or more digits representing the count of that element may follow if the count is greater than 1. If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible. Two formulas concatenated together produce another formula. For example, H2O2He3Mg4 is also a formula. A formula placed in parentheses, and a count (optionally added) is also a formula. For example, (H2O2) and (H2O2)3 are formulas. Given a formula, output the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on. Example 1: Input: formula = "H2O" Output: "H2O" Explanation: The count of elements are {'H': 2, 'O': 1}. Example 2: Input: formula = "Mg(OH)2" Output: "H2MgO2" Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}. Example 3: Input: formula = "K4(ON(SO3)2)2" Output: "K4N2O14S4" Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}. Note: All atom names consist of lowercase letters, except for the first character which is uppercase. The length of formula will be in the range [1, 1000]. formula will only consist of letters, digits, and round parentheses, and is a valid formula as defined in the problem. """ from collections import defaultdict class Solution: # my own solution with bug fixed def countOfAtoms(self, formula): """ :type formula: str :rtype: str """ stack = [] i, element = 0, '' count = defaultdict(int) while i < len(formula): c = formula[i] if 64 < ord(c) < 91: # this is an upper case letter, start a new element j = i + 1 # end index (exclusive) of the new element while j < len(formula) and 96 <ord(formula[j])< 123: j += 1 element = formula[i:j] # new element # now search for the number for this elements i = j while j < len(formula) and 47 < ord(formula[j]) < 58: j += 1 # update count map if i == j: count[element] += 1 else: count[element] += int(formula[i:j]) i = j elif c == '(': # enter a sub formula stack.append(count) count = defaultdict(int) i += 1 else: #if c == ')': # exit a sub formula i += 1 # get the repeat of the sub formula j = i while j < len(formula) and 47 < ord(formula[j]) < 58: j += 1 repeat = 1 if i < j: repeat = int(formula[i:j]) i = j # apply repeat to current count map for e in count: count[e] *= repeat # merge with previous count map previous = stack.pop() for p in previous: if p in count: count[p] += previous[p] else: count[p] = previous[p] # bug fixed: should not push count back to stack #stack.append(count) # out of while loop res = '' for e in sorted(count.keys()): res += e if count[e] > 1: res += str(count[e]) return res formula = "K4(ON(SO3)2)2" print(Solution().countOfAtoms(formula))
87d0969fb317ffbb90bbfcc0ff280fa4e717df0b
MFTI-winter-20-21/LebedevDanya
/07 палендром.py
160
3.796875
4
k1 = input("слово_") k2 = k1[::-1].lower() if k1.lower() == k2: print ("это палиндром") else: print ("это не палиндром")
f22fc3e370897c2b7585e3ab8b2a6a0eb0fc6179
Lusarom/progAvanzada
/ejercicio30.py
247
3.609375
4
KPascal = float(input('Ingresa presion en KPascales:')) PSI = KPascal * 0.14508 mmHg = KPascal * 0.13332 atm = KPascal / 101.325 print('\n lb in^2: %.3f'%(PSI),'(PSI)') print('\n mmHg: %.3f'%(mmHg),'(mmHg)') print('\n atm: %.3f'%(atm),'(atm)')
0154ba072831f115ce83a7171852107bee81ce7b
narasimha7854/qazi
/str1.py
131
3.796875
4
#example of String datatype str="Welcome to Python" print(str) print(str[0]) print(str[3:7]) print(str[11:]) print(str[-1])
4749198dbedff2acf22ce821be69fcdd5a60293f
alcantara17/dminer
/dminer/ingestion/helpers/helpers.py
2,219
3.671875
4
""" This module provides a set of general purpose helpers for use in parser logic. """ import os def build_filename_timestamp(regex_matcher, base_year=2000): """ Given a `re.match` object, this function will return a formatted timestamp in the format of: "yyyy:MM:dd HH:mm:ss:SSS" This function will explicitly throw an error if the `re.match` object passed does not have the following named groups: year month day The explicit throwing of errors on these attributes prevents wierd indexing bugs across different storage backends. The following attributes of the `re.match` object will be normalized if they do not exist: hour -> 00 minute -> 00 second -> 00 """ # We don't normalize these values, as these are minimum necessary for indexing. timestamp = ":".join( [ str(int(regex_matcher.group("year")) + base_year), str(regex_matcher.group("month")).zfill(2), str(regex_matcher.group("day")).zfill(2) ] ) # Normalize the hour to be the afternoon, as we are only pulling to the day # if the values do not exist timestamp += " " + ":".join( [ safe_named_group_value(regex_matcher, "hour", default="00"), safe_named_group_value(regex_matcher, "minute", default="00"), safe_named_group_value(regex_matcher, "second", default="00") ] ) return timestamp def safe_named_group_value(regex_matcher, name, default=None): """ given a `re.match` object, this function will attempt to pull the value of a named group. If it does not exist (IndexError thrown), the `default` value will be returned. """ try: return regex_matcher.group(name) except IndexError: return default def get_files(directory): """ Fetches file paths for a given directory. It returns the full paths to each file in the directory, based off of the directory given. """ if os.path.exists(directory): return [os.path.join(directory, f) for f in os.listdir(directory)] else: raise Exception("Directory does not exist: %s" % directory)
0330ed19241e54b4dcadb420c67ff4a52435f0eb
python-control/python-control
/examples/cruise-control.py
17,248
4.25
4
# cruise-control.py - Cruise control example from FBS # RMM, 16 May 2019 # # The cruise control system of a car is a common feedback system encountered # in everyday life. The system attempts to maintain a constant velocity in the # presence of disturbances primarily caused by changes in the slope of a # road. The controller compensates for these unknowns by measuring the speed # of the car and adjusting the throttle appropriately. # # This file explores the dynamics and control of the cruise control system, # following the material presented in Feedback Systems by Astrom and Murray. # A full nonlinear model of the vehicle dynamics is used, with both PI and # state space control laws. Different methods of constructing control systems # are shown, all using the InputOutputSystem class (and subclasses). import numpy as np import matplotlib.pyplot as plt from math import pi import control as ct # # Section 4.1: Cruise control modeling and control # # Vehicle model: vehicle() # # To develop a mathematical model we start with a force balance for # the car body. Let v be the speed of the car, m the total mass # (including passengers), F the force generated by the contact of the # wheels with the road, and Fd the disturbance force due to gravity, # friction, and aerodynamic drag. def vehicle_update(t, x, u, params={}): """Vehicle dynamics for cruise control system. Parameters ---------- x : array System state: car velocity in m/s u : array System input: [throttle, gear, road_slope], where throttle is a float between 0 and 1, gear is an integer between 1 and 5, and road_slope is in rad. Returns ------- float Vehicle acceleration """ from math import copysign, sin sign = lambda x: copysign(1, x) # define the sign() function # Set up the system parameters m = params.get('m', 1600.) g = params.get('g', 9.8) Cr = params.get('Cr', 0.01) Cd = params.get('Cd', 0.32) rho = params.get('rho', 1.3) A = params.get('A', 2.4) alpha = params.get( 'alpha', [40, 25, 16, 12, 10]) # gear ratio / wheel radius # Define variables for vehicle state and inputs v = x[0] # vehicle velocity throttle = np.clip(u[0], 0, 1) # vehicle throttle gear = u[1] # vehicle gear theta = u[2] # road slope # Force generated by the engine omega = alpha[int(gear)-1] * v # engine angular speed F = alpha[int(gear)-1] * motor_torque(omega, params) * throttle # Disturbance forces # # The disturbance force Fd has three major components: Fg, the forces due # to gravity; Fr, the forces due to rolling friction; and Fa, the # aerodynamic drag. # Letting the slope of the road be \theta (theta), gravity gives the # force Fg = m g sin \theta. Fg = m * g * sin(theta) # A simple model of rolling friction is Fr = m g Cr sgn(v), where Cr is # the coefficient of rolling friction and sgn(v) is the sign of v (+/- 1) or # zero if v = 0. Fr = m * g * Cr * sign(v) # The aerodynamic drag is proportional to the square of the speed: Fa = # 1/\rho Cd A |v| v, where \rho is the density of air, Cd is the # shape-dependent aerodynamic drag coefficient, and A is the frontal area # of the car. Fa = 1/2 * rho * Cd * A * abs(v) * v # Final acceleration on the car Fd = Fg + Fr + Fa dv = (F - Fd) / m return dv # Engine model: motor_torque # # The force F is generated by the engine, whose torque is proportional to # the rate of fuel injection, which is itself proportional to a control # signal 0 <= u <= 1 that controls the throttle position. The torque also # depends on engine speed omega. def motor_torque(omega, params={}): # Set up the system parameters Tm = params.get('Tm', 190.) # engine torque constant omega_m = params.get('omega_m', 420.) # peak engine angular speed beta = params.get('beta', 0.4) # peak engine rolloff return np.clip(Tm * (1 - beta * (omega/omega_m - 1)**2), 0, None) # Define the input/output system for the vehicle vehicle = ct.NonlinearIOSystem( vehicle_update, None, name='vehicle', inputs=('u', 'gear', 'theta'), outputs=('v'), states=('v')) # Figure 1.11: A feedback system for controlling the speed of a vehicle. In # this example, the speed of the vehicle is measured and compared to the # desired speed. The controller is a PI controller represented as a transfer # function. In the textbook, the simulations are done for LTI systems, but # here we simulate the full nonlinear system. # Construct a PI controller with rolloff, as a transfer function Kp = 0.5 # proportional gain Ki = 0.1 # integral gain control_tf =ct.TransferFunction( [Kp, Ki], [1, 0.01*Ki/Kp], name='control', inputs='u', outputs='y') # Construct the closed loop control system # Inputs: vref, gear, theta # Outputs: v (vehicle velocity) cruise_tf = ct.InterconnectedSystem( (control_tf, vehicle), name='cruise', connections=[ ['control.u', '-vehicle.v'], ['vehicle.u', 'control.y']], inplist=['control.u', 'vehicle.gear', 'vehicle.theta'], inputs=['vref', 'gear', 'theta'], outlist=['vehicle.v', 'vehicle.u'], outputs=['v', 'u']) # Define the time and input vectors T = np.linspace(0, 25, 101) vref = 20 * np.ones(T.shape) gear = 4 * np.ones(T.shape) theta0 = np.zeros(T.shape) # Now simulate the effect of a hill at t = 5 seconds plt.figure() plt.suptitle('Response to change in road slope') vel_axes = plt.subplot(2, 1, 1) inp_axes = plt.subplot(2, 1, 2) theta_hill = np.array([ 0 if t <= 5 else 4./180. * pi * (t-5) if t <= 6 else 4./180. * pi for t in T]) for m in (1200, 1600, 2000): # Compute the equilibrium state for the system X0, U0 = ct.find_eqpt( cruise_tf, [0, vref[0]], [vref[0], gear[0], theta0[0]], iu=[1, 2], y0=[vref[0], 0], iy=[0], params={'m': m}) t, y = ct.input_output_response( cruise_tf, T, [vref, gear, theta_hill], X0, params={'m': m}) # Plot the velocity plt.sca(vel_axes) plt.plot(t, y[0]) # Plot the input plt.sca(inp_axes) plt.plot(t, y[1]) # Add labels to the plots plt.sca(vel_axes) plt.ylabel('Speed [m/s]') plt.legend(['m = 1000 kg', 'm = 2000 kg', 'm = 3000 kg'], frameon=False) plt.sca(inp_axes) plt.ylabel('Throttle') plt.xlabel('Time [s]') # Figure 4.2: Torque curves for a typical car engine. The graph on the # left shows the torque generated by the engine as a function of the # angular velocity of the engine, while the curve on the right shows # torque as a function of car speed for different gears. # Figure 4.2 fig, axes = plt.subplots(1, 2, figsize=(7, 3)) # (a) - single torque curve as function of omega ax = axes[0] omega = np.linspace(0, 700, 701) ax.plot(omega, motor_torque(omega)) ax.set_xlabel(r'Angular velocity $\omega$ [rad/s]') ax.set_ylabel('Torque $T$ [Nm]') ax.grid(True, linestyle='dotted') # (b) - torque curves in different gears, as function of velocity ax = axes[1] v = np.linspace(0, 70, 71) alpha = [40, 25, 16, 12, 10] for gear in range(5): omega = alpha[gear] * v T = motor_torque(omega) plt.plot(v, T, color='#1f77b4', linestyle='solid') # Set up the axes and style ax.axis([0, 70, 100, 200]) ax.grid(True, linestyle='dotted') # Add labels plt.text(11.5, 120, '$n$=1') ax.text(24, 120, '$n$=2') ax.text(42.5, 120, '$n$=3') ax.text(58.5, 120, '$n$=4') ax.text(58.5, 185, '$n$=5') ax.set_xlabel('Velocity $v$ [m/s]') ax.set_ylabel('Torque $T$ [Nm]') plt.suptitle('Torque curves for typical car engine') plt.tight_layout() plt.show(block=False) # Figure 4.3: Car with cruise control encountering a sloping road # PI controller model: control_pi() # # We add to this model a feedback controller that attempts to regulate the # speed of the car in the presence of disturbances. We shall use a # proportional-integral controller def pi_update(t, x, u, params={}): # Get the controller parameters that we need ki = params.get('ki', 0.1) kaw = params.get('kaw', 2) # anti-windup gain # Assign variables for inputs and states (for readability) v = u[0] # current velocity vref = u[1] # reference velocity z = x[0] # integrated error # Compute the nominal controller output (needed for anti-windup) u_a = pi_output(t, x, u, params) # Compute anti-windup compensation (scale by ki to account for structure) u_aw = kaw/ki * (np.clip(u_a, 0, 1) - u_a) if ki != 0 else 0 # State is the integrated error, minus anti-windup compensation return (vref - v) + u_aw def pi_output(t, x, u, params={}): # Get the controller parameters that we need kp = params.get('kp', 0.5) ki = params.get('ki', 0.1) # Assign variables for inputs and states (for readability) v = u[0] # current velocity vref = u[1] # reference velocity z = x[0] # integrated error # PI controller return kp * (vref - v) + ki * z control_pi = ct.NonlinearIOSystem( pi_update, pi_output, name='control', inputs=['v', 'vref'], outputs=['u'], states=['z'], params={'kp': 0.5, 'ki': 0.1}) # Create the closed loop system cruise_pi = ct.InterconnectedSystem( (vehicle, control_pi), name='cruise', connections=[ ['vehicle.u', 'control.u'], ['control.v', 'vehicle.v']], inplist=['control.vref', 'vehicle.gear', 'vehicle.theta'], outlist=['control.u', 'vehicle.v'], outputs=['u', 'v']) # Figure 4.3b shows the response of the closed loop system. The figure shows # that even if the hill is so steep that the throttle changes from 0.17 to # almost full throttle, the largest speed error is less than 1 m/s, and the # desired velocity is recovered after 20 s. # Define a function for creating a "standard" cruise control plot def cruise_plot(sys, t, y, label=None, t_hill=None, vref=20, antiwindup=False, linetype='b-', subplots=None, legend=None): if subplots is None: subplots = [None, None] # Figure out the plot bounds and indices v_min = vref-1.2; v_max = vref+0.5; v_ind = sys.find_output('v') u_min = 0; u_max = 2 if antiwindup else 1; u_ind = sys.find_output('u') # Make sure the upper and lower bounds on v are OK while max(y[v_ind]) > v_max: v_max += 1 while min(y[v_ind]) < v_min: v_min -= 1 # Create arrays for return values subplot_axes = list(subplots) # Velocity profile if subplot_axes[0] is None: subplot_axes[0] = plt.subplot(2, 1, 1) else: plt.sca(subplots[0]) plt.plot(t, y[v_ind], linetype) plt.plot(t, vref*np.ones(t.shape), 'k-') if t_hill: plt.axvline(t_hill, color='k', linestyle='--', label='t hill') plt.axis([0, t[-1], v_min, v_max]) plt.xlabel('Time $t$ [s]') plt.ylabel('Velocity $v$ [m/s]') # Commanded input profile if subplot_axes[1] is None: subplot_axes[1] = plt.subplot(2, 1, 2) else: plt.sca(subplots[1]) plt.plot(t, y[u_ind], 'r--' if antiwindup else linetype, label=label) # Applied input profile if antiwindup: # TODO: plot the actual signal from the process? plt.plot(t, np.clip(y[u_ind], 0, 1), linetype, label='Applied') if t_hill: plt.axvline(t_hill, color='k', linestyle='--') if legend: plt.legend(frameon=False) plt.axis([0, t[-1], u_min, u_max]) plt.xlabel('Time $t$ [s]') plt.ylabel('Throttle $u$') return subplot_axes # Define the time and input vectors T = np.linspace(0, 30, 101) vref = 20 * np.ones(T.shape) gear = 4 * np.ones(T.shape) theta0 = np.zeros(T.shape) # Compute the equilibrium throttle setting for the desired speed (solve for x # and u given the gear, slope, and desired output velocity) X0, U0, Y0 = ct.find_eqpt( cruise_pi, [vref[0], 0], [vref[0], gear[0], theta0[0]], y0=[0, vref[0]], iu=[1, 2], iy=[1], return_y=True) # Now simulate the effect of a hill at t = 5 seconds plt.figure() plt.suptitle('Car with cruise control encountering sloping road') theta_hill = [ 0 if t <= 5 else 4./180. * pi * (t-5) if t <= 6 else 4./180. * pi for t in T] t, y = ct.input_output_response(cruise_pi, T, [vref, gear, theta_hill], X0) cruise_plot(cruise_pi, t, y, t_hill=5) # # Example 7.8: State space feedback with integral action # # State space controller model: control_sf_ia() # # Construct a state space controller with integral action, linearized around # an equilibrium point. The controller is constructed around the equilibrium # point (x_d, u_d) and includes both feedforward and feedback compensation. # # Controller inputs: (x, y, r) system states, system output, reference # Controller state: z integrated error (y - r) # Controller output: u state feedback control # # Note: to make the structure of the controller more clear, we implement this # as a "nonlinear" input/output module, even though the actual input/output # system is linear. This also allows the use of parameters to set the # operating point and gains for the controller. def sf_update(t, z, u, params={}): y, r = u[1], u[2] return y - r def sf_output(t, z, u, params={}): # Get the controller parameters that we need K = params.get('K', 0) ki = params.get('ki', 0) kf = params.get('kf', 0) xd = params.get('xd', 0) yd = params.get('yd', 0) ud = params.get('ud', 0) # Get the system state and reference input x, y, r = u[0], u[1], u[2] return ud - K * (x - xd) - ki * z + kf * (r - yd) # Create the input/output system for the controller control_sf = ct.NonlinearIOSystem( sf_update, sf_output, name='control', inputs=('x', 'y', 'r'), outputs=('u'), states=('z')) # Create the closed loop system for the state space controller cruise_sf = ct.InterconnectedSystem( (vehicle, control_sf), name='cruise', connections=[ ['vehicle.u', 'control.u'], ['control.x', 'vehicle.v'], ['control.y', 'vehicle.v']], inplist=['control.r', 'vehicle.gear', 'vehicle.theta'], outlist=['control.u', 'vehicle.v'], outputs=['u', 'v']) # Compute the linearization of the dynamics around the equilibrium point # Y0 represents the steady state with PI control => we can use it to # identify the steady state velocity and required throttle setting. xd = Y0[1] ud = Y0[0] yd = Y0[1] # Compute the linearized system at the eq pt cruise_linearized = ct.linearize(vehicle, xd, [ud, gear[0], 0]) # Construct the gain matrices for the system A, B, C = cruise_linearized.A, cruise_linearized.B[0, 0], cruise_linearized.C K = 0.5 kf = -1 / (C * np.linalg.inv(A - B * K) * B) # Response of the system with no integral feedback term plt.figure() plt.suptitle('Cruise control with proportional and PI control') theta_hill = [ 0 if t <= 8 else 4./180. * pi * (t-8) if t <= 9 else 4./180. * pi for t in T] t, y = ct.input_output_response( cruise_sf, T, [vref, gear, theta_hill], [X0[0], 0], params={'K': K, 'kf': kf, 'ki': 0.0, 'kf': kf, 'xd': xd, 'ud': ud, 'yd': yd}) subplots = cruise_plot(cruise_sf, t, y, label='Proportional', linetype='b--') # Response of the system with state feedback + integral action t, y = ct.input_output_response( cruise_sf, T, [vref, gear, theta_hill], [X0[0], 0], params={'K': K, 'kf': kf, 'ki': 0.1, 'kf': kf, 'xd': xd, 'ud': ud, 'yd': yd}) cruise_plot(cruise_sf, t, y, label='PI control', t_hill=8, linetype='b-', subplots=subplots, legend=True) # Example 11.5: simulate the effect of a (steeper) hill at t = 5 seconds # # The windup effect occurs when a car encounters a hill that is so steep (6 # deg) that the throttle saturates when the cruise controller attempts to # maintain speed. plt.figure() plt.suptitle('Cruise control with integrator windup') T = np.linspace(0, 70, 101) vref = 20 * np.ones(T.shape) theta_hill = [ 0 if t <= 5 else 6./180. * pi * (t-5) if t <= 6 else 6./180. * pi for t in T] t, y = ct.input_output_response( cruise_pi, T, [vref, gear, theta_hill], X0, params={'kaw': 0}) cruise_plot(cruise_pi, t, y, label='Commanded', t_hill=5, antiwindup=True, legend=True) # Example 11.6: add anti-windup compensation # # Anti-windup can be applied to the system to improve the response. Because of # the feedback from the actuator model, the output of the integrator is # quickly reset to a value such that the controller output is at the # saturation limit. plt.figure() plt.suptitle('Cruise control with integrator anti-windup protection') t, y = ct.input_output_response( cruise_pi, T, [vref, gear, theta_hill], X0, params={'kaw': 2.}) cruise_plot(cruise_pi, t, y, label='Commanded', t_hill=5, antiwindup=True, legend=True) # If running as a standalone program, show plots and wait before closing import os if __name__ == '__main__' and 'PYCONTROL_TEST_EXAMPLES' not in os.environ: plt.show() else: plt.show(block=False)
b51722b7d3dae2e6ecdb5ee9362900c154384a72
Aziz1Diallo/python
/rectangle.py
249
4.03125
4
value=eval(input('type the height of the triangle : ')) row=0 while row<value: count=0 while count<row: print(end="") count+=1 count=0 while count<value: print(end="*") count+=1 print() row+=1
f8d7202b89d29c3f595ddc572a09f3d430fca7a1
nfscan/fuzzy_cnpj_matcher
/models/Cnpj.py
3,995
3.5
4
__author__ = 'paulo.rodenas' import random class Cnpj: """ Utilty class defines certain methods related to Brazilian CNPJs validation """ @staticmethod def validate(cnpj): """ Method to validate brazilian cnpjs Tests: >>> print Cnpj.validate('61882613000194') True >>> print Cnpj.validate('61882613000195') False >>> print Cnpj.validate('53.612.734/0001-98') True >>> print Cnpj.validate('69.435.154/0001-02') True >>> print Cnpj.validate('69.435.154/0001-01') False """ # cleaning the cnpj cnpj = cnpj.replace("-", "") cnpj = cnpj.replace(".", "") cnpj = cnpj.replace("/", "") # verifying the length of the cnpj if len(cnpj) != 14: return False # finding out the digits base_cnpj = cnpj[:-2] verificadores = cnpj[-2:] calculated_digits = Cnpj.calculate_last_digits(base_cnpj) # returnig return bool(verificadores == calculated_digits[0] + calculated_digits[1]) @staticmethod def calculate_last_digits(cnpj): """ Method to calculate the last two cnpj's digits to make it a valid cnpj :param cnpj: a base cnpj without the last two digits containing 12 characters :return: """ # verifying the length of the cnpj if len(cnpj) != 12: raise Exception('It should have 12 characters') # defining some variables lista_validacao_um = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] lista_validacao_dois = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] # calculating the first digit soma = 0 id = 0 for numero in cnpj: # to do not raise indexerrors try: lista_validacao_um[id] except: break soma += int(numero) * int(lista_validacao_um[id]) id += 1 soma %= 11 if soma < 2: digito_um = 0 else: digito_um = 11 - soma digito_um = str(digito_um) # converting to string, for later comparison # calculating the second digit # suming the two lists soma = 0 id = 0 cnpj += digito_um # suming the two lists for numero in cnpj: # to do not raise indexerrors try: lista_validacao_dois[id] except: break soma += int(numero) * int(lista_validacao_dois[id]) id += 1 # defining the digit soma = soma % 11 if soma < 2: digito_dois = 0 else: digito_dois = 11 - soma digito_dois = str(digito_dois) return [digito_um, digito_dois] @staticmethod def generate_valid_cnpj(): """ Generates a random valid cnpj :return: a valid cnpj """ base_cnpj = '' for x in range(0, 12): base_cnpj += str(random.randint(0, 9)) last_two_digits = Cnpj.calculate_last_digits(base_cnpj) base_cnpj += ''.join(last_two_digits) return base_cnpj @staticmethod def generate_valid_cnpj_with_no_branch(): """ Generates a random valid cnpj using only 0001 as company's branch :return: a valid cnpj """ base_cnpj = '' for x in range(0, 8): base_cnpj += str(random.randint(0, 9)) base_cnpj += '0001' last_two_digits = Cnpj.calculate_last_digits(base_cnpj) base_cnpj += ''.join(last_two_digits) return base_cnpj @staticmethod def format(cnpj): """ Method to format cnpj numbers. Tests: >>> print Cnpj.format('53612734000198') 53.612.734/0001-98 """ return "%s.%s.%s/%s-%s" % ( cnpj[0:2], cnpj[2:5], cnpj[5:8], cnpj[8:12], cnpj[12:14] )
fa26b38bb75533aa689f4d28c0a2d076764eab09
Sisyphus235/tech_lab
/algorithm/array/search_sorted_2d_array.py
1,021
3.984375
4
# -*- coding: utf8 -*- """ 一个包含整数的二维数组,左到右递增,上到下递增 判断一个整数是否在二维数组中 """ def search_sorted_2d_array(array, n): row_len = len(array) col_len = len(array[0]) row = 0 col = col_len - 1 while row < row_len and col >= 0: if array[row][col] == n: return True elif array[row][col] < n: row += 1 else: col -= 1 return False def test_search_sorted_2d_array(): array = [[1, 8, 9], [2, 10, 21], [5, 13, 35]] assert search_sorted_2d_array(array, 1) is True assert search_sorted_2d_array(array, 2) is True assert search_sorted_2d_array(array, 3) is False assert search_sorted_2d_array(array, 5) is True assert search_sorted_2d_array(array, 11) is False assert search_sorted_2d_array(array, 21) is True assert search_sorted_2d_array(array, 31) is False if __name__ == '__main__': test_search_sorted_2d_array()
0b1c255e8c2cc6e6775c72050919280a3ff0d361
lilianakemi/Projeto_Python_Exemplos_Exercicios
/Desenvolve_py/GravarArquvio,Invetario, Leitura,JSON_5/gravarArquivo.py
412
3.953125
4
with open("pagina.html", "w") as pagina: pagina.write("<body><h1> Esta é uma pagina WEB </h1>") pagina.write("<br><h2> Abaixo seguem alguns nomes importantes para o projeto: </h2>") pagina.write("<h3>") nome=" " while nome!="SAIR": nome=input("Digite um nome ou SAIR: ").upper() if nome!="SAIR": pagina.write("<br>"+nome) pagina.write("</h3></body>")
8dbebf62eb3446030cfe9502f6ba7f8d1839500b
aizigao/keepTraining
/algorithm/leetCode_xx/380.o-1-时间插入、删除和获取随机元素.py
1,212
3.625
4
# # @lc app=leetcode.cn id=380 lang=python3 # # [380] O(1) 时间插入、删除和获取随机元素 # # @lc code=start # 变长数组 + 哈希表 class RandomizedSet: def __init__(self): self.nums = [] self.indeces = {} # 如果 val 不存在集合中,则插入并返回 true,否则直接返回 false def insert(self, val: int) -> bool: if val in self.indeces: return False self.indeces[val] = len(self.nums) self.nums.append(val) return True # 如果 val 在集合中,则删除并返回 true,否则直接返回 false def remove(self, val: int) -> bool: if val not in self.indeces: return False idx = self.indeces[val] self.nums[idx] = self.nums[-1] self.nums.pop() self.indeces[self.nums[idx]] = idx del self.indeces[val] return True # 集合中等概率地随机获得一个元素 def getRandom(self) -> int: return choice(self.nums) # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom() # @lc code=end
4caf13581ab1f7ce234cadd399146a1dd3f5de26
scorp6969/Python-Tutorial
/math/math.py
424
3.734375
4
import math pi = 3.1414 pi_n = -3.1414 a = 10 b = 20 c = 30 # round off the value print(round(pi)) # round off to the nearest top(ceiling) value print(math.ceil(pi)) # round off to the nearest low(floor) value print(math.floor(pi)) # give absolute value print(abs(pi_n)) # gives power print(pow(a, 2)) # gives square root print(math.sqrt(144)) # gives maximum print(max(a, b, c)) # gives minimum print(min(a, b, c))
a1f8005dbce02f4b98a191beb6f4c6e781c6ac5e
uwseds-sp18/homework-3-dwhite105
/test_homework3.py
1,207
3.859375
4
# coding: utf-8 # (5 points). Create a python module named test_homework3.py that tests the code in homework3.py. Write at least 3 tests (e.g., checking column names, number of rows, and verifying which columns constitute a key). Also, write a test to check that the correct exception is generated when an invalid path is provided. import unittest from homework3 import create_dataframe class TestCreateDatabase(unittest.TestCase): def test_columnnames(self): columns = create_dataframe('class.db').columns condition = (len(columns) == 3 and 'category_id' in columns and 'video_id' in columns and 'language' in columns) self.assertTrue(condition) def test_keys(self): df = create_dataframe('class.db') df_dup = df.drop_duplicates(['language','video_id']) self.assertTrue(df_dup.shape[0] == df.shape[0]) def test_rows(self): df = create_dataframe('class.db') self.assertTrue(df.shape[0] > 10) def test_file_path(self): self.assertRaises(ValueError,create_dataframe,'not_a_file_path') if __name__ == '__main__': unittest.main()
525212302d7411619f01585ec9af0e93cb47c769
Mus1cBreaker/Smart-Calculator-Hyperskill
/Problems/The sum of numbers in a range/task.py
315
3.84375
4
def range_sum(numbers, a, b): sum_of_specified_elements = 0 for number in numbers: if a <= int(number) <= b: sum_of_specified_elements += int(number) return sum_of_specified_elements _numbers = input().split() _a, _b = input().split() print(range_sum(_numbers, int(_a), int(_b)))
490d3dc9ba6a5f750c73d854e24dfe60b649388a
Sroczka/URL
/Python/programmation_objet/wyklad/iteracja.py
738
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 16 14:00:33 2018 @author: janik """ class Sequentiel(): def __init__(self): self.i = 0 def __iter__(self): return self def __next__(self): self.i += 1 if self.i>1000: raise StopIteration("fin d'itération") return self.i*self.i mon_seq = Sequentiel() for i in mon_seq: print(i,end=" ") mon_seq = Sequentiel() it = mon_seq.__iter__(mon_seq) try: i = it.__next__() while True: print(i,end=" ") i = it.__next__() except StopIteration: pass mon_seq = Sequentiel() it = iter(mon_seq) try: i = next(it) while True: print(i,end=" ") i = next(it) except StopIteration: pass
bea057491b6d86e77c55c375bb3dc845a7e11a92
daniel-reich/turbo-robot
/EyzmkffNRiEBtjAmf_20.py
972
4.53125
5
""" Write the function that takes three dimensions of a brick: height(a), width(b) and depth(c) and returns `True` if this brick can fit into a hole with the width(w) and height(h). ### Examples does_brick_fit(1, 1, 1, 1, 1) ➞ True does_brick_fit(1, 2, 1, 1, 1) ➞ True does_brick_fit(1, 2, 2, 1, 1) ➞ False ### Notes * You can turn the brick with any side towards the hole. * We assume that the brick fits if its sizes equal the ones of the hole (i.e. brick size should be less than or equal to the size of the hole, not strictly less). * You **can't** put a brick in at a non-orthogonal angle. """ # (a,b,c) -- dimensions of the brick # (w,h) -- dimensions of the hole import math def does_brick_fit(a,b,c, w,h): if max(a,b,c)==c: return math.sqrt(a**a+b**b)<= math.sqrt(w**w+h**h) if max(a,b,c)==b: return math.sqrt(a**a+c**c)<= math.sqrt(w**w+h**h) else: return math.sqrt(c**c+b**b)<= math.sqrt(w**w+h**h)
33a25b0b58fc38d6aac5496b6fd232d1b97394b1
cfranchi/CS4850-Project
/TreeBuilder/csvParser.py
1,469
3.671875
4
class csvParser: def __init__(self, hierarchy, scanner): self.hierarchy = hierarchy self.attributes = scanner.attributes self.attributeNames = scanner.attributeNames def sortToHierarchy(self): print("sorting by hierarchy...") for i in range(0, len(self.attributes)): count = 0 temp = self.attributes[i][:] self.attributes[i] = self.attributes[i][: len(self.hierarchy)] for j in self.hierarchy: for k in range(count, len(self.attributes[i])): self.attributes[i][k] = temp[j] count += 1 break print("sorting compete") print("-----------------------------------------------------------------------------") def printHierarchy(self): print("HIERARCHY:\n") for rank in self.hierarchy: print(rank.__str__() + " - " + self.attributeNames[rank].__str__()) print("-----------------------------------------------------------------------------") def parse(self, tree): print("parsing...") for i in range(0, len(self.attributes)): for j in range(0, len(self.hierarchy)): tree.addNode(self.attributes[i][j], self.hierarchy[j]) tree.updateParentNode(tree.rootNode) print("parse complete") print("-----------------------------------------------------------------------------")
d2f90a6f2e5494d137644d909c66b98902b3cae0
N-ickMorris/Location-Assignment
/assignment.py
4,662
3.796875
4
# facilities planning: assignment IP # this model is intended to minimize the total cost of investing in a set of producers to supply a set of consumers # ---- setup the model ---- from pyomo.environ import * # imports the pyomo envoirnment model = AbstractModel() # creates an abstract model model.name = "Assignment IP Model" # gives the model a name # ---- define set(s) ---- model.P = Set() # a set of producers model.C = Set() # a set of consumers # ---- define parameter(s) ---- model.k = Param(model.P) # cost to set up a producer model.c = Param(model.P) # the total cost/distance for a producer to satisfy a consumer (ie. transportation, labor, maintenance, etc.) model.max = Param(model.P) # the max number of consumers that a producer can satisfy model.xcor = Param(model.C) # the x coordinate of a consumer model.ycor = Param(model.C) # the y coordinate of a consumer model.r = Param() # range for a consumer to be satisfied # ---- define variable(s) ---- model.x = Var(model.C, domain = NonNegativeReals) # the x coordinate of a consumer's producer model.y = Var(model.C, domain = NonNegativeReals) # the y coordinate of a consumer's producer model.z = Var(model.P, model.C, domain = Binary) # a producer does/doesn't service a consumer model.o = Var(model.P, domain = Binary) # a producer is/isn't open model.dx = Var(model.C, domain = NonNegativeReals) # the x-distance between a consumer and it's producer model.dy = Var(model.C, domain = NonNegativeReals) # the y-distance between a consumer and it's producer # ---- define objective function(s) ---- def obj(model): return sum(model.o[i] * model.k[i] for i in model.P) + sum(sum(model.c[i] * (model.dx[i,j] + model.dy[i,j]) for i in model.P) for j in model.C) model.obj = Objective(rule = obj, sense = minimize) # a minimization problem of the function defined above # ---- define constraint(s) ---- def Open(model, i, j): return model.z[i,j] <= model.o[i] # a producer cannot statisfy a consumer unless it is open def Prod(model, i): return sum(model.z[i,j] for j in model.C) <= model.max[i] # a producer cannot satisfy more consumers than it's max def Cons(model, j): return sum(model.z[i,j] for i in model.P) == 1 # a consumer must be satisfied by one producer def RangeX(model, j): return (model.xcor[j] - model.r) <= model.x[j] <= (model.xcor[j] + model.r) # the x-coordinate of a consumer's producer must be within service range def RangeY(model, j): return (model.ycor[j] - model.r) <= model.y[j] <= (model.ycor[j] + model.r) # the y-coordinate of a consumer's producer must be within service range def EqnX1(model, i, j): return model.dx[i,j] >= model.x[j] - model.xcor[j] # set 1 of 2 to calculate the x-distance between a consumer and it's producer def EqnX2(model, i, j): return model.dx[i,j] >= model.xcor[j] - model.x[j] # set 2 of 2 to calculate the x-distance between a consumer and it's producer def EqnY1(model, i, j): return model.dy[i,j] >= model.y[j] - model.ycor[j] # set 1 of 2 to calculate the y-distance between a consumer and it's producer def EqnY2(model, i, j): return model.dy[i,j] >= model.ycor[j] - model.y[j] # set 2 of 2 to calculate the y-distance between a consumer and it's producer model.Setup = Constraint(model.P, model.C, rule = Open) # the setup constraint for every producer model.Producers = Constraint(model.P, rule = Prod) # the service constraint for every producer model.Consumers = Constraint(model.C, rule = Cons) # the assignment constraint for every consumer model.Xrange = Constraint(model.C, rule = RangeX) # the x range constraint on a producer for every consumer model.Yrange = Constraint(model.C, rule = RangeY) # the y range constraint on a producer for every consumer model.Xdistance1 = Constraint(model.P, model.C, rule = EqnX1) # the x distance calculation between every producer and consumer (set 1 of 2) model.Xdistance2 = Constraint(model.P, model.C, rule = EqnX2) # the x distance calculation between every producer and consumer (set 2 of 2) model.Ydistance1 = Constraint(model.P, model.C, rule = EqnY1) # the y distance calculation between every producer and consumer (set 1 of 2) model.Ydistance2 = Constraint(model.P, model.C, rule = EqnY2) # the y distance calculation between every producer and consumer (set 2 of 2) # ---- execute solver ---- from pyomo.opt import SolverFactory opt = SolverFactory("glpk") # opt = SolverFactory('ipopt',solver_io='nl') instance = model.create_instance("assignment.dat") results = opt.solve(instance) instance.display()
bbf940cb21fa2d1dfce5bff3d2180bfb5f333db2
praxpk/Weather_accidents_prediction
/merge_thread.py
7,765
3.546875
4
import pandas as pd import datetime import time import threading from selenium import webdriver import queue import traceback class w_sel: def __init__(self,muni,num): """ The queue stores tuples where each tuple contains start and end indices of the rows of the dataframe. :param muni: the list of municipalities whose data we need to extract """ self.q = queue.Queue() self.muni = muni self.num=num def run(self): """ Each thread returns its start and end index and that is used to remove the start and end segment tuple on the queue. This action denotes the successful extraction of data for corresponding rows in dataframe. :return: None """ for i in self.muni: df = self.filter_records(i) d={} for j in range(0,df.shape[0],50): d[(j,j+50)] = 1 while(True): if len(d)==0: break for j in d.copy(): t=threading.Thread(target=self.create_request,args=(df,j[0],j[1],self.q,self.num)) a = time.time() t.start() t.join() k = self.q.get() print(k) d.pop(k) b=time.time() print("Time = ",int(b)-int(a)) def filter_records(self,municipality): """ Creates a dataframe of munipalities mentioned in the parameters. :param municipality: municipality whose dataframe is needed. :return: """ print(municipality) print("filter records") df = pd.read_csv("filtered_mvc.csv") df = df.loc[df["Municipality"].isin([municipality])] print(df.shape[0]) return df def process_string(self,string_list, _time, _date, muni): """ This method takes in the list and associates the time with the particular record. The list contains weather information where the first entry in the list is the weather condition at 1AM to the last entry in the list which is the weather condition at 12 AM :param string_list: weather list. :param _time: time from the vehicle accident data :param _date: date of the accident :param muni: municipality where the accident occured. :return: list containing date, time, municipality and weather conditions. """ data = string_list[(int(_time.split(":")[0])) - 1] data = data.split() result = [] result.append(_date) result.append(_time) result.append(muni) result.append(data[2] + data[3]) result.append(data[4] + data[5]) result.append(data[6] + data[7]) result.append(data[8]) result.append(data[9] + data[10]) result.append(data[11] + data[12]) result.append(data[13] + data[14]) result.append(data[15] + data[16]) result.append(data[17]) return result def create_request(self,df1,start,end,q,num): """ This method is used to access the county urls to extract the weather information. :param df: dataframe of the entire accident dataset :return: None """ # dictionary containing URL templates for each county, append date after last forward slash url_dict = {"KINGS": "https://www.wunderground.com/history/daily/us/ny/new-york-city/KLGA/date/", "BRONX": "https://www.wunderground.com/history/daily/us/ny/new-york-city/KLGA/date/", "QUEENS": "https://www.wunderground.com/history/daily/us/ny/new-york-city/KLGA/date/", "NEW YORK": "https://www.wunderground.com/history/daily/us/ny/new-york-city/KLGA/date/", "BROOKHAVEN": "https://www.wunderground.com/history/daily/us/ny/brookhaven/KNYBROOK285/date/", "HEMPSTEAD": "https://www.wunderground.com/history/daily/us/ny/hempstead/KNYHEMPS2/date/", "ISLIP": "https://www.wunderground.com/history/daily/us/ny/ronkonkoma/KISP/date/", "BABYLON": "https://www.wunderground.com/history/daily/us/ny/ronkonkoma/KISP/date/", "BUFFALO": "https://www.wunderground.com/history/daily/us/ny/buffalo/KBUF/date/", "ROCHESTER": "https://www.wunderground.com/history/daily/us/ny/rochester/KROC/date/", "RICHMOND": "https://www.wunderground.com/history/daily/us/ny/new-york-city/KJFK/date/", "HUNTINGTON": "https://www.wunderground.com/history/daily/us/ny/huntington/KNYHUNTI77/", "OYSTER BAY": "https://www.wunderground.com/history/daily/us/ny/harrison/KHPN/date/" } try: data_list = [] df = df1.iloc[start:end] driver = webdriver.Firefox() for index, row in df.iterrows(): if url_dict.get(row["Municipality"]) is not None: url = url_dict.get(row["Municipality"]) date = datetime.datetime.strptime(row["Date"], "%m/%d/%Y").strftime( "%Y-%m-%d") # convert date to appropriate format url += str(date) result = [] elem="" # extract table from website using table's Xpath try: driver.get(url) elem = driver.find_elements_by_xpath( "/html/body/app-root/app-history/one-column-layout/wu-header/sidenav/mat-sidenav-container/mat-sidenav-content/div/section/div[2]/div[1]/div[5]/div[1]/div/lib-city-history-observation/div/div[2]/table/tbody") except: driver = webdriver.Firefox() continue # access element's text and process the string. for i in elem: string = "" for j in i.text: if j is not "\n": # append to list when break line element is encountered. string += j else: result.append(string) string = "" try: result = self.process_string(result, row["Time"], row["Date"], row["Municipality"]) # obtain processed data except: continue data_list.append(result) # append data to a list # write the list to a new dataframe object df_data = pd.DataFrame(data_list, index=None, columns=["Date", "Time", "Municipality", "Temperature", "Dew Point", "Humidity", "Wind Direction", "Wind Speed", "Wind Gust", "Pressure", "Precipitation", "Condition"]) # write dataframe object to CSV df_data.to_csv("Weather_municipality"+str(num)+".csv", encoding="utf-8", index=False,mode='a') driver.close() q.put((start,end)) except: traceback.print_exc() if __name__ == '__main__': a = w_sel(["ROCHESTER","BUFFALO","RICHMOND"],1) b = w_sel(["KINGS", "BRONX", "QUEENS","NEW YORK"],2) c = w_sel(["BROOKHAVEN", "ISLIP", "BABYLON", "HUNTINGTON","OYSTER BAY"],3) # the following objects can be run as individual threads based on the processing power of the system. a.run() b.run() c.run()
00da040a1625724485f3ccfb1db5610cffa16990
james153dot/csp-p2-millard
/toobased.py
3,409
3.75
4
######################################################################### ## # # Code Maker - By James Lu # # last revised: 9/24/21 # # # # A cybertext program that uses a randomly generated OTP # # (one-time-pad) to code and decode messages. alpha characters # # are the only inputs allowed, all others will produce no result # # User is asked prompted to enter a word message to code or decode. # # Messages are broken up into individual letters and comapred to the # # OTP's values. To code the message, letters are replaced with the # # OTP code value based on the letter's ascii position. To decode, # # letters are replaced with the OTP code value based on the letter's # # ascii position. Every OTP is random, so if the program is ran again # # and the same letters are inputed, the coded message would be # # different # # # ######################################################################### import random import string alphabet_string0 = string.ascii_uppercase alphabet_string1 = string.ascii_lowercase alphabet_list_up = list(alphabet_string0) alphabet_list_low = list(alphabet_string1) random.shuffle(alphabet_list_up) random.shuffle(alphabet_list_low) print("Welcome to CodeMaker!") choice = 0 while choice != 3: choice = int(input("\n\nPlease enter 1 to code, 2 to decode, or 3 to quit coding \n")) if choice == 1: toocoded = input("\nEnter the message to be coded here: ") waytoocoded = "" for letter in toocoded: if (ord(letter)-97) in range(list(alphabet_string1).index('a'),(list(alphabet_string1).index('z')+1)): waytoocoded += alphabet_list_low[alphabet_list_low.index(letter)-alphabet_list_low.index('z')] elif (ord(letter)-65) in range(list(alphabet_string0).index('A'),(list(alphabet_string0).index('Z')+1)): waytoocoded += alphabet_list_up[alphabet_list_up.index(letter)-alphabet_list_up.index('Z')] elif letter == ' ': waytoocoded += ' ' else: waytoocoded += '?' print (waytoocoded, "\n\n") elif choice == 2: toocoded = input("\nEnter the message to be decoded here: ") waytoocoded = "" for letter in toocoded: if (ord(letter)-97) in range(list(alphabet_string1).index('a'),(list(alphabet_string1).index('z')+1)): waytoocoded += alphabet_list_low[alphabet_list_low.index(letter)+(alphabet_list_low.index('z')-26)] elif (ord(letter)-65) in range(list(alphabet_string0).index('A'),(list(alphabet_string0).index('Z')+1)): waytoocoded += alphabet_list_up[alphabet_list_up.index(letter)+(alphabet_list_up.index('Z')-26)] elif letter == ' ': waytoocoded += ' ' else: waytoocoded += '?' print (waytoocoded, "\n\n") print ("\n***** Thank you, please come again *****\n\n")
090ce23803d6268131fbd6bcefa9774a702a368e
gauravdal/write_config_in_csv
/python_to_csv.py
1,199
3.875
4
import json import csv #making columns for csv files csv_columns = ['interface','mac'] #Taking input from json file and converting it into dictionary data format with open('mac_address_table_sw1','r') as read_mac_sw1: fout = json.loads(read_mac_sw1.read()) print(fout) #naming a csv file csv_file = 'names.csv' try: with open(csv_file,'w') as csvfile: #DictWriter function creates an object and maps dictionary onto output rows. # fieldnames fieldnames parameter is a sequence of keys that identify the # order in which values in the dictionary passed to the writerow() method are written to file "csv_file" # extrasaction : If the dictionary passed to the writerow() method contains a key not found in fieldnames, # the optional extrasaction parameter indicates what action to take. If it is set to 'raise', the default # value, a ValueError is raised. If it is set to 'ignore', extra values in the dictionary are ignored. writer = csv.DictWriter(csvfile, fieldnames=csv_columns, extrasaction='ignore') writer.writeheader() for data in fout: writer.writerow(data) except IOError: print('I/O error')
7b95143b47168036304e3bbe9c9dec95fa444d12
peterjen/MyPython
/D19_Sort_list_tuple_obj.py
1,366
3.84375
4
li = [9,1,8,2,7,3,6,4,5] s_li = sorted(li) print('Sorted list variable\t',s_li) print('Original list variable\t',li) li.sort() print('Original list \t',li) s_li = sorted(li,reverse=True) print('Sorted list variable\t',s_li) print('#####################') tup = (9,1,8,2,7,3,6,4,5) s_tup = sorted(tup) print('Sorted tuple variable\t',s_tup) print('#####################') dic = {'name':'Peter','job':'SE','age':50,'DOB':None} s_dic = sorted(dic) print('Sorted dictionary variable\t',s_dic) li = [-6,-5,-4,1,2,3] s_li = sorted(li) print(s_li) s_li = sorted(li,key=abs) print(s_li) print('##### SORT OBJ/ CLASS ################') class Employee(): def __init__(self,name,age,salary): self.name = name self.age = age self.salary = salary def __repr__(self): return '{} {} ${}'.format(self.name,self.age,self.salary) e1 = Employee('Peter',50,11111) e2 = Employee('June',40,22222) e3 = Employee('Chloe',20,33333) emp_li = [e1,e2,e3] def s_emp_name(e): return e.name def s_emp_age(e): return e.age def s_emp_sal(e): return e.salary s_emp_li = sorted(emp_li,key=s_emp_name) print(s_emp_li) s_emp_li = sorted(emp_li,key=s_emp_age,reverse=True) print(s_emp_li) s_emp_li = sorted(emp_li,key=s_emp_sal) print(s_emp_li) print('USE lambda function') s_emp_li = sorted(emp_li,key=lambda e:e.name) print(s_emp_li)
e527860b7b40e86c4904d708638b8f9155fd6451
Aasthaengg/IBMdataset
/Python_codes/p03502/s059117073.py
133
3.5
4
N = int(input()) fx = 0 Nx = N for i in range(8): fx += Nx % 10 Nx = Nx // 10 if N % fx == 0: print("Yes") else: print("No")
c1dc8e8e5ab3a961a46db3cd2900afc6a68eba65
crowddynamics/crowddynamics-research
/data_analysis/radial_mean.py
2,626
3.875
4
import numpy as np def radial_mean(speed, crowd_pressure, cell_size, width, height): """ An approximate method to calculate average speed and crowd pressure at different distances from the exit. Points at equal spacing along a semicircle are generated, and then it is identified to which cells in the grid these points belong. The average speed and crowd pressure at the distance in question is calculated by averaging over the data in the cells. Parameters ---------- speed : array Array containing the average speed field. crowd_pressure : array Array containing the average crowd pressure field. cell_size: Size of the cell in the grid spanning the room. width: integer Width of the room. height: Length of the room. Returns ------- distances: array Distances to exit. avg_speed : array Average speed at different distances to exit. avg_crowd_pressure : array Average crowd pressure at different distances to exit. """ if width != height: raise ValueError("code designed for square rooms") width = width / cell_size width = int(width) distances = np.arange(0, width / 2, 1, dtype=np.int16) avg_speed = np.zeros(len(distances)) # array for storing average speed at different distances avg_crowd_pressure = np.zeros(len(distances)) # array for storing average crowd pressure # Loop through different distances for dist_indx in range(0, len(distances)): radius = distances[dist_indx] # distance x = np.arange(width - radius, width + 1, 1) # x-values in the range of half-circle x_flip = x[::-1] x = np.concatenate((x_flip, x[1:len(x)]), axis=0) # y-values in the range of half-circle # y = y0 +- sqrt(r^2 - (x-x0)^2) periphery_y1 = width / 2 + np.sqrt(radius * radius - (x_flip - width) * (x_flip - width)) periphery_y2 = width / 2 - np.sqrt(radius * radius - (x_flip - width) * (x_flip - width)) periphery_y = np.concatenate((periphery_y1[:-1], periphery_y2[::-1]), axis=0) # Given a distance, calculate the average speed and crowd pressure. # Use data in the cells that intersect with the half circle. avg_speed[dist_indx] = np.mean(speed[(periphery_y - 1).astype(int), (x - 1).astype(int)]) avg_crowd_pressure[dist_indx] = np.mean(crowd_pressure[(periphery_y - 1).astype(int), (x - 1).astype(int)]) # Change distances array data back to meters distances = cell_size * distances return distances, avg_speed, avg_crowd_pressure
dadf1f67c82e4bf5e0dba1beded55c604ef846e2
salvadb23/CS2.2
/challenges/challenge_3.py
4,367
4.1875
4
#!python """ Vertex Class A helper class for the Graph class that defines vertices and vertex neighbors. """ from sys import argv class Vertex(object): def __init__(self, vertex): """initialize a vertex and its neighbors neighbors: set of vertices adjacent to self, stored in a dictionary with key = vertex, value = weight of edge between self and neighbor. """ self.id = vertex self.neighbors = {} def addNeighbor(self, vertex, weight=0): """add a neighbor along a weighted edge""" if (vertex not in self.neighbors): self.neighbors[vertex] = weight def __str__(self): """output the list of neighbors of this vertex""" return str(self.id) + " adjancent to " + str([x.id for x in self.neighbors]) def getNeighbors(self): """return the neighbors of this vertex""" return self.neighbors def getId(self): """return the id of this vertex""" return self.id def getEdgeWeight(self, vertex): """return the weight of this edge""" return self.neighbors[vertex] class Graph: def __init__(self): """ initializes a graph object with an empty dictionary. """ self.vertList = {} self.numVertices = 0 def __str__(self): for item in self.vertList: print(item) return 'done' def addVertex(self, key): """add a new vertex object to the graph with the given key and return the vertex """ self.numVertices += 1 newVertex = Vertex(key) self.vertList[key] = newVertex return newVertex def getVertex(self, vertex): """return the vertex if it exists""" return self.vertList[vertex] if self.vertList[vertex] is not None else False def addEdge(self, vertexOne, vertexTwo, cost=0): """add an edge from vertex f to vertex t with a cost """ if self.vertList[vertexOne] is None: self.addVertex(vertexOne) elif self.vertList[vertexTwo] is None: self.addVertex(vertexTwo) else: self.vertList[vertexOne].addNeighbor( self.vertList[vertexTwo], cost) def getVertices(self): """return all the vertices in the graph""" return self.vertList.keys() def DFS_recursive(self,v,v2): """searches the graph to see if there is a path between two vertices using DFS""" vertexObj = self.vertList[v] visited = {} visited[vertexObj.getId()] = True def dfs(vertex): visited[vertex.getId()] = True for neighbor in vertex.neighbors: if neighbor.getId() not in visited: dfs(neighbor) dfs(vertexObj) path = list(visited.keys()) end_path = path.index(v2) + 1 is_path = v2 in path return (is_path, path[:end_path]) def __iter__(self): """iterate over the vertex objects in the graph, to use sytax: for v in g """ return iter(self.vertList.values()) def parse_data(): """reads file from command line""" vertices = open(argv[1], 'r') graph_data = vertices.read().split() vertices.close() return graph_data def create_graph(graph_data): """Create a graph from an array of graph information""" is_graph = graph_data[0] is 'G' graph = Graph() for vertex in graph_data[1].split(','): graph.addVertex(vertex) counter = 0 for word in graph_data[2:]: counter += 1 if is_graph: graph.addEdge(word[3], word[1], word[5:].replace(')', '')) graph.addEdge(word[1], word[3], word[5:].replace(')', '')) else: graph.addEdge(word[1], word[3], word[5:].replace(')', '')) return graph def print_path_result(path, path_list): print("There exist a path between vertex {} and {}: {}".format( argv[2], argv[3], path)) print('Vertices in path: {}'.format((',').join(path_list))) if __name__ == "__main__": data = parse_data() g = create_graph(data) g.DFS_recursive(argv[2],argv[3]) path, pathlist = g.DFS_recursive(argv[2],argv[3]) print_path_result(path, pathlist)
ff9488069257e1b9251dc2a6e7d13b6c4e4049e4
johnchoiniere/advent_of_code_2019
/day_3/day3.py
2,068
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 3 00:19:41 2019 @author: john """ # read in input with open('input.txt') as f: infile = f.readlines() # make it intotwo nice, easy lists of steps wire1 = infile[0].split(',') wire2 = infile[1].split(',') def intersect_finder(wire1, wire2): # set up coordinate lists coords_w1 = [] coords_w2 = [] # set up starting points x1 = 0 y1 = 0 x2 = 0 y2 = 0 # loop through wire, adding the new coordinates to the lisy for d in wire1: w = d[0] # the direction to go n = int(d[1:]) # the number of steps for i in range(n): if w == 'R': x1 += 1 coords_w1.append([x1,y1]) elif w == 'L': x1 -= 1 coords_w1.append([x1,y1]) elif w == 'U': y1 += 1 coords_w1.append([x1,y1]) elif w == 'D': y1 -= 1 coords_w1.append([x1,y1]) # same for wire 2 for d in wire2: w = d[0] n = int(d[1:]) for i in range(n): if w == 'R': x2 += 1 coords_w2.append([x2,y2]) elif w == 'L': x2 -= 1 coords_w2.append([x2,y2]) elif w == 'U': y2 += 1 coords_w2.append([x2,y2]) elif w == 'D': y2 -= 1 coords_w2.append([x2,y2]) # intersecting pts are the coords that # are in both lists intersections = [i for i in coords_w1 if i in coords_w2] # Manhattan distances of intersects distances = [abs(c[0])+abs(c[1]) for c in intersections] p1 = min(distances) # use index to find n(steps) to get to point steps = [coords_w1.index(i) + coords_w2.index(i) + 2 for i in intersections] p2 = min(steps) return p1, p2 part1, part2 = intersect_finder(wire1,wire2) print("Part 1 answer: " + str(part1)) print("Part 2 answer: " + str(part2))
5eaf7215636ff6ab4f41e2d6455c251a57ba7ed0
Hallyson34/uPython
/numeuler.py
199
3.53125
4
#Professor fez/code runner x = float(input()) n = int(input()) valor=0.0 for i in range(0,n+1): fat=1 for j in range(1,i+1): fat=fat*j valor=valor + x**i/fat print(f"{valor:.4f}")
59a2bdad1a9604398014265be7ecac9878f73b55
ernestoarbitrio/python-conference-beginners-day
/challenges/basic/boolean_expressions.py
1,573
4.40625
4
""" EXERCISES: ======================================================================================================================== Es.1 Given vars a and b float, print "a > b" if a greater than b else print "a <= b" if b is greater than or equal to a. Es.2 Given two strings 'banana' 'watermelon' check which word has the major number of characters. Hint: len(str) is a python function that return the string length ======================================================================================================================== A Boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise: >>> 5 == 5 True >>> 5 == 6 False >>> 6 < 7 True >>> 8 <= 2 False The == operator is one of the relational operators; the others are: x!=y # x is not equal to y x>y # x is greater than y x<y # x is less than y x>=y # x is greater than or equal to y x<=y # x is less than or equal to y HINT: - in python u have the elif statement that is an abbreviation of "else if" Tip: If you have lines in the docstring (this string) that look like interactive Python sessions, you can use the doctest module to run and test this code. Try: python -m doctest -v boolean_expressions.py See: https://docs.python.org/3/library/doctest.html Credit to Allen Downey and his excellent book Think Python, from which I stole this descriptions. """ # Write your code here or in your interpreter console. Enjoy!!!
8d764d588205566023cde227edd314455cf89a6d
mariavidrasc19/plusivo-tutorials
/RPI Lesson 02 Dim an LED/main.py
1,583
4.09375
4
from time import sleep #we import the sleep module from the time library import RPi.GPIO as GPIO #we import the RPi.GPIO library with the name of GPIO GPIO.setmode(GPIO.BOARD) #we set the pin numbering to the GPIO.BOARD numbering #for more details check the guide atached to this code GPIO.setup(8, GPIO.OUT) #we set the PIN8 as a output pin pwmPIN = GPIO.PWM(8, 1000) #we create a PWM instance on the 8th pin that is set as #an output pwmPIN.start(0) #we start the pwm pin with a duty cycle of 0. This means that at first the pin #has an output of a digital 0 while True: #we start a loop that never ends in which we modify the duty cycle from 0 to 100 #and back. This will make the LED change it's light intensity for i in range(1000): #for an index i which gets the values from 0 to 100 we change the #duty cycle. pwmPIN.ChangeDutyCycle(i) sleep(0.2) #We wait 1 seconds(10 milliseconds) between the cycle changes #to make the light intensity change visible. for i in reversed(range(1000)): #we do the same thing but going from 100 to 0. pwmPIN.ChangeDutyCycle(i) sleep(0.2) #NOTE! The duty cycle in the GPIO library is represented with numbers from 0 to 100. At 0 the PIN #has no output and at 100 the PIN is a digital 1. #The GPIO.PWM method requires 2 arguments. The first is the previously set PIN, and the second #the frequency at which the pin works.
92ead6f875e82d780d89a676e0c602737dafb509
mhelal/COMM054
/python/evennumberedexercise/Exercise03_06.py
175
4.21875
4
# Prompt the user to enter a degree in Celsius code = eval(input("Enter an ASCII code: ")) # Display result print("The character for ASCII code", code, "is", chr(code))
61c1a344a26ab2bf0f5bab6e191cdf1dc7c1979e
Sophia-Li888/python-learning
/Guess the number.py
2,581
4.09375
4
NAME = input("Hi! What is your name?") print("Hi,",NAME,"! You will be guessing from 1 to 10.") randomRangeLimit = 10 import random number = random.randrange(1, randomRangeLimit) game = "start" level = 1 attempts = [] attemptsLimit = 5 AGAIN = "yes" while AGAIN =="yes": while game == "start": if len(attempts) == attemptsLimit: game = "end" losePlayAgain = input("""Game Ended :( Sorry... Do you want to try again?""") losePlayAgain = losePlayAgain.lower() if losePlayAgain == "yes": randomRangeLimit = 10 print("It's OK that you lost last time... You can try your hardest this time... :) Now, in level 1 again! :(, you will have to guess numbers from 1 to",randomRangeLimit,"! Beware, and have fun :)") import random number = random.randrange(1, randomRangeLimit) game = "start" level = 1 attempts = [] attemptsLimit = 5 break else: game = "end" AGAIN = "no" break userAttempt = input("Guess what number I am!") userAttempt = int(userAttempt) if userAttempt == number: level = level + 1 print("Correct! Horray for you! (you are currently on level",level,"!)") winPlayAgain = input("Do you want to play again?") winPlayAgain = winPlayAgain.lower() if winPlayAgain == "yes": randomRangeLimit = randomRangeLimit + 10 attemptsLimit = attemptsLimit + 1 print("What a brave soul! In the next level, you will have to guess numbers from 1 to",randomRangeLimit, "and you will have",attemptsLimit,"tries! Beware, and have fun :)") import random number = random.randrange(1, randomRangeLimit) game = "start" attempts = [] break else: game = "end" AGAIN = "no" break elif userAttempt > number: attempts.append(userAttempt) print("Too high! These are your attempts:", attempts) else: attempts.append(userAttempt) print("Too low! These are your attempts:", attempts) print("BYE", NAME, "!") randomRangeLimit = 10 import random number = random.randrange(1, randomRangeLimit) game = "start" level = 1 attempts = [] attemptsLimit = 5 AGAIN = "yes"
34226704f82c324265397c9e8d2c68032271461a
trejp404/banking-program
/banking_program.py
4,051
4.28125
4
# Prepedigna Trejo # Assignment 8.1 # Parent Class - Account class BankAccount: def __init__(self, num, bal): self.accountNumber = num self.balance = float(bal) print("A Pre-Paid Account has been created") print("The account number is " + str(self.accountNumber)) print("The balance is $" + '{:,.2f}'.format(self.balance)) def withdraw(self): userWithdraw = float(input("How much would you like to withdraw? ")) if self.balance >= userWithdraw: self.balance = self.balance - float(userWithdraw) print ("\nYou Withdrew:", '$'+'{:,.2f}'.format(userWithdraw)) self.getBalance() else: print("\nInsufficient funds") print("Your current account balance is:", '{:,.2f}'.format(self.balance)) def deposit (self): userDeposit = input("How much would you like to deposit? ") self.balance = self.balance + float(userDeposit) self.getBalance() def getBalance(self): print("Current account balance is: $" + '{:,.2f}'.format(self.balance)) # child class 1 - Pre-Paid Account class CheckingAccount(BankAccount): def __init__(self, num, bal, accountFees, minBal): BankAccount.__init__(self, num, bal) self.accountFees = accountFees self.minimumBalance = 50 print("This account is a Checking Account") print("The account fee is $" + '{:,.2f}'.format(self.accountFees)) print("The minimum balance is $" + '{:,.2f}'.format(self.minimumBalance)) def deductFees(self): print("Deducting fee...") if self.balance < self.minimumBalance: self.balance -= 5; else: print("Balance after fee is now $" + '{:,.2f}'.format(self.balance)) def checkMinimumBalance(self): print("Checking if account balance meets minimum balance...") print("") if float(self.balance) < self.minimumBalance: print("Account balance is too low") self.deductFees() print("You must deposit $" + '{:,.2f}'.format(self.minimumBalance - self.balance) + " to meet the minimum account balance") self.deposit() self.checkMinimumBalance() else: print("Account balance meets minimum balance requirements") #child class 2 - Savings Account class SavingsAccount(BankAccount): def __init__(self, num, bal, intRate): self.intRate = 2 super().__init__(num, bal) def add_interest(self): self.balance *= (1 + (self.intRate/100)) # main program print ("Welcome to the Program") try: flag1 = 0 while flag1 == 0: print("") print("--Main Menu--") print("To open a pre-paid account, press 1") print("To exit the program, press 2") loop1 = input("") if loop1 == '1': flag2 = 0 while flag2 == 0: flag2 = 1 print("") print("--Account Creation--") print("To open a Checking Account, press 1") loop2 = input("") if loop2 == '1': print("") print("--Open a Checking Account--") print("Minimum Balance is $50.00") print("Account fees are $5.00") checkingAccountNumber = input("Enter an Account Number: ") checkingAccountBalance = input("Enter Account Balance: $") print("Please wait while account is created...") print("") my_checkingAccount = CheckingAccount(checkingAccountNumber, checkingAccountBalance, 5.0, 50.0) my_checkingAccount.checkMinimumBalance() flag3 = 0 while flag3 == 0: print("") print("--My Checking Account--") print("What would you like to do?") print("To make a deposit, press 1") print("To check your balance, press 3") print("To make a withdrawal, press 4") print("To go to the Main Menu, press 5") loop3 = input("") if loop3 == '1': my_checkingAccount.deposit() elif loop3 == '3': my_checkingAccount.getBalance() elif loop3 == '4': my_checkingAccount.withdraw() elif loop3 == '5': print("Exiting to Main Menu...") flag3 = 1 else: print("Command not recognized") else: print("Command not recognized") flag2 = 0 elif loop1 == '2': print("Exiting program...") flag1 = 1 else: print("Command not recognized") except: print("Command not recognized")
32f2db9ca8ab3c43a6955102c87024a7665ba404
rgj7/coding_challenges
/projeuler/problem_12.py
456
3.78125
4
import math def getDivisorCount(n): divisors = 0 start = 1 end = math.floor(math.sqrt(n)) while start <= end: if n % start == 0: if start == n//start: divisors += 1 else: divisors += 2 start += 1 return divisors divisors = 0 inc = 0 triangle = 0 while divisors < 500: inc += 1 triangle += inc divisors = getDivisorCount(triangle) print(triangle)
784ef46e6c2bc0219f0566bd7ad57385a2314538
nownabe/competitive_programming
/AizuOnlineJudge/ITP1_Introduction_to_Programming_1/ITP1_2_D_Circle_in_a_Rectangle.py
279
3.640625
4
def determine(w, h, x, y, r): if x - r < 0 or x + r > w: return False if y - r < 0 or y + r > h: return False return True w, h, x, y, r = input().split() if determine(int(w), int(h), int(x), int(y), int(r)): print('Yes') else: print('No')
b644303feef1a0b0046d086b0487dca7e7c3e0d1
asdf2014/algorithm
/Codes/asdf2014/4_median_of_two_sorted_arrays/median_of_two_sorted_arrays.py
1,479
4.0625
4
# https://leetcode.com/problems/median-of-two-sorted-arrays/ # There are two sorted arrays nums1 and nums2 of size m and n respectively. # # Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). # # You may assume nums1 and nums2 cannot be both empty. # # Example 1: # nums1 = [1, 3] # nums2 = [2] # The median is 2.0 # # Example 2: # nums1 = [1, 2] # nums2 = [3, 4] # The median is (2 + 3)/2 = 2.5 # # Related Topics Array Binary Search Divide and Conquer def median_of_two_sorted_arrays(nums1, nums2): nums = [] count1 = 0 count2 = 0 len1 = len(nums1) len2 = len(nums2) total_len = len1 + len2 for i in range(total_len): # collect the tail if count1 == len1: nums.extend(nums2[count2::]) break if count2 == len2: nums.extend(nums1[count1::]) break # merge sort n1 = nums1[count1] n2 = nums2[count2] if n1 > n2: nums.append(n2) count2 += 1 else: nums.append(n1) count1 += 1 middle = total_len // 2 if total_len % 2 == 0: return (nums[middle - 1] + nums[middle]) / 2 else: return nums[middle] assert median_of_two_sorted_arrays([1], []) == 1.0 assert median_of_two_sorted_arrays([1, 3], []) == 2.0 assert median_of_two_sorted_arrays([1, 3], [2]) == 2.0 assert median_of_two_sorted_arrays([1, 2], [3, 4]) == 2.5
6bce92b143014d8f86d5655a5869daaa5222db1a
acemodou/Working-Copy
/DataStructures/v1/Queue/circular_queue.py
1,162
3.71875
4
class CircularQueue: def __init__(self, n): self.front = 0 self.rear = 0 self.size = n self.Q = self.buildQueue() def buildQueue(self): self.Q = [0 for _ in range(self.size)] return self.Q def Enqueue(self, value): if self.is_Full(): raise"Overflow" else: self.rear = self.rear +1 % self.size self.Q[self.rear] = value def Dequeue(self): x = -1 if self.is_Empty(): raise "Underflow" else: self.front = self.front +1 % self.size x = self.Q[self.front] return x def is_Empty(self): return self.rear == self.front def is_Full(self): return self.rear +1 % self.size == self.front def peek(self): self.front += 1 return self.Q[self.front] def peek_rear(self): return self.Q[self.rear] def display(self): value = [] for values in range(self.front+1, self.rear +1 % self.size): value.append(self.Q[values]) return value
f826330e546a6da4c7ed25111e45295a87987fdd
spencerhhall/gone-fishing
/event.py
1,787
3.9375
4
# Contains code for Event object. import datetime speciesCount = { # Number of trout and average size "rainbow trout": [0, 0], "brown trout": [0, 0], "brook trout": [0, 0], "cutthroat trout": [0, 0], "golden trout": [0, 0], "bull trout": [0, 0], "Arctic grayling": [0, 0] } class Event: def __init__(self, location, date, fish, notes): self.location = location self.date = date self.fish = fish self.notes = notes def add_date(): dateRange = datetime.datetime.now() return dateRange def add_fish(): for species in speciesCount: while True: try: num = int(input("How many " + species + " did you catch? ")) except ValueError: print("Input a valid number.") continue if num < 0: print("Numer is too low.") continue speciesCount[species][0] = num break if speciesCount[species][0] != 0: while True: try: num = float(input("What was the average size (inches)? ")) except ValueError: print("Input a valid number.") continue if num <= 0: print("Numer is too low.") continue speciesCount[species][1] = num break return speciesCount @classmethod def from_input(cls): return cls( input("\nNEW EVENT\nLocation: "), cls.add_date(), cls.add_fish(), input("Event notes: "), )
9262f6d671851eab6592884f54821ff631c28966
MikyPopescu/DataProcessingUsingPython
/tema1.py
10,541
4
4
# Tema 1 # 1. Să se creeze o listă de numere întregi pozitive si negative de 10 elemente. # Să se filtreze elementele listei astfel incat acestea sa fie pozitive și să se afișeze lista ordonata crescător. ''' from pip._vendor.distlib.compat import raw_input nrElementeLista = 10 lista = [] for element in range(nrElementeLista): element = int(raw_input("Adaugati un element in lista: ")) lista.append(element) if element < 0: lista.remove(element) lista.sort() if len(lista) > 0: print(lista) else: print("Nu au fost introduse valori pozitive! Lista este vida") ''' # 2. Se da lista de orase de mai jos. Să se realizeze un dictionar care sa grupeze orasele dupa lungimea denumirii. # Dictionarul va avea valorile si cheile ordonate in ordine crescatoare, respectiv alfabetica. # lista_o = ['Vaslui','Cluj', 'Iasi', 'Alba', 'Oradea', 'Arad', 'Craiova', 'Mehedinti', 'Bucuresti', 'Orastie’] ''' listaOrase = ["Vaslui", "Cluj", "Iasi", "Alba", "Oradea", "Arad", "Craiova", "Mehedinti", "Bucuresti", "Orastie"] listaOrase.sort() dictionarOrase = {} for oras in listaOrase: dictionarOrase[oras] = len(oras) print(sorted(dictionarOrase.items(), key = lambda x: x[1])) ''' #3. Se da o listă de liste cu denumiri de electrocasnice si electronice (televizor, frigider, laptop_tip1,laptop_tip2), prețul și cantitatea acestora. # Calculați valoarea fiecărui echipament, adăugați-o în lista fiecarui produs și sortați în funcție de pret, utilizand functia lambda. # Pentru produsele care au pretul mai mare de 3000 si cantitatea mai mare de 5 produse, se va diminua pretul cu 10%. #lista = [['tv', 3500,9], ['frigider', 2500, 4], ['laptop_tip1',5000,5],['laptop_tip2',10000,6]] ''' listaDeListe = [['tv', 3500, 9], ['frigider', 2500, 4], ['laptop_tip1', 5000, 5], ['laptop_tip2', 10000, 6]] # lista[0] = tv, frigider, laptop_tip1, laptop_tip2 # lista[1] = 3500, 2500, 5000, 10000 # lista[2] = 9, 4, 5, 6 for lista in listaDeListe: valoare = lista[1] * lista[2] #valoareEchipament = pret*cantitate lista.append(valoare) if lista[1] > 3000 and lista[2] > 5: discount = lista[1] * 0.1 lista[1] -= discount listaDeListe.sort(key=lambda x: x[1]) print(listaDeListe) ''' #4. Să dau două liste de liste: lista produse aflate pe stoc (lps cu denumire_produs si cantitate) și lista produse comandate (lpc cu denumire_produs si cantitate). # Să se afiseze numele produselor care nu au fost comandate. Sa se calculeze diferenta dintre cantitatea aflata pe stoc si cantitatea comandata si sa se actualizeze cantitatea aflata pe stoc. # Daca cantitatea comandata este mai mare decat cantitatea aflata pe stoc, aceasta va fi egala cu 0. #lps=[['tableta',13], ['tv',50], ['smart_phone',4],['laptop_tip1',41], ['desktop',60], ['tastatura',16], ['monitor32inch',28], ['flipchart',6], ['carioca',200]] #lpc=[['tv',52],['laptop_tip1',20], ['desktop',11], ['tastatura',3], ['monitor32inch',11], ['flipchart',1]] ''' lps = [["tableta", 13], ["tv", 50], ["smart_phone", 4],["laptop_tip1", 41], ["desktop", 60], ['tastatura', 16], ["monitor32inch", 28], ["flipchart", 6], ["carioca", 200]] lpc = [["tv", 52],["laptop_tip1", 20], ["desktop", 11], ["tastatura", 3], ["monitor32inch", 11], ["flipchart", 1]] lista = [] for stoc in lps: lista.append(stoc[0]) for comanda in lpc: lista.append(comanda[0]) for element in lista: if lista.count(element) == 1: print('Produs care nu a fost comandat: ' + element) for comanda in lpc: cant_comanda = comanda[1] for stoc in lps: cant_stoc = stoc[1] if comanda[0] == stoc[0]: diferenta= cant_stoc - cant_comanda if diferenta < 0: stoc[1] = 0 else: stoc[1] = diferenta print(lps) ''' #5. Să se creeze o listă de dicționare cu următoarele chei: id, denumire, pret și cantitate pentru produsele: televizor, laptop, frigider. #lista = [{"id":1, "denumire":"tv", "pret":3500, "cantitate":30}, # {"id":2, "denumire":"laptop", "pret":10000, "cantitate":65}, # {"id":3, "denumire":"frigider", "pret":2500, "cantitate":48}] #Dacă produsele au pretul mai mare decât 5000 sau cantitatea este mai mare decat 20, să se reduca pretul cu 5%. ''' lista = [{"id":1, "denumire":"tv", "pret":3500, "cantitate":30}, {"id":2, "denumire":"laptop", "pret":10000, "cantitate":65}, {"id":3, "denumire":"frigider", "pret":2500, "cantitate":48}] for element in lista: pret = element.get("pret") cantitate = element.get("cantitate") if pret > 5000 and cantitate > 20: pret -= pret * 0.05 element.update({"Pret modificat: ":pret}) print(lista) ''' #6. Să se creeze o listă li1, formată din primele m numere naturale, apoi să se realizeze o funcție prin care să se creeze o listă li2 formată din numerele prime ale listei li1. #se citeste de la tastatura dimensiunea ''' from pip._vendor.distlib.compat import raw_input li1 = [] m = int(raw_input("m= ")) for element in range(m): element = int(raw_input("Adaugati un element in lista: ")) li1.append(element) if element < 0: li1.remove(element) if len(li1)>0: print('Lista de numere naturale introduse: ') print(li1) else: print("Nu au fost introduse valori pozitive! Lista este vida") li2 = [] for element in li1: nrDivizori = 0 d = 1 while d <= element: if element % d == 0: nrDivizori += 1 d += 1 if nrDivizori == 2: li2.append(element) if len(li2) > 0: print('Lista cu numere prime: ') print(li2) else: print("Nu exista numere prime") ''' #7. Sa se deschida fisierul csv clienti_leasing si sa se stocheze in 3 liste valorile din coloanele name_client, venit_per_year_ron si description. # Sa se determine de cate ori apare produsul bancar 'CAMIN SUPER BCR - TL dob. fixa 1 an - dob. referinta var. ulterior IND EUR' in coloana descriere ''' import pandas as pd fisier = pd.read_csv('clienti_leasing.csv') # print(fisier) nume = list(fisier.loc[:,"NUME_CLIENT"]) #print(nume) venit = list(fisier.loc[:,"VENIT_ANUAL_RON"]) #print(venit) descriere = list(fisier.loc[:,"DESCRIERE"]) #print(descriere) nr = descriere.count("CAMIN SUPER BCR - TL dob. fixa 1 an - dob. referinta var. ulterior IND EUR") print("Aparitii CAMIN SUPER BCR - TL dob. fixa 1 an - dob. referinta var. ulterior IND EUR in descriere: ") print(nr) ''' # Tema 2 #1. Să se reprezinte grafic (de tip pie) valoarea medie a daunelor pentru al doilea semestru pentru marcile Audi si Ford pentru fiecare an de fabricatie ''' import pandas as pd from pprint import pprint from matplotlib import pyplot as plt fisier = pd.read_csv("clienti_daune.csv") fisier['DATA_CERERE'] = pd.to_datetime(fisier['DATA_CERERE']) # pprint(fisier['DATA_CERERE']) fisier = fisier[(fisier.MARCA == 'AUDI') | (fisier.MARCA == 'FORD')] fisier = fisier[((pd.DatetimeIndex(fisier['DATA_CERERE']).month) >= 4) & ((pd.DatetimeIndex(fisier['DATA_CERERE']).month) <= 6)] fisier = fisier.groupby('AN_FABRICATIE')['VALOARE_DAUNA'].mean() #pprint(fisier) fisier.sort_values().plot(kind='pie') plt.xlabel('An fabricatie') plt.ylabel('Valoarea medie a daunei') plt.title('Valoarea medie a daunei/an fabricatie FORD si AUDI (sem II)') plt.legend() plt.show() ''' #2. Sa se grupeze dupa tara producatoare si sa afiseze valoarea medie a pretului manoperei ''' import pandas as pd from pprint import pprint fisier = pd.read_csv('clienti_daune.csv') #pprint(fisier) pd.options.display.max_rows= 999 print(round(fisier.groupby('TARAPRODUCATOR')['PRET_MANOPERA'].mean(),2)) ''' #3. Sa se grupeze dupa tara producatoare si sa afiseze tara producatoare si toate tagurile fiecarei marci din tara producatoare respctiva. Sa se calculeze de cate ori apare tagul bad pentru fiecare tara producatoare. ''' import pandas as pd from pprint import pprint fisierDaune = pd.read_csv('clienti_daune.csv') fisierMasini = pd.read_csv('cars.csv') fisierMasini = fisierMasini.rename(columns={'MARCA_CARS':'MARCA'}) rezultat = pd.merge(fisierDaune[['MARCA','TARAPRODUCATOR']], fisierMasini[['MARCA','TAGS']], on='MARCA') print(rezultat.groupby(['TARAPRODUCATOR','MARCA','TAGS']).agg({'TAGS':'count'})) rezultat=rezultat.loc[(rezultat['TAGS']=='bad')] print('Tagul BAD pentru fiecare tara: ') print(rezultat.groupby(['TARAPRODUCATOR']).agg({'TAGS':'count'})) ''' #4. Să se creeze setul format din user_usage și supported_devices și să se reprezinte grafic (bare verticale) traficul însumat (coloana monthly_mb) pentru fiecare brand (coloana Retail Branding). ''' import pandas as pd from pprint import pprint import matplotlib.pyplot as plt user_usage = pd.read_csv('user_usage.csv') user_device = pd.read_csv('user_device.csv') supported_devices = pd.read_csv('supported_devices.csv') rezultat = pd.merge(user_usage,user_device[['use_id', 'device']],on='use_id',how='left') supported_devices.rename(columns={"Retail Branding": "manufacturer"}, inplace=True) rezultat = pd.merge(rezultat,supported_devices[['manufacturer', 'Model']],left_on='device',right_on='Model',how='left') print(rezultat.groupby("manufacturer").agg({"monthly_mb": "sum"})) rezultat.groupby("manufacturer").agg({"monthly_mb": "sum"}).plot(kind='bar') plt.ylabel('manufacter') plt.xlabel('monthly_mb') plt.show() ''' #5. Să se afișeze, utilizând fișierul phone_data.csv, durata însumata pentru fiecare lună și durata însumată pentru un anumit tip de rețea (mobile) pentru fiecare lună. ''' import pandas as pd pd.set_option("display.max_columns", 10) fisier = pd.read_csv('phone_data.csv') print('\nDurata pe fiecare luna') print(fisier.groupby('month')['duration'].sum()) print('\nDurata pe tip de retea mobila') print(fisier[fisier['network_type'] == 'mobile'].groupby('month')['duration'].sum()) ''' #6. Sa se construiasca un pivot table utilizand datele: http://bit.ly/2cLzoxH ''' import pandas as pd date = pd.read_csv('https://raw.githubusercontent.com/resbaz/r-novice-gapminder-files/master/data/gapminder-FiveYearData.csv') #print(date) pivot = date.pivot(index='country', columns='year', values=['continent','pop', 'lifeExp', 'gdpPercap']) print(pivot) ''' #7. Sa se reprezinte grafic sub forma de bare 3 marci din Europa care au cele mai mici daune totale ''' import pandas as pd import matplotlib.pyplot as plt fisier = pd.read_csv('clienti_daune.csv') fisier = fisier[(fisier["REGIUNEPRODUCATOR"] == "Europe")].groupby('MARCA')['VALOARE_DAUNA'].sum().nsmallest(3) fisier.plot(kind='bar', color=["blue", "green", "yellow"]) plt.show() '''
05e25645f3889eea27c58351d5de0fbe8bc7f744
abhigyan709/dsalgo
/hackerrank_python_problems/finding_the_percentage.py
396
3.953125
4
number_of_students = int(input("Enter number of students: ")) students_marks = {} for _ in range(number_of_students): name, *line = input().split() scores = list(map(float, line)) students_marks[name] = scores query_name = input() from decimal import Decimal query_score = students_marks[query_name] total_score = sum(query_score) avg = Decimal(total_score/3) print(round(avg, 2))
1620c51512627e034a4abab208aec284e581a216
yangninghua/python_songsong
/Week1(39集)/day4(9集)/代码/test.py
636
3.625
4
a,b=3,5 # a=3 b=5 print(a,b) # a=3,b=5 # print(a,b) a=b=c=3 print(a,b,c) num = int(input('输入四位整数:')) # 8654 ge = num%10 num = num//10 # 865 shi = num%10 num = num//10 # 86 bai = num%10 num = num//10 # 8 print(num,bai,shi,ge) # num = 9 if num%2==0: print('偶数') else: print('奇数') num1=8 num2=4 num3=0 # False 任何非0的就是True if not(num1%num2): # not True --->False # 条件为True的时候执行的代码块 print('----------->AAAAAAAAA') else: print('***********>BBBBBBBBB') if not True: print('999999999999')
cb68983155f712023ac82d566b4cd02d616233f7
aakriti-sharma/Mini-Projects
/SOP-POS-converter/SOP-POS-converter-master/sop.py
588
3.515625
4
print("SOP CONVERSION") print("Enter variables:") v=list(input().split()) n=len(v) print("Enter expression:") ne=list(input().split("+")) e=[] def sop(t,a): e.remove(t) nt=t+a e.append(nt) e.append(nt+"'") for j in v: if nt.find(j)==-1: sop(nt,j) sop(nt+"'",j) break for i in ne: s=i e.append(i) for j in v: if s.find(j)==-1: sop(s,j) break print("Standard SOP form: ") ne=[] for i in e: if i not in ne: ne.append(i) print(*ne,sep=" + ")
36033de9464a200141bc4f3e13ab69fefaaf86fd
WAT36/procon_work
/procon_python/src/atcoder/abc/past/D_166.py
526
3.65625
4
x=int(input()) b=0 while(True): bi=b**5 ai=x+bi # print(ai,bi,(ai**(1/5))%1.0) #X-B^5 は整数を5乗した数か判定 if(int((ai**(1/5))%1.0) == 0): aj=int((ai**(1/5))//1) # print(ai,aj,bi,b) if((aj**5)==ai): print(aj,b) break b*=-1 bi=b**5 ai=x+bi if(ai>=0 and int((ai**(1/5))%1.0) == 0): aj=int((ai**(1/5))//1) # print(ai,aj,bi,b) if((aj**5)==ai): print(aj,b) break b*=-1 b+=1
74978d6d511a44992d3dfeb398f0a9c6498f04e7
hikyru/Python
/HW1MakingShapes.py
1,107
3.75
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 8 1:45 2020 @author: KatherineYu """ # making a right triangle print("* * * *", end = '\n' '\n' '\n') print("* * *", end = '\n' '\n' '\n' ) print("* *", end = '\n' '\n' '\n' ) print("*", end = '\n' '\n' '\n' ) # making a isoceles triangle print(" *", end = '\n' '\n' '\n') print(" * *", end = '\n' '\n' '\n' ) print(" * *", end = '\n' '\n' '\n' ) print(" * * * *", end = '\n' '\n' '\n' ) # making a diamond print(" *", end = '\n' '\n' '\n') print(" * *", end = '\n' '\n' '\n' ) print(" * *", end = '\n' '\n' '\n' ) print(" * *", end = '\n' '\n' '\n' ) print(" * *", end = '\n' '\n' '\n' ) print(" * *", end = '\n' '\n' '\n' ) print(" *", end = '\n' '\n' '\n') # making a solid rectangle print("* * * *", end = '\n' '\n' '\n') print("* * * *", end = '\n' '\n' '\n') print("* * * *", end = '\n' '\n' '\n') print("* * * *", end = '\n' '\n' '\n') # making a hollow rectangle print("* * * *", end = '\n' '\n' '\n') print("* *", end = '\n' '\n' '\n') print("* *", end = '\n' '\n' '\n') print("* * * *", end = '\n' '\n' '\n')
08f4e875029f0191e4dcc89c139d82f7b272b440
malwadkarrk/Python
/guessnumber.py
666
4.0625
4
import random guesscount = 0 number = random.randint(1,100) username = input("Hello, what's your name?") print(f"Well, {username}, you will get 10 chances to guess the number between (1,100) ") while guesscount < 10: print(f"{username}, take a guess:") guess = int(input()) guesscount += 1 if guess > number: print('Your guess is too high.') elif guess < number: print('Your guess is too low.') elif guess == number: print(f"Good Job {username}, you guessed the number in {guesscount} guesses!") break if guess != number: print(f"Better luck next time. The number is {number}")
c21d9b152c0f7360f317ab1f093291fc635e9bda
hooloong/My_TensorFlow
/Test29_tf/apis/dropout.py
1,093
3.6875
4
''' dropout( x, keep_prob, noise_shape=None, seed=None, name=None ) 功能说明: 原理可参考 CS231n: Convolutional Neural Networks for Visual Recognition 参数列表: 参数名 必选 类型 说明 x 是 tensor 输出元素是 x 中的元素以 keep_prob 概率除以 keep_prob,否则为 0 keep_prob 是 scalar Tensor dropout 的概率,一般是占位符 noise_shape 否 tensor 默认情况下,每个元素是否 dropout 是相互独立。如果指定 noise_shape,若 noise_shape[i] == shape(x)[i],该维度的元素是否 dropout 是相互独立,若 noise_shape[i] != shape(x)[i] 该维度元素是否 dropout 不相互独立,要么一起 dropout 要么一起保留 seed 否 数值 如果指定该值,每次 dropout 结果相同 name 否 string 运算名称 ''' import tensorflow as tf a = tf.constant([1,2,3,4,5,6],shape=[2,3],dtype=tf.float32) b = tf.placeholder(tf.float32) c = tf.nn.dropout(a,b,[2,1],1) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print (sess.run(c,feed_dict={b:0.75}))
4084b554985dc01c396f9362d77ef7ef0f6f35b0
GodsloveIsuor123/holbertonschool-higher_level_programming-3
/0x07-python-test_driven_development/2-matrix_divided.py
1,162
4
4
#!/usr/bin/python3 """ 2-matrix_divided.py file Functions: -> matrix_divided(matrix, div) """ def matrix_divided(matrix, div): """ divides all elements of a matrix matrix must be a list of lists of integers or floats Each row of the matrix must be of the same size div must be a number (integer or float) not 0 Returns a new matrix with element divided by div """ matrix_error = 'matrix must be a matrix (list of lists) of integers/floats' if (not matrix or type(matrix) is not list or matrix is [] or not all([type(row) is list for row in matrix]) or not all([all([isinstance(el, (int, float)) for el in row]) for row in matrix])): raise TypeError(matrix_error) if len(set([len(rows) for rows in matrix])) is not 1: raise TypeError('Each row of the matrix must have the same size') if type(div) is not int and type(div) is not float: raise TypeError('div must be a number') if div == 0: raise ZeroDivisionError('division by zero') return [[round(elmnt / div, 2) for elmnt in row] for row in matrix]
662989cbcc71953064d31693b425500aba3c794a
niteesh2268/coding-prepation
/placement-test/pcpt6/Linus-installs-Linux.py
517
3.546875
4
def getAns(string): entries = string.split('/') stack = [] for entry in entries: if entry == '..': if stack: stack.pop() elif entry == '': continue elif entry == '.': continue else: stack.append(entry) answer = '/'.join(stack) return '/'+ answer def main(): t = int(input().strip()) for _ in range(t): string = input().strip() print(getAns(string)) main()
2a1ad4353767190f403019d7513b7c646fff7b48
marcenavuc/python_listings
/1_basics.py
1,319
3.65625
4
from collections import defaultdict, Counter, namedtuple import heapq import enum # Tuple a = tuple() a = () a = 12, 13 a = ('s', ) a = tuple("Hello, world!") print(a) # Операции print(a.index("l")) print(a[0]) print(a[1:5]) print(a.count("l")) # List a = list() a = list("Hello") a = [] a = [1,2,3] # Операции a.append(1) a.extend([1,2,3]) a.insert(0, 10) a.pop() # Set a = set("hello") b = set("world") # Операции a.issubset(b) a.union(b) a.intersection(b) a.difference(b) a.add("l") print(a) # Dict d = {} d = {"a": 1, "b": 2} d = dict(short="dict", long="dict") print(dict.keys()) print(dict.values()) print(dict.get("some key")) # Collections # Counter c = collections.Counter() for word in ['spam', 'egg', 'spam', 'counter', 'counter', 'spam']: c[word] += 1 print(c) print(Counter({'spam': 3, 'counter': 2, 'egg': 1})) print(c.elements()) print(c.most_common()) # Defaultdict defdict = collections.defaultdict(list) print(defdict) for i in range(5): defdict[i].append(i) print(defdict) #namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print(p.x) print(p.y) print(p[0]) print(p[1]) # heapq x = [15, 5, 10, 5, 2] heapq.heapify(x) heapq.heappush(x, 20) print(x) # Enum class Shake(Enum): VANILLA = 7 CHOCOLATE = 4 COOKIES = 9 MINT = 3
b8ca3c2f2a5d94ba85ad886a2c9193121b61d53a
niripsa/python
/20170728.py
2,151
4.1875
4
### 使用python进行数学运算 ### # 加法 # print(1 + 1) # 减法 # print(2 - 1) # 乘法 # print(2 * 4) # 除法 # print(5 / 2) # 求余 # print(5 % 2) # 地板除 # print(5 // 2) # 乘方 # print(2 ** 3) ### 格式控制符 ### # print("%f" % (5/3)) # 1.666667 # print("%.2f" % (5/3)) # 1.67 # print("%f" % (415 * 20.2)) # 8383.000000 # print("%0.f" % (415 * 20.2)) # 8383 # 格式控制会进行四舍五入 # print("$%.3f" % 30.00123) # $30.001 # print("$%.3f" % 30.00173) # $30.002 # 在python中使用浮点数运算会导致整个算式改用浮点数,去掉所有浮点数会导致将所有数看做int,除非结果是浮点数 ### python保留词 ### # and, as, assert, break, class, continue, def, del, elif, else, except, exec # False, finally, for, from, global, if, import, in, is, lambda, not, None # or, pass, print, raise, return, try, True, while, with, yield ### python内置类型 tuple list dict set ### ## 元组 tuple ---- 不可更改的数据序列 ## # 元组是值的序列,其中每个值都可以被访问,但不可更改;元组被小括号()包围 # a = ('first', 'second', 'third') # print(a) # print(a[0]) # print(a[2]) # b = (a, "b\'s second element") # print(b) # print(b[0][1]) # 注:若要创建一个只有一个元素的元组,需要在末尾加一个逗号,否则会被认为是字符串 ## 列表 list ---- 可以更改的数据序列 ## # 列表类似元组,包含从0开始引用元素的序列,其中元素可以被更改;被中括号[]包围;类似php数组 # 列表已有的元素,可以直接修改 # breakfast = ['coffee', 'tea', 'toast', 'egg'] # print(breakfast) # breakfast[0] = 'pie' # print(breakfast) # # # 向列表末尾添加单个元素,使用内置的append方法 # breakfast.append('milk') # print(breakfast) # # 向列表末尾添加多个元素,使用内置的extend方法,该方法传入一个list或tuple,将其中每个元素追加到原列表末尾 # breakfast.extend(['apple', 'banana', 'pear']) # print(breakfast) # # 列表的长度可以由内置的len方法确定,长度是从1开始的 # print(breakfast.__len__())
d2cff5feb2ae49a6bc0607c602ce4b2522a49182
nilesh7808/CodingNinjaDSA
/BasicPythons/HeapSort.py
291
3.96875
4
from heapq import heappop, heappush def heap_sort(array): heap = [] for i in array: heappush(heap, i) HeapSort = [] while heap is True: HeapSort.append(heappop(heap)) return HeapSort array = [13, 21, 15, 5, 26, 4, 17, 18, 24, 2] print(heap_sort(array))
7cc989d93e084c3e90445991dac5f33f2600750e
kajendranL/Daily-Practice
/loops_exec/01.divi_multi.py
260
4.03125
4
print ('''Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700 (both included)''') print() num = [] for num in range (1500, 2700): if num % 7 ==0 and num % 5 == 0: print(num, end=',')
e0d9894638d0428c986b3211b1f57798468d8915
BenHesketh21/QA-Academy-Training
/Powers.py
163
4.125
4
number1 = float(input("First Number: ")) sqr = number1 ** 2 print(sqr) number2 = float(input("To the power of: ")) answer = number1 ** number2 print(answer)
32b8a3f340960e8824d6831f217bde6c73e564d0
ptanoop/pythonTips
/Return multiple values from functions.py
149
3.84375
4
# function returning multiple values. def x(): return 1, 2, 3, 4 # Calling the above function. a, b, c, d = x() print(a, b, c, d) #-> 1 2 3 4
2d5941b7a577ecda00108139603d32675557bb03
jocespitia/EE381
/project 6/lab6.py
456
3.703125
4
''' EE 381 ''' p = float(input("Enter probability of a jump. ")) S = int(input("Enter the standing position. ")) N = int(input("Enter the boundry position.")) J = int(input("Enter the number of jumps wanted. ")) import random for k in range(J): r = random.uniform(0, 1) if S == 0: S = 1 if S == N: S = N - 1 if (S < N) and (S > 0): if r < p: S = S + 1 else: S = S - 1 print(S)
e7f600640ab9293a4788739e1fcb5f8e4ce1df24
zoltankiss/ctci_problems
/ch-3/3-5/python/sort_stack.py
957
3.890625
4
class Stack: def __init__(self, lst): self.lst = lst def push(self, e): self.lst.append(e) def pop(self): return self.lst.pop() def peek(self): return self.lst[-1] def isEmpty(self): return self.lst == [] class SortStack: def __init__(self): self.stck = Stack([]) def sort(self, stack): while not stack.isEmpty(): top = stack.pop() counter = 0 if self.stck.isEmpty(): self.stck.push(top) else: if self.stck.peek() > top: self.stck.push(top) else: while self.stck.peek() < top: counter =+ 1 stack.push(self.stck.pop()) self.stck.push(top) for _ in range(0, counter): self.stck.push(stack.pop()) return self.stck
2ffb6bdaf1fc035d9ba7e827d6730a924911b485
sharanyavenkat25/modelcompression
/data.py
2,176
3.546875
4
from keras.datasets import mnist from keras.datasets import cifar10 from keras.utils import np_utils # Import other necessary packages import numpy as np def get_data_cifar(num_classes=10): """ Get the CIFAR dataset. Parameters: None Returns: train_data - training data split train_labels - training labels test_data - test data split test_labels - test labels """ print('[INFO] Loading the CIFAR10 dataset...') (train_data, train_labels), (test_data, test_labels) = cifar10.load_data() # Transform labels to one hot labels # Example: '0' will become [1, 0, 0, 0, 0, 0, 0, 0, 0] # '1' will become [0, 1, 0, 0, 0, 0, 0, 0, 0] # and so on... train_labels = np_utils.to_categorical(train_labels, num_classes) test_labels = np_utils.to_categorical(test_labels, num_classes) # Change type and normalize data train_data = train_data.astype('float32') test_data = test_data.astype('float32') train_data /= 255 test_data /= 255 return train_data, train_labels, test_data, test_labels def get_data_mnist(num_classes=10): """ Get the MNIST dataset. Will download dataset if first time and will be downloaded to ~/.keras/datasets/mnist.npz Parameters: None Returns: train_data - training data split train_labels - training labels test_data - test data split test_labels - test labels """ print('[INFO] Loading the MNIST dataset...') (train_data, train_labels), (test_data, test_labels) = mnist.load_data() # Reshape the data from (samples, height, width) to # (samples, height, width, depth) where depth is 1 channel (grayscale) train_data = train_data[:, :, :, np.newaxis] test_data = test_data[:, :, :, np.newaxis] # Normalize the data train_data = train_data / 255.0 test_data = test_data / 255.0 # Transform labels to one hot labels # Example: '0' will become [1, 0, 0, 0, 0, 0, 0, 0, 0] # '1' will become [0, 1, 0, 0, 0, 0, 0, 0, 0] # and so on... train_labels = np_utils.to_categorical(train_labels, num_classes) test_labels = np_utils.to_categorical(test_labels, num_classes) return train_data, train_labels, test_data, test_labels # Import other necessary packages
209534f1df40749a6eab5038e1e2abccad088e91
Oniwa/CodinGame
/There_is_no_Spoon_Episode_1/spoon.py
2,786
3.65625
4
import sys import math # Don't let the machines win. You are humanity's last hope... class Node(object): def __init__(self, x_location, y_location): self.x = x_location self.y = y_location self.coordinate = f'{self.x}, {self.y}' self.x_right = -1 self.y_right = -1 self.x_bottom = -1 self.y_bottom = -1 self.used = False def right_neighbor(self, neighbor): if not neighbor: self.x_right = -1 self.y_right = -1 else: self.x_right = neighbor.x self.y_right = neighbor.y def bottom_neighbor(self, neighbor): if not neighbor: self.x_bottom = -1 self.y_bottom = -1 else: self.x_bottom = neighbor.x self.y_bottom = neighbor.y def __str__(self): return f'{self.x} {self.y} {self.x_right} {self.y_right} {self.x_bottom} {self.y_bottom}' def find_nodes(grid): nodes = [] # width = int(input()) # the number of cells on the X axis width = len(grid[0]) # print(width, file=sys.stderr) # height = int(input()) # the number of cells on the Y axis height = len(grid) # max_x_distance = width # print(height, file=sys.stderr) for i in range(height): # line = input() # width characters, each either 0 or . # for idx, val in enumerate(line): for idx, val in enumerate(grid[i]): if val == '0': nodes.append(Node(idx, i)) return nodes def find_neighbors(nodes, max_x_distance, max_y_distance): # Write an action using print # To debug: print("Debug messages...", file=sys.stderr) closest_x = [] closest_y = [] init_max_x = max_x_distance init_max_y = max_y_distance for item in nodes: node = item node.used = True for item in nodes: if not item.used: if item.y == node.y: distance = item.x - node.x if 0 < distance < max_x_distance: closest_x = item max_x_distance = distance if item.x == node.x: distance = item.y - node.y if 0 < distance < max_y_distance: closest_y = item max_y_distance = distance node.used = False node.right_neighbor(closest_x) node.bottom_neighbor(closest_y) # print(node, file=sys.stderr) closest_x = [] closest_y = [] max_x_distance = init_max_x max_y_distance = init_max_y return nodes # # # # Three coordinates: a node, its right neighbor, its bottom neighbor # for item in nodes: # print(item)
255299efedd954180cd741c90bb264451f19bd0c
juliapetiteau/ComputerScience
/do now 1.30.18.py
280
4.15625
4
#code for luggage weight price weight = float(input("How much does your luggage weigh?")) if weight >120: print("Your luggage is too heavy for this flight") elif weight > 50: print ("There is a $25 fee for this luggage") else: print("Your luggage is accepted as is")
a39ba3bceaee7b53a960c3d7629ad0ef16c239e4
fixik338/subject_269
/Lab3.26.py
214
3.6875
4
M = int(input("Кол-во строк = ")) z = input("Введите слог = ").lower() i = 0 while(i < M): arr = input("Введите строку = ").lower() arr = arr.replace(z, "") print(arr) i+=1
fbc62544545866c4d36a6e324ef1737a7b098714
daniel-reich/turbo-robot
/MSX7AHcNiCZpCsiXY_17.py
646
4.34375
4
""" Create a function which returns how many **Friday 13ths** there are in a given year. ### Examples how_unlucky(2020) ➞ 2 how_unlucky(2026) ➞ 3 how_unlucky(2016) ➞ 1 ### Notes Check **Resources** for some helpful tutorials on the Python `datetime` module. """ def how_unlucky(yr): import datetime count = 0 for mon in range(1, 13): for day in range(1, 32): try: x = datetime.date(yr, mon, day) if day == 13 and x.strftime("%A") == "Friday": count += 1 except ValueError: next return count
764a8bceb1f69e1a50db3bfabd68f247b3b15a25
cmgn/problems
/kattis/mirror/mirror.py
353
3.65625
4
#!/usr/bin/env python3 def main(): t = int(input()) for test in range(t): n, m = map(int, input().split()) output = [] for _ in range(n): output.append(input()[::-1]) print("Test " + str(test + 1)) for item in reversed(output): print(item) if __name__ == '__main__': main()
14b6ecf05f7d01e10ea35a66d34ab6fe81019510
kpy4a/python
/Lesson 9/Lesson9_2.py
456
3.734375
4
class Road: __weight = 25 # удельный вес 1 кв м __thickness = 5 # толщина def __init__(self, length, width): self._length = length self._width = width def calculate_weight(self): return self.__weight * self.__thickness * self._length * self._width length = 5000 # метров width = 20 # метров road = Road(length, width) print(road.calculate_weight(), 'кг')
a04744731e767ecba828583544ac33a6e8c1e8b5
Seva-N/Physics
/phys_2/phys.py
18,419
3.8125
4
import math # Welcome to the Module "Phys" 2.1 def help(): print("Dear Guest!") print("Welcome to the physics module _Phys_ 2.1!") print("My name is Seva Naumov. Program is made by me.") print(" You can find a lot of physical \ constans or calculate some physical values from Mechanics.") print("So you can find some astronomical data about our planet, \ solar system, and our galaxy from Astronimical Mechanics.") print("Finally, you саn find functions with formula of idel gas") print("from Thermodynamics.") print() print("You could enter : phys.[q_data]() ") print("[q] is physical quantity or unit (in other case).") print("[q] could be m, ma, f, P, p, G, F, g, a, M, R, r, c, ") print("R_black_hole (R_bh), astro_unit (au), light_year (ly), parsec (pc) and") print("relativity (l_relat).") print("In Astronomical part:") print("[M] is mass of astronomical object") print("[R] is radius of astronomical object") print("[r] is radius of the orbit of astronomical object") print("[data] is some object and can be constant value:") print() print("density of some bodies") print("moon") print("sun") print("mercury") print("venus") print("earth") print("mars") print("jupiter") print("saturn") print("uranus") print("neptune") print("pluto") print("charon") print("galaxy_milky_way (gMW)") print("supermassive_black_hole (sbh)") print() print("If you want to calculate some values, you can use without [data].") print("But _ should to be certainly in that case.") print("It should be that : phys.[q_]") print("Function without _ give you only constants M, R and r,") print("which determines the parameters of the Earth ") print("(it's mass, radiuses of it and orbit)") print() print("Good luck!") # Mechanics:~ # Horizon distance: ~ def l_horizon(h): R = 6356863 l_horizon = ((R + h) ** 2 - R ** 2) ** (1/2) return l_horizon def L_horizon(h): R = 6356863 L_horizon = math.degrees(math.acos(R / (R + h))) * math.pi * R / 180 return L_horizon def l_horizon_(h, R): l_horizon_ = ((R + h) ** 2 - R ** 2) ** (1/2) return l_horizon_ def L_horizon_(h, R): L_horizon_ = math.degrees(math.acos(R / (R + h))) * math.pi * R / 180 return L_horizon_ # Newton's mechanics: def ma(m, a): ma = m * a return ma def f(m, a): f = m * a return f def a_f(f, m): #~ a_f = f / m return a_f # easy physics: def m(p, V): m = p * V return m def P(F, S): p = F / S return p def P_fluid(p, h): #~ g = 9.80665 p_fluid = p * g * h return p_fluid def P_f(p, h): #~ g = 9.80665 p_f = p * g * h return p_f def P_fluid_(p, h, g): #~ P_fluid_ = p * g * h return P_fluid_ def P_f_(p, h, g): #~ P_f_ = p * g * h return P_f_ def P_atmosphere(): #~ for 273 K (0°C) P_atmosphere = 101325 return P_atmosphere def F_a(p, V): #~ g = 9.80665 F_a = p * g * V return F_a def F_a_(p, V, g): #~ F_a_ = p * g * V return F_a_ # Object Density (p ; kg/m³): ~ def p_air(): p_air = 1.225 return p_air def p_aqua(): #~ p_aqua = 999.841 return p_aqua def p_water(): p_water = 1030 return p_water def p_ice(): p_ice = 917 return p_ice def p_oak(): p_oak = 700 return p_oak def p_milk(): p_milk = 1030 return p_milk def p_honey(): p_honey = 1350 return p_honey def p_oil_sunflower(): p_oil_sunflower = 930 return p_oil_sunflower def p_oil_engine(): p_oil_engine = 900 return p_oil_engine def p_sulfuric_acid(): p_sulfuric_acid = 1800 return p_sulfuric_acid def p_quicksilver(): p_quicksilver = 13600 return p_quicksilver def p_kerosene(): p_kerosene = 2700 return p_kerosene def p_alcohol(): p_alcohol = 2500 return p_alcohol def p_oil(): p_oil = 2300 return p_oil def p_acetone(): p_acetone = 2300 return p_acetone def p_ester(): p_ester = 1800 return p_ester def p_gasoline(): p_gasoline = 1600 return p_gasoline def p_aluminum(): p_aluminium = 2700 return p_aluminium def p_cast_iron(): p_cast_iron = 7000 return cast_iron def p_zinc(): p_zinc = 7100 return p_zinc def p_tin(): p_tin = 7300 return p_tin def p_steel(): p_steel = 7800 return p_steel def p_iron(): p_iron = 7800 return p_iron def p_copper(): p_copper = 8900 return p_copper def p_silver(): p_silver = 10500 return p_silver def p_lead(): p_lead = 11300 return p_lead def p_gold(): p_gold = 19300 return p_gold def p_platinum(): p_platinum = 21500 return p_platinum def p_sun(): p_sun = 3300 return p_sun def p_earth(): p_earth = 5520 return p_earth def p_blood(): p_blood = 1050 return p_blood def p_human(): p_human = 1036 return p_human # Elastic force: ~ def F_e(k, x): F_e = -k * x return F_e # Friction force (max): ~ def F_f(n, N): F_f = n * N return F_f def N(m): g = 9.80665 N = m * g return N def N_(m, b): g = 9.80665 N_ = m * g * math.cos(math.radians(b)) return N_ def _N(m, g): _N = m * g return _N def _N_(m, b, g): _N_ = m * g * math.cos(math.radians(b)) return _N_ def a_f(F, m, n): g = 9.80665 a_f = F / m - n * g return a_f def a_f_(n, b): g = 9.80665 if math.tan(math.radians(b)) > n: a_f_ = g * (math.sin(math.radians(b)) - n * math.cos(math.radians(b))) else: a_f_ = 0 return a_f_ def a_f_F(F, m, n, b): g = 9.8066 if F / m + g * math.sin(math.radians(b)) > g * n * math.cos(math.radians(b)): a_f_F = F / m + g * (math.sin(math.radians(b)) - n * math.cos(math.radians(b))) else: a_f_F = 0 return a_f_F def _a_f(F, m, n, g): _a_f = F / m - n * g return _a_f def _a_f_(n, b, g): if math.tan(math.radians(b)) > n: _a_f_ = g * (math.sin(math.radians(b)) - n * math.cos(math.radians(b))) else: _a_f_ = 0 return _a_f_ def _a_f_F_(F, m, n, b, g): if F / m + g * math.sin(math.radians(b)) > g * n * math.cos(math.radians(b)): _a_f_F_ = F / m + g * (math.sin(math.radians(b)) - n * math.cos(math.radians(b))) else: a_f_F_ = 0 return a_f_F_ # Resistance force ~ # for low speed: ~ def F_r1(k, v): F_r1 = -k * v return F_r1 # for high speed: ~ def F_r2(k, v): F_r2 = -k * v * math.fabs(v) return F_r2 # coefficient of resistance: ~ def k_r(p, C, S): k_r = p * C * S / 2 return k_r # C of resistance: ~ def C_parachute(): C_parachute = 1.17 return C_parachute def C_cube(): C_cube = 1.05 return C_cube def C_cylinder(): C_cylinder = 0.82 return C_cylinder def C_sphere(): C_sphere = 0.47 return C_sphere def C_hemisphere(): C_hemisphere = 0.4 return C_hemisphere def C_teardrop(): C_teardrop = 0.04 return C_teardrop # Astronimical Mechanics:~ # Gravity force: ~ def G(): G = 6.6740831 * 10 ** -11 return G def F(m, M, R): G = 6.6740831 * 10 ** -11 F = G * m * M / R ** 2 return F def F_(m, M, R, h): #~ G = 6.6740831 * 10 ** -11 F_ = G * m * M / (R + h) ** 2 return F_ def g(): #~ g = 9.80665 return g def a(M, R): G = 6.6740831 * 10 ** -11 a = G * M / R ** 2 return a def a_(M, R, h): #~ G = 6.6740831 * 10 ** -11 a_ = G * M / (R + h) ** 2 return a_ # masses of the astronomic objects ( M ; kg ): # our planet (Earth): def M(): M = 5.97 * 10 ** 24 return M # search: def M_(a, R): G = 6.6740831 * 10 ** -11 M_= a * R ** 2 / G return M_ # Moon: def M_moon(): M_moon = 7.35 * 10 ** 22 return M_moon # Sun: def M_sun(): M_sun = 1.9885 * 10 ** 30 return M_sun # planets in our solar system: def M_mercury(): M_mercury = 3.33 * 10 ** 23 return M_mercury def M_venus(): M_venus = 4.87 * 10 ** 24 return M_venus def M_earth(): M_earth = 5.97 * 10 ** 24 return M_earth def M_mars(): M_mars = 6.4185 * 10 ** 23 return M_mars def M_jupiter(): M_jupiter = 1.9 * 10 ** 27 return M_jupiter def M_saturn(): M_saturn = 5.68 * 10 ** 26 return M_saturn def M_uranus(): M_uranus = 8.68 * 10 ** 25 return M_uranus def M_neptune(): M_neptune = 1.02 * 10 ** 26 return M_neptune def M_pluto(): M_pluto = 1.303 * 10 ** 22 return M_pluto # Pluto satellites: def M_charon(): M_charon = 1.52 * 10 ** 21 return M_charon # galaxy Milky Way: def M_galaxy_milky_way(): M_sun = 1.9885 * 10 ** 30 R_galaxy_milky_way = 4.8 * 10 ** 11 * R_sun return R_galaxy_milky_way def M_gMW(): M_sun = 1.9885 * 10 ** 30 M_gMW = 4.8 * 10 ** 11 * R_sun return M_gMW # Supermassive black hole def M_supermassive_black_hole(): M_supermassive_black_hole = 1.7449856116 * 10 ** 41 return M_supermassive_black_hole def M_sbh(): M_sbh = 1.7449856116 * 10 ** 41 return M_sbh # radiuses of the astronomic objects ( R ; m ): # our planet (Earth): def R(): R = 6356863 return R # equator of the Earth: ~ def R_equator(): R_eguator = 6378100 return R_eguator def R_e(): R_e = 6378100 return R_e # pole of the Earth: ~ def R_pole(): R_pole = 6356777 return R_pole def R_p(): R_p = 6356777 return R_p # search: def R_(M, a): G = 6.6740831 * 10 ** -11 R_ = (G * M / a) ** (1/2) return R_ # Moon: def R_moon(): R_moon = 1737100 return R_moon # Sun: def R_sun(): R_sun = 6.96 * 10 ** 8 return R_sun # planets in our solar system: def R_mercury(): R_mercury = 2439700 return R_mercury def R_venus(): R_venus = 6051800 return R_venus def R_earth(): R_earth = 6356863 return R_earth def R_mars(): R_mars = 3389500 return R_mars def R_jupiter(): R_jupiter = 69911000 return R_jupiter def R_saturn(): R_saturn = 58232000 return R_saturn def R_uranus(): R_uranus = 25360000 return R_uranus def R_neptune(): R_neptune = 24622000 return R_neptune def R_pluto(): R_pluto = 5900000 return R_pluto # Pluto satellites: def R_charon(): R_charon = 606000 return R_charon # galaxy Milky Way: def R_galaxy_milky_way(): light_year = 299792458 * 60 * 60 * 24 * 365 R_galaxy_milky_way = 50000 * light_year return R_galaxy_milky_way def R_gMW(): light_year = 299792458 * 60 * 60 * 24 * 365 R_gMW = 50000 * light_year return R_gMW # Supermassive black hole: def R_supermassive_black_hole(): R_supermassive_black_hole = 259162433900880.38 return R_supermassive_black_hole def R_sbh(): R_sbh = 259162433900880.38 return R_sbh # black hole (calculate): def R_black_hole(M, R): G = 6.6740831 * 10 ** -11 c = 299792458 R_black_hole = 2 * G / c ** 2 return R_black_hole def R_bh(M, R): G = 6.6740831 * 10 ** -11 c = 299792458 R_bh = 2 * G / c ** 2 return R_bh # radiuses of the orbits of the astronomic objects ( r ; м ): # orbit of our planet (Earth): def r(): r = 149597870700 return r # search: def r_(v, a): r_ = v ** 2 / a return r_ # orbit of the Moon aroud the Earth: def r_moon(): r_moon = 384.4 * 10 ** 6 return r_moon # orbit of the Sun in galaxy Milky Way: def r_sun(): light_year = 299792458 * 60 * 60 * 24 * 365 r_sun = 26000 * light_year return r_sun # orbits of the planets in our solar system: def r_mercury(): r_mercury = 57909227000 return r_mercury def r_venus(): r_venus = 108.2 * 10 ** 9 return r_venus def r_earth(): r_earth = 149597870700 return r_earth def r_mars(): r_mars = 249.2 * 10 ** 9 return r_mars def r_jupiter(): r_jupiter = 7.785 * 10 ** 11 return r_jupiter def r_saturn(): r_saturn = 1429394069000 return r_saturn def r_uranus(): r_uranus = 2876679082000 return r_uranus def r_neptune(): r_neptune = 4503443661000 return r_neptune def r_pluto(): r_pluto = 5906440606290.79 return r_pluto # orbits of the Pluto satellites aroud Pluto: def r_charon(): r_charon = 19.6 * 10 ** 6 return r_charon # speed of light (c ; m/s ): def c(): c = 299792458 return c # astronomical unit: # (a.u. = m) def astro_unit(n): astro_unit = n * 149597870700 return astro_unit def au(n): au = n * 149597870700 return au # (m = a.u.) def astro_unit_(n): astro_unit_ = n / 149597870700 return astro_unit_ def au_(n): au_ = n / 149597870700 return au_ # light year: #(l.y. = m): def light_year(n): light_year = n * 299792458 * 60 * 60 * 24 * 365 return light_year def ly(n): #~ ly = n * 299792458 * 60 * 60 * 24 * 365 return ly # (m = l.y.): def light_year_(n): light_year_ = n / 299792458 / 365 / 24 / 60 / 60 return light_year_ def ly_(n): ly_ = n / 299792458 / 365 / 24 / 60 / 60 return ly_ # parsec: # (pc = m): def parsec(n): parsec = n * 149597870700 * 360 * 60 * 60 / (2 * math.pi) return parsec def pc(n): pc = n * 149597870700 * 360 * 60 * 60 / (2 * math.pi) return pc # (m = pc): def parsec_(n): parsec_ = 2 * n * math.pi / (360 * 60 * 60 * 149597870700) return parsec_ def pc_(n): pc_ = 2 * n * math.pi / (360 * 60 * 60 * 149597870700) return pc_ # Thermodynamics: ~ # values of an ideal gas:~ def R_k(): R_k = 8.31447 return R_k # molar mass of air:~ def M_v(): M_v = 0.0289644 return M_v # temperature:~ def T(t): T = 273 + t return T def t(T): t = T - 273 return t def t_min(): t_min = -273 return t_min # the Mendeleev-Clapeyron equation:~ def V_ideal_gas(P, v, T): R = 8.31447 V_ideal_gas = v * R * T / P return V_ideal_gas def V_ig(P, v, T): R = 8.31447 V_ig = v * R * T / P return V_ig def P_ideal_gas(V, v, T): R = 8.31447 P_ideal_gas = v * R * T / V return P_ideal_gas def P_ig(V, v, R, T): R = 8.31447 P_ig = v * R * T / V return P_ig def v_ideal_gas(P, V, T): R = 8.31447 v_ideal_gas = P * V / (R * T) return v_ideal_gas def v_ig(P, V, T): R = 8.31447 v_ig = P * V / (R * T) return v_ig def T_ideal_gas(P, V, v): R = 8.31447 T_ideal_gas = P * V / (v * R) return T_ideal_gas def T_ig(P, V, v): R = 8.31447 T_ig = P * V / (v * R) return T_ig # Dependence of temperature on height (T ; K):~ def t_h(t, h): t_h = t - 0.0065 * h return t_h def T_h(T, h): T_h = T - 0.0065 * h return T_h # Accurate pressure and density measurement at a specific temperature:~ def p_t(t): R = 8.31447 M = 0.0289644 P = 101325 T = 273 l = t / 100000 d = 0 if t != 0: while math.fabs(d) < math.fabs(t): p = P * M / (R * T) i = d + l T = 273 + i P = p * R * T / M d = d + l i = d + l T = 273 + i else: p = P * M / (R * T) p_t = p return p_t def P_t(t): R = 8.31447 M = 0.0289644 P = 101325 T = 273 l = t / 100000 d = 0 if t != 0: while math.fabs(d) < math.fabs(t): p = P * M / (R * T) i = d + l T = 273 + i P = p * R * T / M d = d + l i = d + l T = 273 + i else: p = P * M / (R * T) P_t = P return P_t def p_h(t, h): R = 8.31447 M = 0.0289644 G = 6.6740831 * 10 ** -11 M_ = 5.97 * 10 ** 24 R_ = 6356863 P = 101325 T = 273 l = t / 100000 d = 0 if t != 0: while math.fabs(d) < math.fabs(t): p = P * M / (R * T) i = d + l T = 273 + i P = p * R * T / M d = d + l i = d + l T = 273 + i else: p = P * M / (R * T) l = h / 100000 T = 273 + t d = 0 while math.fabs(d) < math.fabs(h): if T - 273 > -270.5: T = T - 0.0065 * l g = G * M_ / (R_ + d) ** 2 d_P = -(p * g * l) if h >= 0: P = P + d_P p = P * M / (R * T) d = d + l p_h = p return p_h def P_h(t, h): R = 8.31447 M = 0.0289644 G = 6.6740831 * 10 ** -11 M_ = 5.97 * 10 ** 24 R_ = 6356863 P = 101325 T = 273 l = t / 100000 d = 0 if t != 0: while math.fabs(d) < math.fabs(t): p = P * M / (R * T) i = d + l T = 273 + i P = p * R * T / M d = d + l i = d + l T = 273 + i else: p = P * M / (R * T) l = h / 100000 T = 273 + t d = 0 while math.fabs(d) < math.fabs(h): if T - 273 > -270.5: T = T - 0.0065 * l g = G * M_ / (R_ + d) ** 2 d_P = -(p * g * l) if h >= 0: P = P + d_P p = P * M / (R * T) d = d + l P_h = P return P_h # Relativity of Einstein:~ # relativity def relativity_v(n, v): c = 299792458 relativity_v = n / (1 - (v / c) ** 2) ** (1/2) return relativity_v def l_relat_v(n, v): c = 299792458 l_relat_v = n / (1 - (v / c) ** 2) ** (1/2) return l_relat_v def relativity_v_(n, v): c = 299792458 relativity_v_ = n * (1 - (v / c) ** 2) ** (1/2) return relativity_v_ def l_relat_v_(n, v): c = 299792458 l_relat_v_ = n * (1 - (v / c) ** 2) ** (1/2) return l_relat_v_ def l_relativity_g(n, M, r): G = 6.6740831 * 10 ** -11 c = 299792458 l_relativity_g = n / (1 - (2 * G * M / (r * c ** 2))) ** (1/2) return l_relativity_g def l_relat_g(n, M, r): G = 6.6740831 * 10 ** -11 c = 299792458 l_relat_g = n / (1 - (2 * G * M / (r * c ** 2))) ** (1/2) return l_relat_g def l_relativity_g_(n, M, r): G = 6.6740831 * 10 ** -11 c = 299792458 l_relativity_g_ = n * (1 - (2 * G * M / (r * c ** 2))) ** (1/2) return l_relativity_g_ def l_relat_g_(n, M, r): G = 6.6740831 * 10 ** -11 c = 299792458 l_relat_g_ = n * (1 - (2 * G * M / (r * c ** 2))) ** (1/2) return l_relat_g_