blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
32c179910080008ebe41364381adceea35184213
sejongjeong/Algorithm-Baekjoon
/src/2108_통계학.py
645
3.5
4
import sys import math from collections import Counter input = sys.stdin.readline n = int(input()) num_list = [0 for _ in range(n)] for i in range(n): temp = int(input()) num_list[i] = temp print(round(sum(num_list)/n)) num_list.sort() print(num_list[int(n/2)]) def mode(x): count_dic = Counter(x) most_count = count_dic.most_common() result = None if len(x) > 1: if most_count[0][1] == most_count[1][1]: result = most_count[1][0] else: result = most_count[0][0] else: result = most_count[0][0] return result print(mode(num_list)) print(num_list[-1] - num_list[0])
acc8b91a7053473fea2c945182098c08167e11cc
panditprogrammer/python-mysql
/py_db6.py
549
3.65625
4
#Extracting data from table with python import mysql.connector #conneting to database and select mydatabase = mysql.connector.connect(host='localhost', user='root', password='', database='pythondb') #for any operation use cursor object cur = mydatabase.cursor() #sql command sql="SELECT * FROM student" cur.execute(sql) #getting result from database in the form of tuple result = cur.fetchall() for record in result: print(record)
db051f889ee762f75c0f9a93768155286ee4ec40
shivenpurohit/algorithmic-toolbox-coursera-UC-San-Diego
/week3_greedy_algorithms/4_maximum_advertisement_revenue/dot_product.py
626
3.578125
4
#Uses python3 import sys def max_dot_product(a, b): #write your code here res = 0 while(len(a) > 0): max_a = 0 max_b = 0 for i in range(len(a)): if(a[i] > a[max_a]): max_a = i if(b[i] > b[max_b]): max_b = i res += a[max_a] * b[max_b] del a[max_a:max_a+1] del b[max_b:max_b+1] return res if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n = data[0] a = data[1:(n + 1)] b = data[(n + 1):] print(max_dot_product(a, b))
47166f536c68baea2d0e2b99f33454ba93c2abd8
sandysuehe/LintCode-Learning
/Algorithms/StringProcess/valid-word-abbreviation.py
1,057
3.71875
4
#!/usr/bin/env python #-*- coding: utf-8 -*- # Author: ([email protected]) ######################################################################### # Created Time: 2018-08-28 16:28:08 # File Name: valid-word-abbreviation.py # Description: Valid Word Abbreviation # LintCode: https://www.lintcode.com/problem/valid-word-abbreviation/ ######################################################################### def validWordAbbreviation(word, abbr): m = len(word) n = len(abbr) i = 0 j = 0 while i < m and j < n: if abbr[j].isdigit(): if abbr[j] == "0": return False val = 0 while j < n and abbr[j].isdigit(): val = val*10 + int(abbr[j]) j += 1 i += val else: if word[i] != abbr[j]: return False i += 1 j += 1 return i == m and j == n s = "internationalization" abbr = "i12iz4n" print validWordAbbreviation(s, abbr) s = "apple" abbr = "a2e" print validWordAbbreviation(s, abbr)
e48c32b7f889e6dc05c8f10c709a027abbac8fac
kudoxi/hanshoushou
/public/uploads/20180328/0853d54f58806ae2ecc7d6df1067bca7.py
474
3.84375
4
name = input("what is your name") age = input("how old are you")#input 接受的所有数据都是字符串,即使你输入的是数字 death_age = 100 print(type(age)) # str print ("my name is ",name," and I am ",age," years old,I can still live for ",str(death_age - int(age))," years") #python里字符串和数字无法拼接在一起 #或者 print ("my name is "+name+" and I am "+age+" years old,I can still live for "+str(death_age - int(age))+" years")
fbaf13dae8cd7c6ac80fb75ef6896f4c985150ab
abhi-python/python-programs
/tryexceptprog.py
215
3.828125
4
print("Enter num 1") num1 = input() print("Enter num 2") num2 = input() try: print("The sum of these two numbers is", int(num1)+int(num2)) except Exception as e: print(e) print("This should be executed")
7e5f59e843b4ff68cf7edccc5442f2b63e65a150
Nimor111/101-v5
/week3/Tasks.py
1,088
3.796875
4
def gcd(a, b): if a == b: return a else: if a > b: return gcd(a - b, b) else: return gcd(a, b - a) def gcd_second(a, b): if b == 0: return a else: return gcd_second(b, a % b) def simplify_fraction(fraction): if fraction[0] == fraction[1]: return 1 if fraction[0] == 0: return 0 if fraction[1] == 0: raise ZeroDivisionError return (fraction[0] // gcd_second(fraction[0], fraction[1]), fraction[1] // gcd_second(fraction[0], fraction[1])) def sort_fractions(fractions): return [j[1] for j in sorted([(i[0] / i[1], i) for i in fractions])] def main(): print(simplify_fraction((3, 9))) print(simplify_fraction((1, 7))) print(simplify_fraction((4, 10))) print(simplify_fraction((63, 462))) print(sort_fractions([(2, 3), (1, 2)])) print(sort_fractions([(2, 3), (1, 2), (1, 3)])) print(sort_fractions([(5, 6), (22, 78), (22, 7), (7, 8), (9, 6), (15, 32)])) if __name__ == '__main__': main()
39dd771022b0c5d03e4853b16fa89443d64e862f
DillonSteyl/SCIE1000
/Other/Multiple_Input/attempt.py
234
3.90625
4
number = eval(input('Please enter a number: ')) number2 = eval(input('Please enter a different number: ')) abb = int(number) if (abb < 0): abb *= -1 print(abb) else: print(abb) print(number2) print('Sum:', number2+abb)
f40b748d889777bb3e16bebdaa67fc4c8e4e1d6f
prstepic/DataStructuresAndAlgorithms
/Queue.py
503
3.515625
4
class Queue: def __init__(self) -> None: self.queueList = [] def dequeue(self): if(self.queueList): return self.queueList.pop(0) else: return None def enqueue(self, val) -> None: self.queueList.append(val) def first(self): if(self.queueList): return self.queueList[0] else: return None def size(self) -> int: return len(self.queueList)
3084dc5674d4c3d30ffd858106145c213158b115
THAMIZHP/python-programing
/count the frquency of character in string.py
357
4.3125
4
''' Write a Python program to count the number of characters (character frequency) in a string. Sample String : google.com' Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1} ''' # Solution q=input("Enter a String: ").strip() def counter(a): return(q.count(a)) i={} for x in q: i[x]=counter(x) print(i)
6be9422c0d8428dbff04205af84d13559b65110f
BayanFaisal/Word-Cloud-Python
/Tile of two cities-python.py
1,156
4.34375
4
# We use the text of the famous novel by Charles Dickens, A Tale of Two Cities. Credit to Project Gutenberg. # We want to read and clean the input, then count the frequencies of each word. from collections import Counter file=open('98-0.txt', encoding="utf8") # We want to use stopwords file <--- common words to exclude. Credit to Andreas Mueller stopwords = set(line.strip() for line in open('stopwords')) # We create our data structure here. wordcount = {} # We instantiate a dictionary, replace punctuation , and add every word in the file to the dictionary. for word in file.read().lower().split(): word = word.replace(".", "") word = word.replace(",", "") word = word.replace("\"", "") word = word.replace("“", "") if word not in stopwords: if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 # We want to count of each words present in wordcount, and sort it. d = collections.Counter(wordcount) # We want to extract the top ten most frequently occurring words from our data structure, and print them. for word, count in d.most_common(10): print(word, ":", count)
85cf6bce8f21e7abf00bdd2df443f05b9500c717
pppoke/poke
/第九周-源码/源码/threading_ex1.py
712
3.609375
4
__author__ = "Alex Li" import threading import time count = 0 def run(n): print("task ",n, threading.current_thread(), threading.active_count() ) time.sleep(2) print("task done",n) global count count +=1 start_time = time.time() t_objs = [] #存线程实例 for i in range(50): t = threading.Thread(target=run,args=("t-%s" %i ,)) t.start() t_objs.append(t) #为了不阻塞后面线程的启动,不在这里join,先放到一个列表里 # for t in t_objs: #循环线程实例列表,等待所有线程执行完毕 # t.join() while count != 50: pass print("----------all threads has finished...") print("cost:",time.time() - start_time) # run("t1") # run("t2")
d0b7b5a9ad9686a4016e1434f2d0c91f78a8dbec
Margasoiu-Luca/Chatbot-Project
/WeatherRecognition.py
1,147
3.765625
4
import requests def chatbot(): print("Hello i am ChatBot. I can forecast the weather, tell the time") print(" anywhere in the world and give you sports fixtures and news.") command = input("What would you like? ").lower() location = input("Enter Location ") webadd = "http://api.openweathermap.org/data/2.5/weather?appid=9777aeb5531c2d51d999a49783fb454d&q=" url = webadd+location data = requests.get(url).json() description = data["weather"][0]["description"] temperature = data["main"]["temp"] temperature2 = round((temperature-273.15) ,2) wordlist = command.split() for command in wordlist: if command == "weather": print("In" ,location, ", the weather is", description, "with temperatures of" ,temperature2,"degrees Celcius") def play_again(): choice = input("Would you like anything else? ('y' or 'n') ") if choice == 'y': chatbot() elif choice == 'n': print("Okay, Goodbye!") else: print("Your input is not recognised. Please enter 'y' or 'n'.") play_again() play_again() chatbot()
23b44d25d065d0c7650736f4334a9fe32e9eeeee
juil/project-euler
/p001.py
265
4.1875
4
# Problem 1 # Multiples of 3 and 5 # # Find the sum of all multiples of 3 or 5 below 1000. def sum3or5(max): sum = 0 for i in range(max): if i%3==0 or i%5==0: sum += i return sum # Test Cases print sum3or5(10) print sum3or5(1000)
72bf64382bfcd6a3d98090392941b0d3812c4e83
Shaikhmohddanish/python
/python/dictionary/1.py
376
4.4375
4
#Dictionary is a {key,value} pairs dict={"name":"ABC","Rno":43,"Branch":"EXTC"} print(dict) #Adding #key=name,Rno,Branch #Values=ABC,43,EXTC dict["course"]="Engineering" print(dict) #Modify dict["course"]="B-tech" print(dict) #Deleting # key word ====> del (one or more elements) #clear====> clear all the elements (funtions) del dict["name"] print(dict) del dict print(dict)
5dff9b8ba8378d3997fa94fdbafd7d83ad40d5df
vivekgupta8983/python_tut
/Python_Tutorials/number_opreations.py
110
3.65625
4
""" This Numiercal Operation """ exponents = (10 ** 5) print(exponents) remainder = (12 % 4) print(remainder)
4d9cfa7eaa895cc24905fab97a76ad72c14a3401
tborisova/homeworks
/7th-semester/ai/hw2.3 (1).py
3,249
3.515625
4
from queue import * from copy import deepcopy number = int(input()) count_of_rows = int(number/2 - 1) count_of_cols = int(number/2 - 1) expected_matrix = [[0 for x in range(count_of_rows)] for y in range(count_of_cols)] actual_matrix = [[0 for x in range(count_of_rows)] for y in range(count_of_cols)] visited = {} start = 1 end = count_of_rows + 1 for x in range(0, count_of_rows): expected_matrix[x] = list(range(start, end)) start = start + count_of_rows end = start + count_of_rows expected_matrix[count_of_cols - 1][count_of_rows - 1] = 0 actual_matrix = [[int(input()) for x in range(count_of_rows)] for y in range(count_of_cols)] def index_of_zero(table): [(row_of_zero, col_of_zero)] = [(index, row.index(0)) for index, row in enumerate(table) if 0 in row] return [(row_of_zero, col_of_zero)] def neighbors(current_table): [(row_of_zero, col_of_zero)] = index_of_zero(current_table) result = [] if row_of_zero - 1 >= 0: # up new_table = deepcopy(current_table) new_table[row_of_zero][col_of_zero] = current_table[row_of_zero - 1][col_of_zero] new_table[row_of_zero - 1][col_of_zero] = 0 result.append((new_table, "up")) if row_of_zero + 1 <= count_of_rows - 1: # down new_table = deepcopy(current_table) new_table[row_of_zero][col_of_zero] = current_table[row_of_zero + 1][col_of_zero] new_table[row_of_zero + 1][col_of_zero] = 0 result.append((new_table, "down")) if col_of_zero - 1 >= 0: # left new_table = deepcopy(current_table) new_table[row_of_zero][col_of_zero] = current_table[row_of_zero][col_of_zero - 1] new_table[row_of_zero][col_of_zero - 1] = 0 result.append((new_table, "right")) if col_of_zero + 1 <= count_of_rows - 1: #right new_table = deepcopy(current_table) new_table[row_of_zero][col_of_zero] = current_table[row_of_zero][col_of_zero + 1] new_table[row_of_zero][col_of_zero + 1] = 0 result.append((new_table, "left")) return result def to_string(table): result = "" for row in table: for el in row: result += str(el) return result def heuristic(a, b): [(x1, y1)] = index_of_zero(a) [(x2, y2)] = index_of_zero(b) return abs(x1 - x2) + abs(y1 - y2) def a_star_search(start, goal): frontier = PriorityQueue() frontier.put((0, start)) came_from = {} cost = {} came_from[to_string(start)] = None visited[to_string(start)] = False counter = 0 result = [] while not frontier.empty(): _, current = frontier.get() result.append(came_from[to_string(current)]) counter += 1 if current == goal: # if table is the final break for (next, step) in neighbors(current): # get all possible states priority = heuristic(goal, next) if visited.get(to_string(next), False) == False or cost[to_string(next)] > priority: visited[to_string(next)] = True cost[to_string(next)] = priority frontier.put((priority, next)) came_from[to_string(next)] = step return counter, result counter, path = a_star_search(actual_matrix, expected_matrix) print(counter - 1) for el in reversed(path): if el != None: print(el)
d0cba706ca49737a5d8a9d5c7f6fd8de831d3f7d
NirmaniWarakaulla/HackerRankSolutions
/Python/Python If-Else.py
141
3.828125
4
N = int(input()) if (N % 2 == 1) | (6 <= N <= 20): print("Weird") elif N >= 2 & N <= 5: print("Not Weird") elif N > 20: print()
1d70db077c874f75b3911d94f58428037734fa66
saurabhchris1/Algorithm-and-Data-Structure-Python
/Bubble_Sort/Bubble_Sort_Iterative_Optimized.py
644
4.3125
4
# Bubble Sort Iterative Optimized # Print i,j will help you figure out calculations def bubble_sort_iterative(num_arr): len_arr = len(num_arr) flag = True for i in range(len_arr): if not flag: break flag = False for j in range(len_arr - i - 1): print(i, j) if num_arr[j] > num_arr[j + 1]: flag = True num_arr[j], num_arr[j + 1] = num_arr[j + 1], num_arr[j] return num_arr if __name__ == '__main__': num = [2, 11, 6, 4, 7, 8] sorted_arr = bubble_sort_iterative(num) print ("The sorted array is : " + str(sorted_arr))
4103a3049390234b0441d486683ffee6dbda97ae
HarshaaArunachalam/guvi
/ten.py
90
3.78125
4
num=int(input()) length=0 while(num>0): length=length+1 num=num//10 print(length)
3d472d8c680add89e845a5be2d7ccaf6cdb7a52e
gmarson/Federal-University-of-Uberlandia
/Comparison of Sorting Algorithms/Trabalho_Final/Codigos/Quick/QuickSort.py
475
3.625
4
#@profile def Particiona(A,p,r): x = A[r] #pivo é o último elemento i = p-1 for j in range(p,r): if A[j] <= x: i = i + 1 aux = A[i] A[i] = A[j] A[j] = aux temp = A[i+1] A[i+1] = A[r] A[r] = temp return i+1 #@profile def quickSort(A,p,r): if(p < r): q = Particiona(A,p,r) quickSort(A,p,(q-1)) quickSort(A,(q+1),r) return A @profile def quick(A): quickSort(A,0,(len(A)-1)) #A = [i for i in range(10)] #quick(A) #quickSort(A,0,6) #print(A)
9cb346320683190c7f929882cf63f0b336188fd3
owengmiller/rockpaperscissors
/rockpaperscissors(1.2.1).py
2,274
4.09375
4
import random print('~Rock Paper Scissors~') print('') def getPlayerMove(): # Gets the player's move, allowing for variation in length of word. print('Choose...\n Rock (R)\n Paper (P)\n Scissors (S)') print('') pDrop = input().lower() if pDrop == 'r' \ or pDrop == 'ro' \ or pDrop == 'roc' \ or pDrop == 'rock': pMove = 'rock' elif pDrop == 'p' \ or pDrop == 'pa' \ or pDrop == 'pap' \ or pDrop == 'pape' \ or pDrop == 'paper': pMove = 'paper' elif pDrop == 's' \ or pDrop == 'sc' \ or pDrop == 'sci' \ or pDrop == 'scis' \ or pDrop == 'sciss' \ or pDrop == 'scisso' \ or pDrop == 'scissor' \ or pDrop == 'scissors': pMove = 'scissors' else: print('Please enter a valid move!') pMove = '' return pMove def getComputerMove(): # Gets the computer's move and displays it to the player. moveList = ['rock', 'paper', 'scissors'] cMove = random.choice(moveList) print('Your opponent chooses ' + cMove + '.') return cMove def getResults(): # Tells the player whether they won or lost. if playerMove == computerMove: print('It is a tie.') elif playerMove == 'rock' and computerMove == 'paper' \ or playerMove == 'paper' and computerMove == 'scissors' \ or playerMove == 'scissors' and computerMove == 'rock': print(computerMove.capitalize() + ' beats ' + playerMove + '! You lose!') elif playerMove == 'rock' and computerMove == 'scissors' \ or playerMove == 'scissors' and computerMove == 'paper' \ or playerMove == 'paper' and computerMove == 'rock': print(playerMove.capitalize() + ' beats ' + computerMove + '! You win!') gameInProgress = 'yes' while gameInProgress == 'yes' or gameInProgress == 'y': playerMove = getPlayerMove() if playerMove == 'rock' or playerMove == 'paper' or playerMove == 'scissors': computerMove = getComputerMove() getResults() print('Play again? (y/n)') gameInProgress = input().lower()
4fdba5741ed99f4fb49d8552ccd523860a102363
abzilla786/error-handling-exercise
/main.py
1,377
4.03125
4
from functions import * order_list = [] food_list = [] order_no = 0 while True: print('1. Create an order') print('2. Display an order') print('3. Number of orders') print('4. Exit') menu = int(input('Please select a menu number. e.g \'2\'\n')) if menu == 1: while True: # I want a program to ask for food food = str(input('What food do you want? Write \'done\' if you\'re finished\n')) if 'done' in food: # As a user I ask for any amount of food break else: food_list.append(food) # As a user I create different orders(different files) [create_write_file('order' + str(order_no+1) + '.txt', i + '\n') for i in food_list] order_list.append(food_list) food_list = [] order_no += 1 if menu == 2: # As a user I want to see my order while True: which_order = int(input('Please enter the number of the order e.g. \'1\'\n')) read_file('order' + str(which_order) + '.txt') input('\n Press enter/return to continue.\n') break if menu == 3: print('Number of orders:', order_no) input('\n Press enter/return to continue.\n') if menu == 4: print('Have a great day!') break #TODO add exception handling
4f8dc21888f92b5031c54c3877e3d0ef811c1ba2
DeadManGTPS/wm_bot
/src/extensions/random_cog.py
3,564
3.640625
4
import random from collections import Counter from typing import Optional import discord from discord.ext import commands class Plural: """Converts a text to plural when used in a f string Examples -------- >>> f"{Plural(1):time}" '1 time' >>> f"{Plural(5):time}" '5 times' >>> f"{Plural(1):match|es}" '1 match' >>> f"{Plural(5):match|es}" '5 matches' """ def __init__(self, value): self.value = value def __format__(self, format_spec): v = self.value singular, sep, plural = format_spec.partition("|") plural = plural or f"{singular}s" if abs(v) != 1: return f"{v} {plural}" return f"{v} {singular}" class Random(commands.Cog): """Random commands""" def __init__(self, bot): self.bot = bot @commands.command(daliases=["cbo"]) async def choosebestof(self, ctx, times: Optional[int], *choices: commands.clean_content): """Chooses between multiple choices N times.""" if len(choices) < 2: return await ctx.send("Not enough choices to pick from.") if times is None: times = (len(choices) ** 2) + 1 # The times can be a minimum of 1 and a maximum of 10000 times = min(10001, max(1, times)) results = Counter(random.choice(choices) for i in range(times)) builder = [] if len(results) > 10: builder.append("Only showing top 10 results...") for index, (elem, count) in enumerate(results.most_common(10), start=1): builder.append(f"{index}. {elem} ({Plural(count):time}, {count / times:.2%})") await ctx.send("\n".join(builder)) @commands.command( name="8ball", aliases=["eightball", "eight ball", "question", "answer", "8b"], ) async def _8ball(self, ctx, *, question: commands.clean_content): """The user asks a yes-no question to the ball, then the bot reveals an answer.""" answers = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes - definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Yes Signs point to yes", "Reply hazy", "try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful", ] await ctx.send(f"`Question:` {question}\n`Answer:` {random.choice(answers)}") @commands.command(aliases=["pick", "choice", "ch"]) async def choose(self, ctx, *, choices): """Chooses a random item from a list of items.""" # We split it by comma and a comma followed by a space choices = choices.split(", ").split(",") # We generate the embed embed = discord.Embed( title="Chosen", description=f"__Choices__: {', '.join(choices)}\n__Chosen__: {random.choice(choices)}" ) # We send the embed await ctx.send(embed=embed) @commands.command(aliases=["rcmd"]) async def randomcommand(self, ctx): """Sends a random command for you to try""" await ctx.send_help(random.choice(list(self.bot.commands))) def setup(bot): """Adds the cog to the bot""" bot.add_cog(Random(bot))
d5e4d329a5b5ba003119f629c1c4163a58bf7266
mclaveria/Project_Euler
/Problem029_Distinct_Powers.py
469
3.5625
4
#Michael Claveria #Project Euler Problem 29 Distict powers ''' Find the number of distinct terms generated by a^b for 2 <= a <= 100 and 2 <= b <= 100 ''' aList = range(2,101) bList = range(2,101) def distPow(list1, list2): rList = [] for i in list1: for j in list2: #print (str(i ** j)) rList.append((str(i ** j))) #remove duplicates from rList result = set(rList) return len(result) print(distPow(aList, bList))
300664997a8f5f68f798974f8335bdb67bf547ae
davidbailey/dpd
/dpd/mechanics/kinematic_body_with_acceleration.py
2,709
3.9375
4
import numpy from .kinematic_body import KinematicBody class KinematicBodyWithAcceleration(KinematicBody): """ A class to simulate a kinematic body. Provides methods to move the body with constant acceleration and decelerate the body with constant deceleration. """ def __init__( self, initial_acceleration, max_velocity=None, min_velocity=None, max_deceleration=None, final_velocity=None, *args, **kwargs ): super().__init__(*args, **kwargs) self.initial_acceleration = initial_acceleration self.acceleration = initial_acceleration self.max_velocity = max_velocity self.min_velocity = min_velocity self.max_deceleration = max_deceleration self.final_velocity = final_velocity def step_velocity(self): self.velocity = self.velocity + self.acceleration * self.model.time_unit if self.max_velocity is not None: self.velocity = numpy.minimum(self.velocity, self.max_velocity) if self.velocity == self.max_velocity: self.acceleration = 0 * self.acceleration if self.min_velocity is not None: self.velocity = numpy.maximum(self.velocity, self.min_velocity) if self.velocity == self.min_velocity: self.acceleration = 0 * self.acceleration if ( self.max_deceleration is not None and self.final_velocity is not None and self.max_position is not None ): stopping_distance_velocity_max_position = numpy.sqrt( self.final_velocity**2 + 2 * self.max_deceleration * (self.max_position - self.position) ) self.velocity = numpy.minimum( self.velocity, stopping_distance_velocity_max_position ) if self.velocity == stopping_distance_velocity_max_position: self.acceleration = -self.max_deceleration if ( self.max_deceleration is not None and self.final_velocity is not None and self.min_position is not None ): stopping_distance_velocity_min_position = numpy.sqrt( self.final_velocity**2 + 2 * self.max_deceleration * (self.min_position - self.position) ) self.velocity = numpy.minimum( self.velocity, stopping_distance_velocity_min_position ) if self.velocity == stopping_distance_velocity_min_position: self.acceleration = -self.max_deceleration def step(self): self.step_velocity() super().step()
8e08ca255a4e8f5c939db99f8f2fdb95241f40cf
EdouardPascal/projet
/test/union.py
143
3.84375
4
#Fonction union def union (a,b): i=0 d=len(b) while i<d: a.append(b[i]) i+=1 return a a=[1,2,3,4] b=[2,4,5,6,7,8] print(union(a,b))
90c4d37e10b9273f90489f78e644a8799e01645b
chernyshevdv/py_training
/fill_matrix.py
1,348
4.03125
4
# fill matrix NxN with numbers in spiral # create a matrix # fill outer layer # go with recursion def fill_ring(matrix, start_x=0, start_y=0, start_value=1, n=0): # fill top row x, y, value = start_x, start_y, start_value while x < len(matrix) and matrix[y][x] == 0: matrix[y][x] = value x += 1 value += 1 n += 1 # fill right column y += 1 x -= 1 while y < len(matrix) and matrix[y][x] == 0: matrix[y][x] = value y += 1 value += 1 n += 1 # fill bottom row y -= 1 x -= 1 while x >= 0 and matrix[y][x] == 0: matrix[y][x] = value x -= 1 value += 1 n += 1 # fill left column y -= 1 x += 1 while matrix[y][x] == 0: matrix[y][x] = value y -= 1 value += 1 n += 1 # cycle is done # print(f"Cycle end. y={y}, x={x}, value={value}, n={n}") if n < len(matrix)**2: fill_ring(matrix, start_x+1, start_y+1, value, n) # fill_ring(matrix, shift+1, start) def print_matrix(matrix): for i in range(len(matrix)): print(*matrix[i]) if __name__ == "__main__": size = int(input()) # create the matrix mtrx = [] for i in range(size): mtrx.append([0 for _ in range(size)]) fill_ring(mtrx) print_matrix(mtrx)
4491fcff1ed03fb796efab9a8bee866d86c55da3
sparshagarwal16/Assignment
/Assignment17.py
1,496
4
4
import tkinter from tkinter import * import tkinter as tk #Question 1 print("Question 1") r=Tk() r.title('HEY') z=Label(r,text="HELLO WORLD",width=15,height=5,bg="blue") z.pack() button=tk.Button(r, text='Exit',width=15,activebackground='red',activeforeground="black",bg="red",command=sys.exit) button.pack() #Question 2 print("Question 2") def print1(): s=Label(r,text="WELCOME",width=10,height=5,bg="white") s.pack(side=BOTTOM) button2=tk.Button(r,text='Print',width=15, activebackground='black',activeforeground='white',bg='white',command=print1) button2.pack() #Question 3 print("Question 3") def display(): w.configure(text="HOW ARE YOU?") w.pack() r=Tk() p=Frame(r,bg='yellow') w=Label(r,text='HEY',bg='green',width='15',height='15') w.pack() button2 = tk.Button(r, text='start', width=20, activebackground='#ccff00', activeforeground="white", bg="red",command=display) button2.pack() b = tk.Button(r, text='exit', width=20, activebackground='#ccff00', activeforeground="white", bg="blue", command=sys.exit) b.pack() #Question 4 print("Question 4") root = Tk() def returnEntry(arg=None): result = myEntry.get() resultLabel.config(text=result) myEntry.delete(0, END) myEntry = Entry(root, width='20', bg="white") myEntry.focus() myEntry.bind("<Return>", returnEntry) myEntry.pack() enterEntry = Button(root, text="Print", command=returnEntry, width=20, bg="red") enterEntry.pack() resultLabel = Label(root, text="", bg="white") resultLabel.pack() root.mainloop()
7cc34f1fb8444b81691ed66d01eaf8cf2e079608
teretupiro/rpg_part2
/zxc.py
977
3.921875
4
hello=input('Press \'Enter\' to start ') feelings=input('\"Как ты себя чувствуешь?\" ') help = '' while help != 'да': if feelings =='плохо': print ('Я тебе сочувствую ') elif feelings == 'хорошо': print ('Это хорошо') else: print('Почему ты молчишь?') help = input('Ты поможешь мне? ') dead = ('Вы умерли') life = ('Вы выжили') if help == 'нет': print('\"Ты предатель\"') print('Хозяин убивает Вас.') print(dead) elif help=='да': print('Идем') print('О!Монстр! ') monsters=input('Ваше действие: атака, защита' ) if monsters== 'атака': print('Вы убили монстра ' ) elif monsters== 'зашита': print('Вы зашитились' ) else: print(dead)
8fc0486deda380f6c230a798bdcc1b6637192826
DiegoDenzer/exercicios
/src/iniciante/distancia_dois_pontos.py
769
3.65625
4
""" Leia os quatro valores correspondentes aos eixos x e y de dois pontos quaisquer no plano, p1(x1,y1) e p2(x2,y2) e calcule a distância entre eles, mostrando 4 casas decimais após a vírgula, segundo a fórmula: Entrada O arquivo de entrada contém duas linhas de dados. A primeira linha contém dois valores de ponto flutuante: x1 y1 e a segunda linha contém dois valores de ponto flutuante x2 y2. Saída 1 7 5 9 = 4.4721 Calcule e imprima o valor da distância segundo a fórmula fornecida, com 4 casas após o ponto decimal. """ xy1 = input().split() xy2 = input().split() x_y = ([float(i) for i in xy1]) x_y2 = [float(i) for i in xy2] num1 = (x_y2[0] - x_y[0]) ** 2 num2 = (x_y2[1] - x_y[1]) ** 2 fim = (num1 + num2) ** (1/2) print("{:.4f}".format(fim))
3c6cc83b4108ad872af86ab35e9f66de034ccde7
Mattie-07/DCWork.python
/thursdayEx4.py
176
4.125
4
#Make a string and remove any strings that happen to be duplicates and print that list. name = "Matthew" nameWithoutDups = "".join(dict.fromkeys(name)) print(nameWithoutDups)
ea2adc00865b21977a5a854b4779f395d3848217
Mondirkb/HTB-Writeups
/ForwardSlash/bruteForce.py
1,169
3.6875
4
#!/usr/bin/python # from string import printable def decrypt(key, msg): key = list(key) msg = list(msg) for char_key in reversed(key): for i in reversed(range(len(msg))): if i == 0: tmp = ord(msg[i]) - (ord(char_key) + ord(msg[-1])) else: tmp = ord(msg[i]) - (ord(char_key) + ord(msg[i-1])) while tmp < 0: tmp += 256 msg[i] = chr(tmp) return ''.join(msg) c = open('encryptorinator/ciphertext','r') ciphertext = c.read() # print(ciphertext) f = open('/usr/share/wordlists/rockyou.txt','rb') passwords = f.readlines() # printableOrd = [ord(x) for x in printable] wordsInMsg = ['pass', 'crypto', 'message', 'key', 'Key', 'the', 'The'] for p in passwords: passwd = p[:-1] # print(passwd) plaintext = decrypt(passwd,ciphertext) flag = 0 for i in wordsInMsg: if i in plaintext: print(passwd) print(plaintext) flag = 1 break if flag == 1: break # flag = 0 # last = len(plaintext) # for i in range(last): # if ord(plaintext[i]) not in printableOrd: # break # if i==last-1: # flag = 1 # if flag == 1: # print(passwd) # print(plaintext) # break
1b309d00df493d1c40c9e9fe6a5abe0448fd9bf0
Class19-002/python
/4.py
347
3.515625
4
import sys argument=sys.argv[1] number=int(argument) end=range(1,(number+1)) def four(): for i in end: if i%12 == 0: dozen=i/12 print(str(dozen)+' dozen') elif i%4 == 0: print('square') elif i%3 == 0: print('triangle') print(sum(end)) four()
b116930b70f79fdae156095cb25bc3e2475fceb2
Phillyclause89/ISO-8601_time_converter
/time_converter.py
3,094
3.890625
4
# iso_time must be a timestamp string in ISO 8601 format and offset is to change the timezone def time_convert(iso_time, offset=0): # months dict for converting from numerical month representation to name months = {1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December"} # last_dy dict for getting the last day of a month last_dy = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31} # Parse out the iso_time string and convert year, month, day and hour into integers. (keep minutes as a string) yr = int(iso_time[0:4]) mo = int(iso_time[5:7]) dy = int(iso_time[8:10]) hr = int(iso_time[12:14]) mi = iso_time[15:17] # Add the offset to hour to calculate new time zone time. hr = hr + offset # Check if the timestamp is in a leap year and update February's last day in the last_dy dict. if yr % 4 == 0: last_dy[2] = 29 # Check if adding the offset pushes the hour into the negative thus requiring the day be changed to the day before. if hr < 0: # If true we add 24 to our negative hour value to get our new hour value. hr = 24 + hr # Check if our timestamp for the 1st of a month if dy == 1: # If true we set the month to the month prior mo = mo - 1 # Check if the month is Jan so that we can update the year if needed. if mo < 1: # If true, we set the moth to december, subtract 1 from the year and finally update the day. mo = 12 yr = yr - 1 dy = last_dy[mo] # If the year doesnt change we just update the day using the last day dict. else: dy = last_dy[mo] # Check if adding the offset pushes the hour greater than 11pm thus requiring the day tobe changed to the day after. elif hr > 23: # If true we calculate our new hour by subtracting 24 from our hour value and add 1 to the day hr = hr - 24 dy = dy + 1 # if our new day value is greater than the last day of the month we update our month value if dy > last_dy[mo]: mo = mo + 1 # If our month is greater than 12, we update our year, set the month to jan and finally set the day to 1. if mo > 12: mo = 1 yr = yr + 1 dy = 1 # Otherwise we just set the day to 1 if the year doesnt change. else: dy = 1 # reference our month dict to get our month name. month = months[mo] # Convert from 24hour time to AM/PM format. if hr > 12: hr = hr - 12 t = "PM" elif hr == 0: hr = 12 t = "AM" else: t = "AM" # Finally return our new datetime as a string. return month + " " + str(dy) + ", " + str(yr) + ", " + str(hr) + ":" + mi + " " + t
bbbdc3e97f085e8c90c1997957e0c8c2aed00f01
sunchit17/June-LeetCode-30dayChallenge
/week3/Permutation_Sequence(day 20).py
901
3.9375
4
''' The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 inclusive. Given k will be between 1 and n! inclusive. Example 1: Input: n = 3, k = 3 Output: "213" Example 2: Input: n = 4, k = 9 Output: "2314" ''' class Solution: def getPermutation(self, n: int, k: int) -> str: nums = [str(i) for i in range(1,n+1)] result = [] fact = math.factorial(n) index = k-1 while(nums): fact = fact // len(nums) pos = index // fact num = nums.pop(pos) result.append(num) index = index % fact return "".join(result)
63f4faafaec5f9d553c25969e74cb94b873f5625
AidenLong/ai
/test/test/test_find_2shape_array.py
698
3.65625
4
# -*- coding:utf-8 -*- class Solution: # array 二维列表 def Find(self, target, array): # write code here rows = len(array) cols = len(array[0]) if rows > 0 and cols > 0: row = 0 col = cols - 1 while row < rows and col >= 0: if target == array[row][col]: return True elif target < array[row][col]: col -= 1 else: row += 1 return False if __name__ == '__main__': target = 15 array = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 12, 13]] answer = Solution() print(answer.Find(target, array))
540112a132623a1657fef3c8822e1307f989b072
lsom11/coding-challenges
/hackerrank/python/cracking-the-coding-interview/chapter-1-arrays-and-strings/is_unique.py
181
3.734375
4
def is_unique(S): dict = {} unique = True for char in S: if char in dict: unique = False else: dict[char] = 1 return unique
9f8672f4291bc754e839a9f440a3d99fb362c3e4
AndreKauffman/EstudoPython
/Exercicios/ex013 - Reajuste Salarial.py
239
3.765625
4
salary = float(input("qual o salario? ")) increase = int(input("qual o aumento? ")) porcent = (salary * increase) / 100 value = salary + porcent print("O salario que era {} com {}% de aumento fica {}".format(salary, increase, value))
a48a11fb259b1069b90c5f8745574ae226c05da9
Arjun2001/coding
/codechef stacks.py
684
3.546875
4
def search(arr, st, en, key): mid = st + (en-st)//2 if key < arr[mid]: if key >= arr[mid-1] or st == en or mid == st: arr[mid] = key return arr else: return search(arr, st, mid-1, key) else: if st == en: arr.append(key) return arr else: return search(arr, mid+1, en, key) if __name__ == '__main__': tc = int(input()) for i in range(tc): n = int(input()) a = list(map(int,input().split())) arr = [a[0]] for i in range(1,n): arr = search(arr, 0, len(arr)-1, a[i]) print(len(arr),*arr)
df7e9413a592b28ba8661e96e4cb6839759dc471
alpiges/LinConGauss
/src/LinConGauss/core/linear_constraints.py
2,500
3.578125
4
import numpy as np class LinearConstraints(): def __init__(self, A, b, mode='Intersection'): """ Defines linear functions f(x) = Ax + b. The integration domain is defined as the union of where all of these functions are positive if mode='Union' or the domain where any of the functions is positive, when mode='Intersection' :param A: matrix A with shape (M, D) where M is the number of constraints and D the dimension :param b: offset, shape (M, 1) """ self.A = A self.b = b self.N_constraints = b.shape[0] self.N_dim = A.shape[1] self.mode = mode def evaluate(self, x): """ Evaluate linear functions at N locations x :param x: location, shape (D, N) :return: Ax + b """ return np.dot(self.A, x) + self.b def integration_domain(self, x): """ is 1 if x is in the integration domain, else 0 :param x: location, shape (D, N) :return: either self.indicator_union or self.indicator_intersection, depending on setting of self.mode """ if self.mode == 'Union': return self.indicator_union(x) elif self.mode == 'Intersection': return self.indicator_intersection(x) else: raise NotImplementedError def indicator_intersection(self, x): """ Intersection of indicator functions taken to be 1 when the linear function is >= 0 :param x: location, shape (D, N) :return: 1 if all linear functions are >= 0, else 0. """ return np.where(self.evaluate(x) >= 0, 1, 0).prod(axis=0) def indicator_union(self, x): """ Union of indicator functions taken to be 1 when the linear function is >= 0 :param x: location, shape (D, N) :return: 1 if any of the linear functions is >= 0, else 0. """ return 1 - (np.where(self.evaluate(x) >= 0, 0, 1)).prod(axis=0) class ShiftedLinearConstraints(LinearConstraints): def __init__(self, A, b, shift): """ Class for shifted linear constraints that appear in multilevel splitting method :param A: matrix A with shape (M, D) where M is the number of constraints and D the dimension :param b: offset, shape (M, 1) :param shift: (positive) scalar value denoting the shift """ self.shift = shift super(ShiftedLinearConstraints, self).__init__(A, b + shift)
fb3924b99a3a27027984e8648ea070d4d64f1361
chrisr1896/Exercises
/algorithms/dynamic_programming/palindromic_substring/solution/solution.py
1,655
4
4
def longest_palindrome_substr(str): n = len(str) if n == 0: return 0 # We create an n by n table, wwhere table[i][j] # will be True if substring str[i..j] is a palindrome # and False otherwise. We initialise all values to 0. table = [[0 for x in range(n)] for y in range(n)] # All substrings of length 1 are palindromes set the # maxLength palindrome we've seen so far to be 1. maxLength = 1 # table[i][i] is looking at substrings str[i] only one # element, so it will always be True that it is a palindrome. for i in range(n): table[i][i] = True # check for sub-strings of length 2. for i in range(n-1): # for substring length 2 we just need to check if str[i] == str[i+1] if (str[i] == str[i + 1]): table[i][i + 1] = True # maxLength we've seen so far is 2. maxLength = 2 # Check for lengths greater than 2. # k is length of substring for k in range(3, n+1): # Fix the starting index for i in range(n - k + 1): # Get the ending index of substring from # starting index i and length k j = i + k - 1 # checking for sub-string from ith index to jth index # iff str[i+1] to st[j-1] is a palindrome if (table[i + 1][j - 1] and str[i] == str[j]): table[i][j] = True if (k > maxLength): maxLength = k # return the maxLength substring we have found. return maxLength
7ceda05eb58317c1c306e7afd4eb25318aab0623
ameyyadav09/daily-stuff
/collections/namedtuples.py
257
3.75
4
# Enter your code here. Read input from STDIN. Print output to STDOUT from collections import namedtuple N, Student= int(raw_input()),namedtuple('Student',raw_input().strip().split()) print (sum(int(Student(*raw_input().split()).MARKS) for i in range(N))/N)
39c10ec6d03ad3994c39110adcce83e2269b3315
JushBJJ/Everything
/numpy/ndarray.py
158
3.921875
4
import numpy as np foo=np.array([1,2,3]) print(foo) for i in foo: print(i) foo=np.array([[1],[2],[3]]) for i in foo: for x in i: print(x)
6d43bb9659589642d45e59a87dc9806989c86132
Hieumoon/C4E_Homework
/Session05/Homework/Homework5_exercise7.py
347
4.71875
5
# Write a function that removes the dollar sign ('$') in a string, named 'remove_dollar_sign', takes 1 arguments: s, where s is the input string, returns the new string with no dollar sign in it. def remove_dollar_sign(s): new_s = s.replace("$","") return new_s s = input('Enter the string containing $: ') print(remove_dollar_sign(s))
0875ab01c3d3833e3c96dc323af8236176007136
yuhanlyu/coding-challenge
/lintcode/climbing_stairs.py
306
3.8125
4
class Solution: """ @param n: An integer @return: An integer """ def climbStairs(self, n): x, y, a, b = 1, 0, 1, 1 while n > 0: if n & 1: x, y = a * x + b * y, b * x + y * (a - b) a, b, n = a * a + b * b, b * (2 * a - b), n >> 1 return x
eaa2d985b1037f28e57b6b7aef250f0c1fdd5476
rohaneden10/luminar_programs
/functions/calculator.py
434
3.953125
4
def calculator(): print("1:add") print("2:sub") print("3:mul") print("4:div") a=int(input("enter 1st no")) b=int(input("enter 2nd no")) c=int(input("enter the choice")) if(c==1): print("addition",a+b) elif(c==2): print("difference",a-b) elif(c==3): print("product",a*b) elif(c==4): print("divison",a/b) else: print("ivalid option") calculator()
9fa723a51f75057d5eead30f70842787122a9a43
NallamilliRageswari/Python
/Adam_Number.py
184
3.96875
4
n=int(input("Enter a number : ")) sum=0 product=0 while(n>0): sum+=(n%10) product+=(n%10) n=n//10 if(sum==product): print("Adam Number") else: print("not Adam Number")
ec37c5d0f4d8aa0030358850ee8628d7ddc95d11
Rogalowski/Podstawy-programowania-w-Pythonie-egzamin-probny
/10_Egzamin_-_rozwiazanie/01_Zadanie_1/answer3.py
394
4.09375
4
def check_palindrome(text): """Check if given text is palindrome. :param str text: some text :rtype: bool :return: True if given text is palindrome False elsewhere """ text = text.lower().replace(' ', '') return text == text[::-1] if __name__ == '__main__': print(check_palindrome("Kobyła ma mały bok")) print(check_palindrome("To nie jest palindrom"))
ada4be9b85aab1e84dc646c42d0bea5383461ace
RanranYang1110/LEETCODE11
/numSquare.py
1,248
3.75
4
#-*- coding:utf-8 -*- # @author: qianli # @file: numSquare.py # @time: 2019/09/20 # def numSquare(n): # if n == 1: # return 1 # else: # mm = 0 # while n > 1: # t = n # while t ** 2 > n: # t -= 1 # mm += 1 # n -= t ** 2 # if n == 1: # return mm+1 # return mm class node: def __init__(self, value, step=0): self.value = value self.step = step def __str__(self): return '<value:{}, step:{}>'.format(self.value, self.step) class Solution: def numSquares(self, n: int) -> int: queue = [node(n)] visited = set([node(n).value]) while queue: vertex = queue.pop(0) residuals = [vertex.value - n*n for n in range(1, int(vertex.value **.5)+1)] for i in residuals: new_vertex = node(i, vertex.step + 1) if i == 0: return new_vertex.step elif i not in visited: queue.append(new_vertex) visited.add(i) return -1 # n = 10 # res= numSquare(12) # print(res) # print(numSquare(n)) n = 18 clf = Solution() res = clf.numSquares(n) print(res)
420843516d9fa428e8aa8a6004829ad66c6e5cb8
JoshPennPierson/HackerRank
/Algorithms/Graph Theory/Even Tree.py
2,795
4.0625
4
#https://www.hackerrank.com/challenges/even-tree def find_tree_size(node,edge_list): #get the size of the tree from this node down all_children_found = False tree_list = [node] while not all_children_found: new_additions = 0 for i in range(len(tree_list)): #go through all the nodes in the tree list this_node = tree_list[i] for i in range(len(edge_list)): #find all the children to each node in the tree list if edge_list[i][1] == this_node: child_node = edge_list[i][0] #the child node if not child_node in tree_list: #if the child node isn't already in the list tree_list.append(child_node); #add the new node to the tree list new_additions += 1 if new_additions == 0: #if no new nodes have been added to the tree list, then all the children have been found all_children_found = True return(len(tree_list)) def find_tree_tops(node_count,edge_list): tree_tops = [] #If a node doesn't point to any other nodes, add it to the tree top list for i in range(1,node_count+1): found = False for j in range(len(edge_list)): if edge_list[j][0] == i: found = True if not found: tree_tops.append(i) return(tree_tops) a = [int(i) for i in input().strip().split(' ')] node_count = a[0] edge_count = a[1] edge_list = [[int(i) for i in input().strip().split(' ')] for j in range(edge_count)] answer = False counter = 0 node_list = [] for i in range(1,node_count+1): node_list.append(i) while True: smallest_tree = -1 smallest_tree_node = 0 for i in range(len(node_list)): node = node_list[i] tree_size = find_tree_size(node,edge_list) if tree_size%2 == 0: #if the tree size is even if smallest_tree == -1: smallest_tree = tree_size smallest_tree_node = node elif tree_size < smallest_tree: smallest_tree = tree_size smallest_tree_node = node if smallest_tree_node == 1: #if the smallest even tree left in the node list is the tree that starts with "1" break #Remove node from node list node_to_pop = -1 for i in range(len(node_list)): if node_list[i] == smallest_tree_node: node_to_pop = i counter += 1 if node_to_pop > 0: node_list.pop(node_to_pop) #Remove the edge from tree list edge_to_pop = -1 for i in range(len(edge_list)): if edge_list[i][0] == smallest_tree_node: edge_to_pop = i if edge_to_pop > 0: edge_list.pop(edge_to_pop) print(counter)
bd87ae9d100461a27a799310d8656ee316f919aa
megannguyen6898/dataminingcourse
/python-bootcamp-main/session4/intro_OOP/intro_classes.py
1,041
4.0625
4
# source: https://www.csdojo.io/class class Robot: #module #Initilize key vars using constructor def __init__(self, name, color, weight): #methods with main components such as name color weight self.name = name self.color = color self.weight = weight self.height = 10 def introduce_self(self): print("My name is " + self.name) def calc_area(self): area = self.weight * self.height def set_properties(self, name, color, weight): self.name = name self.color = color self.weight = weight self.height = 10 #r1 = Robot() #robot class wont walk, but once you initialize, robot must have sth in () # r1.name = "Tom" #accessing vars from constructor # r1.color = "red" # r1.weight = 30 # # r2 = Robot() # r2.name = "Jerry" # r2.color = "blue" # r2.weight = 40 r1 = Robot("Tom", "red", 30) r2 = Robot("Jerry", "blue", 40) r1.introduce_self() r2.introduce_self() r2.set_properties("Megan", "red", 9, 19) total = r2.calc_area() + r1.calc_area()
ec3b61f279ce966427301c0e79d20495e519d0da
Montechiari/Socios_SBPC
/socios.py
1,279
3.515625
4
import sqlite3 import pandas as pd ENDERECO = "./" NOME_BANCO = "socios.db" ARQUIVO_DADOS_CSV = "socios.csv" class Socio(): def __init__(self, nome, email, ultimo_pago, local, instituicao): self.nome = nome self.email = email self.ultimo_pago = ultimo_pago self.local = local self.instituicao = instituicao def gera_banco_de_dados(): data_frame_socios = pd.read_csv(ENDERECO + ARQUIVO_DADOS_CSV, header=0) banco_de_dados = sqlite3.connect(ENDERECO + NOME_BANCO, uri=False) with banco_de_dados: data_frame_socios.to_sql("socios", banco_de_dados) return banco_de_dados def faz_recorte(conexao, consulta): data_frame = pd.read_sql_query(consulta, conexao, index_col="nome") data_frame.drop_duplicates(inplace=True) return data_frame.drop(columns="index") def inicializar(): try: arquivo = ENDERECO + NOME_BANCO conexao = sqlite3.connect(f"file:{arquivo}?mode=rw", uri=True) except sqlite3.OperationalError: conexao = gera_banco_de_dados() except Exception as e: print(e) return conexao if __name__ == '__main__': conexao = inicializar() print(faz_recorte(conexao, "SELECT * FROM socios WHERE anuidade > 2018"))
42063fb1552aaf03402b8eef3c2ef481f4c73b13
coding-corgi/homework-prac-week3
/prac1사칙연산 자료 딕셔너리.py
565
3.515625
4
# print('hello wolrd') # a= 3 # b= '상하' # c =True # # print(a) # print(b) # print(c) # # list_a = [1,2,3] # # print((list_a)) # list_a.append(4) # print(list_a) dic = [{'name':'상하','height':183},{'name':'송영','height':1}] print(dic) dic[0]['age']=30 print((dic)) person = {'name':'지우','height':163} print(person) dic.append(person) print(dic) # people = [{'name':'bob','age':20},{'name':'carry','age':38}] # # # people[0]['name']의 값은? 'bob' # # people[1]['name']의 값은? 'carry' # # person = {'name':'john','age':7} # people.append(person)
5229f84b4bfacfe63f03aae1c9b528430257bcbc
nsafai/Data-Structures
/palindromes.py
3,250
4.21875
4
#!python import string import re # string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz' # string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # string.ascii_letters is ascii_lowercase + ascii_uppercase LETTERS = set(string.ascii_letters) def is_palindrome(text): """A string of characters is a palindrome if it reads the same forwards and backwards, ignoring punctuation, whitespace, and letter casing.""" assert isinstance(text, str), 'input is not a string: {}'.format(text) # return is_palindrome_iterative(text) return is_palindrome_recursive(text) def is_palindrome_iterative(text): '''time complexity - Best: O(1) -- first and last letters don't match Worst: O(n) -- go through each letter once ''' left = 0 # starts as first letter right = len(text) - 1 # starts as last letter while left < right: # until we reach middle of word and left = right if text[left] not in LETTERS: # if left is not a letter left += 1 # skip that character if text[right] not in LETTERS: # if right not a letter right -= 1 # skip that character if text[left] in LETTERS and text[right] in LETTERS: if text[left] == text[right]: # if letters are same w/o changing case # keep shrinking window left += 1 right -= 1 elif text[left].lower() == text[right].lower(): # if letters are same in lowercase # keep shrinking window left += 1 right -= 1 else: # if letters are different return False return True # reached end of word def is_palindrome_recursive(text, left=0, right=None): '''time complexity - Best: O(1) -- first and last letters don't match Worst: O(n) -- go through each letter once ''' if right == None: # only true first time this function gets called right = len(text) - 1 if left > right: # reached middle of word, b/c when left == right, it is the same letter return True if text[left] not in LETTERS: return is_palindrome_recursive(text, left + 1, right) # skip text[left] if not a letter if text[right] not in LETTERS: return is_palindrome_recursive(text, left, right - 1) # skip text[right] if not a letter if text[left] == text[right]: # letters are same w/o changing case return is_palindrome_recursive(text, left + 1, right - 1) elif text[left].lower() == text[right].lower(): # if letters are same in lowercase return is_palindrome_recursive(text, left + 1, right - 1) else: return False def main(): import sys args = sys.argv[1:] # Ignore script file name if len(args) > 0: for arg in args: is_pal = is_palindrome(arg) result = 'PASS' if is_pal else 'FAIL' is_str = 'is' if is_pal else 'is not' print('{}: {} {} a palindrome'.format(result, repr(arg), is_str)) else: print('Usage: {} string1 string2 ... stringN'.format(sys.argv[0])) print(' checks if each argument given is a palindrome') if __name__ == '__main__': main()
f392a4650c57f1b243defc2856664e415bd63d98
liush79/codewars
/6kyu/what_is_the_pattern.py
879
3.53125
4
def check_pattern(pattern, sequence): len_pattern = len(pattern) if (len(sequence) - 1) % len(pattern) != 0: return False for i, s in enumerate(sequence): if i == 0: continue idx = (i % len_pattern) - 1 if pattern[idx] != sequence[i] - sequence[i - 1]: break else: if (len(sequence) - 1) % len_pattern != 0: return False return True return False def find_pattern(sequence): pattern = [] for i, s in enumerate(sequence): if i == 0: continue pattern.append(sequence[i] - sequence[i - 1]) if check_pattern(pattern, sequence): return pattern print find_pattern([1, 2, 3, 4, 5, 4, 3, 2, 1, 2, 3, 4, 5, 4, 3, 2, 1]) # [1, 1, 1, 1, -1, -1, -1, -1] print find_pattern([1, 5, 2, 3, 1, 5, 2, 3, 1]) # [4, -3, 1, -2]
dcd898b40ff05057d9cee6aad4ecab07d02e6350
PitPietro/python-project
/math_study/numpy_basics/statistics/statistic_mean.py
811
4
4
import numpy as np from math_study.numpy_basics.statistics.statistics import ordered_data if __name__ == '__main__': print('Numpy - Statistic - mean') # https://numpy.org/doc/stable/reference/generated/numpy.mean.html print('\nCompute the arithmetic mean of the whole array:') print(ordered_data.mean()) print('\nCompute the arithmetic mean along the specified axis:') print(ordered_data.mean(axis=0)) # array filled with vertical means: means of the values in the same column print(ordered_data.mean(axis=1)) # array filled with horizontal means: means of the values in the same row # if you exceed the number of dimensions, you'll get a 'numpy.AxisError' try: print(ordered_data.mean(axis=3)) except np.AxisError as axis_error: print(axis_error)
b2f575108c84fbc8c21eedeb96a10690278e8099
rollingball211/Algorithms
/알고리즘/week-1/sum1to100.py
123
3.640625
4
def sum(n): sum=0 for i in range(1, n+1): sum=sum+i return sum print(sum(10)) print(sum(100))
b95b374ac796d641f78c0613e15bf0d323c4a31f
Casper2nd/slope
/main.py
814
3.8125
4
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. from random import randint import parser from math import sin from decimal import Decimal formula = "sin(x)*x^2" formula = formula.replace("^","**") def slope(): functie = input("type your function\n") functie = functie.replace("^","**") startingX = input("type your X\n") length = len(startingX) startingX = int(startingX) dx = 10**-(12 - length) lowX = startingX highX = startingX + dx x = lowX compiledF = parser.expr(functie).compile() lowY = eval(compiledF) x = highX highY = eval(compiledF) dy = highY - lowY dydx = dy / dx print(dydx) slope()
2878ab757a7bec39acf6cd01bef7d78b1a492892
EndavaTraining/python_training
/python_fundamentals/generators.py
564
4
4
def sick_pets_identifier(pets): """ Generator for identifying sick pets """ for name, food in pets.items(): if food < 300: yield {name: food} pets = { "IronMan": 100, "CaptainAmerica": 350, "BlackWidow": 250, "Hulk": 800, "AntMan": 300, "Spiderman": 190 } sick_pets = sick_pets_identifier(pets) print("Manually displaying each sickly pet:") print(next(sick_pets)) print(next(sick_pets)) print(next(sick_pets)) print("Using a for loop to display the sick pets:") sick_pets2 = sick_pets_identifier(pets) for item in sick_pets2: print(item)
2ec81e3f1be9d2882ddfad3d53f8156fe2a65dd8
gabriellaec/desoft-analise-exercicios
/backup/user_018/ch35_2020_03_22_19_00_27_065571.py
163
4
4
n = int(input('Digite um número: ')) s = 0 while n != 0: s += n n = int(input('Digite um número: ')) else: print('A soma é igual a {}'.format(s))
31a3df580d643e6e4d47e44484984d70d4c5ef77
1san4ik/git_lessons
/mnozhestva-2.py
1,332
4.1875
4
# Задание 2 # Создайте программу, которая эмулирует работу сервиса по сокращению ссылок. Должна быть # реализована возможность ввода изначальной ссылки и короткого названия и получения изначальной # ссылки по её названию. dict1 = {} while True: a = input("\nНажмите '1' - чтобы ввести ссылки в базу\nНажмите '2' - чтобы получить ссылку\nНажмите '3' - чтобы выйти\n=> ") if a == "1": longlink = input("Введите полную ссылку: ") shortlink = input("Введите сокращение для ссылки: ") dict1[shortlink] = longlink elif a == "2": shortlink2 = input("Введите сокращенную ссылку: ") if shortlink2 in dict1.keys(): print(f"Ваша полная ссылка: {dict1[shortlink2]}") else: print("Такой ссылки не вводилось. Попробуйте еще.") elif a == "3": print("*** Программа завершена ***") break else: print("Не корректный ввод.")
2a21d36e22e43137a44f34a58501295a4ecdf941
sylviocesart/Curso_em_Video
/Desafios/Desafio06.py
368
4.03125
4
""" Crie um algoritmo que leia um número e mostre o seu dobro, triplo e raiz quadrada """ n = int(input('Digite um número: ')) d = n * 2 t = n * 3 # rz = n ** (1/2) # Raiz quadrada usando a funcao pow rz = pow(n, (1/2)) print('O número digitado foi: {}. O dobro dele é {}'.format(n, d), end=' ') print('e o triplo é {} e a raiz quadrada é {:.2f}'.format(t, rz))
365c0f1e155f1b713963a454a7a1e2d5a7eaca96
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/largest-series-product/3d61f04624354421afe4846b347e1054.py
822
3.84375
4
def slices(digits, k): # Raise ValueError if length argument is larger than number of digits if (len(digits) < k): raise ValueError("Error: Length argument does not fit the series.") # Add list of k digits to series until no more k digit long slices left series = [] i = 0 while i <= len(digits) - k: series.append([int(digit) for digit in digits[i:i+k]]) i += 1 return(series) def largest_product(digits, k): # Create slices slice_list = slices(digits, k) # Iterate over created slices, multiple together all numbers in each slice, # and return the largest max = 0 for s in slice_list: temp = 1 for digit in s: temp *= digit if temp > max: max = temp return(max)
d162504c9ffa2e5b2a85037c96aba299d9e87a1d
suyeonme/python-journey
/basic syntax/error_handling.py
204
3.6875
4
try: division = 10/0 number = int(input('Enter a number: ')) print(number) except ZeroDivisionError as err: # you can name an error using as print(err) except ValueError: print('Invalid input')
abf2513d019f52ed360c10bb3562541196127500
ihFernando/Python
/encriptar.py
544
3.5625
4
palavra = input("Qual frase deseja criptografar? "); def encriptar(k,m): aux = "" for letra in m: # k[letra] -> Olha na tabela aux = aux + k[letra] return aux def montarDicionario(gamma1, gamma2): if len(gamma1) != len(gamma2): return {} else: dic = {} z = zip(gamma1, gamma2) for (x,y) in z: dic[x] = y return dic chave = montarDicionario(" ABCDEFGHIJKLMNOPQRSTUVWXYZ", "DP JSQBTKCIHOVAREZULENGXWMF") print encriptar(chave,format(palavra))
4e37689170d83d40a684e3e4e9ae804a7f10df98
ckiekim/Python-Lecture-1903
/Unit 19/judge_star_mountain.py
198
3.8125
4
count = int(input('높이를 입력하세요: ')) for i in range(count): for k in range(count-1-i): print(' ', end='') for k in range(2*i+1): print('*', end='') print()
17bb2260d1a2edfb4bd5284dffd47ac6b3afbfee
MrDNA2018/data_structure_and_algorithm
/divide_and_conquer.py
13,815
3.703125
4
# -*- coding: utf-8 -*- # ============================================================================= # 分治一般形式: T(n) = k*T(n/m) + f(n) # k为子问题个数,一般均分或者等比分 # n/m问题规模,一般情况下m已经确认了子问题的个数,可以通过变换减少为a个 # f(n) 为数据的处理,划分和综合工作量,可以增加预处理,从而减少在递归里面的操作 # 也就是把递归里面的操作尽量放在循环体外面处理 # ============================================================================= #%% # 注意递归的返回值,递归的要返回的话,要前后一致,或者直接基于某一层考虑,把递归看成结果 def binary_Serach_recursive(arr,left,right,target): middle = (left + right) // 2 # 递归出口 if left > right : return(-1) if arr[middle] == target: return(middle) elif arr[middle] < target: # 这里没有return的话,结果就没法return出来 return binary_Serach_recursive(arr,middle+1,right,target) else: return binary_Serach_recursive(arr,left,middle-1,target) def binary_Serach_iterative(arr,target): left = 0 right = len(arr)-1 # 循环体条件 while left <= right: middle = (left + right) // 2 if arr[middle] == target: return middle elif arr[middle] < target: left = middle +1 else: right = middle -1 return -1 #%% arr = [7,3,66,33,22,66,99,0,1] sort_arr = sorted(arr) print(sort_arr) print(binary_Serach_recursive(sort_arr,0,len(arr)-1,22)) print(binary_Serach_recursive(sort_arr,0,len(arr)-1,100)) print(binary_Serach_iterative(sort_arr,22)) print(binary_Serach_iterative(sort_arr,100)) #%% def MergeSort(arr,N): # 递归出口,出口需要返回当前的那个数 if N == 1: return arr # 以下当作某一层的处理 middle = N //2 # 获取待排序的两个已排序的数组 left_list = MergeSort(arr[:middle],len(arr[:middle])) right_list = MergeSort(arr[middle:],len(arr[middle:])) # 如下是针对两个已排序的数组合并成一个有序数组的排列方法,为最基本的双针模型 i ,j =0,0 result =[] while i < len(left_list) and j < len(right_list): if left_list[i] <= right_list[j]: result.append(left_list[i]) i +=1 else: result.append(right_list[j]) j += 1 result += left_list[i:] result += right_list[j:] # 返回已排序的结果,用于上一层获取待排序的有序数组 return result def MergeSort_iteration(arr): # 把一个数组arr[left:mid+1]和arr[mid+1:right+1]排成一个有序的序列,最后结果还是在 # arr里 def sorting_two_sorted_arr_in_place(arr,left,mid,right): left_list = arr[left:mid+1] right_list = arr[mid+1:right+1] i ,j =0,0 result =[] while i < len(left_list) and j < len(right_list): if left_list[i] <= right_list[j]: result.append(left_list[i]) i +=1 else: result.append(right_list[j]) j += 1 result += left_list[i:] result += right_list[j:] arr[left:right+1] = result[:] # 双针模型自然合并排序 # 最外面的大的指针,1,2,4,8,16,32...,直到大于len(arr) cur_size = 1 # 终止条件为超过了数组长度,前半部分为2的i次方,后半部分为2的i次方到end while cur_size < len(arr): # 内部循环,用于更新每一块的顺序,只要一个left指针就可以更新每一个局部 left = 0 # 截至条件同样是left越界 while left < len(arr)-1: # mid的位置,-1为数组是从0开始,简单分析一个实例就明白了 mid = left + cur_size -1 # right的位置,一般情况下是mid + cur_size,同样不能越界,越界时区len(arr)-1 right = (mid + cur_size,len(arr)-1)[mid + cur_size>len(arr)-1] # 把制定区域的数排列有序 sorting_two_sorted_arr_in_place(arr,left,mid,right) # 更新下一块,每一个固定cur_size循环里面的步长为2倍cur_size left += 2*cur_size # 更新外部循环的步长 cur_size *=2 return arr arr = [7,3,66,33,22,66,99,0,1] print(arr) print(MergeSort(arr,len(arr))) print(MergeSort_iteration(arr)) #%% def partition_1(arr,low,high): # 把基准元素取出来,留出一个空位,这里是在首位,这种留出空位的方式,比较容易理解 pivot = arr[low] # 循环体终止条件,因为是先走右边再走左边,终止的时候一定是两个指针重合在一起 # 也可以交叉,但是可以控制循环他们重合在一起跳出循环 # 这里解释以下low,high这两个指针代表什么,low,high代表从其实到low都是小于基准的元素 # 从high到end都是大于基准的元素,当low和high重合时,那左边都是小的,右边都是大的 # 重合的位置是空的(实际上有值),因为每个时刻都有一个位置都是空的,重合剩下最后一个位置, # 这个位置也必然是空的,也可以用一个小的实例分析一下 while low < high: # 首先右边一直往左走,直到遇到小于基准的元素,这里控制一下,不让他们交叉 # 不添加的low <high,往左走不会越界,但是可能小于low while arr[high] > pivot and low <high: high -=1 # 避免他们两交叉,只要相等就退出,右边遇到小于基准的元素,把左边的那个空位填上,左边的指针更新一下 if low <high: arr[low] = arr[high] low +=1 # 左指针往左就是小于基准的元素,这时右边空出来一个位置,左指针往右扫描 while arr[low] < pivot and low <high: low +=1 # 找到大于基准的元素,放到右边空出来的位置,那右指针往右全部都是大于基准元素的 if low <high: arr[high] = arr[low] high -=1 # 当只剩下唯一的空位置时,把基准元素放待空的位置上 arr[low] = pivot return low def partition_2(arr,low,high): # 这时另外一种考虑方式,而且他是不需要额外空间的,他只使用一个指针来区分小于基准和大于基准的 # pointer_less_than代表这个指针的左边全部都是小于基准的(包括自己,不包括首元素) # 然后从左往右扫描,遇到小于基准的元素,就把小于基准元素区域的后面紧接着的一个元素和他交换 # 那么小于基准元素区域就多了一个元素,。。。就这样小于基准的元素就连在了一起 # 首元素是基准元素,小于基准元素区域块,大于基准元素区域块,现在分成了三个部分 # 把首元素和小于基准元素区域块最后一个元素交换,那三部分就变成,小于的,基准,大于的 # 刚开始小于基准的元素为0,暂且指向首位值 pointer_less_than = low # 然后一次扫描后面所有元素 for i in range(pointer_less_than +1,high+1): # 遇到小于基准的,就把小于基准元素区域的后面紧接着的一个元素和他交换,小于的块相当于也更新了 if arr[i] < arr[low] : pointer_less_than +=1 arr[pointer_less_than],arr[i]=arr[i],arr[pointer_less_than] # 把首元素和小于基准元素区域块最后一个元素交换,那三部分就变成,小于的,基准,大于的 arr[low],arr[pointer_less_than] = arr[pointer_less_than],arr[low] return pointer_less_than def partition_3(arr,start,end): # 这个方式也是不需要额外的辅助空间的 # 他的思想是:从左(或者右也可以)扫描到第一个大于基准的元素,然后从右往左扫描到第一个小于基准的 # 元素,将他们两交换,然后再重复上述操作,直到两个指针重合位置 # 这两个指针分别代表:前面(除了首元素)到low为小于基准,high到end为大于基准元素 # 他们是可能会交叉的,也有可能重合,这时数组分成三个部分:首元素基准,小于的,大于的 # 这个地方可能会交叉的,也有可能重合,分3种情况:第一种情况[大于,小于],然后他们两个交换 # [小于,大于],low-->大于,high-->小于,这时首元素需要和high互换 # [小于],high-->小于,没有大于的元素和他互换,low一直加直到等于high,这时这时首元素需要和high互换 # [大于],low-->大于,没有小于的元素和他互换,high会一直减,直到比low小1,这时这时这时首元素需要和high互换 # 不管是那种情况下,high指向肯定是最后一个小于基准的元素 # 这里不能利用两者指针重合,因为两个指针重合指向的元素,可能大于基准也可能小于基准, # 要使用high指向的元素 # 初始化左指针和右指针 low = start high = end +1 # 循环体退出条件为两指针重合或者交叉 while True: # 需要先-1,因为交换之后,指针需要更新一下,不更新的话,循环体会多运算一步 high -=1 # 这里就是需要两指针交叉,这样high才能指向小于区域里面的最后一个元素 while arr[high] > arr[start] : high -=1 low +=1 while arr[low] < arr[start] and low < end: low +=1 # 在这个时候,数组分成三个部分:首元素是基准元素,小于基准元素区域块,大于基准元素区域块 if low >= high: break # 把这两个元素交换,小的跑到左边,大的跑到右边 arr[low],arr[high] = arr[high],arr[low] # 把首元素和小于基准元素区域块最后一个元素交换,那三部分就变成,小于的,基准,大于的 arr[start],arr[high] = arr[high],arr[start] return high #%% def quickSort(arr,low,high): if low < high: index = partition_1(arr,low,high) quickSort(arr,low,index-1) quickSort(arr,index+1,high) def quickSort1(arr,low,high): if low < high: index = partition_2(arr,low,high) quickSort1(arr,low,index-1) quickSort1(arr,index+1,high) def quickSort2(arr,low,high): if low < high: index = partition_3(arr,low,high) quickSort2(arr,low,index-1) quickSort2(arr,index+1,high) #%% import random def randomizedPartition(arr,low,high): def partition(arr,low,high): # 这时另外一种考虑方式,而且他是不需要额外空间的,他只使用一个指针来区分小于基准和大于基准的 # pointer_less_than代表这个指针的左边全部都是小于基准的(包括自己,不包括首元素) # 然后从左往右扫描,遇到小于基准的元素,就把小于基准元素区域的后面紧接着的一个元素和他交换 # 那么小于基准元素区域就多了一个元素,。。。就这样小于基准的元素就连在了一起 # 首元素是基准元素,小于基准元素区域块,大于基准元素区域块,现在分成了三个部分 # 把首元素和小于基准元素区域块最后一个元素交换,那三部分就变成,小于的,基准,大于的 # 刚开始小于基准的元素为0,暂且指向首位值 pointer_less_than = low # 然后一次扫描后面所有元素 for i in range(pointer_less_than +1,high+1): # 遇到小于基准的,就把小于基准元素区域的后面紧接着的一个元素和他交换,小于的块相当于也更新了 if arr[i] < arr[low] : pointer_less_than +=1 arr[pointer_less_than],arr[i]=arr[i],arr[pointer_less_than] # 把首元素和小于基准元素区域块最后一个元素交换,那三部分就变成,小于的,基准,大于的 arr[low],arr[pointer_less_than] = arr[pointer_less_than],arr[low] return pointer_less_than index = random.randint(low,high) arr[low],arr[index]=arr[index],arr[low] return partition(arr,low,high) def randomizedQuicksort(arr,low,high): if low < high: index = randomizedPartition(arr,low,high) randomizedQuicksort(arr,low,index-1) randomizedQuicksort(arr,index+1,high) arr3 = [7,3,66,33,22,66,99,0,1] print(arr3) randomizedQuicksort(arr3,0,len(arr3)-1) print(arr3) #%% arr = [7,3,66,33,22,66,99,0,1] print(arr) quickSort(arr,0,len(arr)-1) print(arr) arr1 = [7,3,66,33,22,66,99,0,1] #print(arr1) quickSort1(arr1,0,len(arr1)-1) print(arr1) arr2 = [7,3,66,33,22,66,99,0,1] #print(arr2) quickSort2(arr2,0,len(arr2)-1) print(arr2) #%% #%%
f795cb2964f20a64945fa5072aecf33498a7e23c
DavidSuarezM/python-3
/03_Taller.py
372
3.65625
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 18 15:20:56 2021 @author: David Suárez Molina """ nombre=input('Ingrese su nombre: ') apellido=input('Ingrese su Apellido: ') ubicacion=input('Ingrese donde vive: ') edad=input('Ingrese su edad: ') print('\nHola, mi nombre es', nombre,apellido, ", tengo",edad, "años de edad y, actualmente vivo en", ubicacion,".")
fccce91d127bbcf1c155af0f146977f19d553720
sankaku/deep-learning-from-scratch-py
/ch06/DropoutLayer.py
849
3.8125
4
# Layer for Dropout # mod ch05.ReluLayer import numpy as np class DropoutLayer: def __init__(self, dropout_ratio=0.5): """ initialization dropout_ratio: this ratio of nodes are droppped out """ self.mask = None self.dropout_ratio = dropout_ratio def forward(self, x): """x: NumPy array""" self.mask = np.random.rand(*x.shape) > self.dropout_ratio return x * self.mask def backward(self, dout): """dout: NumPy array""" return dout * self.mask if __name__ == '__main__': dropout = DropoutLayer() x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) print('x = {0}'.format(x)) forward = dropout.forward(x) print('forward = {0}'.format(forward)) backward = dropout.backward(1) print('backward = {0}'.format(backward))
d04f1da3c158ca87349f621803a34bda90e4b02c
EunhaKyeong/studyRepo
/python/2. 파이썬 프로그래밍의 기초, 자료형/formatting_upgrade.py
957
4.375
4
#고급 문자열 포매팅 #숫자 바로 대입하기 print("I eat {0} apples.".format(3)) #문자열 바로 대입하기 print("I eat {0} apples.".format("five")) #숫자 값을 가진 변수로 대입하기 number = 3 print("I eat {0} apples.".format(number)) #2개 이상의 값 넣기 number = 10 day = "three" print("I ate {0} apples. So I was sick for {1} days.".format(number, day)) #이름으로 넣기 print("I ate {number} apples. So I was sick for {day} days.".format(number=10, day="three")) #인덱스와 이름을 혼용해서 넣기 print("I ate {0} apples. So I was sick for {day} days.".format(10, day="three")) #왼쪽 정렬 print("{0:<10}".format("hi")) #오른쪽 정렬 print("{0:>10}".format("hi")) #가운데 정렬 print("{0:^10}".format("hi")) #공백 채우기 print("{0:=^10}".format("hi")) print("{0:!<10}".format("hi")) #소수점 표현하기 y = 3.42134234 print("{0:0.4f}".format(y)) print("{0:10.4f}".format(y))
771038cbcce90143026d673ebd776f0265c7b57d
shankar7791/MI-11-DevOps
/Personel/Nitesh/Python/Assignment11/program02.py
198
4.03125
4
from itertools import groupby def rmc(input): result = [] for (key,group) in groupby(input): result.append(key) print (''.join(result)) input = input("Enter Word Or Sentence: ") rmc(input)
52994bd0917b903ac022ce3d176d312d6f55e1aa
madhuripawar12/python_basic
/union_list.py
184
3.75
4
def Union(list1, list2): final_list = list1 + list2 return final_list list1 = [23, 15, 2, 14, 14, 16, 20 ,52] list2 = [2, 48, 15, 12, 26, 32, 47, 54] print Union(list1, list2)
996cf5620ada64bfccb8aafa1f2a0375f558f1ec
MeghaJK/Python_Assignment-CS043-
/arithmetic.py
255
4
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 11 22:05:25 2020 @author: Megha """ a=int(input("enter 1st number")) b=int(input("enter 2nd number")) sum=a+b diff=a-b mul=a*b print("sum=",sum) print("difference=",diff) print("product=",mul)
e099f2b42ebad9e02d41a83d138689b40fe1aac1
beetroot-academy-rivne/hw-bogdan-quiz
/hw11.py
997
3.859375
4
import json def get_user_info(): user = dict() user['name'] = input('Enter your name: ') user['last_name'] = input('Enter your last name: ') user['phone_number'] = input('Enter your phone number: ') user['address'] = input('Enter your address: ') save_data(user) def save_data(user): with open('user.json', 'w') as user_file: json.dump(user, user_file) # for data in user: # user_file.write(user[data]) # user_file.write('\n') def print_user_info(): with open('user.json') as user_file: user = json.load(user_file) for k,v in user.items(): print(k, ':', v) get_user_info() print_user_info() # with open ('week.txt') as week_file: # weekdays = [day.rstrip() for day in week_file.readlines()] # print(weekdays) # username = input('Hey, what\'s your name?: ') # with open('user_info.txt', 'w') as file_object: # file_object.write(username) # with open('user_info.txt') as file_object: # username = file_object.read() # print('Hello, and welcome back,', username)
4a79d6834e93c935fe76ad345c55ceab73f5093c
ESRIN-RSS/msg-data-tools
/check_msg_data_report.py
12,271
3.546875
4
"""Monitor and report on the availability of MSG data in a local directory. Each day should have 96 timestamp directories and each of those should contain 114 files. So for each day, there should be 10944 H-0000-MSG* files. You can use this script to simply report on missing data by email (useful for setting up via cron) or to check (without emailing) a specific directory, and report on missing data. """ import argparse import logging import os import tempfile from calendar import Calendar from datetime import datetime, timedelta from typing import List from send_email import send_from_mutt REPORT_TO_EMAILS = ['[email protected]'] FILES_PER_TIMESTAMP = 114 report_html = """\ <html> <head><title></title></head> <body> <h1>MSG data status report</h1> """ def setup_cmd_args(): """Setup command line arguments.""" parser = argparse.ArgumentParser(description="Check for missing MSG files inside a directory.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("root_dir", help="The root directory containing MSG data to check (contains YEAR directories)") parser.add_argument("--report", default=3, help="Report only on the last X days") parser.add_argument("--date", help="Select end date in the past for the scan. Format: YYYY/MM/DD") parser.add_argument("--check", help="Instead of emailing a report, check a specific Year/Month/Day. Use format 'YYYY', or 'YYYY/MM' or 'YYYY/MM/DD'") return parser.parse_args() def timeslots(minute_split=15) -> List[str]: """Generate list of timeslots for a 24H range.""" tslots = [] for hour in range(24): for hour_split in range(0, 60, minute_split): tslots.append(str(hour).zfill(2) + str(hour_split).zfill(2)) return tslots TIMESLOTS = timeslots() def check_files(file_path: str, timestamp: str) -> int: """Check the files path for the required MSG data, report on missing files.""" ok_files_count = 0 for file in os.listdir(file_path): if len(file) == 61 and file.startswith('H-000-MSG') and file[46:58] == timestamp: ok_files_count += 1 else: logging.warning(f"{os.path.join(file_path, file)} does not belong here") return FILES_PER_TIMESTAMP-ok_files_count def compose_order_link(year,month,day,tslot,fullday): starttime=f'{year}-{month}-{day}T{tslot[:2]}:{tslot[2:]}' if tslot=='2345' or fullday: endtime = f'{year}-{month}-{day}T23:59' else: endtime=f'{year}-{month}-{day}T{TIMESLOTS[TIMESLOTS.index(tslot)+1][:2]}:{TIMESLOTS[TIMESLOTS.index(tslot)+1][2:]}' # link=f'http://archive.eumetsat.int/usc/#co:;id=EO:EUM:DAT:MSG:HRSEVIRI;delm=O;form=HRITTAR;band=1,2,3,4,5,6,7,8,9,10,11,12;subl=1,1,3712,3712;comp=GZIP;med=NET;noti=1;satellite=MSG4,MSG2,MSG1,MSG3;ssbt={starttime};ssst={endtime};udsp=OPE;subSat=0;qqov=ALL;seev=0;smod=ALTHRV' link=f'https://archive.eumetsat.int/usc/#st:;id=EO:EUM:DAT:MSG:HRSEVIRI;delm=O;form=HRITTAR;band=1,2,3,4,5,6,7,8,9,10,11,12;subl=1,1,3712,3712;comp=NONE;med=NET;noti=1;satellite=MSG4,MSG2,MSG1,MSG3;ssbt={starttime};ssst={endtime};udsp=OPE;subSat=0;qqov=ALL;seev=0;smod=ALTHRV' return link def check_msgdata(root_msg_data_dir: str, days_back: int, enddate: str,): """Cycle through the previous days, checking the msg data. Exclude present day.""" missing_days = [] missing_slots = [] missing_days_report = [] missing_files = 0 if enddate: enddate=datetime.strptime(enddate, '%Y/%m/%d') else: enddate=datetime.today() global TIMESLOTS, report_html startdate = (enddate - timedelta(days=int(days_back))).strftime('%Y/%m/%d') report_html += f'\t\t\t<h2>scanned period => from {startdate} to {enddate.strftime("%Y/%m/%d")}\n</h2>' now = datetime.today().strftime("%Y%m%d") links_file = os.path.join("/data/eo/MSG_DATA/missing_slots", f"msg_missing_slots_links_{now}.txt") with open(links_file, "w") as l: for num_day in reversed(range(1, int(days_back) + 1)): year, month, day = (enddate - timedelta(days=num_day)).strftime('%Y %m %d').split() day_path = os.path.join(root_msg_data_dir, year, month, day) if not os.path.isdir(day_path): logging.info(f"Could not find day {day_path}") missing_days.append(year+month+day) missing_files = missing_files + 96*FILES_PER_TIMESTAMP # report_html += f'\t\t\t<tr bgcolor="#dd7060"><td>{year+month+day}</td><td align="center">NOT FOUND</td></tr>\n' continue for tslot in TIMESLOTS: data_path = os.path.join(day_path, tslot) if not os.path.isdir(data_path): logging.warning(f"Could not find timeslot {data_path}") missing_slots.append(year + month + day + tslot) missing_files = missing_files + FILES_PER_TIMESTAMP # report_html += f'\t\t\t<tr bgcolor="#dd7060"><td>{year+month+day+tslot}</td><td align="center">NOT FOUND</td></tr>\n' continue missing = check_files(data_path, f'{year+month+day+tslot}') logging.info(f"{year+month+day+tslot}: Missing {missing} files.") if missing: # report_html += f'\t\t\t<tr bgcolor="#dd7060"><td>{year+month+day+tslot}</td><td align="center">{missing}</td></tr>\n' orderlink=compose_order_link(year,month,day,tslot, False) l.write(orderlink+"\n") if 0 < missing < 3: color = "yellow" else: color = "red" missing_days_report.append( f'\t\t\t<p style="color:{color}">{year+month+day+tslot}: Missing {missing} files of {str(FILES_PER_TIMESTAMP)} (<a href="{orderlink}">order</a>)</p>\n') missing_files = missing_files + missing else: continue # report_html += f'\t\t\t<tr><td>{year+month+day+tslot}</td><td align="center">OK</td></tr>\n' # if len(missing_days) > 0: perc_of_days_missing = len(missing_days)/int(days_back)*100 print(perc_of_days_missing) if 0 < perc_of_days_missing < 30: color = "yellow" elif perc_of_days_missing > 30: color = "red" else: color = "green" report_html += f'\n<p style="color:{color}">{str(int(days_back)-len(missing_days))+" days found out of "+days_back+" days scanned"}</p>' total_missing_slots = (96*int(days_back))-(96*int(days_back)-(len(missing_days)*96+(len(missing_slots)))) if 0 < total_missing_slots < 3: color = "yellow" elif total_missing_slots > 3: color = "red" else: color = "green" report_html += f'\n<p style="color:{color}">{str(96*int(days_back)-(len(missing_days)*96+(len(missing_slots))))+" timeslots found out of "+str(96*int(days_back))+ " expected"}</p>' if 0<missing_files<3: color = "yellow" elif missing_files>3: color = "red" else: color = "green" report_html += f'\n<p style="color:{color}">{str((96*int(days_back)*FILES_PER_TIMESTAMP)-missing_files)+" files found out of "+str(96*int(days_back)*FILES_PER_TIMESTAMP)+ " expected"}</p>' if len(missing_days)>0: report_html += f'\n<h3 style="color:red">Missing days:</h3>\n\n' for day in missing_days: year,month,dday = day[:4], day[4:6], day[-2:] orderlink = compose_order_link(year, month, dday, '0000', True) l.write(orderlink+"\n") report_html += f'\t\t\t<p style="color:red">{day} (<a href="{orderlink}">order</a>)</p>\n' if len(missing_slots) > 0: report_html += f'\n<h3 style="color:red">Missing slots:</h3>\n\n' for slot in missing_slots: year,month,day,tslot = slot[:4], slot[4:6], slot[6:8], slot[-4:] orderlink = compose_order_link(year, month, day, tslot, False) l.write(orderlink+"\n") report_html += f'\t\t\t<p style="color:red">{slot} (<a href="{orderlink}">order</a>)</p>\n' if len(missing_days_report) > 0: report_html += f'\n<h3 style="color:red">Missing files:</h3>\n' for files in missing_days_report: report_html += f'{files}' def check_year_dir(path: str): """Check the MSG data from this year path.""" for month in range(1, 13): month_str = str(month).zfill(2) month_path_to_check = os.path.join(path, month_str) if not os.path.isdir(month_path_to_check): logging.warning(f"Could not find {month_path_to_check}") continue check_month_dir(month_path_to_check) def check_month_dir(path: str): """Check the MSG data from this month path.""" year, month = path[-7:-3], path[-2:] # .../2018/12 c = Calendar() for day in c.itermonthdays(int(year), int(month)): if day == 0: continue day_str = str(day).zfill(2) day_path_to_check = os.path.join(path, day_str) if not os.path.isdir(day_path_to_check): logging.warning(f"Could not find {day_path_to_check}") continue if check_day_dir(day_path_to_check): logging.info(f'{day_path_to_check} complete') def check_day_dir(path: str) -> bool: """Check the MSG data from this day path.""" year, month, day = path[-10:-6], path[-5:-3], path[-2:] # .../2018/12/31 complete = True for tslot in TIMESLOTS: data_path = os.path.join(path, tslot) if not os.path.isdir(data_path): logging.warning(f"{data_path} missing") complete = False continue missing = check_files(data_path, f'{year+month+day+tslot}') if missing: logging.warning(f"{year+month+day+tslot} incomplete by {missing} files") complete = False return complete def check_missing_data(msg_root_dir: str, date_fields: List[str]): """Check for missing data in the given root directory, and date fields (YYYY, MM, DD).""" year = month = day = path_to_check = None if len(date_fields) == 3: year, month, day = date_fields month = month.zfill(2) day = day.zfill(2) path_to_check = os.path.join(msg_root_dir, year, month, day) elif len(date_fields) == 2: year, month = date_fields month = month.zfill(2) path_to_check = os.path.join(msg_root_dir, year, month) else: year = date_fields[0] path_to_check = os.path.join(msg_root_dir, year) if not os.path.isdir(path_to_check): logging.critical(f'Invalid dir {path_to_check}') exit(1) if day: if check_day_dir(path_to_check): logging.info(f'{path_to_check} complete') elif month: check_month_dir(path_to_check) else: check_year_dir(path_to_check) if __name__ == '__main__': logging.basicConfig(format='%(asctime)-15s:%(levelname)s:%(message)s', level=logging.INFO) args = setup_cmd_args() if not args.root_dir.startswith('/'): logging.critical('root_dir parameter must be an absolute path') exit(1) if args.check: date_values = list(filter(None, args.check.split('/'))) # remove empty strings if not date_values or len(date_values) > 3: logging.critical('check parameter is not in valid format (YYYY/MM/DD)') exit(1) check_missing_data(args.root_dir, date_values) exit() else: check_msgdata(args.root_dir, args.report, args.date) report_html += '\t\t\t</body>\n</html>' # Finishing up the report text/formatting filename = os.path.join("/tmp/", 'checkmsgdata.log') with tempfile.TemporaryDirectory() as tempdir: with open(filename, 'w') as output: output.write(report_html) if REPORT_TO_EMAILS: logging.info(f"Sending email to {', '.join(REPORT_TO_EMAILS)}") send_from_mutt(REPORT_TO_EMAILS, 'MSG data status report', filename) logging.info("Done")
70c4c508af6bd34e2f5ca618365321ee2ea87ee1
Zihua-Liu/LeetCode
/148/148.sort-list.python3.py
1,696
3.90625
4
# # [148] Sort List # # https://leetcode.com/problems/sort-list/description/ # # algorithms # Medium (31.28%) # Total Accepted: 145K # Total Submissions: 463.1K # Testcase Example: '[4,2,1,3]' # # Sort a linked list in O(n log n) time using constant space complexity. # # Example 1: # # # Input: 4->2->1->3 # Output: 1->2->3->4 # # # Example 2: # # # Input: -1->5->3->4->0 # Output: -1->0->3->4->5 # # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ return self.divideMerge(head) def divideMerge(self, head): if head == None: return head if head.next == None: return head cnt = 0 ptr = head while ptr != None: cnt += 1 ptr = ptr.next ptr = head for i in range(cnt // 2 - 1): ptr = ptr.next head2 = ptr.next ptr.next = None head1 = head head1 = self.divideMerge(head1) head2 = self.divideMerge(head2) return self.mergeSort(head1, head2) def mergeSort(self, head1, head2): if head1.val > head2.val: return self.mergeSort(head2, head1) ptr1 = head1 ptr2 = head2 while ptr2 != None: while ptr1.next != None and ptr2.val > ptr1.next.val: ptr1 = ptr1.next if ptr1.next == None: ptr1.next = ptr2 return head1 else: ptr1_next = ptr1.next ptr2_next = ptr2.next ptr1.next = ptr2 ptr2.next = ptr1_next ptr1 = ptr1.next ptr2 = ptr2_next return head1
bbbc226f4c38e98ebb6723158265270b30a90130
shailis17/CS100H
/HW08_Problem2.py
649
3.578125
4
''' Shaili Soni CS100, H01 Oct 29, 2020 HW8, Problem 2 ''' def twoWordsV2(integer, firstLetter): word1 = '' word2 = '' lst = [] run = True while run: word1 = input("Enter a " + str(integer) + "-letter word please: ") if len(word1) == integer: lst.append(word1) run = False run = True while run: word2 = input("Enter a word beginning with " + firstLetter + " please: ") if word2[0] == firstLetter.upper() or word2[0] == firstLetter.lower(): lst.append(word2) run = False return lst print(twoWordsV2(4, 'B'))
d613bcaf287e9d1cbf31960e565aeaf10d17a090
linth/learn-python
/async_IO/coroutines/base_example/2_asyncio_async_blocking.py
945
4
4
''' 非同步阻塞 (synchronous + blocking) - 使用 await 方式條列出來,皆會使用順序方式執行完畢。 [思考]: 嘗試 main1, main2 使用裝飾器去計算時間會有問題。 Reference: - https://juejin.cn/post/7095400034165850148 ''' import asyncio async def fn2(): print("fn2") async def fn1(): print("start fn1") await fn2() print("end fn1") # 請注意 main1 跟 main2 之間的任務順序 async def main1(): print("start main") await fn2() await fn1() print("end main") async def main2(): print("start main") await fn1() await fn2() print("end main") if __name__ == '__main__': # 非同步函式執行 # 請注意 main1 跟 main2 之間的任務順序 # asyncio.run(main1()) asyncio.run(main2()) ''' main1() start main fn2 start fn1 fn2 end fn1 end main ''' ''' main2() start main start fn1 fn2 end fn1 fn2 end main '''
cc5c2c39ba63ce105d2c0b8c4c45667e9919555e
AnishaSabu/Python-Learning-
/dictionary.py
817
4.28125
4
num=int(raw_input("enter the number of groups: ")) #enter number of groups present students_data={} #declare an empty dictionary for i in range(1,num+1): limit=int(raw_input("enter the number of student in %d group: "%i)) #enter the number of students in ith group students_data[i]={} #to make each item of student_data dictionary, another dictionary for j in range(limit): #to enter the names of students in ith group students_data[i][j]=raw_input("enter the name of the student: ") groupnum=int(raw_input("enter the roll no of the student: ")) #to enter each name if groupnum in students_data.keys(): #to enter group number whose member's list is required print "students names in the entered group number" print students_data[groupnum] #to print list of students in the desired group
b3d5f787fca90dd4072445e4960dcefa74635482
EydenVillanueva/Exercises
/Python/relativeSortArray.py
406
3.609375
4
def relativeSortArray(a1,a2): if len(a1) < len(a2): return [] cont, aux= 0,0 for i in range(len(a2)): for j in range(len(a1)): if a2[i] == a1[j]: aux = a1[cont] a1[cont] = a1[j] a1[j] = aux cont += 1 return a1 if __name__ == "__main__": print(relativeSortArray([2,4,1,5,4,2,3],[2,1,4,5,3]))
ba42ac0913efa8e64bdf7bd4c86a90b3dbd5bb46
acothaha/Learn-Python-3-The-Hard-Way
/ex45/fight.py
584
3.65625
4
from suit import suit def fight(hero, foe, death): if foe.hp <= 0: print(f"\n\t\t\tYOU DEFEAT {foe.name}") return 1 elif hero.hp <= 0: death.enter() exit(1) else: pass print(f"\n\t\t\t{hero.name}: {hero.hp} HP VS {foe.hp} HP :{foe.name}\n") battle = suit() if battle == "lose": hero.hp = hero.hp - foe.atk fight(hero, foe, death) elif battle == "win": foe.hp = foe.hp - hero.atk fight(hero, foe, death) else: print("something wrong")
4aa127711a403de55b87de470186653e3442b95b
dylngg/weekly-programs
/week13/Alarm.py
1,456
3.515625
4
import time import os import threading import argparse import sys class Alarm(threading.Thread): def __init__(self, wakeupTime): # init class super(Alarm, self).__init__() self.wakeupTime = wakeupTime self.keep_running = True # runs alarm clock def run(self): # check time try: while self.keep_running: currentTime = time.strftime("%H:%M") if self.wakeupTime in currentTime: print('\nALARM IS GOING OFF') self.stop() # wait a bit time.sleep(1) except: # do nothing! return # stops alarm clock def stop(self): self.keep_running = False #sys.exit() def main(args): # get input for alarm clock parser = argparse.ArgumentParser(description='A simple Alarm Clock') parser.add_argument('-t','--time', help='Enter wakeup time (h:mm), no military time',required=True) parser.add_argument('-y','--type', help='AM or PM?',required=True) args = parser.parse_args() # check for valid time input wakeupTime = args.time try: time.strptime(wakeupTime, '%H:%M') except ValueError: print('Use correct time format (h:mm)') # format time if 'pm' in args.type or 'PM' in args.type: hour = wakeupTime[:wakeupTime.index(':')] militaryHour = str(int(hour) + 12) wakeupTime = militaryHour + wakeupTime[wakeupTime.index(':'):] print('Alarm set for: ' + wakeupTime) # turn on alarm clock alarm = Alarm(wakeupTime) alarm.start() if __name__ == '__main__': sys.exit(main(sys.argv))
1a003b34530b74da5e6b2ccfa5303dfd0ff9f98f
jqjZhu/Dictionaries-word-count-
/wordcount.py
448
3.9375
4
def count_word(filename): """Count words in file.""" input_file = open(filename) word_counts = {} for line in input_file: # The default argument in rstrip() and split()is whitespace. line = line.rstrip() words = line.split() for word in words: word_counts[word] = word_counts.get(word, 0) + 1 for word, count in word_counts.items(): print(word, count) # count_word('test.txt')
0f7e07c5f96939f5748c8a93a95564f1919750b0
Akshen/TP
/BTIT.py
397
3.59375
4
''' Binary Tree Inorder Traversal using Stacks 1 2 3 4 5 6 7 expected = [4, 2, 5,1,6,3,7] ''' def inorderT(root): stk = [] res = [] while root is not None and stk != []: while root is not None: stk.append(root) root = root.left root = stk.pop() res.append(root.val) root = root.right return res
c3d68eb4e0ba48d0006c520c595ae40de648d143
carltonf/pymotw-workout
/text/templates.py
2,683
3.546875
4
# TODO: string formats are very complex # string_template.py import string values = { 'var': 'foo', 'var2': 'bar' } t = string.Template(""" Variable : $var Escape : $$ Variable in text: ${var}iable Variable 2 : $var2 Escape : $$ Variable in text : ${var2}iable """) print('TEMPLATE:', t.substitute(values)) # Below: string interpolations: s = """ Variable : %(var)s Escape : %% Variable in text: %(var)siable Variable 2 : %(var2)s Escape : %% Variable in text : %(var2)siable """ print('INTERPOLATION:', s % values) s = """ Variable : {var} Escape : {{}} Variable 2 in text: {var}iable Variable : {var2} Escape : {{}} Variable in text : {var2}iable """ print('FORMAT:', s.format(**values)) # limitation nums = { 'num': 30, 'num2': 103 } s = "Number: {num:04d}, Number 2: {num:05d}" print( 'FORMAT:', s.format(**nums) ) # Template: No formatting options are available. # s = string.Template( "Number: ${num:04d}, Number 2: ${num2:05d}" ) s = string.Template( "Number: ${num}, Number 2: ${num2}" ) print( 'TEMPLATE:', s.substitute(nums) ) # string_template_missing.py # safe_substitute values = {'var': 'foo'} t = string.Template("$var is here but $missing is not provided") try: print('substitute() :', t.substitute(values)) except KeyError as err: print('ERROR:', str(err)) print('safe_substitute():', t.safe_substitute(values)) # string_template_advanced.py class MyTemplate(string.Template): delimiter = '%' idpattern = '[a-z]+_[a-z]+' template_text = ''' Delimiter : %% Replaced : %with_underscore Ignored : %notunderscored ''' d = { 'with_underscore': 'replaced', 'notunderscored': 'not replaced' } t = MyTemplate(template_text) print('Modified ID pattern:') print( t.safe_substitute(d) ) t = string.Template('$var') print( t.pattern ) print( t.pattern.pattern ) # completely change the pattern class MyTemplate(string.Template): delimiter = '{{' pattern = r''' \{\{(?: (?P<escaped>\{\{)| (?P<named>[_a-z][_a-z0-9]*)\}\}| (?P<braced>[_a-z][_a-z0-9]*)\}\}| (?P<invalid>) ) ''' t = MyTemplate(''' {{{{ {{var}} ''') print('MATCHES:', t.pattern.findall( t.template )) print('SUBSTITUTED:', t.safe_substitute(var = 'replacement')) # string constants import inspect def is_str(value): return isinstance(value, str) for name, value in inspect.getmembers(string, is_str): if name.startswith('_'): continue print('%s=%r\n' % (name, value))
1ee450026577c380d6ce30c73ca18af812495d19
pittcat/Algorithm_Practice
/leetcode/deleteDuplicates-83.py
716
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ res = [] cur = head cur_value = float('inf') while cur: if cur_value != cur.val: res.append(cur.val) cur_value = cur.val cur = cur.next res_node = ListNode(0) res_cur = res_node for i in res: res_cur.next = ListNode(i) res_cur = res_cur.next return res_node.next
b74a62f522f38c585549a37222f207e29ce76459
VictorxSR/BlackJack
/Joc.py
1,839
3.765625
4
from Cartes import * import random class Joc: def crearCartes(): # crear totes les cartes de poker cartes = [] for x in range(1,13): cartes.append(Cartes("Picas", x)) # es crea un objecte Cartes amb un string i un numero for x in range(1,13): cartes.append(Cartes("Corazones", x)) for x in range(1,13): cartes.append(Cartes("Diamantes", x)) for x in range(1,13): cartes.append(Cartes("Treboles", x)) return cartes # retorna una llista amb totes les cartes def veureCartes(cartes): # printar una carta for carta in cartes: print("%i de %s" % (carta.numero, carta.pal)) def pujarAposta(aposta, diners): print("Aposta actual: " + str(aposta)) while True: print("Els teus diners: " + str(diners)) try: new_aposta = int(input("Quant vols pujar: ")) if new_aposta <= diners and new_aposta > 1: # comprovacio de que no apostis mes diners dels que tens i que l'aposta sigui superior a 1 diners -= new_aposta # es resta l'aposta dels diners del jugador return new_aposta + aposta, diners # retorna l'aposta que queda i els diners que li queden al jugador else: print("\nL'aposta no pot ser superior als diners del jugador ni inferior a 1\n") except ValueError as e: print("\nNo es poden introduir caracters\n") # obtenir una carta de forma aleatoria def obtenirCarta(cartes): carta = random.choice(cartes) # obte una carta aleatoria dins de la llista cartes.remove(carta) # s'elimina la carta obtinguda per que no torni a sortir return carta, cartes
2851a7882f9e1d0fa1a6fcb1d0d7b6333e0f8136
itibbers/nb
/CodingInterviews/reference/数组中重复的数字.py
2,188
3.953125
4
''' 题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。 也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3}, 那么对应的输出是第一个重复的数字2。 ''' ''' 应该是在线编辑器的bug 思路一: 未通过 ''' # -*- coding:utf-8 -*- class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, numbers, duplication): # write code here if not numbers: return -1 num = [] for i in numbers: if i in num: duplication[0] = i return True else: num.append(i) return False ''' 思路二: 最简单的方法:我最直接的想法就是构造一个容量为N的辅助数组B,原数组A中每个数对应B中下标,首次命中,B中对应元素+1。如果某次命中时,B中对应的不为0,说明,前边已经有一样数字了,那它就是重复的了。 举例:A{1,2,3,3,4,5},刚开始B是{0,0,0,0,0,0},开始扫描A。 A[0] = 1  {0,1,0,0,0,0} A[1] = 2 {0,1,1,0,0,0} A[2] = 3 {0,1,1,1,0,0} A[3] = 3 {0,1,1,2,0,0},到这一步,就已经找到了重复数字。 A[4] = 4 {0,1,1,2,1,0} A[5] = 5 {0,1,1,2,1,1} 时间复杂度O(n),空间复杂度O(n),算法优点是简单快速,比用set更轻量更快,不打乱原数组顺序。 未能通过 ''' # -*- coding:utf-8 -*- class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, numbers, duplication): # write code here if not numbers: return False length = len(numbers) assist = [0] * length for i in numbers: if assist[numbers[i]] == 0: assist[numbers[i]] += 1 else: duplication[0] = numbers[i] return True return False
755b00e91ec28072644b1b471699d63b758e5c09
sandeepbaldawa/Programming-Concepts-Python
/data_structures/disjoint_sets/merge_tables.py
3,143
4.0625
4
''' Problem Introduction In this problem, your goal is to simulate a sequence of merge operations with tables in a database. Problem Description Task. There are n tables stored in some database. The tables are numbered from 1 to n. All tables share the same set of columns. Each table contains either several rows with real data or a symbolic link to another table. Initially, all tables contain data, and i-th table has ri rows Sample 1. Input: 5 5 1 1 1 1 1 3 5 2 4 1 4 5 4 5 3 Output: 2 2 3 5 5 Explanation: In this sample, all the tables initially have exactly 1 row of data. Consider the merging operations: 1. All the data from the table 5 is copied to table number 3. Table 5 now contains only a symbolic link to table 3, while table 3 has 2 rows. 2 becomes the new maximum size. 2. 2 and 4 are merged in the same way as 3 and 5. 3. We are trying to merge 1 and 4, but 4 has a symbolic link pointing to 2, so we actually copy all the data from the table number 2 to the table number 1, clear the table number 2 and put a symbolic link to the table number 1 in it. Table 1 now has 3 rows of data, and 3 becomes the new maximum size. 4. Traversing the path of symbolic links from 4 we have 4 → 2 → 1, and the path from 5 is 5 → 3. So we are actually merging tables 3 and 1. We copy all the rows from the table number 1 into the table number 3, and now the table number 3 has 5 rows of data, which is the new maximum. 5. All tables now directly or indirectly point to table 3, so all other merges won’t change anything. ''' #!/usr/bin/python # -*- coding: utf-8 -*- # python3 import sys (n, m) = map(int, sys.stdin.readline().split()) # n,m = 5,5, lines = list(map(int, sys.stdin.readline().split())) # lines = [1,1,1,1,1] rank = [0] * n parent = list(range(0, n)) ans = max(lines) def getParent(table): # print(table,parent[table]) if table != parent[table]: parent[table] = getParent(parent[table]) return parent[table] def merge(destination, source): global ans # print(destination,source) (realDestination, realSource) = (getParent(destination), getParent(source)) if realDestination == realSource: return if rank[realSource] > rank[realDestination]: parent[realDestination] = realSource lines[realSource] = lines[realDestination] + lines[realSource] if lines[realSource] > ans: ans = lines[realSource] else: parent[realSource] = realDestination lines[realDestination] = lines[realDestination] \ + lines[realSource] if lines[realDestination] > ans: ans = lines[realDestination] if rank[realSource] == rank[realDestination]: rank[realDestination] = rank[realDestination] + 1 return # d = [3,2,1,5,5] # s = [5,4,4,4,3] for i in range(m): # destination, source = map(int, sys.stdin.readline().split()) # destination, source = map(int, [d[i],s[i]]) # merge(d[i]-1, s[i]-1) (destination, source) = map(int, sys.stdin.readline().split()) merge(destination - 1, source - 1) # ans = max(lines) print ans
653ab6bc60559666afc1d9c903a01ff6322ccc13
lum4chi/chinltk
/tokenize.py
898
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2016 Francesco Lumachi <[email protected]> import nltk, string def words(text): """ Tokenize by word AND removed punctuation token """ return [w for w in nltk.word_tokenize(text.lower()) if w not in string.punctuation] def filter_stopwords(words): """ Filter stopwords from a list of words """ stopwords = set(nltk.corpus.stopwords.words('english')) # push this in comprehension slow A LOT! return [w for w in words if w.lower() not in stopwords] def filter_words(words, filters): """ Filter words from a list of filters """ filters = set(filters) return [w for w in words if w.lower() not in filters] def biwords(text): """ Iterate over biword """ word_list = words(text) first, second = iter(word_list), iter(word_list[1:]) return [' '.join([f, s]) for f, s in zip(first, second)] # -> 'first second'
b8220207d21e392a6586454b3f003ac8800f0af3
Yanl05/LeetCode
/six_hundred_thirty_seven.py
2,623
3.765625
4
# -*- coding: UTF-8 -*- """ # @Time : 2019-07-13 09:44 # @Author : yanlei # @FileName: six_hundred_thirty_seven.py 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组. 示例 1: 输入: 3 / \ 9 20 / \ 15 7 输出: [3, 14.5, 11] 解释: 第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11]. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/average-of-levels-in-binary-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def createTree(nodelist): """ 传入一个list, 使用层序便利创建二叉树 :param nodelist: :return: """ if nodelist == []: return None head = TreeNode(nodelist[0]) Nodes = [head] j = 1 for node in Nodes: if node != None: node.left = TreeNode(nodelist[j]) if nodelist[j] != None else None Nodes.append(node.left) j += 1 if j == len(nodelist): return head node.right = TreeNode(nodelist[j]) if nodelist[j] != None else None Nodes.append(node.right) j += 1 if j == len(nodelist): return head # 构建二叉树 # nums = [1,2,2,3,4,4,3] nums = [3,9,20,15,7] root = createTree(nums) class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ levels = [] if not root: return levels def helper(node, level): if level == len(levels): levels.append([]) levels[level].append(node.val) if node.left: helper(node.left, level+1) if node.right: helper(node.right, level+1) return levels helper(root, 0) print(len(levels[1])) print(type(len(levels[1]))) print(sum(levels[1])) print(type(sum(levels[1]))) print(type(sum(levels[1])/len(levels[1]))) # python2中 int 除 int 会默认得到int型 python3中只直接执行 / 就可以了 python2:return [sum(tmp)/len(tmp) for tmp in levels] --> [3.0, 14.0, 11.0] return [sum(tmp)/float(len(tmp)) for tmp in levels] # return [sum(tmp) / len(tmp) for tmp in levels] # [3.0, 14.5, 11.0] print(Solution().averageOfLevels(root))
fefa5c186aa06f148fd66a0c8ae7220e364f9e9c
DilyanTsenkov/SoftUni-Software-Engineering
/Python_Advanced/05_Functions Advanced/Lab/04_operate.py
367
3.875
4
from functools import reduce def operate(opr, *args): operators = { "+": reduce(lambda x, y: x + y, args), "-": reduce(lambda x, y: x - y, args), "*": reduce(lambda x, y: x * y, args), "/": reduce(lambda x, y: x / y, args) } return operators[opr] print(operate("+", 1, 2, 3)) print(operate("*", 3, 4))
c40bb2fd8c2d832b63fc1cd49c3718f6d8b96a87
ipcoo43/pythonone
/lesson145.py
758
4.21875
4
print(''' [ 범위 만들기 ] range(<숫자1>) : 0부터 (<숫자1>-1)까지의 정수 범위 range(<숫자1>,<숫자2>) : <숫자1>부터 (<숫자2>-1)까지의 정수의 범위 ringe(<숫자1>,<숫자2>,<숫자3>) : <숫자1>부터 <숫자3> 만큼의 차이를 가진 (<숫자2>-1)까지 범위 [ 범위와 반복문 ] for <범위 내부의 숫자를 담을 변수> in <범위>: <코드> ''') print(range(5)) print(list(range(5))) for i in range(5): print('{}번째 반복문입니다.'.format(i)) print() print(range(5,10)) print(list(range(5,10))) for i in range(5,10): print('{}번째 반복문입니다.'.format(i)) print() print(range(0,10,2)) print(list(range(0,10,2))) for i in range(0,10,2): print('{}번째 반복문입니다.'.format(i))
53e90cbfca12d204fa1f9bdc9e2ca7fb2e99d855
ernestojfcosta/IPRP_LIVRO_2013_06
/controlo/programas/poli_1.py
959
4.125
4
# -*- coding: mac-roman -*- # condicionais - exemplo raízes de polinómio # Ernesto costa - 2006 import math def main(): """ Calculo das raízes reais de um polinómio. """ a,b,c = eval(input("Os coeficientes sff (a,b,c):\t")) r1,r2=raizes(a,b,c) if r1 == r2 == None: print("Não tem raízes reais!") elif r1 == r2: print("O polinómio de coeficientes\ a=%d b=%d c= %d tem raízes múltiplas r1=%3.2f r2=%3.2f" % (a,b,c,r1,r2)) else: print("As raízes do polinómio de coeficientes\ a=%d b=%d c= %d são r1=%3.2f r2=%3.2f" % (a,b,c,r1,r2)) def raizes(a,b,c): """ Calcula raízes. """ discriminante= pow(b,2) - 4 * a * c if discriminante < 0: return None,None elif discriminante == 0: raiz1 = raiz2 = float(-b)/ (2 * a) return raiz1, raiz2 else: raiz_discrim = math.sqrt(discriminante) raiz1=float((-b + raiz_discrim)) / (2 * a) raiz2=float((-b - raiz_discrim)) / (2 * a) return raiz1,raiz2 if __name__ == '__main__': main()
9c1861f3f4fd8d7390644ed6fd30b9b6f4cf6f0b
oleoalonso/atvPython-12-10
/main.py
1,547
3.640625
4
from Hotel import Hotel from Hospede import Hospede from Reserva import Reserva hotel = Hotel("Feras", "Centro Histórico", 25) hospede = Hospede("Maria", "Feminino", 32) reserva = Reserva("25/12/2021", "05/01/2022", "600") # H O T E L hotel.Abrir() hotel.Endereco() print(f"O Hotel {hotel.nomeHotel} possui {hotel.acomodacoes} acomodações.") # R E S E R V A reserva.ConfirmarReserva() # R E S E R V A print(f"Data de Entrada: {reserva.dataEntrada}") # H O S P E D E hospede.Hospede() print(f"Cliente do sexo: {hospede.sexoHospede}") print(f"Cliente tem a idade: {hospede.idadeHospede} anos.") # R E S E R V A # Método da classe Reserva para receber parâmetros digitados pelo usuário (input) formaPagamento = input(f"\nQual é a forma de pagamento ? ") reserva.FormaPagamento(formaPagamento) # H O S P E D E hospede.Checkin() # R E S E R V A reserva.Valor() # H O S P E D E # Método da classe Hospede para receber parâmetros digitados pelo usuário (input) avaliacao = input(f"\nComo o Hospede {hospede.get_NomeHospede()} avalia o serviço ? ") hospede.Avaliar(avaliacao) # H O T E L # Método da classe Hotel para receber parâmetros digitados pelo usuário (input) estrelas = input(f"\nQuantas estrelas possui o Hotel {hotel.get_NomeHotel()} ? ") hotel.Estrelas(estrelas) # H O S P E D E hospede.Checkout() # R E S E R V A print(f"Data de Saída: {reserva.dataSaida}") # A g r a d e c i m e n t o print("Agradecemos pela preferência!!!") # H O T E L hotel.Fechar()
d9237b612cf82ce010dcbd3cc987db8976e889de
limpingstone/socionics-engine
/cognitive_function.py
3,525
3.75
4
#!/usr/bin/env python3 # # cognitive_function.py - By Steven Chen Hao Nyeo # The script that creates the eight cognitive functions in socionics # Created: January 1, 2019 # Label - F or T or N or S # Sublabel - i or e class CognitiveFunction: def __init__ (self, label, name, description): self.label = label[0] self.sublabel = label[1] self.name = name self.description = description # The function that returns the corresponding cognitive function (T - F / N - S) def opposite_orientation (self): if (self.label + self.sublabel == "Ti"): return Fi elif (self.label + self.sublabel == "Fi"): return Ti elif (self.label + self.sublabel == "Ni"): return Si elif (self.label + self.sublabel == "Si"): return Ni elif (self.label + self.sublabel == "Te"): return Fe elif (self.label + self.sublabel == "Fe"): return Te elif (self.label + self.sublabel == "Ne"): return Se elif (self.label + self.sublabel == "Se"): return Ne # The helper method that changes the sublabel from introverted to extroverted or vice versa (i - e) def opposite (self): if (self.label + self.sublabel == "Ti"): return Te elif (self.label + self.sublabel == "Fi"): return Fe elif (self.label + self.sublabel == "Ni"): return Ne elif (self.label + self.sublabel == "Si"): return Se elif (self.label + self.sublabel == "Te"): return Ti elif (self.label + self.sublabel == "Fe"): return Fi elif (self.label + self.sublabel == "Ne"): return Ni elif (self.label + self.sublabel == "Se"): return Si Ni = CognitiveFunction("Ni", "Introveted Intuition", "development over time, historicity, cause and effect, consequences, repetition, archetypal themes and examples, looking for causes in history or the past, past-future forecasting of event dynamics, rhythm, delay or act-now, past-turned imagination ") Ne = CognitiveFunction("Ne", "Extroverted Intuition", "potential, permutation, isomorphism, semblance, essence, uncertainty, the unknown, opening up new \"windows\" and bringing up new possibilities in conversation, seeing opportunities, chance, being the first, refreshing informational suddenness, diversity of interests and involvements") Ti = CognitiveFunction("Ti", "Introveted Thinking", "structure, analysis, coherence, consistency, cogency, accordance, match, commensurability, understanding, order, or the lack of thereof") Te = CognitiveFunction("Te", "Extroverted Thinking", "efficiency, method, mechanism, knowledge, work, reason in motion, direction of activity into its most logical course of action, \"logic of actions\", utilitarianism, expediency, benefit ") Si = CognitiveFunction("Si", "Introveted Sensing", "homeostasis, continuity, smoothness, flow, satisfaction, aesthetics, quality of life, pleasure, relaxation, convenience, quality ") Se = CognitiveFunction("Se", "Extroverted Sensing", "sensing of immediate static qualities of objects, sensing of immediate reality, external appearance, texture, form, static objects, impact, direct physical effect, span, extent, scope ") Fi = CognitiveFunction("Fi", "Introveted Ethics", "internal harmony, resonance or dissonance of personal sentiments, sympathy, pity, compassion, support, condemnation, judgement, positive and negative emotional space ") Fe = CognitiveFunction("Fe", "Extroverted Ethics", "emotional atmosphere, romanticism, cooperation, treatment, qualitative judgement of behavior, sympathy, ethical estimations of observable actions, \"ethics of actions\" ")
dccb0d10eb58230d336d12a1a754d86935073c77
mayankdiatm/PythonScrapping
/oddEven.py
295
4.15625
4
#!/usr/bin/python import math number = int(raw_input("Enter a number of your choice :")) if number%2 is 0: if number%4 is 0: print("The number is even and is divisible by 4") else: print("The number you entered is even") else: print("The number you entered is odd")
7abddaf9df3bbcdbb7dc8dc64cd3a8abc7ec60a2
reute/sys-python
/13/sortthings/sortthings.py
1,838
3.59375
4
import random, sys def einlesen_datei(namen): unsortiert = [] for index, zeile in enumerate(open(namen, "r", encoding='utf-8', errors='ignore')): namen, hoehe = zeile.rstrip('\n').split(":") hoehe = int(hoehe) berg = namen, hoehe if index < MAX_BERGE: unsortiert.append(berg) else: r = random.randint(0, index) if r < MAX_BERGE: unsortiert[r] = berg return unsortiert def ausgabe_spielstand(unsortiert, spieler): print("Current state:") for index, zeile in enumerate(spieler): print(str(index + 1) + ": " + zeile[0]) print("Still to be sorted:") for index, zeile in enumerate(unsortiert): print(str(index + 1) + ": " + zeile[0]) def ausgabe_endergebnis(spieler): for zeile in spieler: print("{0:5d} {1:s}".format(zeile[1], zeile[0])) def eingabe_spieler(): eingabe = (input("What is to be inserted where ? ")).split() eingabe = [int(i) for i in eingabe] return eingabe def spieler_unsortiert(spieler): max_hoehe = 0 for index, zeile in enumerate(spieler): tmp = zeile[1] if tmp > max_hoehe: max_hoehe = tmp else: return True return False def einfuegen(berg, index_spieler, spieler): if index_spieler > len(spieler): spieler.append(berg) else: spieler.insert(index_spieler, berg) return spieler def entfernen(unsortiert, index_unsortiert): del unsortiert[index_unsortiert] return unsortiert MAX_BERGE = 8 spieler = [] unsortiert = einlesen_datei("berge") while True: ausgabe_spielstand(unsortiert, spieler) index_unsortiert, index_spieler = eingabe_spieler() if index_unsortiert == 0: break berg = unsortiert[index_unsortiert - 1] spieler = einfuegen(berg, index_spieler, spieler) unsortiert = entfernen(unsortiert, index_unsortiert) if spieler_unsortiert(spieler): print("Sorry, then it is no longer sorted") break ausgabe_endergebnis(spieler)
332fb5c75048cf6b24ca940ae341f02fd69f200d
patthrasher/codewars-practice
/kyu6-6.py
807
3.5
4
def meeting(s) : count = 0 how_many_names = s.count(':') fn = [] ln = [] while count < how_many_names : x = s.find(':') y = s.find(';') fn.append(s[:x].upper()) ln_range = s[x+1:y] if y == -1 : ln_range = s[x+1:] ln.append(ln_range.upper()) s = s[y + 1:] count = count + 1 zippy = sorted(list(zip(ln, fn))) new_str = '' for first, last in zippy : new_str += '(' + first + ', ' + last + ')' return(new_str) print(meeting("Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill")) print(meeting("Alexis:Wahl;John:Bell;Victoria:Schwarz;Abba:Dorny;Grace:Meta;Ann:Arno;Madison:STAN;Alex:Cornwell;Lewis:Kern;Megan:Stan;Alex:Korn"))