blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3c866e16fd2941bdcd5a0a51cf7017b702e72f0d
MatheusOldAccount/Exerc-cios-de-Python-do-Curso-em-Video
/exercicios/ex042.py
507
3.96875
4
l1 = float(input('Digite o comprimento do primeiro lado: ')) l2 = float(input('Digite o comprimento do segundo lado: ')) l3 = float(input('Digite o comprimento do terceiro lado: ')) if l1 > l2: sub = l1 - l2 else: sub = l2 - l1 if l1 + l2 > l3 > sub: print('É um triângulo', end=' ') if l1 == l2 and l1 == l3: print('Equilátero') elif l1 != l2 and l1 != l3 and l2 != l3: print('Escaleno') else: print('Isósceles') else: print('Não é um triângulo')
3cf991e79ae9b0c84b2893c3f913cdd4ddebc67c
rwooley159/PublicScrap
/looptest.py
2,913
3.515625
4
from threading import Thread from time import sleep isUnderMaintenance = False class BaseThread(Thread): def __init__(self, parent=None): super(BaseThread, self).__init__() self.parent = parent self.stay_alive = True def run(self): pass def interruptible_sleep(self): '''Sleep conditionally, until stay_alive is False''' while self.stay_alive: sleep(0.1) def halt(self): self.stay_alive = False class MainLoopThread(BaseThread): def __init__(self): super(MainLoopThread, self).__init__() self.barcode_thread = None self.service_thread = None def start_barcode_thread(self): self.stop_barcode_thread() self.barcode_thread = BarcodeThread() self.barcode_thread.start() def stop_barcode_thread(self): if self.barcode_thread is not None: try: self.barcode_thread.halt() self.barcode_thread.join() except: pass def start_service_thread(self): self.stop_service_thread() self.service_thread = ServiceThread() self.service_thread.start() def stop_service_thread(self): if self.service_thread is not None: try: self.service_thread.halt() self.service_thread.join() except: pass main_loop = MainLoopThread() class ServiceThread(BaseThread): def run(self): global isUnderMaintenance while isUnderMaintenance == True: print "Screen Update" sleep(3) self.interruptible_sleep() # Sleep until thread halt class BarcodeThread(BaseThread): def run(self): global isUnderMaintenance global main_loop while True: barcode = raw_input("Please Scan A Barcode: ") if barcode == str(True): isUnderMaintenance = True print str(isUnderMaintenance) print "Starting Service Thread" main_loop.start_service_thread() else: isUnderMaintenance = False print str(isUnderMaintenance) print "Stopping Service Thread" main_loop.stop_service_thread() self.interruptible_sleep() # Sleep until thread halt, useful if needed # Usage example: def main(): global main_loop main_loop.start_barcode_thread() main_loop.interruptible_sleep() #main_loop.start_service_thread() # main_loop.interruptible_sleep() # from other code, you can call the following methods to control the main loop - remember main_loop must be a global # main_loop.start_barcode_thread() # main_loop.stop_barcode_thread() # main_loop.start_service_thread() # main_loop.stop_service_thread() if __name__ == "__main__": main()
38a7024503fe28181c21c90a4a341bb21fcd5ab5
svworld01/group-coding
/day0001/2_Kids_candies.py
376
3.625
4
# created by KUMAR SHANU # 2. Kids With the Greatest Number of Candies # https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ class Solution: def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: max_candy = max(candies) return [((candy + extraCandies) >= max_candy) for candy in candies]
9d150095760de25f5b589642c6e5529671327d88
osmarsalesjr/AtividadesProfFabioGomesEmPython3
/Atividades1/At1Q29.py
345
3.796875
4
def main(): qtd_meses = int(input("Quantidade de tempo em meses: ")) print("Valor é equivalente a ", calcula_anos(qtd_meses), " anos e ", calcula_meses(qtd_meses), " meses.") def calcula_anos(total_meses): return int(total_meses/12) def calcula_meses(total_meses): return total_meses%12 if __name__ == '__main__': main()
23528108997a2c5a97e6fcc58d87ee79e7eacacb
GabrielT98/Representa-grafica-de-grafo
/grafos.py
1,652
3.703125
4
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import networkx as nx while True: print("**************************************") print(" Algoritmos de grafos ") print("**************************************") print(" MENU PRINCIPAL ") print("**************************************") print("1 - Criar um Grafo") print("2 - Exibir um Grafo") print("3 - Finalizar o Programa") opt = int(input("Escolha uma opção: ")) if opt == 1: i = 1 vertice_list = [] arestas_list = [] qtd_vertice = int(input("Quantos vértices terá o grafo? ")) for j in range(1,qtd_vertice+1): vertice_list.append(j) qtd_aresta = int(input("Quantas arestas terá o grafo? ")) while i <= qtd_aresta: aresta_num1 = int(input("Informe o primeiro número da aresta: ")) aresta_num2 = int(input("Informe o segundo número da aresta: ")) tupla = (aresta_num1,aresta_num2) arestas_list.append(tupla) i+=1 G = nx.Graph() G.add_nodes_from(vertice_list) G.add_edges_from(arestas_list) print("Grafo criado com sucesso!") elif opt == 2: try: nx.draw(G) plt.show() except NameError: print("Nenhum grafo encontrado") elif opt ==3: break else: print("Escolha uma opção válida.") continue print("\nPrograma finalizado.")
106a0f3a353109736c3cd0ae9078643972c35e12
robinDovo/data
/data03.py
262
3.9375
4
scores = list() total = number = 0 while number != -1: number = int(input('請輸入學生分數:')) if number != -1: scores.append(number) total += number avg = total/len(scores) print('全班人數%d個,總分:%d,平均:%.2f'%(len(scores),total,avg))
fb4727c9d6a9b898d0a0f3718d938a587e5443bb
Baltimer/Ejercicios_Python
/Ejercicios de inicio/Ejercicio 7.py
565
4.21875
4
# Escribe un programa que pida por teclado un número y que a continuación muestre # el mensaje el número leído es positivo o bien el número leído es negativo # dependiendo de que el número introducido por teclado sea positivo o negativo. # Consideramos al número 0 positivo. # # Autor: Luis Cifre # # Casos tipo: # # numero = 5, Positivo ==> numero = -4, Negativo numero = int(input("Introduce un número y te diré si es positivo o negativo: ")) if numero >= 0: print "El número introducido es positivo" else: print "El número introducido es negativo"
dcba5776bfcc4213887fe0efbb8bce6e030c7358
loongqiao/learn
/python1707A/0724/bigfile.py
590
3.65625
4
""" 由于计算机内存有限所以对大文件 进行分开处理 """ def copy(): #提示用户输入原文件名称 source=input("请输入源文件名称") target=input("请输入目标文件名称") #打开文件 old_file=open(source,"br") new_file=open(target,"bw") #复制文件 while True: contennt=old_file.read(1024*1024) if contennt: new_file.write(contennt) else: print("文件复制完成") break #关闭文件 old_file.close() new_file.close() #程序的入口 copy()
02e1b7b9f30c17c14d4b1cea325d8c56e789bc50
kirbalbek/pprog_balbek
/warmup_uml.py
1,443
4.09375
4
#1 задача ''' class Shape: def __init__(self, side, height): self.side = side self.height = height class Triangle(Shape): def area(self): return self.side*self.height/2 class Rectangle(Shape): def area(self): return self.side*self.height a = int(input()) b = int(input()) d = Triangle(a, b) ans = d.area() print(ans) ''' #2 задача ''' class Mother: def print(self): print(self.voice()) def voice(self): return "я мама" class Daughter(Mother): def voice(self): return "я не мама, я дочка" a = Daughter() a.print() ''' #3 задача ''' class Animal: def __init__(self,name): self.name=name print("возвращаю я животное") class Zebra(Animal): def __init__(self,name,age): super().__init__(name) print("возвращаю я зёбра") print("возвращаю мне " + age +" лет") print("я зёбра " + name ) class Hryusha(Animal): def __init__(self,name,age): super().__init__(name) print("возвращаю я хрюша") print("возвращаю мне " + age +" лет") print("я хрюша " + name ) print("Верните Массимо!!! Вернулись, чтобы править!") na = "vasya" ag = "18" d = Zebra(na, ag) print() print() p = Hryusha(na, ag) '''
038014593c90df86257166ae6e86c849a3e2d378
ctc316/algorithm-python
/Lintcode/Ladder_23_L/1_Easy/30. Insert Interval.py
989
3.96875
4
""" Definition of Interval. class Interval(object): def __init__(self, start, end): self.start = start self.end = end """ class Solution: """ @param intervals: Sorted interval list. @param newInterval: new interval. @return: A new interval list. """ def insert(self, intervals, newInterval): intervals.insert(0, newInterval) i = 0 while i < len(intervals) - 1: if intervals[i].end < intervals[i + 1].start: break if intervals[i].start > intervals[i + 1].end: self.swap(intervals, i, i + 1) i += 1 continue intervals[i] = self.merge(intervals[i], intervals[i + 1]) intervals.pop(i + 1) return intervals def merge(self, a, b): return Interval(min(a.start, b.start), max(a.end, b.end)) def swap(self, arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp
acdabcf4f84f1033ae71487c3f63850d9792bc34
vbelous2020/PythonIntro
/Homework5/task1 - drawings.py
541
4.15625
4
height = 11 width = 11 # Треугольник for x in range(width): for y in range(height): if x == width//2 or y == width//2 - x or y == width//2 + x: print('* ', end='') else: print(' ', end='') print() print() # Ромб for x in range(width): for y in range(height): if x == width // 2 - y or x == width // 2 + y or y == width // 2 + x or x == width-1 - y + width // 2: print('* ', end='') else: print(' ', end='') print() print()
58da33017fd50ed4fba1b70336248cc1b804437b
bssrdf/pyleet
/M/MinimumNumberofFlipstoMaketheBinaryStringAlternating.py
2,529
4.53125
5
''' -Medium- *Sliding Window* Minimum Number of Flips to Make the Binary String Alternating You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Type-1: Remove the character at the start of the string s and append it to the end of the string. Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa. Return the minimum number of type-2 operations you need to perform such that s becomes alternating. The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not. Example 1: Input: s = "111000" Output: 2 Explanation: Use the first operation two times to make s = "100011". Then, use the second operation on the third and sixth elements to make s = "101010". Example 2: Input: s = "010" Output: 0 Explanation: The string is already alternating. Example 3: Input: s = "1110" Output: 1 Explanation: Use the second operation on the second element to make s = "1010". Constraints: 1 <= s.length <= 10^5 s[i] is either '0' or '1'. ''' class Solution: def minFlips(self, s: str) -> int: # For the 1st operation, we can simply do s += s to append the whole # string to the end. # then we make two different string with the same length by 01 and 10 # alternative. for example: s = 11100 # s = 1110011100 # s1= 1010101010 # s2= 0101010101 # finally, use sliding window(size n)to compare s to both s1 and s2. # why we can double s to fullfil the first operation, let's look at # the same example s = 11100: # double s: 1110011100 # size n window: |11100|11100 ==> 1|11001|1100 ==> 11|10011|100 and # so on, when we move one step of the sliding window, it is the same # to append 1 more element from beginning. # Time complexity # Time O(N) # Space O(N) ==> O(1) n = len(s) ss = s + s ss1, ss2 = '01' * n, '10' * n r1 = r2 = 0 res = float('inf') for i in range(2*n): r1 += ss[i] != ss1[i] r2 += ss[i] != ss2[i] if i >= n: r1 -= ss[i-n] != ss1[i-n] r2 -= ss[i-n] != ss2[i-n] if i >= n-1: res = min(res, r1, r2) return res if __name__ == "__main__": print(Solution().minFlips("111000"))
b219902a453ca046ece3abb248adcce5a247b3eb
joshuafreemn/py
/tshirt.py
168
3.515625
4
def make_shirt(size='Large', msg='I <3 Python'): print("You have chosen a shirt size: " + size) print("You shirt will read: " + msg) make_shirt(msg='Lorem Ipsum')
aa358097e440f671b5549c7ff6eec8570ee34b7e
efren1990/codepy
/PythonMultiplataforma_Udemy/00_Iniciales/Condicionales.py
666
4.0625
4
"""------------------------------CONDICIONALES-------------------------------------""" """ if(condicion): Haga Esto() elif(condicion2): Haga Aquello () else: Entonces haga esto () """ """-------------------------------------------------------------------------------------------------------""" accion = int(input("Digite 1 para si, Digite 2 para no: " )) #Verificar la desicion del usuario con un if if(accion == 1): print("Usted dijo que si") elif(accion == 2): print("Usted dijo que no") else: print("Escoja una opcion correcta") """-------------------------------------------------------------------------------------------------------"""
0ce7498244b64c2ee29933a32b458e0f0f1d1c65
NULLCT/LOMC
/src/data/1268.py
2,017
3.796875
4
class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] # 隣接リストG[u][i] := 頂点uのi個目の隣接辺 self._E = 0 # 辺の数 self._V = V # 頂点の数 def E(self): return self._E def V(self): return self._V def add(self, _from, _to): self.G[_from].append(self.Edge(_to, 1)) self._E += 1 def shortest_path(self, s): import heapq que = [] # プライオリティキュー(ヒープ木) d = [float("INF")] * self._V d[s] = 0 heapq.heappush(que, (0, s)) # 始点の(最短距離, 頂点番号)をヒープに追加する while len(que) != 0: cost, v = heapq.heappop(que) # キューに格納されている最短経路の候補がdの距離よりも大きければ、他の経路で最短経路が存在するので、処理をスキップ if d[v] < cost: continue for i in range(len(self.G[v])): # 頂点vに隣接する各頂点に関して、頂点vを経由した場合の距離を計算し、今までの距離(d)よりも小さければ更新する e = self.G[v][i] # vのi個目の隣接辺e if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost # dの更新 heapq.heappush( que, (d[e.to], e.to)) # キューに新たな最短経路の候補(最短距離, 頂点番号)の情報をpush return d N, Q = map(int, input().split()) djk = Dijkstra(N) for i in range(N - 1): u, v = map(int, input().split()) djk.add(u - 1, v - 1) djk.add(v - 1, u - 1) d1 = djk.shortest_path(0) for i in range(Q): c, d = map(int, input().split()) if (d1[c - 1] + d1[d - 1]) % 2 == 0: print("Town") else: print("Road")
c1e62df16ffce5461b47b06719f86f37b57e48db
ma-al/plusser
/yamler/main.py
2,131
4
4
"""Parses CSVs and outputs a YAML.""" import csv import os import argparse from datetime import datetime as dt import yaml def parse_arguments(): """ Get and parse the program arguments. :return: Parsed arguments object :rtype: argparse.Namespace """ pars = argparse.ArgumentParser() pars.add_argument( '-s', '--save', action='store_true', help='Save all output to files') pars.add_argument( 'csv', metavar='input_csv', type=argparse.FileType('r'), help='The CSV file to convert') args = pars.parse_args() for key, val in vars(args).iteritems(): print '{:>6} : {}'.format(key, val) return args def verify(data): """ Simple checks on the read CSV data. :param list data: List of dictionaries """ for dic in data: assert dic['Amount'] assert dic['Balance'] assert dic['Entered Date'] assert dic['Transaction Description'] print print 'Verify OK on {} records'.format(len(data)) def main(): """Main entry point.""" args = parse_arguments() with args.csv as f: reader = csv.DictReader(f) data = [r for r in reader] verify(data) for idx, val in enumerate(data): nd = dt.strptime(val['Entered Date'], '%d/%m/%Y').strftime('%Y-%m-%d') new = \ { 'SN': idx, 'Amount': float(val['Amount']), 'Balance': float(val['Balance']), 'Notes': [' '.join(val['Transaction Description'].split())], 'Date': nd } val.update(new) del val['Entered Date'] del val['Effective Date'] del val['Transaction Description'] if not args.save: print print yaml.dump(data, indent=2, default_flow_style=False) return path, _ = os.path.splitext(args.csv.name) with open(path + '.yaml', 'w') as f: yaml.dump(data, f, indent=2, default_flow_style=False) print print '"{}" saved. Size: {}'.format(f.name, f.tell()) if __name__ == '__main__': main()
81faf74289315b9446929cd79b1c5a69f80d26bc
DamonZCR/PythonStu
/47Tkinter/Text文本输入/14-2Text中Mark的用法.py
328
3.5
4
from tkinter import * '''Mark 这里面就是将这个索引位标记为‘here’这个名字, 可以使用mark.unset()删除这个索引名。''' root = Tk() text = Text(root, width=30, height=20) text.pack() text.insert(INSERT, 'Damon wants to sleep') text.mark_set('here', 1.2) text.insert('here', '插入') mainloop()
80677410e2e07307fcf7f8ac6d6bbd040ad3c927
JeongWonjae/Coding_Practice
/Python/Parity_Bit.py
360
3.796875
4
#Odd parity def prtBit(bit): bit=list(str(bit)) count=0 if len(bit)!=7: print('Input Wrong!') return for j in bit: if j=='1': count=count+1 if count%2==0: bit.append('1') elif count%2==1: bit.append('0') return bit res=prtBit(1001101) print('Result of odd parity is ' ,end='') for n in res: print(n, end='')
0899109e62885d39b35ecfea79cb18c3c9af244b
praveenbommali/DS_Python
/sorting-algo/SelectionSort/SelectionSortImpl.py
739
3.78125
4
# Implementation of Selection Sort class SelectionSortImpl(object): def __init__(self, inputdata): self.inputdata = inputdata def selection_sort(self): input_lenght = len(self.inputdata) for i in range(input_lenght): min = i for j in range(i + 1, input_lenght): if self.inputdata[j] < self.inputdata[min]: min = j temp = self.inputdata[min] self.inputdata[min] = self.inputdata[i] self.inputdata[i] = temp print(self.inputdata) if __name__ == '__main__': inputdata = [20, 10, 5, 6, 2, 12, 17, 88, 76] selectionSortImpl = SelectionSortImpl(inputdata) selectionSortImpl.selection_sort()
f7e9fbc925b1d817e0c6489950f62956cffd7f6a
heechul90/study-python-basic-1
/Python_coding_dojang/Unit 28/practice.py
625
4.21875
4
### Unit 28. 회문 판별과 N-gram 만들기 ## 28.3 연습문제: 단어 단위 N-gram 만들기 ## 표준 입력으로 정수와 문자열이 각 줄에 입력됩니다. ## 다음 소스 코드를 완성하여 입력된 숫자에 해당하는 단어 ## 단위 N-gram을 튜플로 출력하세요(리스트 표현식 사용). ## 만약 입력된 문자열의 단어 개수가 입력된 정수 미만이라면 'wrong'을 출력하세요. n = int(input()) text = input() words = text.split() if len(words) < n: print('wrong') else: n_gram = zip(*[words[i:] for i in range(n)]) for i in n_gram: print(i)
d1504f658319e9469b5329d62e1f3e560eefa119
ThatGuy00000/LPTHW
/ex4.py
839
4.0625
4
cars=100 #how many cars space_in_a_car=4.0 #how many people can fit in each car drivers=30 #people able to drive any of the 1000 cars passengers=90 #number of people that need to fit into cars_not_driven=cars-drivers #more cars than drivers so all the leftover cars cars_driven=drivers # how many cars actually get driven carpool_capacity=cars_driven*space_in_a_car #total number of people in the carpool average_passengers_per_car=passengers/cars_driven #about how many will be in each car, hence the FPO print "There are", cars, "cars around" print "There are only" , drivers, "drivers around" print "There will be", cars_not_driven, "empty cars today" print "We can transport", carpool_capacity, "people today" print "We have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "in each car."
11b9786b7b910e733ad89747c3a0f20b69c874e5
max-conroy/Python
/TrainTimeCalculator.py
3,456
4.53125
5
#Max Conroy; Jordan Westfall; Andrew Weaver #CSC 485; Program 1- Train Problem #Group 2 #User enters data and program calculates time that trains will meet based on the data entered import datetime from datetime import timedelta # Print welcome messages print("=================================") print(" Train Time Calculator Program ") print("=================================") # City names city1=input('Enter the name of the first city: ') city2=input('Enter the name of the second city: ') # Distance between cities distance=input("Enter the distance between "+city1+" and "+city2+" (miles): ") # Train 1 information t1time=input("Enter the time that the first train left " + city1 +" (hh:mm:ss): ") t1speed=input("Enter the speed of the train that left " + city1 + " (mph): ") # Train 2 Information t2time=input("Enter the time that the second train left " + city1 + " (hh:mm:ss): ") t2speed=input("Enter the speed of the train that left " + city1+ " (mph): ") # Convert strings to floats distance = float(distance) # Train speeds in miles per hour t1speed=float(t1speed) t2speed=float(t2speed) # Convert hh:mm:ss:ff time input to decimal (gives integer seconds from midnight i.e. 0) (h,m,s) = t1time.split(":") resultt1 = int(h) * 3600 + int(m) * 60 + int(s) (h,m,s) = t2time.split(":") resultt2 = int(h) * 3600 + int(m) * 60 + int(s) timeapart = resultt2-resultt1 # Number of seconds the trains are apart speeddifference = t2speed-t1speed # Difference in speed of the trains t1distance = (t1speed/3600)*timeapart #Convert speed to miles per second and multiply by timeapart to get current distance of the first train timetomeet = t1distance/speeddifference #How long it takes the trains to meet in hours # Since the trains are parallel heading in the same direction the point at which they meet will cause them to be the same distances on the track therefore only one distance needs to be calculated distancein = t2speed*timetomeet percentagein = (distancein/distance) # Calculate the percentage of voyage t1speedpercent = (t1speed/t2speed) t2speedpercent = (t2speed/t1speed) # Display the full problem to the user print("========================================================================================================") print("The Problem:") print("At "+str(t1time)+" a train left "+str(city1)+" for " +str(city2)+ " at an average speed of "+str(t1speed)+" miles per hour.\n" +str(datetime.timedelta(seconds=timeapart))+ " hours later a second train left "+str(city2)+" for "+str(city1)+", on a parallel track, traveling\nat an average speed of "+str(t2speed)+ " miles per hour. At what distance and time will the two trains meet?") print("========================================================================================================") # Display outputs print("The trains will meet in " + str(datetime.timedelta(hours=timetomeet)) + " hours.") print("At the time the trains meet they will be " + str(format(distancein, '.2f')) + " miles into their journey.") print("The trains completed " +str(format(percentagein, '.1%'))+" of their journey between the two cities.") print("The closure speed of the trains are "+ str(format(speeddifference, '.2f')) +" miles per hour") print("Train 1 is traveling at " + str(format(t1speedpercent, '.1%')) + " of the speed of train 2") print("Train 2 is traveling at " + str(format(t2speedpercent, '.1%')) + " of the speed of train 1")
38499faebc2c08cceafb8dd0049d1c72851311a7
WolfeLogic/CS372-Computer-Networking
/PROJECT-1/chatserver.py
2,587
3.703125
4
#!/usr/bin/env python #****************************************************************************** # COURSE: CS372-400 W2018 # PROJECT: Programming Assignment #1, client-server network application # AUTHOR: DREW WOLFE # RUN: python chatserver.py <port number> # NOTES: # USABLE TCP PORT RANGE: 1024-65535 (49152 - 65535 dynamic, ephemeral ports) # Your terminal will provide an error if the port is already in use. # The chatclient.c must connect to the same host as that of chatserver.py # Initiate chatserver.py prior to starting chatclient.c # Terminate the connection between server and client with "\quit" # Terminate chatserver.py with CTRL + C # # REFERENCES: # Socket Programming HOWTO # https://docs.python.org/3/howto/sockets.html # # Internet Protocols and Support # https://docs.python.org/release/2.6.5/library/internet.html # # List of TCP and UDP port numbers # https://www.wikiwand.com/en/List_of_TCP_and_UDP_port_numbers# #****************************************************************************** import socket import os import sys # User validation def validateArgs(): if len(sys.argv) < 2: print "Expected format => python" + " " + sys.argv[0] + " " + "port" sys.exit() # Starts server | Code based on python.org HOWTO docs def serverStart(): portnumber = int(sys.argv[1]) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('',portnumber)) s.listen(1) return s # Sends to client def mSend(c): fromUser = raw_input(handle + ": ") c.send(handle + ": " + fromUser) return fromUser # Receives from client def mReceive(c): return c.recv(500) # FUNCTION CALLS / PROGRAM START #****************************************************************************** validateArgs() chatServer = serverStart() # SIGINT (signal interupt) to close loop while 1: os.system('clear') #tidy up # Server handle handle = "" handle = raw_input("Enter a handle: ") print "Sever connection with client by inputting \"\\quit\"" print "Terminate chatserver.py via CTRL+C" print "LISTENING FOR CLIENT..." waiting = True # Client connection acceptance conn, addr = chatServer.accept() # \quit to close loop while 1: received = mReceive(conn) if "\quit" in received: break if waiting: os.system('clear') #tidy up print "-Messages-" waiting = False # Print client message print received sent = mSend(conn) if "\quit" in sent: break conn.close()
64c8b8b0346a617a0cdf17a2c3868b004fd0fee3
YuliiaAntonova/leetcode
/Truncate_sentence.py
377
3.625
4
# Input: s = "Hello how are you Contestant", k = 4 # Output: "Hello how are you" # Explanation: # The words in s are ["Hello", "how" "are", "you", "Contestant"]. # The first 4 words are ["Hello", "how", "are", "you"]. # Hence, you should return "Hello how are you". class Solution: def truncateSentence(self, s: str, k: int) -> str: return ' '.join(s.split()[:k])
e06b89fc9cd786a01e350ce061fbd350cd539d46
chemplife/Python
/python_core/meta_programming/meta_programming_basics.py
3,369
4.40625
4
''' MetaProgramming is a technique in which our programs will treat other programs as their data. -> These programs are designed to read, generate, analyze, or transform, and even modify other programs and/or itself while running. -> Basically, code can modify code.. -> Keeps our code DRY (Don't Repeat Yourself) -> Use the existing piece of code.. Some MetaProgramming Techniques: -> Decorators: Using code to modify funcionality of another piece of code -> We can Decorate entire class, not just a function. -> We can have Decorator-Classes, that can be used to decorate other functions and classes. -> Descriptors: Use code to modify the behavior of dot-notation of classes. -> Metaclasses: Used to write more Generic-Code that can be used at many places.. -> (Like a Library or Framework.. Not at application level.. EVER) Used for creating 'type' objects (Classes basically.) -> MetaClasses are in essence class(type) factory. Can be used to hook into Class-Creation-Cylce (when we use the 'class' keyword to create a class, something do creates it.) (They don't play very well with Multiple Inheritance so, to learn it, we will use Single-Inheritance in the beggining.) CAUTION: MetaClasses are easy to understand, but it is not easy to know 'when to use it'. -> If in a case, use of MetaClass is Obvious, "DON'T USE IT THERE..." -> Makes the code harder to read and the details can become very complicated very easily. -> (If you have a Hammer, doesn't mean everything is a nail..) UseCases: -> Writing Libraries / Frameworks -> Mostly not for day-to-day application programs. ''' print('--------------------------------------------------------- Decorators ---------------------------------------------------------\n') from functools import wraps def debugger(fn): @wraps(fn) def inner(*args, **kwargs): print(f'{fn.__qualname__}', args, kwargs) return fn(*args, **kwargs) return inner @debugger def func_1(*args, **kwargs): pass @debugger def func_2(*args, **kwargs): pass func_1(10,20, kw_1='a', kw_2='b') func_2([1,2,3]) # Any change we want in the debugger for both of these, we only need to make the change at 1 place.. print('\n\n--------------------------------------------------------- Descriptors ---------------------------------------------------------\n') class IntegerField: def __set_name__(self, owner, name): self.name = name def __get__(self, instance, owner): print('__get__ called..') return instance.__dict__.get(self.name, None) def __set__(self, instance, value): print('__set__ called..') if not isinstance(value, int): raise TypeError('Must be an Integer Value..') instance.__dict__[self.name] = value class Point: x = IntegerField() y = IntegerField() def __init__(self, x, y): self.x = x self.y = y # When the dot-notation happens on 'x or y', Python know that since they are Descriptor-Instances, we need to call the __get__ and __set__ methods. # This will call __set__() 2 times (1 for 'x' and 1 for 'y') p = Point(10,20) # These will call __get__() print('x= ', p.x) print('y= ', p.y) print('\nSet a Non-Integer value for x.') try: p.x = 10.5 except TypeError as ex: print('Exception happened: ', ex) # Any more checks we want for the 'Point Class' attributes, we can make those changes in 1 place..
2c21688b1d96f0157d5efe380917627f3c765243
mehulthakral/logic_detector
/backend/dataset/solveSudoku/sudoku_10.py
2,017
4
4
from typing import List class Solution: def solveSudoku(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ ## RC ## ## APPROACH : BACKTRACKING ## ## Similar to Leetcode : 51. N Queens, 36. Valid Sudoku ## ## Time Complexity: O(9^(m * n)) ## Space Complexity: O(m*n) n = len(board) rows= [set() for _ in range(n)] cols = [set() for _ in range(n)] grids = [set() for _ in range(n)] def add_val_to_board(row, col, val): rows[row].add( val ) cols[col].add( val ) grids[(row//3)*3+ (col//3)].add( val ) board[row][col] = str(val) def remove_val_from_board(row, col, val): rows[row].remove( val ) cols[col].remove( val ) grids[(row//3)*3+ (col//3)].remove( val ) board[row][col] = "." def fill_board(row, col, val, board): if( row < 0 or col < 0 or row >= n or col >= n ): return ## GIST, incrementing row and col here while not board[row][col] == '.': col += 1 if col == 9: col, row = 0, row+1 if row == 9: return True for val in range( 1, n+1 ): if( val in rows[row] or val in cols[col] or val in grids[(row//3)*3+ (col//3)]): continue add_val_to_board(row, col, val) if( fill_board(row, col, val, board) ): return board remove_val_from_board(row, col, val) for i in range(n): for j in range(n): if( not board[i][j] == "." ): add_val_to_board( i, j, int(board[i][j]) ) return fill_board(0, 0, board[0][0], board)
63436bb4b87c6c50eb7e4b8f1376347a7e2059a3
Satily/leetcode_python_solution
/solutions/solution367.py
639
3.640625
4
class Solution: def isPerfectSquare(self, num): """ :type num: int :rtype: bool """ n = 0 n_list = [] while n ** 2 <= num: n_list.append(n) n += 1 result = 0 for n in reversed(n_list): r = result + n r_square = r ** 2 if r_square == num: return True elif r_square < num: result = r return False if __name__ == "__main__": print(Solution().isPerfectSquare(16)) print(Solution().isPerfectSquare(14)) print(Solution().isPerfectSquare(225))
4c816318ec99eb66bb7bb8da480e0b10a12c21a4
pdebuyl/threefry
/example_gallery/plot_random_series.py
298
3.96875
4
""" ====================== Drawing random numbers ====================== Example of drawing random uniform number with threefry. """ import threefry import matplotlib.pyplot as plt r = threefry.rng(8760396957664838051) data = [r.random_uniform() for i in range(10)] plt.plot(data) plt.show()
e9053b482794d360f0e942196f785d6f4afcbe15
106360130/Python_Class
/HW1_106360130/quiz5.py
599
3.84375
4
def main(): import random num_right = random.randint(0,100) print("num_right : {}".format(num_right)) i = 1 start = 0 end = 100 while(i <= 6) : num_guess = int(input("Please guess a number from {} to {} : ".format(start, end))) if(num_guess > start and num_guess < num_right) : start = num_guess elif(num_guess < end and num_guess > num_right) : end = num_guess elif(num_guess == num_right) : print("You passed") break i = i + 1 if(i > 6) : print("Achive limitted")
e5bd6196455138ec5b148610b3e9b04d77d8fd26
barcenitas/Django
/Serie 1/10.py
222
3.84375
4
cadena =input("Dígame la palabra: ") lista=list(cadena) print("inicio") for letra in lista: if letra == 'a' or letra== 'e' or letra== 'i' or letra== 'o' or letra== 'u': continue print (letra) print("fin")
45de67fa918326557323a9ae6f119949469c3cdd
jytaloramon/monitoria-estrutura-dados-2k20
/prova-ab1/main_driver.py
1,669
3.59375
4
count_pass = 0 def main(): data = [ {'id': '15', 'dist': 52}, {'id': '56', 'dist': 41}, {'id': '1', 'dist': 10}, {'id': '5', 'dist': 2}, {'id': '2', 'dist': 156}, {'id': '136', 'dist': 465} ] print('Antes da Ordenação') for d in data: print(' - id: {}, dist: {}'.format(d['id'], d['dist'])) merge_sort(data, 0, len(data)) print('Depois da Ordenação') for d in data: print(' - id: {}, dist: {}'.format(d['id'], d['dist'])) print(f'PASSOS TOTAIS: {count_pass}') # Merge Sort: complexidade O(n * log(n)) def merge_sort(data, start_i, end_i): # Complexidade: O(log(n)) global count_pass count_pass += 1 if (start_i == end_i - 1): return middle = (start_i + end_i) // 2 merge_sort(data, start_i, middle) merge_sort(data, middle, end_i) merge_sort_curr(data, start_i, middle, end_i) def merge_sort_curr(data, start_i, middle, end_i): # Complexida O(n): Linear arr_aux = [0] * (end_i - start_i) i, j, t = start_i, middle, 0 global count_pass while i < middle and j < end_i: if (data[i]['dist'] <= data[j]['dist']): arr_aux[t] = data[i] i += 1 else: arr_aux[t] = data[j] j += 1 t += 1 count_pass += 1 while i < middle: arr_aux[t] = data[i] i += 1 t += 1 count_pass += 1 while j < end_i: arr_aux[t] = data[j] j += 1 t += 1 count_pass += 1 for s in range(t): data[start_i + s] = arr_aux[s] count_pass += 1 main()
f2f8abfadab38e887900e6b005cc372629103f4d
jemsonjacob/Mypythonworks
/venv/bin/file/opps/calc.py
399
3.8125
4
class Calc: def __init__(self,a,b): self.a = a self.b = b def add(self): return self.a+self.b def sub(self): return self.a - self.b def mul(self): return self.a * self.b def div(self): return self.a/self.b a=int(input("first")) b=int(input("second")) ca = Calc(a,b) print(ca.add()) print(ca.sub()) print(ca.mul()) print(ca.div())
d48834b99a1a10004ec7d8ac2b3b2499f6f88617
saikpr/short_codes
/py/network_security_lab/hill.py
1,393
3.78125
4
import utils def encrypt(message, matrix, encryption=True): """ Hill encryption (decryption). """ message = message.upper() if not utils.invertible(matrix): # The matrix should be invertible. return "Non invertible matrix" if len(message) % 2 != 0: message = message + 'X' couple = [list(message[i*2:(i*2)+2]) for i in range(0, len(message)/2)] result = [i[:] for i in couple] if not encryption: # To decrypt, just need to inverse the matrix. matrix = utils.inverse_matrix(matrix) for i, c in enumerate(couple): if c[0].isalpha() and c[1].isalpha(): result[i][0] = chr(((ord(c[0])-65) * matrix[0][0] + \ (ord(c[1])-65) * matrix[0][1]) % 26 + 65) result[i][1] = chr(((ord(c[0])-65) * matrix[1][0] + \ (ord(c[1])-65) * matrix[1][1]) % 26 + 65) return "".join(["".join(i) for i in result]) def decrypt (cypher, matrix): """ Hill decryption. """ return encrypt(cypher, matrix, False) if __name__ == '__main__': # Point of entry in execution mode print "Encrpted value :" print encrypt("""Hello world""", [[11, 3], [8, 7]]) print "\n\n\nDecrypted value" print decrypt(encrypt("""Hello world""", [[11, 3], [8, 7]]), [[11, 3], [8, 7]])
9576ee1260fa82e6efacb7ddc4710e282ead9ecd
Manvichauhan/python-project
/tuple.py
144
3.515625
4
# a = ("ram","rohit","mohit"1,20.3,True,) print(a) a[0]="abc" #not update print(a) b=() b = (1) #empty tuple b = (1, ) print(b) print(type(b))
d10b78da747c5826df42f5d81989cf26dccbbf34
idnd/mit-algorithms
/sort.py
1,987
4.03125
4
def arrayPrint(A): for i in xrange( len( A) ): print A[i] , print '' def less(a,b): return a < b def greater(a,b): return a > b def insertionSort(A, func = less): """ Insertion sort: - Simple implementation - Efficient for (quite) small data sets - Adaptive (i.e., efficient) for data sets that are already substantially sorted: the time complexity is O(n + d), where d is the number of inversions - More efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such as selection sort or bubble sort; the best case (nearly sorted input) is O(n) - Stable; i.e., does not change the relative order of elements with equal keys - In-place; i.e., only requires a constant amount O(1) of additional memory space - Online; i.e., can sort a list as it receives it """ for i in xrange( len(A) ): valueToInsert = A[i] holePos = i while holePos > 0 and func(valueToInsert, A[holePos-1]): A[holePos] = A[holePos - 1] holePos = holePos - 1 A[holePos] = valueToInsert def quickSort(A,p,r,myflag = False): def partition(A,p,r,myflag): print 'partition a=',A,'p=',p,'r=',r x = A[r-1] #pivot i = p - 1 for j in xrange(p,r-2): if A[j] <= x: i = i + 1 A[i],A[j] = A[j],A[i] if myflag: print A if myflag: print (i+1),(r-1) print A[i+1], A[r-1] A[i+1],A[r-1] = A[r-1],A[i+1] if myflag: print A[i+1], A[r-1] print 'return =', (i + 1) print A return i + 1 if p<r-1: q = partition(A,p,r,myflag) quickSort(A,p,q-1,True) quickSort(A,q+1,r,True) ''' X = [1,5,3,2,4] X = [2,8,7,1,3,5,6,4] arrayPrint(X) quickSort(X, 0,len(X),True) arrayPrint(X) ''' import RedBlackTree
c675d8b48f5c249f335e69d113f5952db9c0bcd6
bikongyouran/python_practice
/BasicAlgorithm/bubbleSort.py
509
3.828125
4
import numpy as np def bubble_sort(source): length = len(source) i = 0 j = 0 while j < length: while i < length - j - 1: if source[i] > source[i + 1]: temp = source[i] source[i] = source[i + 1] source[i+1] = temp i += 1 j += 1 i = 0 if __name__ == '__main__': source = np.random.random_integers(1, 20, 10) print "source is ", source bubble_sort(source) print 'target is ', source
746c9e902bea010214cda6f547e398d5db6712f3
jaeyoon-lee2/ICS3U-Assignment-03-Python
/the_bigger_number.py
1,152
4.46875
4
#!/user/bin/env python3 # Created by: Jaeyoon # Created on: Oct 2019 # This program display which number is bigger import random def main(): # this function display which number is bigger # input integer1_as_string = input("Enter the first number (integer): ") integer2_as_string = input("Enter the second number (integer): ") # process & output try: integer1_as_number = int(integer1_as_string) integer2_as_number = int(integer2_as_string) if integer1_as_number > integer2_as_number: print("The first number ({0}) is bigger than the second " + "number ({1})." .format(integer1_as_number, integer2_as_number)) elif integer1_as_number < integer2_as_number: print("The second number ({1}) is bigger than the first " + "number ({0})." .format(integer1_as_number, integer2_as_number)) else: print("Those numbers are the same.") except Exception: print("It is not an integer") finally: print("Thanks for playing") if __name__ == "__main__": main()
d9f6354ae5a567166ec312cb3e95e68b5ea0dec3
weltonvaz/Zumbis
/alfabeticamente.py
483
3.625
4
# organizar_alfabeticamente.py - 20.07.2004 # por Luiz E. Lepchak Jr. <jr.lepchak@ig.com,br> # Declaração da função def organizar_alfabeticamente(lista): "Organiza alfabeticamente as strings contidas dentro de uma lista." for x in range (len(lista)): for y in range (len(lista)): if lista[x] < lista[y]: lista[x], lista[y] = lista[y], lista[x] # Exemplo da aplicação lista = ["linux", "google", "kde, kdf"] print ("Antes:", lista) organizar_alfabeticamente(lista) print ("Depois:", lista)
89a115d1acdacc49522ddfbd9e55e27f1acc2b58
amelialin/tuple-mudder
/ex42.py
2,000
4.46875
4
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): def __init__(self): print "Made an Animal" ## ?? Dog is-a Animal class Dog(Animal): def __init__(self, name): ## ?? Dog has-a name self.name = name print "Made a Dog named %s" % name ## ?? Cat is-a Animal class Cat(Animal): def __init__(self, name): ## ?? Cat has a name self.name = name print "Made a Cat named %s" % name ## ?? Person is a object class Person(object): def __init__(self, name): ## ?? Person has a name self.name = name ## Person has-a pet of some kind self.pet = None print "Made a Person named %s" % name ## ?? Employee is a Person class Employee(Person): def __init__(self, name, salary): ## ?? hmm what is this strange magic? Popping up one level using super(), to Person; Person has a name. super(Employee, self).__init__(name) ## ?? Employee has a salary self.salary = salary print "Made an Employee with salary %d" % salary ## ?? Fish is an object class Fish(object): def __init__(self): print "Made a Fish" ## ?? Salmon is a Fish class Salmon(Fish): def __init__(self): print "Made a Salmon" ## ?? Halibut is a Fish class Halibut(Fish): def __init__(self): print "Made a Halibut" ## rover is-a Dog that has a name Rover rover = Dog("Rover") ## ?? satan is a Cat that has a name Satan satan = Cat("Satan") ## ?? mary is a Person that has a name Mary mary = Person("Mary") ## ?? mary has a pet, satan mary.pet = satan print "mary.pet", mary.pet ## ?? frank is an Employee that has a name Frank and salaray 120,000 frank = Employee("Frank", 120000) ## frank has a pet that we set equal to rover frank.pet = rover print "frank.pet", frank.pet ## flipper is a Fish flipper = Fish() ## crouse is a Salmon crouse = Salmon() ## harry is a Halibut harry = Halibut()
c13ab31e5b014dda5de92c286de7253cf34b42fe
loongqiao/learn
/python1707A/0710-0716/demo01私用字典.py
1,407
3.875
4
""" 这是一个私有字典的 有用户的固定信息 可以增加信息 可以修改信息 可以查询信息 """ users=[] u1={"name":"a","age":"20","sex":"男","phone":"123456"} u2={"name":"b","age":"18","sex":"女","phone":"124563"} users.append(u1) users.append(u2) while True: #打印界面 print("\t\t信息查询") print("------------------------------------------------------------------") print("\t1.查看所有用户信息") print("\t2.客户信息修改") print("\t3.新增一个客户") print("\t4.客户资料查询") print("\t5.退出系统") print("------------------------------------------------------------------") choice=input("请输入你的选项:") if choice=="1": #遍历所有用户 for user in users: print("用户姓名:%s;年龄:%s;性别:%s,电话:%s" % (user.get("name"), \ user.get("age"),user.get("sex"),user.get("phone"))) else: input("按任意键返回上一层") elif choice=="2": #改 elif choice=="3": #增加用户 #定义一个空字典 name=input("请请输入你要添加的姓名:").strip() age=input("请输入你要添加的年龄:").strip() xb=input("请输入你要添加的性别:").strip() pn=input("请输入电话号码").strip() #创建用户字典 user={"name":name,"age":age,"sex":xb,"phone":pn} #存储信息 users.append(user) input("用户添加完成,按任意键继续")
74d28ab2eb606f887bcf11615d6948198e48952c
yqz/myalgoquestions
/partition.py
992
3.90625
4
#!/usr/bin/python """ QUESTION: Quick sort partition function """ def partition(a, p): """ Parition array a by pivot a[p]. """ if a is None or len(a) == 1: return 0 # Swap a[p] to the last position pivot = a[p] a[p] = a[len(a) - 1] a[len(a) - 1] = pivot j = 0 k = 0 # [0..j-1] contains elements that is smaller than pivot. # [j..k-1] contains elements that is greater or equal to pivot. # [0..k-1] is all the elements that is processed so far. while k < len(a) - 1: if a[k] >= pivot: k += 1 else: t = a[k] a[k] = a[j] a[j] = t j += 1 k += 1 # swap pivot to a[j] a[len(a) - 1] = a[j] a[j] = pivot return j, a import unittest class MyUnitTest(unittest.TestCase): def setUp(self): pass def test_func(self): print partition([5,5,5,5,5,5], 2) if __name__ == '__main__': unittest.main()
d1ff201eea78a78f404ae1d0fccd18b80aa58dcd
ethyl2/Intro-Python-I
/src/misc/hackerrank/activity_notifications.py
2,795
3.984375
4
""" https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=sorting&isFullScreen=true&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen Given d <- number of trailing days needed before bank sends notifications Given expenditure <- arr of amount spent each day Bank sends notification if amount spent that day is >= 2 times the median spending for trailing num of days. Print num of times the client will receive a notification (during the days included in expenditure arr) If d=3, expenditure=[10,20,30,40,50] Day 4: median of [10,20,30] is 20 and 40 is spent. 40 >= 20 * 2 so notification is sent. Day 5: median of [20, 30, 40] is 30. 50 is spent. 50 is not >= 30 * 2 so no notification. Print 1. The median of a list of numbers can be found by arranging all the numbers from smallest to greatest. If there is an odd number of numbers, the middle one is picked. If there is an even number of numbers, median is then defined to be the average of the two middle values. """ import statistics import sys import os def find_median(nums): nums.sort() if len(nums) % 2 == 1: # odd length return nums[len(nums)//2] else: # even length mid_num1 = nums[len(nums)//2] mid_num2 = nums[(len(nums)//2) - 1] return (mid_num1 + mid_num2)/2 def activityNotifications(expenditure, d): # Initialize var for num of notifications num_notifications = 0 # Loop through expenditure, starting at index d # Calculate median of past d days # Compare median to 2 * that day's expenditure # If >= then increment counter. for i in range(d, len(expenditure)): print("i is: " + str(i)) print(expenditure[i-3:i]) current_median = statistics.median(expenditure[i-3:i]) # Or to use my function: # current_median = find_median(expenditure[i-3:i]) print("median: " + str(current_median) + ' * 2 = ' + str(current_median * 2) + " versus " + str(expenditure[i])) # print("day_amount: ", str(expenditure[i])) if (current_median * 2) <= expenditure[i]: num_notifications += 1 print(num_notifications) return(num_notifications) # print(find_median([10, 20, 30])) # activityNotifications([10, 20, 30, 40, 50], 3) # 1 # activityNotifications([1, 2, 3, 4, 4], 4) # 0 # activityNotifications([2, 3, 4, 2, 3, 6, 8, 4, 5], 5) # 2 activityNotifications([0, 82, 180, 55, 168, 41, 179, 59, 139, 71, 6, 12, 135, 139, 73, 157, 4, 74, 195], 14) ''' with open(os.path.join(sys.path[0], 'large_case.txt'), 'r') as f: nums = f.read().split(" ") activityNotifications(nums, 10000) # 633 '''
fd9154d5a2686f190e80945b95cf8f9ce5ba3d08
allester/cis40
/day_converter.py
498
4.03125
4
def day_converter(num): if num == 1: day = "Monday" elif num == 2: day = "Tuesday" elif num == 3: day = "Wednesday" elif num == 4: day = "Thursday" elif num == 5: day = "Friday" elif num == 6: day = "Saturday" else: day = "Sunday" return day print(day_converter(1)) print(day_converter(2)) print(day_converter(3)) print(day_converter(4)) print(day_converter(5)) print(day_converter(6)) print(day_converter(7))
954eec135fd979cec4bb3aa59c98cfcc307258d3
TREMOUILLEThomas/ex-68
/ex 68 (3).py
401
3.96875
4
from turtle import * def triangle(a): begin_fill() for i in range (3): forward(a) left(120) end_fill() def tritri(a): for i in range(3): triangle(a) left(90) up() forward(a/2) right(90) forward(a/6) down() a=a*(2/3) if i == 7: a=100 a=int(input("cote")) tritri(a) hideturtle() input()
f275dea1b8f0cadacfccb70b5bcd4b3001f79bf7
Anikcse18/CodeforcesSlovedProblempart-1
/A. Rainbow Dash, Fluttershy and Chess Coloring.py
122
3.765625
4
size = int(input()) for i in range(size): s = int(input()) if s==1: print(s) else: print(s-1)
09cd2d99b22d3a678adbe6cf3c794e7e79b8b9a1
juanbolivar/python
/agenda_telefonica.py
3,461
3.875
4
#Agregar un contacto #Eliminar Contactos #Actualizar un Contacto #Ver un Contacto #Ver toos nuestros contactos agenda_telefonica = dict() def imprimir_operacion(nombre_operacion): print() print("------------Agenda Telefónica------------") print(nombre_operacion) print("-------------------------------------------") print() def agregar_contacto(): # print("agregar contacto") nombre = input("Nombre del nuevo contacto: ") numero = input("Numero del nuevo contacto: ") agenda_telefonica[nombre] = numero imprimir_operacion("Contacto Agregado") # print() # print("------------Agenda Telefónica------------") # print("Contacto Agregado") # print("-------------------------------------------") # print() def eliminar_contacto(): # print("eliminar contacto") nombre = input("Nombre del contacto que desea borrar: ") try: del agenda_telefonica[nombre] except KeyError: imprimir_operacion("Ese contacto no existe") else: imprimir_operacion("Contacto Eliminado") def actualizar_contacto(): # print("actualizar contacto") nombre = input("Nombre del contacto que deseas actualizar: ") numero = input("Nuevo numero de este contacto: ") agenda_telefonica[nombre] = numero imprimir_operacion("Contacto Actualizado") def ver_contacto(): # print("ver contacto") nombre = input("Nombre del contacto: ") nombre_operacion = None try: # nombre_operacion = print(nombre + " - " + agenda_telefonica[nombre]) nombre_operacion = "{} - {}".format(nombre,agenda_telefonica[nombre]) except KeyError: nombre_operacion = print("Ese contacto no existe") imprimir_operacion(nombre_operacion) def ver_contactos(): # print("ver contactos") nombre_operacion = None if len(agenda_telefonica) == 0: nombre_operacion = print("No existe ningún contacto") else: for contacto in agenda_telefonica: # nombre_operacion = print(contacto + "-" + agenda_telefonica[contacto]) if nombre_operacion == None: nombre_operacion = "{} - {}".format(contacto,agenda_telefonica[contacto]) else: nombre_operacion += "\n{} - {}".format(contacto,agenda_telefonica[contacto]) imprimir_operacion(nombre_operacion) def iniciar_agenda(): print("Bienvenido a la Agenda Telefónica de Juan") while True: print("1 - Agregar Contacto") print("2 - Eliminar Contacto") print("3 - Actualiza Contacto") print("4 - Ver un Contacto") print("5 - Ver todos los Contacto") print("6 - Salir") try: operacion = int(input(": ")) except ValueError: print() print("Porfavor selecciona un numero del 1 al 6") print() else: if operacion == 1: agregar_contacto() elif operacion ==2: eliminar_contacto() elif operacion == 3: actualizar_contacto() elif operacion == 4: ver_contacto() elif operacion == 5: ver_contactos() elif operacion == 6: break else: print("operación desconnocida") def dar_despedida(): print() print("Gracias por usar nuestra agenda telefónica") print() iniciar_agenda() dar_despedida()
1e954a288215b45f0c10f7fceb70772c8752053b
aa18514/workbook-solutions
/Python/challenge 22 super_saving.py
927
4.09375
4
total_money = input("What is the total amount in Rs. before discount?") if total_money > 5000: discount = 1000 elif total_money > 1000: discount = 150 elif total_money > 500: discount = 50 elif total_money > 100: discount = 5 else: disount = 0 discounted_price = total_money - discount print("The discount you receive is Rs." + str(discount) + " and the discounted price is Rs." + str(discounted_price)) total_money = input("What is the total amount in Rs. before discount?") if total_money <= 100: discount = 0 elif total_money > 100 and total_money <= 500: discount = 5 elif total_money > 500 and total_money <= 1000: discount = 50 elif total_money > 1000 and total_money <= 5000: discount = 150 else: disount = 1000 discounted_price = total_money - discount print("The discount you receive is Rs." + str(discount) + " and the discounted price is Rs." + str(discounted_price))
e5fb4d48ef90a4a3d77d88e313949c24562bc3d5
Mohamad11002/Mixed-Python-Projects
/WordCloud/test.py
832
3.734375
4
################################################## #### Word Cloud with Python #### pip install matplotlib #### pip install wordcloud #### pip install numpy #### pip install Pillow #### you have to run this code on terminal or cmd ################################################## import matplotlib.pyplot as pPlot from wordcloud import WordCloud, STOPWORDS import numpy as np from PIL import Image # You can paste the text you want into file 'test.txt' and save it. dataset = open("test.txt", "r", encoding="utf8").read() def create_word_cloud(string): maskArray = np.array(Image.open("white.png")) cloud = WordCloud(background_color = "white", max_words = 200, mask = maskArray, stopwords = set(STOPWORDS)) cloud.generate(string) cloud.to_file("wordCloud.png") dataset = dataset.lower() create_word_cloud(dataset)
a12107517ff64eb1332b2dcfcbe955419bc5d935
kelvin5hart/calculator
/main.py
1,302
4.15625
4
import art print(art.logo) #Calculator Functions #Addition def add (n1, n2): return n1 + n2 #Subtraction def substract (n1, n2): return n1 - n2 #Multiplication def multiply (n1, n2): return n1 * n2 #Division def divide(n1, n2): return n1 / n2 opperators = { "+": add, "-":substract, "*": multiply, "/": divide } def calculator(): num1 = float(input("What's the first number? \n")) nextCalculation = True for i in opperators: print (i) while nextCalculation: operator = input("Pick an operation from the line above: ") if operator not in opperators: nextCalculation = False print("Your entry was invalid") calculator() num2 = float(input("What's the next number? \n")) operation = opperators[operator] result = operation(num1, num2) print(f"{num1} {operator} {num2} = {result}") continueCalculation = input(f"Type 'y' to continue calculating with {result}, or type 'n' to start a new calculation or 'e' to exit. \n").lower() if continueCalculation == "y": num1 = result elif continueCalculation == "n": nextCalculation = False calculator() elif continueCalculation == "e": nextCalculation = False else: print("Invalid Entry") nextCalculation = False calculator()
9d5786dcca0cfe8aa14663ee338da17b5b3b1b1a
StarkTan/Python
/OpenCV/image_processing/contours/contour_features.py
6,161
3.515625
4
""" To find the different features of contours, like area, perimeter, centroid, bounding box etc """ import numpy as np import cv2 as cv def feature_1(): """ 图像矩 cv.moments(cnt) : mji 几何矩,muji 中心距,nuji 中心归一化距 图形面积 cv.contourArea(cnt) 图形周长 cv.arcLength(cnt, True) 图形多边拟合 cv.approxPolyDP(cnt, epsilon, True) 图形点集,轮廓点之间的最大距离数,是否封闭图形 图形凸包 cv.convexHull(cnt[, hull[, clockwise[, returnPoints]]) 图形点集,凸包点集,输出包点的方向,输出类型(点或索引) 检查凸性 cv.isContourConvex(approx) 外接矩形,外接最小矩阵 最小包围圆 椭圆拟合 拟合线 """ img = cv.imread('../../resources/start_light.png') imgray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) ret, thresh = cv.threshold(imgray, 127, 255, 0) contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) cnt = contours[1] img_copy = img.copy() image = cv.drawContours(img_copy, [cnt], 0, (0, 255, 0), 3) cv.imshow(winname='contours', mat=image) cv.waitKey(0) cv.destroyWindow(winname='contours') M = cv.moments(cnt) # 计算一个图像的图像矩 print(M) # 计算图像中心 cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) print(cx, cy) # 计算图像的轮廓面积 area = cv.contourArea(cnt) print(area) # 计算图形的周长 perimeter = cv.arcLength(cnt, True) print(perimeter) # 多边拟合函数 epsilon = 0.06 * cv.arcLength(cnt, True) approx = cv.approxPolyDP(cnt, epsilon, True) img_copy = img.copy() image = cv.drawContours(img_copy, [approx], 0, (0, 255, 0), 3) cv.imshow(winname='approximation', mat=image) cv.waitKey(0) epsilon = 0.01 * cv.arcLength(cnt, True) approx = cv.approxPolyDP(cnt, epsilon, True) img_copy = img.copy() image = cv.drawContours(img_copy, [approx], 0, (0, 255, 0), 3) cv.imshow(winname='approximation', mat=image) cv.waitKey(0) cv.destroyWindow(winname='approximation') # 凸包计算 hull = cv.convexHull(cnt) img_copy = img.copy() image = cv.drawContours(img_copy, [hull], 0, (0, 255, 0), 3) cv.imshow(winname='convexHull', mat=image) cv.waitKey(0) cv.destroyWindow(winname='convexHull') # 凸性检测 检测一个曲线是不是凸的 print(cv.isContourConvex(approx)) print(cv.isContourConvex(hull)) # 外接矩形展示 cnt = contours[2] x, y, w, h = cv.boundingRect(cnt) # 计算方式一:算出矩阵起始坐标和高宽 img_copy = img.copy() cv.rectangle(img_copy, (x, y), (x+w, y+h), (0, 255, 0), 2) # 在图片中画出第一个矩形 rect = cv.minAreaRect(cnt) # 旋转获取最小外接矩阵数据 返回 ( center (x,y), (width, height), angle of rotation ) box = cv.boxPoints(rect) # 根据矩阵数据获取4个坐标点 box = np.int0(box) cv.drawContours(img_copy, [box], 0, (0, 0, 255), 2) cv.imshow(winname='boundingRect', mat=img_copy) cv.waitKey(0) cv.destroyWindow(winname='boundingRect') # 最小包围圆 img_copy = img.copy() (x, y), radius = cv.minEnclosingCircle(cnt) # 获取最小包围圆的 圆心坐标和半径 center = (int(x), int(y)) radius = int(radius) cv.circle(img_copy, center, radius, (0, 255, 0), 2) cv.imshow(winname='EnclosingCircle', mat=img_copy) cv.waitKey(0) cv.destroyWindow(winname='EnclosingCircle') # 椭圆拟合 img_copy = img.copy() ellipse = cv.fitEllipse(cnt) # 返回旋转的包含椭圆的矩形数据 cv.ellipse(img_copy, ellipse, (0, 255, 0), 2) # 根据矩形数据画图 cv.imshow(winname='fitEllipse', mat=img_copy) cv.waitKey(0) cv.destroyWindow(winname='fitEllipse') # 拟合线 img_copy = img.copy() rows, cols = img_copy.shape[:2] # 获取图像的长宽 # 参数:待拟合的点集,最小距离的类型,距离参数,拟合直线所需要的径向和角度精度 输出 前俩个为方向(计算斜率),后两个为直线上一点 [vx, vy, x, y] = cv.fitLine(cnt, cv.DIST_L2, 0, 0.01, 0.01) lefty = int((-x * vy / vx) + y) righty = int(((cols - x) * vy / vx) + y) cv.line(img_copy, (cols - 1, righty), (0, lefty), (0, 255, 0), 2) cv.imshow(winname='line', mat=img_copy) cv.waitKey(0) cv.destroyWindow(winname='line') def feature_2(): """ 计算轮廓缺陷 计算特定点到轮廓的距离 """ img = cv.imread('../../resources/start_light.png') imgray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) ret, thresh = cv.threshold(imgray, 127, 255, 0) contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) cnt = contours[1] hull = cv.convexHull(cnt, returnPoints=False) # 获取凸包 # 根据图形和凸包判断轮廓缺陷 # [ start point(曲线起点), end point(曲线终点), farthest point(曲线距离图形最远点), # approximate distance to farthest point] defects = cv.convexityDefects(cnt, hull) for i in range(defects.shape[0]): s, e, f, d = defects[i, 0] start = tuple(cnt[s][0]) end = tuple(cnt[e][0]) far = tuple(cnt[f][0]) cv.line(img, start, end, [0, 255, 0], 2) cv.circle(img, far, 5, [0, 0, 255], -1) cv.imshow('img', img) cv.waitKey(0) cv.destroyAllWindows() # 判断某个点是否在图形中 point = (100, 100) # 参数 图形点集,检查的点,True,表示具体距离,Flase 返回 -1,0,1 表示是否在图形内 dist = cv.pointPolygonTest(cnt, point, True) print(dist) # 判断图形的相似性 img2 = cv.imread('../../resources/stars.png', 0) ret, thresh2 = cv.threshold(img2, 127, 255, 0) contours, hierarchy = cv.findContours(thresh2, 2, 1) ret = cv.matchShapes(cnt, cnt, 1, 0.0) print(ret) for i in range(5, 0, -1): cnt1 = contours[i] ret = cv.matchShapes(cnt, cnt1, 1, 0.0) print(ret) # feature_1() feature_2()
d319ffd027d11cca12d7e2260ab66ab6b16cc18a
jpusterhofer/polynomial-regression
/regression.py
2,568
3.640625
4
import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt #Calculate h(x) def h(x, weights): y = 0 for i in range(len(weights)): y += weights[i] * x**i return y #Calculate the model's weights def calc_weights(data, degree): alpha = 0.001 weights = np.zeros(degree + 1) updates = np.ones(degree + 1) #Update weights until updates are small while(max(abs(updates)) >= 0.00001): #Calculate an update for every weight for i in range(len(updates)): update = 0 for point in data: update += (h(point[0], weights) - point[1]) * point[0]**i update = update / len(data) * alpha updates[i] = update #Check if the updates are diverging, for testing purposes if updates[0] > 10: print("Diverging") #Update weights weights -= updates return weights #Use the model to make predictions for the given inputs def predict(data, weights): predictions = np.zeros((len(data), 2)) for row in range(len(data)): predictions[row, 0] = data[row, 0] predictions[row, 1] = h(data[row, 0], weights) return predictions #Calculate the mean squared error for the predictions def get_error(data, predictions): error = 0 for row in range(len(data)): error += (predictions[row, 1] - data[row, 1])**2 error /= len(data) return error #Use polynomial regression to predict the outputs of a dataset #Prints the weights and error of the model #Returns the model's predictions def regression(data, degree): weights = calc_weights(data, degree) predictions = predict(data, weights) error = get_error(data, predictions) print("Degree " + str(degree)) print("\tWeights: " + str(weights)) print("\tError: " + str(error)) return predictions #Make plots of the data and regression model for num in range(1, 4): print("Synthetic Data " + str(num)) data = np.genfromtxt("./synthetic-" + str(num) + ".csv", delimiter=",") data = data[data[:,0].argsort()] #Sort the data points degrees = [1, 2, 4, 7] fig, axs = plt.subplots(2, 2) fig.suptitle("Synthetic Data " + str(num)) axs = axs.flatten() for i in range(4): axs[i].set_title("Degree " + str(degrees[i])) axs[i].scatter(data[:, 0], data[:, 1]) predictions = regression(data, degrees[i]) axs[i].plot(predictions[:, 0], predictions[:, 1], "r") fig.tight_layout() fig.savefig("pic" + str(num) + ".png")
6f5a7790b1e0c62345d9cc6ef593378b35074d81
evansuslovich/PythonPrograms-
/quadratic.py
392
3.859375
4
import math def main(): print("Hello! Welcome to to a quadratic calculator") a, b, c = input("Please enter the coefficients(a,b,c):") start = (-1*b) root = math.sqrt((b*b) - 4 * a * c) divide = (2*a) first = (start + root) / divide second = (start - root) / divide print("The first solution is", first) print("The second solution is", second) main()
2e728d3e739dbcc38a5f3ffddeea066ca3add4f3
divya-nk/hackerrank_solutions
/Python-practice/itertools/comb_with_replacement.py
530
3.765625
4
itertools.combinations_with_replacement(iterable, r) This tool returns r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once. Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order. from itertools import combinations_with_replacement s, r = input().split(' ') t = list(combinations_with_replacement(sorted(s),int(r))) for j in range(len(t)): print("".join(t[j]))
e2f3e5037b1fb6af94504e5eedd156b992dba018
dks1018/CoffeeShopCoding
/2021/Code/Python/PythonCrypto/Module_3/Fernet_Cryptograhy.py
1,867
3.875
4
from cryptography.fernet import Fernet from Cryptodome.Cipher import AES def generate_key(): key = Fernet.generate_key() return key def save_key(): file = open('key.key', 'wb') store_key = generate_key() file.write(store_key) file.close() def get_key(): file = open('key.key', 'rb') get_stored_key = file.read() file.close() return get_stored_key def create_message(): message = str(input("Enter the message you want to encrypt: ")) return message def store_encrypted_message(message): file = open('stored_message.txt', 'wb') file.write(message) file.close() def read_stored_message(): file = open('stored_message.txt', 'rb') get_stored_message = file.read() file.close() return get_stored_message def encrypt_with_key(): f_key = Fernet(get_key()) message_encrypted = f_key.encrypt(create_message().encode()) store_encrypted_message(message_encrypted) return message_encrypted def decrypt_message(): f_key = Fernet(get_key()) message_decrypted = f_key.decrypt(read_stored_message()) decoded_message = message_decrypted.decode() return decoded_message def main(): save_key() encrypted_message = encrypt_with_key() decrypted_message = decrypt_message() # print(encrypted_message) # print(decrypted_message) while(True): user_input = str(input("\tIf you would like to see you encrypted message type 1.\n\ \tIf you would like to see your decrypted message type 2.\n\ \tIf you would like to quit type q.\n")) if(user_input == "1"): print(encrypted_message,"\n") elif(user_input == "2"): print(decrypted_message,"\n") elif(user_input == "q"): break else: print("Please enter a valid choice.") if __name__ == "__main__": main()
95df76b25a85ac603507d25268b936fd7399ec84
Ankit-Developer143/Python-Medium-Question-Solve
/python Hard edabit/sentence Searcher.py
520
3.515625
4
def sentence_searcher(txt,word): txt = txt.split(".") for i in txt: if word.lower() in i.lower(): return "{}".format(i) txt = "I have a cat. I have a mat. Things are going swell." print(sentence_searcher(txt,"have")) #I have a cat def using_lambda(text,sentence): lst = ([i for i in txt.split(".") if (word.lower()) in i.lower()]) return '' if not lst else lst[0].strip()+'.' text = "I have a cat. I have a mat. Things are going swell." print(sentence_searcher(text,"have"))
cea6eac4eae56b5cb5246f602da345bb5071700f
shaneslone/cs_week4_day4
/quicksort.py
359
3.953125
4
def quicksort(a): if len(a) <= 1: return a pivot = a[0] left = [] right = [] for i in range(1, len(a)): if a[i] > pivot: right.append(a[i]) else: left.append(a[i]) left = quicksort(left) right = quicksort(right) return left + [pivot] + right print(quicksort([4, 3, 5, 1, 2]))
739a5f1b330ee2b2b9992b25fd52686ac8129c99
libasoles/search-and-sort-algorithms
/algorythms/binary_search_tree.py
994
3.828125
4
class Node: value = None left = None right = None def __init__(self, value=None): self.value = value def attach(self, value): if not self.value: self.value = value return if value >= self.value: if not self.right: self.right = Node(value) return self.right.attach(value) return if not self.left: self.left = Node(value) return self.left.attach(value) return def to_list(self, list=[]): if self.left: self.left.to_list(list) list.append(self.value) if self.right: self.right.to_list(list) return list class Tree: main_node = None def __init__(self, data): self.main_node = Node(None) for value in data: self.main_node.attach(value) def to_list(self): return self.main_node.to_list([])
5b3e9921963e09babb38189b51ac0ccef9bf2cdd
tormobr/Programming
/chess/movement.py
3,424
3.78125
4
class Movement: def __init__(self, board): self.board = board def move(self, board, piece, start, end): self.board = board if piece.name == "pawn": return self.pawn(piece, start, end) elif piece.name == "bish": return self.bishop(piece, start, end) elif piece.name == "knig": return self.knight(piece, start, end) elif piece.name == "rook": return self.rook(piece, start, end) elif piece.name == "quen": return self.queen(piece, start, end) elif piece.name == "king": return self.king(piece, start, end) def pawn(self, piece, start, end): distX = end.x - start.x distY = 0 if piece.color == "white": distY = end.y - start.y else: distY = start.y - end.y if distX == 0 and end.piece != None: return False if distY == 1 and distX == 1 and end.piece != None: print("capture") return True if piece.moved == False: if (distY == 2 or distY == 1) and distX == 0: return True else: if distY == 1 and distX == 0: return True return False def bishop(self, piece, start, end): distX = end.x - start.x distY = end.y - start.y if not self.check_path(piece, start, end, distX, distY): return False if abs(distX) == abs(distY): return True return False def knight(self, piece, start, end): distX = abs(end.x - start.x) distY = abs(end.y - start.y) if distX == 2 and distY == 1: return True elif distX == 1 and distY == 2: return True return False def rook(self, piece, start, end): distX = end.x - start.x distY = end.y - start.y if not self.check_path(piece, start, end, distX, distY): return False if abs(distX) == 0 or abs(distY) == 0: return True return False def queen(self, piece, start, end): return self.rook(piece, start, end) or self.bishop(piece, start, end) def king(self, piece, start, end): distX = abs(end.x - start.x) distY = abs(end.y - start.y) if distX <= 1 and distY <= 1: return True return False def check_path(self, piece, start, end, distX, distY): moveX = 0 moveY = 0 if distX < 0: moveX = -1 elif distX > 0: moveX = 1 if distY < 0: moveY = -1 elif distY > 0: moveY = 1 x = start.x + moveX y = start.y + moveY while x != end.x or y != end.y: if self.board[y][x].piece != None and self.board[y][x].piece.color == piece.color: print("square: {} piece: {} in the way".format(self.board[y][x].position, self.board[y][x].piece)) return False x += moveX y += moveY return True def check_check(self, board, white_king, black_king): self.board = board check_white = False check_black = False permutations = [(0,1), (0,-1), (1,0), (-1,0), (1,1), (1,-1), (-1,1), (-1,-1)] #for p in permutations: # if self.check_check_help(p, "white", white_king) == True: # check_white = True for p in permutations: if self.check_check_help(p, "red", black_king) == True: check_black = True return (check_white, check_black) def check_check_help(self, movement, color, king): threats = ["knig", "bish", "quen", "rook"] x = king.x + movement[0] y = king.y + movement[1] while 0 <= x <= 7 and 0 <= y <= 7: if self.board[y][x].piece != None and self.board[y][x].piece.name in threats and self.board[y][x].piece.color != color: print("check detected!!!!!!!!!") print("x: {} y: {} piece: {}".format(x, y, self.board[y][x].piece)) return True x += movement[0] y += movement[1] return False
c8c6b42f2dcc3d77138473ecaa6eb324f14c40c7
matkuhlm/python-challenge
/PyBank/main.py
2,407
3.890625
4
# Modules import os import csv print("__________________________________________________________") csvpath = os.path.join("Resources", "budget_data.csv") # Method 2: Improved Reading using CSV module with open(csvpath) as csvfile: #CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) print(f"CSV Header: {csv_header}") #setting variables months = [] net_rev = 0 maxRev = 0 minRev = 0 #add change #loop data for months and net rev for row in csvreader: months.append(row[0]) net_rev +=int(row[1]) #find min revenue if(minRev>int(row[1])): minRev=int(row[1]) minRev_month = row[0] #find max revenue if(maxRev<int(row[1])): maxRev = int(row[1]) maxRev_month = row[0] #print the statements print(f'Financial Analysis') print(f'----------------------------') print(f'Total Months: {len(months)}') print(f'Net Revenue: ${net_rev}') print(f'Average Change: ${net_rev / len(months), 2}') print(f'Greatest increase in Profits: {maxRev_month} ({maxRev})') print(f'Greatest decrease in Profits: {minRev} ({minRev_month})') print('________________________________________________________________') textList =['Financial Analysis','----------------------------',f'Total Months: {len(months)}',f'Net Revenue: ${net_rev}',f'Average Change: ${net_rev / len(months), 2}',f'Greatest increase in Profits: {maxRev_month} ({maxRev})',f'Greatest decrease in Profits: {minRev} ({minRev_month})'] analysis_txt = open("budget_analysis_output.txt", "w") for line in textList: f.write(line) f.write("\n") outF.close() #The net total amount of "Profit/Losses" over the entire period #The average of the changes in "Profit/Losses" over the entire period #The greatest increase in profits (date and amount) over the entire period #The greatest decrease in losses (date and amount) over the entire period #As an example, your analysis should look similar to the one below: #Financial Analysis #---------------------------- #Total Months: 86 #Total: $38382578 #Average Change: $-2315.12 #Greatest Increase in Profits: Feb-2012 ($1926159) #Greatest Decrease in Profits: Sep-2013 ($-2196167)
bed18016bff322cef041fee3b03c276e1a8718c7
kiransy015/Python-Frameworks
/venvScripts1/venvScripts/Pgmlambda.py
807
3.953125
4
# filter functionality from functools import reduce List = [1,2,3,4,5,6,7,8] # evens = [] # # def get_even_no(list): # for i in range(0,len(list)): # if list[i]%2==0: # evens.append(list[i]) # print("Even nos :",evens) # # get_even_no(List) # # # def even(n): # if n%2==0: # return True # # evens = list(filter(even,List)) # print("Even nos :",evens) # # # evens = list(filter(lambda n:n%2==0,List)) # print("Even nos :",evens) # Reduce functionality # evens = list(filter(lambda n:n%2==0,List)) # print("Even nos :",evens) # sum = reduce(lambda a,b:a+b,evens) # print("Sum of even nos :",sum) # map functionality # square = list(map(lambda n:n*n,List)) # print("Square of nos :",square) # # div = list(map(lambda n:n/2,List)) # print("Division by 2 :",div)
b37cbac9a53341c3075a711c8c68c30ead49c973
dongkooi/ngothedong-fundamental-C4E18
/session04/login.py
455
3.671875
4
import getpass user = "qweqwe" password = "123123" u = input("User: ") count = 0 while True: if u == user: p = getpass.getpass('Pass:') if p == password: print("Welcom, c4e") break else: print("Wrong password, please try again") elif u != user: print("You are not super user") u = input("User: ") count +=1 if count == 3: print("faild") break
b83b0599ae5737069b8e90f5d2ae1bdc940fc66b
yuto-dev/fsd-corona-new
/test/test.py
266
3.65625
4
newList = ["a;b", "c;d"] f = open("test.txt", "w") counter = 0 for items in newList: f.writelines(newList[counter]) f.writelines("\n") counter = counter + 1 f.close() #open and read the file after the appending: f = open("test.txt", "r") print(f.read())
3e1be83dfb0645c4066e656632359e73a2921c02
Phil-U-U/Evaluate-Amazon-Book-Reviews
/code/featureEngineering.py
1,791
3.5
4
''' Evaluate Amazon Book Reviews - create categorical features Author: Phil H. Cui Time: 10/12/2016 ''' import numpy as np class feature_engineering( object ): def __init__( self, df ): self.df = df def createNWordsLabel( self ): NWords_category = np.empty( [ len(self.df['N_words']), 1], dtype = object ) # print self.N_words for i, val in enumerate(self.df['N_words']): if val <= 100: NWords_category[i] = '1' elif val <= 300: NWords_category[i] = '2' elif val <= 600: NWords_category[i] = '3' else: NWords_category[i] = '4' self.df['NWords_category'] = NWords_category def createNUniqueWordsLabel( self ): NUniqueWords_category = np.empty( [ len(self.df['N_unique_words']), 1], dtype = object ) for i, val in enumerate(self.df['N_unique_words']): if val <= 90: NUniqueWords_category[i] = '1' elif val <= 300: NUniqueWords_category[i] = '2' # elif val <= 200: # NUniqueWords_category[i] = '3' else: NUniqueWords_category[i] = '3' self.df['NUniqueWords_category'] = NUniqueWords_category def createNUniquePuncsLabel( self ): NUniquePuncs_category = np.empty( [ len(self.df['N_puncs_unique']), 1], dtype = object ) for i, val in enumerate( self.df['N_puncs_unique'] ): if val < 2: NUniquePuncs_category[i] = '1' elif val == 2: NUniquePuncs_category[i] = '2' else: NUniquePuncs_category[i] = '3' self.df['NUniquePuncs_category'] = NUniquePuncs_category
1b0528e2f35aea0327c30fbd0642573b968e8e44
marcellasiqueira/programacao1
/minmax/minmax.py
934
3.828125
4
# coding: utf-8 # MinMax Sort = Selection Sort Duplicado # 2017, Marcella Siqueira / UFCG, Programação 1 # Matrícula: 117110492 def minmax_sort(lista): lista_final = [] maior, menor, m = 0, 0, len(lista) for i in range(0, int(m/2)): for j in range(i, m): if lista[j] < lista[menor]: menor = j lista[menor], lista[i] = lista[i], lista[menor] for k in range(i, m): if lista[k] > lista[maior]: maior = k lista[maior], lista[m - 1] = lista[m - 1], lista[maior] m -= 1 lista_copia = [] for i in range(len(lista)): lista_copia.append(lista[i]) lista_final.append(lista_copia) return lista_final assert minmax_sort([7, 4, 8, 1, 2, 3]) == [[1, 4, 3, 7, 2, 8], [1, 2, 3, 4, 7, 8], [1, 2, 3, 4, 7, 8]]
9c57b7a8a70d5ae1ea2eae273239c11be01911d1
barun12/PythonClass
/calculator_file_input.py
2,251
3.890625
4
""" simple calculator with file IO author: Barun Kumar Sharma(barun12) """ def addition(num1, num2): """ :param num1: 1st number :param num2: 2nd number :return: sum of num1 and num2 """ return num1 + num2 def subtraction(num1, num2): """ :param num1: 1st number :param num2: 2nd number :return: subtraction of num2 from num1 """ return num1 - num2 def multiplication(num1, num2): """ :param num1: 1st number :param num2: 2nd number :return: multiplication of num1 and num2 """ return num1 * num2 def devision(num1, num2): """ :param num1: 1st number, numerator :param num2: 2nd number, denominator :return: division of num1 and num2 """ return num1 / num2 if __name__ == "__main__": # list of possible operator signs signs = ["+", "-", "*", "/"] output_file_path = "./IOFiles/output.txt" with open("./IOFiles/input.txt", "r") as input_file, open(output_file_path, "w") as output_file: print "Writing output to file: {}".format(output_file_path) # read file line by line l = input_file.readline() # execute this till we read all the lines while l: # iterate over all operators for sign in signs: try: num1, num2 = l.split(sign) except: continue # typecast both numbers to integer, strip to remove extra spaces(if any) num1 = int(num1.strip()) num2 = int(num2.strip()) if sign == "+": res = addition(num1, num2) res_str = "{} + {} = {}".format(num1, num2, res) elif sign == "-": res = subtraction(num1, num2) res_str = "{} - {} = {}".format(num1, num2, res) elif sign == "*": res = multiplication(num1, num2) res_str = "{} * {} = {}".format(num1, num2, res) elif sign == "/": res = devision(num1, num2) res_str = "{} / {} = {}".format(num1, num2, res) output_file.write(res_str + "\n") l = input_file.readline()
b33dd6402c054a1f13940008cbc817928bf162ab
henryyecode/Constraint-Satisfaction
/constraint.py
2,163
3.546875
4
from domain import domainDay, domainTime def sameDay(m1, m2): #Works day1I = m1.split(' ', 1)[0] day2I = m2.split(' ', 1)[0] if day1I == day2I: return True else: return False def oneDayBetween(m1, m2): #Works day1I = domainDay.index(m1.split(' ')[0]) day2I = domainDay.index(m2.split(' ')[0]) diff = day2I - day1I print(m1.split()[0], day1I) print(m2.split()[0], day2I) if diff == -2 or diff == 2: return True else: return False def oneHourBetween(m1, m2): #Works time1I = domainTime.index(m1.split(' ')[1]) time2I = domainTime.index(m2.split(' ')[1]) day1I = domainDay.index(m1.split(' ')[0]) day2I = domainDay.index(m2.split(' ')[0]) diff = time2I - time1I if day1I == day2I: if diff == -2 or diff == 2: return True else: return False return False def before1(m1, m2): #Works day1I = domainDay.index(m1.split(' ')[0]) day2I = domainDay.index(m2.split(' ')[0]) time1I = domainTime.index(m1.split(' ')[1]) time2I = domainTime.index(m2.split(' ')[1]) if day1I < day2I: return True elif day1I == day2I: if time1I < time2I: return True else: return False, else: return False def before1(schedule1, schedule2): """not equal value""" # nev = lambda x: x != val # alternative definition # nev = partial(neq,val) # another alternative definition def nev(x): return schedule1 != x nev.__name__ = str(schedule1) + "!=" # name of the function return nev def before(schedule1, schedule2): #Works #print(schedule1, schedule2) day1I = schedule1.split(' ')[0] day2I = schedule2.split(' ')[0] time1I = schedule1.split(' ')[1] time2I = schedule2.split(' ')[1] if day1I < day2I: return True elif day1I == day2I: if time1I < time2I: return True else: return False, else: return False
aaed5b59897d3cd3da97da0fca8fbf20fb8fb008
NCRivera/Personal-Projects
/dnd_dice_roll_function.py
311
4.0625
4
import random def roll_dice(sides, rolls): for roll in range(rolls): score = random.randint(1,sides) print(score) dice_sides = int(input("How many sides does your dice have? ")) roll_number = int(input("How many rolls do you want to make? ")) roll_dice(dice_sides,roll_number)
f884b7dd94b61ccc2c290d33e266dab8b6222742
PimpatDev/CP3-Peerapat-Pimmaha
/Lecture53_Peerapat_P/Lecture53_Peerapat_P.py
161
3.734375
4
def vatCaculate(totalPrice): result = totalPrice + (totalPrice*7/100) return result print("Total price : ", vatCaculate(float(input("Enter price : "))))
fa61bd648e9b4397c09e2555d1687dcf8d4ec892
zhangshv123/superjump
/interview/google/hard/LC683. K Empty Slots.py
3,320
4
4
""" There is a garden with N slots. In each slot, there is a flower. The N flowers will bloom one by one in N days. In each day, there will be exactly one flower blooming and it will be in the status of blooming since then. Given an array flowers consists of number from 1 to N. Each number in the array represents the place where the flower will open in that day. For example, flowers[i] = x means that the unique flower that blooms at day i will be at position x, where i and x will be in the range from 1 to N. Also given an integer k, you need to output in which day there exists two flowers in the status of blooming, and also the number of flowers between them is k and these flowers are not blooming. If there isn't such day, output -1. Example 1: Input: flowers: [1,3,2] k: 1 Output: 2 Explanation: In the second day, the first and the third flower have become blooming. Example 2: Input: flowers: [1,2,3] k: 1 Output: -1 """ # 循环每一天,然后开花,然后检查新开花位置两边距离各多少,更新hashset。 class Solution(object): def kEmptySlots(self, flowers, k): """ :type flowers: List[int] :type k: int :rtype: int """ n = len(flowers) gardens = [False] * n for i in range(n): x = flowers[i] - 1 gardens[x] = True for dx in [-1, 1]: xx = x + dx while xx >= 0 and xx < n: if gardens[xx]: if abs(xx - x) - 1 == k: return i + 1 break xx += dx return -1 class Solution(object): def kEmptySlots(self, flowers, k): n = len(flowers) garden = [False] * n d = set() # iterate through day i = 0 while i < n: x = flowers[i] - 1 garden[x] = True # iterate through flowers left = 1 right = 1 while x - left >= 0: if garden[x - left]: d.add(left - 1) break left += 1 while x + right < n: if garden[x + right]: d.add(right - 1) break right += 1 if k in d: return i + 1 i += 1 return -1 #BST treeset """ public int kEmptySlots(int[] flowers, int k) { TreeSet<Integer> treeSet = new TreeSet<>(); for (int i = 0; i < flowers.length; i++) { int current = flowers[i]; Integer next = treeSet.higher(current); if (next != null && next - current == k + 1) { return i + 1; } Integer pre = treeSet.lower(current); if (pre != null && current - pre == k + 1) { return i + 1; } treeSet.add(current); } return -1; } """ """ 小变形 就是说给你一个k,如果这一排里面有任意一组连续的几朵花长度是k,即满足要求。不过它问的是最后一天满足这个要求的天数。 解法倒是不难,我是按照lc的解法改了改,把天数从后往前遍历的,当做每天有一朵花要收起来,然后把现在的empty slot 当做是原版题里面的花,把花当做原版里面empty slots。这个做法有一个要特别注意的地方:原版里面的empty slots 要求两边都有花夹住这一组empty slots,但是这道题里面如果有连续k朵花是从墙开始数的,那么这个是要算成符合要求的。 所以你要想办法把这个改动解决掉。 """
5fca54ea42d1625c4fe03c994acfe8c22037a2b4
EslamFawzyMahmoud/Data-Structure
/Algorithms/Sorting/BubbleSort.py
333
4.09375
4
def bubblesort(arr): for i in range(len(arr)-1): for j in range(len(arr)-1): if arr[j] > arr[j+1]: temp = arr[j] arr[j] = arr[j+1] arr[j+1] = temp return arr arr=[5,4,1,2,7,8,0,100,6] print("Before Sort: ",arr) print("After Sort: ",bubblesort(arr))
b2b4729cfbe47e3b3f417795bee9c0975ca3da20
Theofilos-Chamalis/edX-6.00.2x-Introduction-to-Computational-Thinking-and-Data-Science
/Running The Simulation.py
1,823
3.921875
4
# Enter your code for runSimulation in this box. def runSimulation(num_robots, speed, width, height, min_coverage, num_trials, robot_type): """ Runs NUM_TRIALS trials of the simulation and returns the mean number of time-steps needed to clean the fraction MIN_COVERAGE of the room. The simulation is run with NUM_ROBOTS robots of type ROBOT_TYPE, each with speed SPEED, in a room of dimensions WIDTH x HEIGHT. num_robots: an int (num_robots > 0) speed: a float (speed > 0) width: an int (width > 0) height: an int (height > 0) min_coverage: a float (0 <= min_coverage <= 1.0) num_trials: an int (num_trials > 0) robot_type: class of robot to be instantiated (e.g. StandardRobot or RandomWalkRobot) """ trialsList = [] # Run num_trials amount of tests for trial in range(num_trials): #### Create room room = RectangularRoom(width,height) botList = [] #### Create bots and add them to the botList for n in range(num_robots): botList.append(robot_type(room,speed)) #print botList #anim = ps7_visualize.RobotVisualization(num_robots, width, height) steps = 0 #### While the room is not cleaned enough: Let all bots have another 'turn' while (1.0*room.getNumCleanedTiles()/room.getNumTiles()) <= min_coverage: #print room.getNumCleanedTiles() #print steps for bot in botList: #print bot #anim.update(room, bots) bot.updatePositionAndClean() steps += 1 #### Add test to trialsList trialsList.append(steps) #anim.done() # return mean-value of all values in trialsList return float(sum(trialsList)) / len(trialsList)
bb92f164096cc04ef6799ec06ac02c0b6855202c
jayjay1973/CIS115-Python-Labs
/williamPrudencio_lab2-15.py
697
4.28125
4
#program, williamPrudencio_lab2-15.py, 01/26/19 ''' This program will use Turtle Graphics to draw the first shape shown on page 107 of the "Starting Out With Python" book. ''' import turtle; #Change the fill color to orange------------ turtle.fillcolor("orange") #Begin filling the shape with color---------- turtle.begin_fill() #Move turtle using x & y coordinates to make the design turtle.goto(200, 200) turtle.goto(400, 0) turtle.goto(200, -200) turtle.goto(-200, 200) turtle.goto(-400, 0) turtle.goto(-200,-200) turtle.goto(0, 0) #Hide turtle turtle.hideturtle() #Stop filling the shape with color---------- turtle.end_fill() #Close turtle---------------------------- turtle.done()
94397c3ce7ec4c3032bf1e24e0439e1fb44a6fa7
cosmincelea/CodeAdvent2018
/day1/main.py
392
3.78125
4
import itertools fileName = input('What is the name of the file my Dude?\n') data = [float(x) for x in open(fileName).readlines()] print("The Total freq is: " + str(sum(data))) freq = 0 allFreqValues = set() for val in itertools.cycle(data): freq = freq + val if freq in allFreqValues: print("The Repeatable freq is: " + str(freq)) break allFreqValues.add(freq)
1fa80a84529ad474148f03cfad123d7666f38029
lichangg/myleet
/titles/226. 翻转二叉树.py
333
3.78125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- from utils.util_funcs import TreeNode class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if root: root.right, root.left = root.left,root.right self.invertTree(root.left) self.invertTree(root.right) return root
843732c8e492928da162bbe34766f65d138a0fa0
govex/python-lessons-for-gov
/section_14_(exceptions)/exceptions_03.py
840
4.1875
4
# Example #3: Different types of exceptions can be caught. print("Example #3: Phonebook!") phonebook = {} while True: # this will loop forever until we issue a break! key = raw_input(" (Ex #3, Phonebook) Please enter a person's name, or leave blank to quit: ") if key == '': break value = raw_input(" (Ex #3, Phonebook) Please enter {0}'s phone number with no punctuation: ") phonebook[key] = value user_input = raw_input(" Okay, now we're done entering names. Please enter the name of the person whose number you would like: ") try: print(int(phonebook[user_input])) except KeyError: print("You don't have {0}'s phone number!".format(user_input)) except ValueError: print("You typed in punctuation, didn't you?") print("Here's the number anyway ... {0}".format(phonebook[user_input]))
956d46bf238375a95f184d1dfd9d9001644d4fe0
Genyu-Song/LeetCode
/Algorithm/GreedyAlgorithm/QueueReconstructionByHeight.py
1,636
3.953125
4
# -*- coding: UTF-8 -*- ''' Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. Note: The number of people is less than 1,100. ''' class Solution(object): # Ascending order def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ people.sort(key=lambda x:x[0]) new_list = [[-1, -1] for i in range(len(people))] for h, k in people: count = 0 ind = 0 while count != k: if new_list[ind][0] >= h or new_list[ind][0] == -1: count += 1 ind += 1 while new_list[ind][0] != -1: ind += 1 new_list[ind] = [h, k] return new_list class Solution2(object): # Descending order def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ people.sort(key=lambda x: (-x[0], x[1])) # TODO: 注意排序写法people.sort(key=lambda x: x[0], reverse=True)错在哪儿! new_list = [] for h, k in people: new_list.insert(k, (h, k)) # insert() takes no keyword arguments, 不支持用键值对传参 return new_list if __name__ == '__main__': print(Solution2().reconstructQueue(people=[[9,0],[7,0],[1,9],[3,0],[2,7],[5,3],[6,0],[3,4],[6,2],[5,2]]))
9dce87320791825b0b614f10cb2e41ed1fe66e5d
Jsonghh/leetcode
/200101/Degree_of_An_Array.py
766
3.640625
4
from collections import Counter class Solution: def findShortestSubArray(self, nums): if not nums: return 0 nums_degree = self.find_degree(nums, 0, len(nums) - 1) l, r, min_len = 0, 0, len(nums) for l in range(len(nums)): while r < len(nums) and self.find_degree(nums, l, r) < nums_degree: r += 1 if self.find_degree(nums, l, r) == nums_degree: min_len = min(min_len, r - l + 1) print(nums_degree, r) return min_len def find_degree(self, nums, l, r): counter = Counter(nums[l : r + 1]) degree = max(counter.values()) return degree print(Solution().findShortestSubArray([1,2,2,3,1,4,2]))
392cddb1c6414144eca29a9ef8591d748604a2c4
wgrh12/gitdemo3
/code1.py
124
3.546875
4
#!/usr/bin/env python print("Hello world!") from datetime import timedelta year = timedelta(days=365) year.total_seconds()
20c51cd040743803cb34b9b0c838af57841d7dd5
madeibao/PythonAlgorithm
/PartB/py回文子串2.py
286
3.5625
4
class Solution(object): def countSubString(self, s): count = 0 for i in range(len(s)): for j in range(i+1,len(s)+1): if s[i:j] ==s[i:j][::-1]: count += 1 return count if __name__ == "__main__": s = Solution() str2 ="abc" print(s.countSubString(str2))
65b9ec3d91d2297b5c9b1391ebc7a4ac9057ab1c
1012378819/2020kingstar
/src/fun/func1.py
1,479
3.890625
4
def init(data): data['first']={} data['middle']={} data['last']={} def lookup(data,lable,name): return data[lable].get(name) def store(data,full_name): names=full_name.split() if len(names)==2: names.insert(1,'') lables=('first','middle','last') for lable,name in zip(lables,names): people=lookup(data,lable,name) if people: people.append(full_name) else: data[lable][name]=[full_name] #这边需要存为list,list才有append方法,把相同首中尾相同的存在一起 def store_2(data,*full_names): for full_name in full_names: store(data,full_name) # names=full_name.split() # if len(names)==2: # names.insert(1,'') # lables=('first','middle','last') # for lable,name in zip(lables,names): # people=lookup(data,lable,name) # if people: # people.append(full_name) # else: # data[lable][name]=[full_name] #这边需要存为list,list才有append方法,把相同首中尾相同的存在一起 def test(): MyNames={} MyNames_2={} init(MyNames) init(MyNames_2) store(MyNames,'zhang san feng') store(MyNames,'lu pei') store(MyNames,'jia chen') store_2(MyNames_2,'zhang san feng','zhang xiao huang','zhang hua') print(lookup(MyNames,'middle','san')) print(lookup(MyNames,'middle','')) print(lookup(MyNames_2,'first','zhang')) # test()
e8ebbfb45ea8455b488fe36bbede3b7bbb5bfae0
Rapha-Y/My_Python_Studies
/Basic_Python/NinthClass.py
1,264
3.578125
4
import shutil def write_file(text): path = 'C:/Users/Anni/Documents/Projects/My_Python_Studies/teste.txt' file = open(path, 'w') file.write(text) file.close() def update_file(file_name, text): file = open(file_name, 'a') file.write(text) file.close() def read_file(file_name): file = open(file_name, 'r') text = file.read() print(text) def mean_grades(file_name): file = open(file_name, 'r') std_grades = file.read() std_grades = std_grades.split("\n") mean_list = [] for i in std_grades: grade_list = i.split(",") student = grade_list[0] grade_list.pop(0) mean = lambda grades: sum([int(j) for j in grades]) / 4 mean_list.append({student:mean(grade_list)}) return mean_list def copy_file(file_name): shutil.copy(file_name, "C:/Users/Anni/Documents/Projects/notas_alunos.txt") def move_file(file_name): shutil.move(file_name, "C:/Users/Anni/Documents/Projects") if __name__ == '__main__': #write_file("First\nSecond") #student = "\nOkuyasu,2,2,2,1" #update_file("notas.txt", student) #read_file("teste.txt") mean_list = mean_grades("notas.txt") print(mean_list) #copy_file("notas.txt") #move_file("notas.txt")
e96219a0c2c5d06589d5e596bce1935b33145981
amangla20/CS550
/decimaltobinary.py
248
3.671875
4
import math import sys binarynum = sys.argv[1] def toDecimal(binarynum): i = 0 number = 0 binarynum = binarynum[::-1] for num in binarynum: number += int(num)*2**i i += 1 print(number) toDecimal(binarynum) # with 1101 should answer 13
96071bd6c69a7ed1e5fc2584f180d73bfefe9625
MegIvanova/PythonTesting
/PythonTests/TestingPython/PythonLab1Exercise11.py
304
3.6875
4
''' Created on Sep 8, 2015 @author: Meglena ''' #Python Program to Print all factorials Numbers in an Interval 0 to 20 def main(): f = 1 n = 0 for a in range (0,20): n += 1 f = f * n print(n,"! = ",f) main() # prints all factorials from 1 to 20
435f565922d1354cae3436e415f2830667defea7
ZhangRui111/MorvanRL
/02_Q_learning_maze/RL_brain.py
3,263
3.6875
4
""" This part of code is the Q learning brain, which is a brain of the agent. All decisions are made in here. View more on my tutorial page: https://morvanzhou.github.io/tutorials/ """ import numpy as np import pandas as pd class QLearningTable: def __init__(self, actions, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9): self.actions = actions # a list ['u', 'd', 'l', 'r'] self.lr = learning_rate self.gamma = reward_decay self.epsilon = e_greedy self.q_table = pd.DataFrame(columns=self.actions, dtype=np.float64) def choose_action(self, observation): self.check_state_exist(observation) # action selection if np.random.uniform() < self.epsilon: # choose best action a = self.q_table state_action = self.q_table.loc[observation, :] # self.q_table's rows' index is a four-elements list. # some actions may have same value. # # DataFrame.idxmax(axis=0, skipna=True) # Return index of first occurrence of maximum over requested axis. So if there are some # actions with same value, we need to shuffle all actions before we choose the idxmax action. state_action = state_action.reindex(np.random.permutation(state_action.index)) # # numpy.random.permutation(x) # # DataFrame.reindex(......) # Conform DataFrame to new index with optional filling logic, placing NA/NaN in locations having # no value in the previous index. A new object is produced unless the new index is equivalent to # the current one and copy=False action = state_action.idxmax() else: # choose random action action = np.random.choice(self.actions) return action def learn(self, s, a, r, s_): self.check_state_exist(s_) q_predict = self.q_table.loc[s, a] if s_ != 'terminal': q_target = r + self.gamma * self.q_table.loc[s_, :].max() # next state is not terminal else: q_target = r # next state is terminal self.q_table.loc[s, a] += self.lr * (q_target - q_predict) # update def check_state_exist(self, state): if state not in self.q_table.index: # append new state to q table self.q_table = self.q_table.append( pd.Series( [0]*len(self.actions), index=self.q_table.columns, name=state, ) ) # # numpy.random.permutation(x) # Randomly permute a sequence, or return a permuted range. # If x is a multi-dimensional array, it is only shuffled along its first index. # # Parameters: # x : int or array_like # If x is an integer, randomly permute np.arange(x). If x is an array, make a copy and shuffle # the elements randomly. # >>> np.random.permutation(10) # array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6]) # >>> np.random.permutation([1, 4, 9, 12, 15]) # array([15, 1, 9, 4, 12]) # >>> arr = np.arange(9).reshape((3, 3)) # >>> np.random.permutation(arr) # array([[6, 7, 8], # [0, 1, 2], # [3, 4, 5]])
bb50e0c0a8f33699865edb9acec46429a2551a70
Karagul/Hierarchical-Portfolio-Construction
/Supplied code/CovarianceEstimator.py
3,235
3.671875
4
import numpy as np from random import random from scipy.interpolate import pchip_interpolate import matplotlib.pyplot as plt ##################### # STEP 1 # import the data ##################### # uncomment for a toy example #n=5 # problem size #A = 10*np.random.rand(n,n+3) # n stocks with n+3 different prices #A = np.abs(A) # load the data: it must be pre-processed - 9:00AM-3:30PM prices - about 62 obs. A = np.transpose( np.loadtxt('data.txt') ) # it is a tiny example print('There are ', A.shape[0], ' stocks and ',A.shape[1],'observations.') stock_number = A.shape[0] # Important : the rows represent each stock and the columns represent prices at certain moment ##################### # STEP 2 # interpolate ##################### ### toy example 1 #data = np.array([[0, 4, 12, 27, 47, 60, 79, 87, 99, 100], [-33, -33, -19, -2, 12, 26, 38, 45, 53, 55]]) #xx = np.linspace(0,100,200) #curve = pchip_interpolate(data[0], data[1],xx) #plt.plot(xx, curve, "x"); #plt.plot(data[0],data[1],"o"); #plt.show() ### toy example 2 #x = np.arange(A.shape[1]) #m = 200 # number of the final data points #xx = np.linspace(0,x[-1],200) #curve1 = pchip_interpolate(x , A[0,:], xx) #print(curve1.shape, type(curve1)) ; #plt.plot(xx, curve1, "x"); #plt.plot(x,A[0,:],"o") ;#plt.show() m = 200 curve_save = np.zeros((stock_number,m)) # array created to save the interpolated data for ii in range(stock_number): # loop through each stock x = np.arange(A.shape[1]) # the prices m = 200 # number of the final data points xx = np.linspace(0, x[-1], 200) # filling the mappings of these points via interpolation curve = pchip_interpolate(x, A[ii, :], xx) # interpolate curve_save[ii,:] = curve # saving the interpolated points A = curve_save # this is now the NEW data ##################### # STEP 3 # get the scaling factor c - this needs history of opening and closing prices ##################### # getting c -- these need the correct data open_price = A[:,0] # open price of each stock for the entire period close_price = A[:,-1] # closing price of each stock for the entire period #### must get the right variance var_oc = np.abs(np.random.rand( stock_number)) # artifically created var_co = np.abs(np.random.rand( stock_number)) # artifically created c = 1 + np.divide(var_oc,var_co) # compute the scaling factor c ##################### # STEP 4 # obtain the log return ##################### # obtain the log return P_pre = A[:,0:A.shape[1]-1] # denominator, truncate the last price P_next = A[:,1:A.shape[1]] # numerator, truncate the first price r_tilde = np.log( np.divide(P_next,P_pre) ) ##################### # STEP 5 # obtain the daily convariance from the intra-day return ##################### # obtain the daily convariance from the intra-day return Sigmasum = np.zeros(A.shape[0]) for ii in range(r_tilde.shape[1]): r_hat = np.multiply( np.sqrt(c), r_tilde[:,ii]) S = np.transpose(np.asmatrix(r_hat)) * np.asmatrix(r_hat) Sigmasum = Sigmasum + S #print(Sigmasum)
df4ae7d7d057e542b206cf15a4995b64718c8dbc
voicezyxzyx/python
/Exercise/面向对象/对象属性与类属性/动态给实例添加属性和方法并使用.py
693
3.75
4
from types import MethodType #创建一个空类 class Person(object): __slots__ = ("name","age","speak") per=Person() #动态添加属性,这体现了动态语言的特点(灵活) per.name="zyx" #动态添加方法 def say(self): print("my name is " +self.name) per.speak=MethodType(say,per) per.speak() #思考:如果我们想要限制实例的属性怎么办? #比如:只允许给对象添加name,age,height,weight属性 #解决:定义类的时候,定义一个特殊的属性(__slots__),可以限制动态添加的属性 #比如动态给体重赋值,这样会报错,这样是限制了实例的属性 # per.weight=170 # print(per.weight)
836060c2af40adefaa9f526790dd112af3dc977e
kkemppi/TIE-courses
/Ohjelmointi 1/Ohjelmointi 1/alle 7. krs/kolmio.py
529
4.09375
4
# Johdatus ohjelmointiin # Introduction to programming # Mikko Kemppi, 272670, mikko.kemppi@tuni.fi # Area from math import sqrt def area(a, b, c): s = float((a + b + c)/2) ala = float(sqrt(s*(s - a)*(s - b)*(s - c))) return ala def main(): line1 = float(input("Enter the length of the first side: ")) line2 = float(input("Enter the length of the second side: ")) line3 = float(input("Enter the length of the third side: ")) kolmio = area(line1, line2, line3) print("The triangle's area is {:.1f}".format(kolmio)) main()
ad35a773796f6ed21c283dfd257b0be69129fe9a
Abusagit/practise
/Stepik/dataStructures/traversls.py
4,537
3.671875
4
import sys class Node: def __init__(self, key, value, left=None, right=None, parent=None): self.key = key self.payload = value self.left = left self.right = right self.parent = parent class Tree: def __init__(self, n): self.root = None self.n = n self.structure = {None: None} self.nodes = {} self.parents = {} def _print(self, node, indent='', last=True): if node: sys.stdout.write(indent) if last: sys.stdout.write('R----') indent += '\t' else: sys.stdout.write('L----') indent += '|\t' print(f'{node.key} ({node.payload})') self._print(node.left, indent, last=False) self._print(node.right, indent) def __str__(self): self._print(node=self.root) return '' def add(self, key, value, left, right): node = Node(key, value, left, right) if not self.root: self.root = node if left: self.parents[left] = value if right: self.parents[right] = value self.structure[value] = node self.nodes[key] = node def adjust_relation(self): for index in range(self.n): self.structure[index].parent = self.structure[self.parents.get(index)] self.structure[index].left = self.structure[self.structure[index].left] self.structure[index].right = self.structure[self.structure[index].right] def inorder(self, root: Node): if root: self.inorder(root.left) print(root.key, end=' ') self.inorder(root.right) def preorder(self, root): if root: print(root.key, end=' ') self.preorder(root.left) self.preorder(root.right) def postorder(self, root): if root: self.postorder(root.left) self.postorder(root.right) print(root.key, end=' ') def _find(self, node, key): if not node: return False if node.key == key: return True if node.key > key: return self._find(node.left, key) if node.key < key: return self._find(node.right, key) def __inorder(self, root, answer=None): if root: answer = self.__inorder(root.left, answer=answer) or [] answer.append(root.key) answer = self.__inorder(root.right, answer=answer) or [] return answer def check(self): if self.n: traversal = self.__inorder(self.root) # print(traversal) max_ = float('-inf') for i in range(len(traversal) - 1): max_ = max(max_, traversal[i]) if max_ > traversal[i + 1]: break else: return 'CORRECT' return 'INCORRECT' return 'CORRECT' @staticmethod def maxleft(root): if not root: return float('-inf') while root.right: root = root.right return root.key @staticmethod def minright(root): if not root: return float('inf') if not root.left: return root.key while root.left: root = root.left return root.key def check2(self, root): if root: if not (self.maxleft(root.left) < root.key < self.minright(root.right)): return False return self.check2(root.left) and self.check2(root.right) return True def read(): stdin = sys.stdin n = int(stdin.readline().strip()) nodes = tuple(tuple(map(int, stdin.readline().strip().split())) for _ in range(n)) t = Tree(n) for index, (key, left, right) in enumerate(nodes): left = left if left != -1 else None right = right if right != -1 else None t.add(key, value=index, left=left, right=right) t.adjust_relation() return t bin_tree = read() # bin_tree.inorder(bin_tree.root) # print() # bin_tree.preorder(bin_tree.root) # print() # bin_tree.postorder(bin_tree.root) # print(bin_tree) # print(bin_tree.structure) print(bin_tree) print(f'{"CORRECT" if bin_tree.check2(bin_tree.root) else "INCORRECT"}')
2a381a40ced555a26802737a25b6a4d051a63176
alejandrogonzalvo/Python3_learning
/IES El Puig/for-range/eqsegundogrado2/eqsegundogrado.py
1,075
3.859375
4
#!/usr/bin/python3.6 # -*- coding: utf-8 -*- # Este programa genera numeros de forma pseudo aleatoria y los utiliza como valores para resolver una equación de segundo grado. import math import funciones as f import random as r import time as t coef = [] soluciones = [] for x in range(3): coef.append(r.randrange(100)) coef.append(r.randrange(100)) coef.append(r.randrange(100)) while True: try: a = coef.pop(-1) b = coef.pop(-1) c = coef.pop(-1) except IndexError: print("\nYa no quedan mas datos en la lista") print("Resultados obtenidos:\n") print(soluciones) break sol1, sol2 = f.eqsegundogrado(a,b,c) soluciones.append({(f'{a}x*x', f'{b} x', f'{c}') : (f'{sol1} , {sol2}')}) # almacena los coeficientes y las soluciones en un diccionario. print (f"\nel valor de la solución 1 es {sol1}\n") print (f"el valor de la solución 2 es {sol2}\n") print("Reiniciando...") t.sleep(2) # espera en segundos
108f548024053725f59b0d97a375781a0ddda1fc
SyXo/InfoSecEngineering
/directory_buster.py
435
3.625
4
#Python dirb (Web Content Scanner) import requests site = input("Site name to scan: ") webReq = "http://www." + site + "/" wordlist = input("Wordlist to use: ") wordlistFile = open(wordlist, 'r') print("These paths returned an HTTP status code of 200:") for line in wordlistFile: line = line.strip() response = requests.get(webReq + line) if response.status_code == 200: print(site + "/" + line)
f26ef8085fcea1c3c96ccb601b3f229ee33f15c0
huongtran196/Python_DataCamp
/Introduction to Python/list.py
1,482
4.09375
4
# Create a list # area variables hall = 11.25 kit = 18.0 liv = 20.0 bed = 10.75 bath = 9.50 # Create a list areas areas = [hall, kit, liv, bed, bath] print(areas) # Update the list house = [['hallway', hall], ['kitchen', kit], ['living room', liv], ['bedroom', bed], ['bathroom', bath]] print(house) print(type(house)) # Subset & conquer areas = ['hallway', 11.25, 'kitchen', 18.0, 'living room', 20.0, 'bedroom', '10.75', 'bathroom', 9.50] # Print out the second element from areas print(areas[1]) # Print out the last element from areas print(areas[9]) # Print out the area of living room print(areas[4:6]) # Subset & Calculate eat_sleep_area = areas[3] + areas[7] print(eat_sleep_area) downstairs = areas[:6] upstairs = areas[6:] print(downstairs) print(upstairs) # Subsetting lists of lists house[-1][1] house[2][0] # Manipulating lists areas = ['hallway', 11.25, 'kitchen', 18.0, 'living room', 20.0, 'bedroom', 10.75, 'bathroom', 9.50] areas[-1] = 10.50 # Update the size of the bathroom areas[4] = 'chill zone' # Change the name of living room into chill zone print(areas) areas_1 = areas + ['poolhouse', 24.5] areas_2 = areas_1 + ['garage', 15.45] print(areas_1) print(areas_2) del(areas[-4:-2]) # Delete bedroom information areas_copy = list(areas) # Create an explicit copy of the original list areas_copy = areas[:] areas_copy[0] = 0.5 print(areas_copy)
1eb4e9372d0e34ae8f7ccaed52727d3f81013c40
mekhrimary/python3
/csvwriterandreader.py
2,145
4.5625
5
#!/usr/bin/env python3 # Write a comma separated value (CSV) file and then read it. def main(): """Write and read a comma separated value (CSV) file.""" persons = [('George', 'New York', 32), ('Eve', 'Boston', 29), ('Matt', 'Los Angeles', 26)] print('This program demonstrates how to write and read CSV files.') print('CSV (comma-separated values) is a plain text consists of records;') print('records include the same fields (i.e. values) separated by commas.') print() print('The example data list consists of 3 tuples (each with 3 values):') print('name (of a person), city and age.') print() print('These records:') print('------------------') records = show_persons(persons) print('Let\'s write these data into a CVS-file (persons.cvs)...') filename = 'persons.cvs' write_csv(records, filename) print('Well, then read and display a CVS-file (persons.cvs)...') print() print('The content of this file:') print('-------------') print_csv(filename) print('Seems our program works well!') print('And do you know that a CVS file can be read by almost all') print('spreadsheets and database management systems, including') print('Microsoft Excel, Apple Numbers and LibreOffice Calc & Base?') def show_persons(persons): """Show and return data from list of tuples.""" records = list() for person in persons: name, city, age = person record = f'{name},{city},{age}\n' records.append(record) print(record, end='') print() return records def write_csv(records, filename): """Write data into a CSV file.""" with open(filename, 'w') as csv: csv.write('name,city,age\n'); for record in records: csv.write(record) def print_csv(filename): """Read and print a CVS file.""" with open(filename, 'r') as csv: for record in csv: print(record, end='') print() if __name__ == '__main__': main()
2ac4aabc1359f50e2d2de5da511a7fe627b11570
superggn/myleetcode
/array/easy/53-maximum-subarray.py
549
3.921875
4
""" 去除边界条件 初始化cursum和res 更新cursum和res(全局最大子序列之和,就是max) """ from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: if len(nums) == 0: return 0 res, current_sum = float('-inf'), float('-inf') for n in nums: current_sum = n if current_sum < 0 else n + current_sum res = max(current_sum, res) return res # n = [-2, 1, -3, 4, -1, 2, 1, -5, 4] # s = Solution() # print(s.maxSubArray(n))
3910fd17e87e747a6a07771ec8682c0aee37322c
BParesh89/The_Modern_Python3_Bootcamp
/dictionaries/playlist_example.py
707
3.9375
4
# make a spotifyesque playlist using nested dicts and lists #my approach: playlist will be a dict, song list will be a list, each song will be a dict example1 = {"song_name": "cool boys", "song_artist/s": ["the boiz"], "duration": 2.3} example2 = {"song_name": "chilly billy", "song_artist/s": ["bill","chill"], "duration": 3.7} example3 = {"song_name": "popular peeps", "song_artist/s": ["Jeff"], "duration": 5.2} list_of_cool_songs = [example1, example2, example3] playlist = { "playlist_title": "cool songs 3", "playlist_creator": "Tim", "song_list": list_of_cool_songs, } print(playlist) total_length = 0 for song in playlist["song_list"]: total_length += song["duration"] print(total_length)
7d5906599387b55730106806ad0fa146ff7ba387
andregalvez79/Intro_to_Python
/2/chaptertrurtle.py
5,152
4.3125
4
#turtles import turtle # allows us to use the turtles library wn = turtle.Screen() # creates a graphics window alex = turtle.Turtle() # create a turtle named alex alex.forward(150) # tell alex to move forward by 150 units alex.left(90) # turn by 90 degrees alex.forward(75) # complete the second side of a rectangle alex.left(90) alex.forward(150) alex.left(90) alex.forward(75) #wn.exitonclick() #apparently this doesnt allow to close and open new screens #so i comment it out #changing properties or attributes #wn = turtle.Screen() wn.bgcolor("lightgreen") # set the window background color x = turtle.Turtle() x.color("blue") # make tess blue x.pensize(3) # set the width of her pen x.forward(50) x.left(120) x.forward(50) #wn.exitonclick() # wait for a user click on the canvas #extension #changing properties or attributes #import turtle #it's not necessary to import it again wn = turtle.Screen() color_str = input("type the color of the background") print(color_str) wn.bgcolor(color_str) # set the window background color tess = turtle.Turtle() colort_str = input("type the color of the turtle") tess.color(colort_str) # make tess a color size_str = input("type the size of the pen") tess.pensize(int(size_str)) # set the width of her pen tess.right(90) tess.forward(80) tess.left(190) tess.forward(110) wn.exitonclick() # wait for a user click on the canvas ############## #for loop for name in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]: print("Hi", name, "Please come to my party on Saturday!") #executes the print for every name in the list once #it can be used for commands too... it's gonna crash because of the wn problem #import turtle # set up alex #wn = turtle.Screen() #alex = turtle.Turtle() #for i in [0, 1, 2, 3]: # repeat four times # alex.forward(50) # alex.left(90) #wn.exitonclick() #### you can also sepcify this values as str or properties of a class #import turtle # set up alex #wn = turtle.Screen() #alex = turtle.Turtle() #for aColor in ["yellow", "red", "purple", "blue"]: # alex.color(aColor) #itll draw one line in yellow, then red, then purple then blue # alex.forward(50) # alex.left(90) #wn.exitonclick() ######## #instead of a list in the for loop thi is legal too #for i in range(4): #this means [0,1,2,3] # Executes the body with i = 0, then 1, then 2, then 3 #for x in range(10): # sets x to each of ... [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #this is legal too: range(1,5) this is [1,2,3,4] print(range(4)) print(range(1, 5)) #or more complicated: range(start, stop, step) print(range(0, 19, 2)) print(range(0, 20, 2)) print(range(10, 0, -1)) #cool stuff import turtle wn = turtle.Screen() wn.bgcolor("lightgreen") tess = turtle.Turtle() tess.color("blue") tess.shape("turtle") print(range(5, 60, 2)) #range starts on 5 ends 59 and skips two tess.up() # this is new for size in range(5, 60, 2): # start with size = 5 and grow by 2 tess.stamp() # leave an impression on the canvas tess.forward(size) # move tess along tess.right(24) # and turn her wn.exitonclick() ################################################################# #chapter functions #import turtle def drawSquare(t, sz): #here you define the structure of the function name(variables) """Make turtle t draw a square of with side sz.""" for i in range(4): t.forward(sz) #this is what will happen in the funtion t.left(90) #(this is a constant) wn = turtle.Screen() # Set up the window and its attributes wn.bgcolor("lightgreen") alex = turtle.Turtle() # create alex drawSquare(alex, 50) #here you recall the function and t, is substituted for the object turtle and you define the size wn.exitonclick() #you can use functions in for loops example: #def drawMulticolorSquare(t, sz): # """Make turtle t draw a multi-colour square of sz.""" # for i in ['red','purple','hotpink','blue']: # t.color(i) # t.forward(sz) # t.left(90) #wn = turtle.Screen() # Set up the window and its attributes #wn.bgcolor("lightgreen") #tess = turtle.Turtle() # create tess and set some attributes #tess.pensize(3) #size = 20 # size of the smallest square #for i in range(15): # drawMulticolorSquare(tess, size) THIS IS THE FUNCTION # size = size + 10 # increase the size for next time # tess.forward(10) # move tess along a little # tess.right(18) # and give her some extra turn #wn.exitonclick() #in a function definition if you add return a varaible it will return a value... #sounds obvious but if you don't then it just computes #but can't see the result... ALSO RETURN ENDS THE FUNCTION...
94a815ffa2e4a98ce36f8acc019bd4da6a1489e3
hotoku/samples
/python/pandas/iterate.py
298
4.15625
4
#!/usr/bin/env python """ 単純にiterateすると、列をなめる """ import pandas as pd df = pd.DataFrame(dict( x=range(3), y=range(3) )) for c in df: print(c) """ 行をなめたい場合はiterrowsを使う """ for r in df.iterrows(): print(r[0], r[1]["x"], r[1]["y"])
1159d141238837b0e607821c6756bbb362e46a10
mdagostino00/First-Integration-Project
/main.py
36,504
3.75
4
""" RPG Battle Sim for Integration Project This was originally a fighting game themed project, but I thought it was too limited in scope, so it's now an RPG themed project. This is a script that plays like an autoclicker with RPG elements. It uses python's tools to manage files, perform calculations, and present information that show off what I learned about the language. Sources: https://gamefaqs.gamespot.com/ps/197341-final-fantasy-vii/faqs/22395 https://www.w3schools.com/ https://www.tutorialspoint.com/python/index.htm https://realpython.com/ """ __author__ = "Michael D'Agostino" import random import json import os import time def main(): """ Displays main menu, where user selects what function the program should run. """ print("Welcome to my Integration Project! \nIt's a small game about " "managing a fantasy guild that serves to demonstrate my " "knowledge of Python programming!" '\nIf this is your first time playing, start by selecting ' '"Initialize" from the menu by pressing "r".') display_main_menu() menu_loop = True while menu_loop: # simple main menu loop menu_selection = input("What would you like to do? :") if menu_selection == "1": print("Sending Adventuring Party...") initialize_battle() display_main_menu() elif menu_selection == "2": print("Scouting a new adventurer...") initialize_char() display_main_menu() elif menu_selection == "3": print("Viewing Adventurer Stats...") display_char_stats() display_main_menu() elif menu_selection == "4": print("Commencing Guild Promotion...") level_up_from_menu() display_main_menu() elif menu_selection == "5": print("Viewing Guild Hall Status...") display_player_stats() display_main_menu() elif menu_selection == "k": print("Bringing out the shovel...") kill_char_from_menu() display_main_menu() elif menu_selection == "r": restart_game = input( "Are you sure you want to initialize the game? (y/n) :") if restart_game == "y": initialize_game() display_main_menu() else: print("Returning to Main Menu... ") display_main_menu() elif menu_selection == "0": close_game = input("Are you sure you want to quit? (y/n) :") if close_game == "y": menu_loop = False print("Thanks for playing!") else: print("Returning to Main Menu... ") display_main_menu() else: print("Unknown command input. Try again!") def display_main_menu(): """ Prints the main menu. """ print(''' Main Menu: [1] Send Adventuring Party [2] Hire Adventurer [3] View Adventurer Stats [4] Guild Promotion [5] View Guild Hall Status [k] Kill [r] Initialize [0] Close Program ''') def initialize_game(): """ Creates gamestate.txt if it doesn't exist, which is used to store player data. """ path = get_file_directory() try: os.makedirs(path) player_dict = create_player_stats() name = "gamestate" save_char_data(player_dict, name) print("Game Successfully Initialized! \nNow that you're all set up," "try hiring some adventurers to party up!") except FileExistsError: print("You have a working \\characterFiles folder at", path, ".") print( "If you wish to restart the game, please delete the contents of " "\\characterFiles and the file itself.") print("Returning to Main Menu... ") def create_player_stats(): """ Creates starting dictionary values for gamestate file. :return: player stats dictionary """ player_dict = { "level": 1, "exp": 0, "gold": 300 } return player_dict def initialize_char(): """ Creates character file, using name user inputs. Rolls a bunch of stats using roll_stats() and roll_skills() and saves values to a dictionary, and character file. """ name = str(input("What's the name of the scouted adventurer? :")) name_check = check_name_characters(name) # check if name is valid path = get_file_directory() try: if not name_check: print("This name is invalid!") elif name in os.listdir(path): print("This person is already a registered adventurer!") else: skills = [] lv = 0 exp = 0 (lv, hp, mp, strength, dexterity, vitality, magic, spirit, luck) = roll_stats(lv) weapon_choice, skill_type = roll_weapon() skills = roll_skills(lv, skill_type, skills) stat_dict = { "name": name, "level": lv, "exp": exp, "hp": hp, "mp": mp, "strength": strength, "dexterity": dexterity, "vitality": vitality, "magic": magic, "spirit": spirit, "luck": luck, "weapon": weapon_choice, "skill_type": skill_type, "skills": skills, } save_char_data(stat_dict, name) print("Adventurer Successfully Registered!") except FileNotFoundError: print('\nThe \\characterFiles folder was not found! \nPlease ' 'initialize the game by pressing "r" on the Main Menu!\n') def level_up_from_menu(): """ Takes character file, rolls stats, changes file dictionary, and saves file. """ try: player_dict = get_stats("gamestate") if player_dict["gold"] < 100: # checks player file's gold value print("It takes 100 gold to level up a character! \nCome back " "when you're a bit... mmmh... richer!") return False else: pass prompt = "It costs 100 gold to level up a character. \nYou have " + \ str(player_dict["gold"]) + " gold. \nWho would you like to " \ "level up? :" char_list = get_char_list() file_select = select_file(char_list, prompt) if not char_list: print( "You don't have any adventurers to promote! \nReturning to " "Main Menu... ") elif not file_select: print("Returning to Main Menu... ") else: player_dict["gold"] -= 100 save_char_data(player_dict, "gamestate") level_up_stats(file_select) except FileNotFoundError: print('\nThe \\characterFiles folder was not found! \nPlease ' 'initialize the game by pressing "r" on the Main Menu!\n') def level_up_stats(file_select): """ Rolls stats and adds them to chosen filename's dictionary :param file_select: name of file dictionary """ char_dict = get_stats(file_select) stat_list = roll_stats(char_dict["level"]) roll_skills(char_dict['level'], char_dict['skill_type'], char_dict['skills']) char_dict_updated = { 'level': char_dict["level"] + 1, 'exp': 0, 'hp': char_dict['hp'] + stat_list[0], 'mp': char_dict['mp'] + stat_list[1], 'strength': char_dict['strength'] + stat_list[2], 'dexterity': char_dict['dexterity'] + stat_list[3], 'vitality': char_dict['vitality'] + stat_list[4], 'magic': char_dict['magic'] + stat_list[5], 'spirit': char_dict['spirit'] + stat_list[6], } char_dict.update(char_dict_updated) save_char_data(char_dict, char_dict['name']) print(char_dict['name'], " has been successfully promoted to level ", char_dict['level'], "!", sep='') def roll_stats(lv): """ Rolls a new character or rolls stat additions to existing character. :param lv: integer of character level, taken from file. :return: stat_list, to be used as list, or as additions to stats """ stat_list = [] if lv == 0: # roll new lvl 1 char stat_list.append(lv + 1) stat_list.append(random.randrange(20, 30)) # hp stat_list.append(random.randrange(10, 20)) # mp for x in range(5): stat_list.append(random.randrange(6, 15)) # str,dex,vit,mag,spi stat_list.append(random.randrange(1, 5)) # luck return stat_list else: # roll stat additions lv += 1 stat_list.append(random.randrange(3 * lv + 5, 4 * lv + 5) + lv) # hp stat_list.append(random.randrange(lv, 2 * lv) + (lv // 2)) # mp for x in range(5): stat_list.append(random.randrange(1, 5)) # str,dex,vit,mag,spi return stat_list def roll_weapon(): """ Rolls and outputs weapon and weapon type :return: weapon, skill_type """ skill_type_list = ["melee", "ranged", "magic"] skill_type = random.choice(skill_type_list) if skill_type == "melee": weapon_list = ['Greatsword', 'Longsword', 'Axe', 'Lance', 'Dagger', 'Hammer'] elif skill_type == "ranged": weapon_list = ['Longbow', 'Crossbow', 'Shortbow', 'Javelin', 'Throwing Knife', 'Sling'] elif skill_type == "magic": weapon_list = ['Staff', 'Tome', 'Wand', 'Magecraft', 'Orb of Casting', 'BDE'] else: skill_type = "normal" weapon_list = ['Fists', 'Pitchfork', 'Shotgun', 'Words'] weapon = random.choice(weapon_list) return weapon, skill_type def roll_skills(lv, skill_type, skills): """ Checks level to see if character is new, or is a lv where lv % 8 = 0. For new char, rolls 2 stats and saves as list. For existing char, rolls a stat, and appends to existing skill list. :param lv: level of char grabbed from file :param skill_type: skill_type of char's weapon :param skills: chars already learned skills :return: skills as list """ skill_list = determine_skill_list(skill_type) if lv == 1: skills = [] for skill in range(2): skills.append(random.choice(skill_list)) skill_list.remove(skills[skill]) elif lv % 5 == 0 and lv <= 16: skill_list_set = set(skill_list) skills_set = set(skills) skill_list = list(skill_list_set - skills_set) skills.append(random.choice(skill_list)) else: skills = skills return skills def determine_skill_list(skill_type): """ Prints skills available, determined by skill_type. :param skill_type: type of skill, from roll. :return: skill_list as list """ if skill_type == "melee": skill_list = ['Rising Force', 'Overhead Swing', 'Vital Piercer', 'Judo Grapple', 'Mother Rosario', 'Dual Wield', 'Demon Mode', 'Feint Strike', 'Hilt Thrust', 'The move that Levy from Attack on Titan uses', 'Kingly Slash', 'French Beheading'] elif skill_type == "ranged": skill_list = ['Rapid Fire', 'Exploding Shot', 'Armor Piercer', 'Poison Tip', 'Oil-Tipped Flint', 'Curved Shot', "Bull's Eye", 'Steady Aim', 'Asphyxiating Arrow', 'Wyvern Shot', 'Thieves Aim', "Rangers' Guile"] elif skill_type == "magic": skill_list = ['Fireball', 'Thunderstruck', 'Nosferatu', 'Fortify Arms', 'Summon Ghosts', 'Ancient Power', 'Draconian Breath', 'Confusing Ray', 'UnHealing', 'UnRestore', 'UnCure', 'Fortnite Dance', 'Slurred Cantrips', 'Mundane Thesis'] else: skill_list = ['Hide', 'Run', 'Yell', 'Fortnite Dance'] return skill_list def initialize_battle(): """ A script where you can send your party into battle. :return: False if something goes wrong or declined by user """ party_chars = initialize_char_select() # grabs a list of 3 chars if not party_chars: print("Returning to Main Menu... ") else: char1, char2, char3 = party_chars # unpacks list into variables print(char1['name'], ", ", char2['name'], ", and ", char3['name'], " will be partying up together.", sep='') location_list = generate_location_list() message = "Where will the party be adventuring? :" try: location = select_file(location_list, message) # select level if not location: print("Returning to Main Menu...") return False else: pass print(char1['name'], ", ", char2['name'] + ", and ", char3['name'], " will be heading to ", location, ".", sep='') agreement = input("Are you sure you want to send this party out? " "(y/n) :") if agreement == "y": start_battle(char1, char2, char3, location) else: print("Returning to Main Menu...") return False except TypeError: print("Returning to Main Menu...") def generate_location_list(): """ Generates list of locations depending on player level. :return: location_list, selectable locations """ player_dict = get_stats("gamestate") total_locations = ["Flowering Plains", "Misty Rainforest", "Graven Marsh", "Bellowing Mountains", "Cryptic Caverns", "Ancient Spire", "Cloudy Peaks", "Canada", "Volcanic Isles", "Desolate Wasteland"] location_list = [] if player_dict["level"] > 10: for location in range(10): location_list.append(total_locations[location]) else: for location in range(player_dict["level"]): location_list.append(total_locations[location]) return location_list def start_battle(char1, char2, char3, location): """ Starts a battle using selected player characters, and an enemy created from selected location. :param char1: character 1 :param char2: character 2 :param char3: character 3 :param location: chosen location from location list """ enemy = generate_enemy(location) print("\nThe party encountered a ", enemy["name"], "!", sep='') time.sleep(3) party_list = [char1, char2, char3] battle_list = [char1, char2, char3, enemy] battle_list.sort(reverse=True, key=grab_char_dex_stat) x = 0 while enemy["hp"] > 0 and char1["hp"] > 0 and char2["hp"] > 0 and \ char3["hp"] > 0: action = select_char_action(battle_list[x]["mp"]) if 'money' in battle_list[x]: attacker = battle_list[x] defender = random.choice(party_list) else: attacker = battle_list[x] defender = enemy if action == "Attack": print(attacker['name'], " performs an attack on ", defender['name'], "!", sep='') elif action == "Skill": print(battle_list[x]['name'], " uses ", random.choice(attacker["skills"]), " on ", defender['name'], "!", sep='') battle_list[x]['mp'] -= random.randrange( 6 * battle_list[x]['level'] / 2, 10 * battle_list[x]['level'] / 2) time.sleep(2) attack_damage = calculate_action_damage(attacker, defender, action) defender["hp"] -= attack_damage print(defender["name"], " is at ", defender["hp"], " HP!", sep='') print() time.sleep(3) # checks if dead guy is ally or enemy, then cues respective scene if defender["hp"] <= 0: defender_team = check_defender_team(defender, party_list) if defender_team: cue_party_member_death(defender) else: cue_enemy_death(defender, char1, char2, char3) else: x += 1 if x == 4: x = 0 else: pass print("Returning to Main Menu...") def initialize_char_select(): """ Asks for 3 characters to be used in the battle script. :return: party_stats, which is a list of character dictionaries from files. """ party_stats = [] char_select = None char_list = get_char_list() if not char_list: # this if/else branch checks number of chars print( "You don't have any adventurers to form a party! " "\nCome back with at least three adventurers.") return False elif len(char_list) < 3: print( "You don't have enough adventurers to form a party! " "\nCome back with at least three adventurers.") return False else: message = "Which adventurers will party together? :" while len(party_stats) < 3 and char_select != "0": try: character = select_file(char_list, message) if character is False: # this one if 0 was entered return False else: party_stats.append(get_stats(character)) char_list.remove(character) print(character, "has been added to the party.") message = "Who else will party up? :" except TypeError: # type the number, not the name, plz print( "Please enter the ID number of the adventurer you will " "use, \nor enter 0 to go back.") return party_stats def generate_enemy(location): """ Generates enemy used for battle. :param location: Selected location :return: enemy name, enemy_stats as dict """ enemy_list = [] if location == "Flowering Plains": enemies = ["Slime", "Cursed Cornstalk", "Buzzy Bee", "Feral Mutt"] lv = 1 elif location == "Misty Rainforest": enemies = ["Slime", "Cain Toad", "Vociferous Viper", "Crocodire"] lv = 2 elif location == "Graven Marsh": enemies = ["Slime", "Wild Roots", "Pecking Vulture", "Breaking Bat"] lv = 3 elif location == "Bellowing Mountains": enemies = ["Slime", "Billy Goat", "Mountain Ape", "Laughing Lion"] lv = 4 elif location == "Cryptic Caverns": enemies = ["Cryptic Slime", "Walking Dead", "Ghast", "Spider Monkey", "????"] lv = 5 elif location == "Ancient Spire": enemies = ["Slime Knight", "Haunted Armor", "Kobold Squadron", "Rock Solid"] lv = 6 elif location == "Cloudy Peaks": enemies = ["Liquid Slime", "Gilded Goose", "Dragon Hatchling", "Mountain Giant"] lv = 7 elif location == "Canada": enemies = ["Canadian Slime", "Dire Wolf", "Friendless Citizen", "Pal"] lv = 8 elif location == "Volcanic Isles": enemies = ["Flaming Slime", "Lava Golem", "Dancing Devil"] lv = 9 elif location == "Desolate Wasteland": enemies = ["Metal Slime", "Fallout Zombie Hoard", "Dragon Remains", "Roaming Gargantuan"] lv = 10 else: print("Something went wrong, and the location name wasn't found!") return False enemy_list.extend(enemies) # puts enemy list into empty list enemy = random.choice(enemy_list) # selects random choice from list enemy_stats = roll_enemy_stats(lv, enemy) # rolls stats for enemy return enemy_stats def roll_enemy_stats(lv, enemy): """ Generates enemy stats based on location level, and assigns it to enemy dictionary. :param lv: Level of chosen location :param enemy: name of enemy :return: enemy stats as dictionary """ exp = random.randrange((1 << lv) + (lv * 5), ((1 << lv) * 2) + (lv * 5)) hp = random.randrange((2 ** lv) + (lv * 15), ((2 ** lv) * 2) + (lv * 15)) + (20 * lv) mp = random.randrange((2 ** lv) + (lv * 10), ((2 ** lv) * 2) + (lv * 10)) strength = random.randrange(3 * lv, 4 * lv) + 8 + lv dexterity = random.randrange(3 * lv, 4 * lv) + 8 + lv vitality = random.randrange(3 * lv, 4 * lv) + 8 + lv magic = random.randrange(3 * lv, 4 * lv) + 8 + lv spirit = random.randrange(3 * lv, 4 * lv) + 8 + lv luck = random.randrange(1, 4) skill_type = random.choice(["melee", "ranged", "magic"]) money = random.randrange((2 ** lv) + (lv * 5), ((2 ** lv) * 2) + (lv * 5)) # money used to distinguish enemy from party, given to player after battle enemy_dict = { "name": enemy, "level": lv, "exp": exp, "hp": hp, "mp": mp, "strength": strength, "dexterity": dexterity, "vitality": vitality, "magic": magic, "spirit": spirit, "luck": luck, "skill_type": skill_type, "skills": ["Sweeping Attack", "Heavy Blow", "Enraged Charge", "Leaping Crush", "Wild Swing"], "money": money } return enemy_dict def select_char_action(character_mp): """ Selects random action dependant on mp :param character_mp: mp taken from loaded char dictionary :return: action_choice """ if character_mp > 0: action_list = ["Attack", "Skill"] action_choice = random.choices(action_list, weights=[8, 2]) choice = action_choice[0] else: choice = "Attack" return choice def calculate_hit_probability(attacker, defender): """ Calculates probability of hitting based on dexterity values :param attacker: attaacker dexterity :param defender: defender dexterity :return: probability of hitting defender """ hit_probability = round((((10 - (defender / attacker)) ** 3) / 10), 2) # a triple roll probability, then given in percent form return hit_probability def calculate_hit_roll(probability): """ Calculates if attack hits using calculated probability :param probability: hit probability :return: true or false, did attack hit or not """ hit_roll = ((random.randrange(0, 100) + (random.randrange(0, 100))) / 2) if hit_roll <= probability: return True else: return False def grab_char_dex_stat(char_dict): """ Grabs stat from dictionary and returns it :return: the stat found in the dictionary """ return char_dict["dexterity"] def calculate_action_damage(attacker, defender, action): """ Determine what effect happens when action takes place. :param attacker: attacker dictionary :param defender: defender dictionary :param action: """ hit_probability = calculate_hit_probability(attacker["dexterity"], defender["dexterity"]) hit_roll = calculate_hit_roll(hit_probability) if action == "Attack" and hit_roll is not False: damage = calculate_attack_damage(attacker["level"], attacker["skill_type"], attacker["strength"], attacker["magic"], attacker["luck"], defender["vitality"], defender["spirit"], defender["luck"]) print("The ", action, " does ", damage, " damage!", sep='') elif action == "Skill" and hit_roll is not False: base_damage = calculate_attack_damage(attacker["level"], attacker["skill_type"], attacker["strength"], attacker["magic"], attacker["luck"], defender["vitality"], defender["spirit"], defender["luck"]) damage_mod = random.randrange(2, 5) / 2 # multiplies damage by mod damage = round(base_damage * damage_mod) print("The ", action, " does ", damage, " damage!", sep='') else: print("The ", action, " missed!", sep='') damage = 0 time.sleep(2) return damage def calculate_attack_damage(atlvl, attype, atstr, atmag, atlu, dfvit, dfspi, dflu): """ Calculates attack damage from given attacker and defender parameters. :param atlvl: attacker level :param attype: attacker skill type :param atstr: attacker strength :param atmag: attacker magic :param atlu: attacker luck :param dfvit: defender vitality :param dfspi: defender spirit :param dflu: defender luck :return: damage """ if attype == "melee": # inspired by ffvii damage calcs (sources) base_damage = atstr + ((atstr + atlvl) / 32) * ((atstr * atlvl) / 32) damage = round(base_damage + atlvl - ((base_damage + atstr) / dfvit)) elif attype == "ranged": base_damage = atstr + ((atstr + atlvl) / 32) * ((atstr * atlvl) / 32) damage = round(base_damage + atlvl - ((base_damage + atstr) / dfvit)) elif attype == "magic": base_damage = atmag + ((atmag + atlvl) / 32) * ((atmag * atlvl) / 32) damage = round(base_damage + atmag + atlvl - ((base_damage + atmag) / dfspi) - (dfspi // 2)) else: damage = 1 critical_hit = ((atlu + atlvl - dflu) / 4) + 1 random_critical = random.randrange(1, 16) if random_critical <= critical_hit: damage *= 3 print("Critical Hit!!" * 2) time.sleep(2) else: pass if damage < 0: damage = 1 else: pass return damage def check_defender_team(defender, party_list): """ Checks if killed object was a player object or enemy object :param defender: :param party_list: :return: """ if defender in party_list: print(defender["name"], "has perished!") return True else: print("The enemy ", defender["name"], " has perished!", sep='') return False def cue_enemy_death(defender, char1, char2, char3): """ Runs script when enemy is killed in battle. :param defender: enemy dictionary :param char1: char 1 dict :param char2: char 2 dict :param char3: char 3 dict """ print("\nThe victorious adventurers return to the guild with their heads\n" "held high. The trip proved successful thanks to your great \n" "thinking. The odds of battle proved to be no better than your \n" "party's teamwork and your planning. Well done, guild master.\n") time.sleep(4) player_dict = get_stats("gamestate") player_dict["gold"] += defender["money"] player_dict["exp"] += defender["exp"] # Does the Guild level up? message = "Your Guild Hall has leveled up!" player_dict["level"] = level_up_guild(player_dict, message) time.sleep(2) save_char_data(player_dict, "gamestate") # Update char exp, and check for level up file1 = get_stats(char1["name"]) file2 = get_stats(char2["name"]) file3 = get_stats(char3["name"]) file1["exp"] += defender["exp"] * 2 file2["exp"] += defender["exp"] * 2 file3["exp"] += defender["exp"] * 2 lvl_check = check_level_up(file1) if lvl_check: level_up_stats(file1["name"]) time.sleep(2) else: pass lvl_check = check_level_up(file2) if lvl_check: level_up_stats(file2["name"]) time.sleep(2) else: pass lvl_check = check_level_up(file3) if lvl_check: level_up_stats(file3["name"]) time.sleep(2) else: pass def level_up_guild(player_dict, message): """ Levels up dictionary level using check function :param player_dict: any dictionary :param message: given level up message """ lvl_change = check_level_up(player_dict) if lvl_change: level = player_dict["level"] + 1 print(message) return level else: return player_dict["level"] def check_level_up(player_dict): """ Checks player exp vs their level to see if guild level increases :param player_dict: any dictionary :return: """ if player_dict["exp"] > (5 << player_dict["level"]): return True else: return False def cue_party_member_death(defender): """ May the dead rest in peace. :param defender: you let this happen """ print("\nThe adventurers return to the guild, defeated, and with one " "less \nmember in tow. Their inadequacy and your lack of judgement " "has \nled to one of your guild members perishing. The dead won't " "be \nreturning anytime soon, so don't expect to come across", defender["name"], "\nagain. Reflect, and don't make the same " "mistake next time.") time.sleep(8) kill_char(defender) def display_char_stats(): """ Asks for which character to be shown, and displays stats from file. :return: """ prompt = "Whose stats would you like to see? :" char_list = get_char_list() if not char_list: print( "You don't have any adventurers! \nTry hiring some from the " "Main Menu!") else: file_select = select_file(char_list, prompt) if file_select in char_list: stat_line = ["name", "level", "exp", "hp", "mp", "strength", "dexterity", "vitality", "magic", "spirit", "weapon", "skills"] stats = get_stats(file_select) for index in range(12): print(stat_line[index], ":", stats.get(stat_line[index])) else: print("Returning to Main Menu... ") def kill_char_from_menu(): """ Removes character from file directory, essentially killing character :return: """ try: prompt = "Who would you like to kill? :" char_list = get_char_list() if not char_list: print( "There are no lucky adventurers for you to kill! " "Try hiring some!") char_select = select_file(char_list, prompt) char_file = get_stats(char_select) kill_choice = input("Are you sure you want to kill " + char_file[ 'name'] + " ? (y/n) :") if kill_choice == "y": print(char_file['name'], "has been put down. \nReturning to Main Menu.") # F kill_char(char_file) else: print("Returning to Main Menu... ") except TypeError: print("Returning to Main Menu... ") def kill_char(char_file): """ Modular remove file from characterFiles directory :param char_file: name of file """ path = get_file_directory() os.remove(path + '\\' + char_file['name']) def select_file(char_list, message): """ Displays char list in numbered format, asks for selection as number, returns given file name. :param char_list: list of characters grabbed from function :param message: message taken from other function, allows modularity :return: the specific file name to be read as file, or False to return to Main Menu. """ if not char_list: return False print("\nEnter an ID number, or enter 0 to go back.") for value, char in enumerate(char_list, start=1): # woah, enumerate print("[", value, "] ", char, sep="") while True: try: file_select = int(input("\n" + message)) - 1 # fixing for index if 0 <= file_select <= (len(char_list) - 1): # choice is number return char_list[file_select] elif file_select == (-1): # if input is 0, return to main menu return False else: print( "This is not a valid selection! " "\nTry another ID, or enter 0 to go back.") except ValueError: # If value not a number, repeat loop print( "This is not a valid selection! " "\nTry another ID, or enter 0 to go back.") def get_stats(char_select): """ Outputs chosen character file as dictionary :param char_select: name grabbed from other functions. :return: character dictionary if true, False if file doesn't exist. """ try: path = get_file_directory() with open(os.path.join(path, char_select), 'r') as openfile: char_dict = json.load(openfile) return char_dict except TypeError: return False def display_player_stats(): """ Prints stats found in gamestate file. """ try: char_select = "gamestate" player_dict = get_stats(char_select) for key, value in player_dict.items(): # prints the dict in the file print(value, ":", key) except FileNotFoundError: print('\nThe \\characterFiles folder was not found! \nPlease ' 'initialize the game by pressing "r" on the Main Menu!', end='\n\n') def save_char_data(stat_dict, name): """ Takes given char dictionary and file name and saves to char's file name :return: "Adventurer stats successfully recorded!" """ char_json = json.dumps(stat_dict, indent=4) # turns the dict into json path = get_file_directory() with open(os.path.join(path, name), 'w') as writer: writer.write(char_json) # saves json to file message = "Adventurer stats successfully recorded!" return message def get_char_list(): """ View files in the game file directory, check if none exist, and output as list :return: char_list as list """ try: path = get_file_directory() files = os.listdir(path) char_list = [] for file in files: # prints all files found in \\characterFiles char_list.append(file) # reads stores all files from dir into list char_list.remove("gamestate") # removes the gamestate file if not char_list: # checks if list is empty return False else: return char_list except FileNotFoundError: print('\nThe \\characterFiles folder was not found! \nPlease ' 'initialize the game by pressing "r" on the Main Menu!\n') def check_name_characters(name): """ Checks if filename is valid. https://www.mtu.edu/umc/services/websites/writing/characters-avoid/ :param name: name :return: better name """ name = name.replace(" ", "A") # allows spaces... if name == "" or name == "0" or name == "gamestate": return False elif name.isalnum(): # ...but no other special chars return True else: return False def get_file_directory(): """ Get the directory where the game files are stored, = cwd\\characterFiles :return: path for files """ path = os.getcwd() + "\\characterFiles" return path if __name__ == "__main__": main()
ebca0c7654af2c383b50a3920e9292083d398957
eoriont/machine-learning
/src/graphs/node.py
734
3.640625
4
class Node: def __init__(self, index, value=0): self.index = index self.value = value self.neighbors = [] self.parent = None def set_value(self, value): self.value = value def set_parent(self, parent): self.parent = parent def set_neighbor(self, neighbor): self.neighbors.append(neighbor) neighbor.neighbors.append(self) def depth_first_search(self, already_visited=None): already_visited.append(self.index) neighbor_indices = (neighbor.depth_first_search(already_visited) for neighbor in self.neighbors if neighbor.index not in already_visited) return [self.index] + sum(neighbor_indices, [])
f04cf9e49d65696a94f156ab2f70e9ee2e3898e9
Aaron-cdx/py-codecode
/Leetcode117_FixTheNodeRightNode.py
1,175
4.03125
4
# -*- coding:utf-8 -*- """ @author caoduanxi @date 2020/9/28 10:27 Keep thinking, keep coding! """ class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next class Solution: """ python中默认一个变量使用if就代表不为空,如果要对None类型数据进行判断,使用 if not None => 即可判断是否为None类型类 """ def connect(self, root: 'Node') -> 'Node': if root is None: return root if root.left and root.right: root.left.next = root.right if root.left and not root.right: root.left.next = self.next_node(root.next) if root.right: root.right.next = self.next_node(root.next) self.connect(root.right) self.connect(root.left) return root def next_node(self, node: 'Node') -> 'Node': if not node: return node if node.left: return node.left if node.right: return node.right if node.next: return self.next_node(node.next) return None
fdafa0f0003012113288513d58fc9ee0de7d6f2b
timetobye/BOJ_Solution
/problem_solve_result/2947.py
327
3.59375
4
def bubble_sort(a): n = len(a) if n <= 1: return a for j in range(n - 1, 0, -1): for i in range(j): if a[i] > a[i + 1]: a[i], a[i + 1] = a[i + 1], a[i] print(a[0], a[1], a[2], a[3], a[4]) return a n = list(map(int, input().split())) bubble_sort(n)