blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
291d09272a542e9b24fab373d154466f9d1b0c30
shreeji0312/learning-python
/python-Bootcamp/assignment4/assignment4notes/functionEx2.py
1,611
4.84375
5
# WPCC # functionEx2.py # When we call some Python standard functions, it gives us back # a value that we can assign to a variable and use later in our programs. # For example: import random randomNumber = random.randint(0, 10) # This function will return the value it generates so we can assign its # value to `randomNumber` # So how can we do that in our own functions: # Let's take a look at the function from the last note: ''' def myAddFunction(a, b): print("The sum is", a + b) ''' # This function will add the numbers, but we can't use it later in our # program ''' sum = myAddFunction(10, 5) ''' # This will not give us the expected 15. `myAddFunction` will only print the sum, # not return it # So we can modify this function to return the value instead. def myAddFunction(a, b): return a+b theSum = myAddFunction(10, 20) print(theSum) # Our function now "returns" the value instead of printing it. # This means that during runtime, the function call will take on the value # that is returned: # This is what it would look like behind the scenes: ''' theSum = myAddFunction(10, 20) theSum = .... compute theSum = 20 ''' # Note: when a function reaches a `return` statement, it will terminate the whole # function. For example: def exFunc(): return True print("PRINT ME PLS!!") exFunc() # The print will never happen because the function will have terminated # at the return statement ######################### # EXERCISE ######################### # Write a function called `letterGrade()` that will take in # a grade (integer) and return the appropriate letter grade
151bbbd0b691acd494d84f4f5c5968a4699b3ed1
mahimrocky/NumerialMathMetics
/runge_kutta_fourth_order.py
515
3.734375
4
import math import parser formula = str(input("Enter the equation:\n")) code = parser.expr(formula).compile() def f(x,y): return eval(code) print("Enter the value of x0:\n") x0=float(input()) print("Enter the value of yo:\n") y0=float(input()) print("Enter the value of h:\n") h=float(input()) k1=round(float(h*(f(x0,y0))),5) k2=round(float(h*(f(x0+h/2,y0+k1/2))),5) k3=round(float(h*(f(x0+h/2,y0+k2/2))),5) k4=round(float(h*(f(x0+h,y0+k3))),5) del_y=(k1+(2*k2)+(2*k3)+k4)/6 y=round(y0+del_y,5) print(y)
66244ffaa12f9a0e056c3da3477ef771f9f7523a
luwinher/Python_Practice
/Day1_15/main.py
352
3.828125
4
import module1 as m if __name__ == "__main__": num = int(input("Please input a number: ")) if m.is_palindrome(num) and m.is_prime(num): print("%d is a palindrome and prime number."% num) a = int(input("Please input 2 number: ")) b = int(input()) print("%d and %d gcd is %d, lcm is %d." % (a, b, m.gcd(a, b), m.lcm(a, b)))
bc64977973a02300fc179ad7e9d1a38e90aeb1f4
leandroS08/SME0602_Projeto1
/newton.py
527
4
4
# Calculo Numerico (SME0602) - Projeto Pratico 1 - Metodo de Newton # Alunos: Leandro Silva, Marianna Karenina, Marilene Garcia import math import numpy as np def newton( f, x0, e ): x = [] x.append(x0) x_now = x0 - f(x0)/f_der(f,x0) x_previous = x0 while abs(x_now - x_previous) > e: if(f_der(f,x_now) != 0): x_next = x_now - f(x_now)/f_der(f,x_now) x.append(x_now) x_previous = x_now x_now = x_next return x def f_der( f, x ): h = 1e-5 return (f(x+h)-f(x-h))/(2*h)
2d9a58c322d52353857e3032e6a99c1f28fb49bb
buming65/LeetCode
/剑指offer/leetcode/editor/cn/[面试题58 - II]左旋转字符串.py
742
3.703125
4
# 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数 # 将返回左旋转两位得到的结果"cdefgab"。 # # # # 示例 1: # # 输入: s = "abcdefg", k = 2 # 输出: "cdefgab" # # # 示例 2: # # 输入: s = "lrloseumgh", k = 6 # 输出: "umghlrlose" # # # # # 限制: # # # 1 <= k < s.length <= 10000 # # Related Topics 字符串 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def reverseLeftWords(self, s: str, n: int) -> str: # leetcode submit region end(Prohibit modification and deletion)
e1771aa360ab52c754c04b0b267830bb2fae580f
kovasa/academy
/Lesson I/ex07.py
387
3.546875
4
def merge_dicts(dict1, dict2): new_dict = {} new_dict.update(dict1) new_dict.update(dict2) return new_dict def test1_7(): print(merge_dicts({1: 'one', 2: 'two', 3: 'three'}, {4: 'four', 5: 'five'})) print(merge_dicts({1: 'one', 2: 'two', 3: 'three'}, {2: 'new_two', 4: 'four', 5: 'five'})) test1_7()
33af18bf1f21c3fc2769c772031d2f612dae8298
mehulchopradev/muhammad-python
/com/abc/college/college_user.py
808
3.78125
4
# generalize code in this parent class # super class # parent class # CollegeUser -> object : Single Inheritance class CollegeUser(object): # every class in python implicitly inherits from the object class def __init__(self, name, gender): # self - (5006 Student object) # self - (5004 Professor object) # self - any child class object of CollegeUser # common set of attributes self.name = name self.gender = gender # method is inherited in its child classes def get_details(self): # self - (5006 Student object) # self - (5004 Professor object) # self - any child class object of CollegeUser return 'Name: {0}\nGender: {1}'.format(self.name, self.gender) def __str__(self): return self.get_details()
894083cec80f728ca38a463aa5ce48967c69529e
Aasthaengg/IBMdataset
/Python_codes/p03252/s313883542.py
231
3.5
4
s = input().rstrip() t = input().rstrip() m = dict() for a, b in zip(s, t): if a in m and b != m[a]: print('No') exit() m[a] = b if len(m) == len(set(m.values())): print('Yes') else: print('No')
d737f0c70363695a1b64a24d7da8224134115f4c
TongLing916/alien_invasion
/settings.py
1,653
3.515625
4
class Settings(): """ a class to store all settings""" def __init__(self): """initialize settings for the game""" # settings for screen self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230, 230, 230) # settings for ship self.ship_speed_factor = 1.5 self.ship_limit = 3 # settings for bullet self.bullet_speed_factor = 3 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = 60, 60, 60 self.bullets_allowed = 3 # settings for aliens self.alien_speed_factor = 1 self.fleet_drop_speed = 10 # fleet_direction == 1: moving right # fleet_direction == -1: moving left self.fleet_direction = 1 # speed up the rythme self.speedup_scale = 1.1 # speed of increasing the score of an alien self.score_scale = 1.5 self.initialize_dynamic_settings() def initialize_dynamic_settings(self): """initialize with the game""" self.ship_speed_factor = 1.5 self.bullet_speed_factor = 3 self.alien_speed_factor = 1 # fleet_direction == 1: moving right # fleet_direction == -1: moving left self.fleet_direction = 1 # score self.alien_points = 50 def increase_speed(self): """increase speed in the settings""" self.ship_speed_factor *= self.speedup_scale self.bullet_speed_factor *= self.speedup_scale self.alien_speed_factor *= self.speedup_scale self.alien_points = int(self.alien_points * self.score_scale)
db34643b2992f0108a07b2d66f52c2072d317ad1
Stonewang123/AlienInvasion
/bullet.py
747
3.53125
4
import pygame from pygame.sprite import Sprite class Bullet(Sprite): def __init__(self, screen, ai_settings, ship): super(Bullet, self).__init__() self.screen = screen self.rect = pygame.Rect(0, 0, ai_settings.get_bullet_width(), ai_settings.get_bullet_height()) self.rect.centerx = ship.get_rect().centerx self.rect.top = ship.get_rect().top self.color = ai_settings.get_bullet_color() self.y = float(self.rect.y) self.speed_factor = ai_settings.get_bullet_speed_factor() def update(self): self.y -= self.speed_factor self.rect.y = self.y def draw_bullet(self): pygame.draw.rect(self.screen, self.color, self.rect)
27ec6d51c19cacc5d401fbb61997e40ba90382ca
yordan-marinov/fundamentals_python
/text_processing/replace_repeating_chars.py
346
4
4
string = input() print( "".join( [ symbol for index, symbol in enumerate(string) if index == 0 or symbol != string[index - 1] ] ) ) # result = "" # for index, letter in enumerate(string): # if index == 0 or letter != string[index - 1]: # result += letter # # print(result)
aef46e63006f735b0f9557f41c00e7e2a0117328
Hamng/hamnguyen-sources
/python/set_intersection.py
1,918
4.0625
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 27 21:03:24 2019 @author: Ham HackerRanch Challenge: Set .intersection() Operation Task The students of District College have subscriptions to English and French newspapers. Some students have subscribed only to English, some have subscribed to only French and some have subscribed to both newspapers. You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and the other set is subscribed to the French newspaper. The same student could be in both sets. Your task is to find the total number of students who have subscribed to at least one newspaper. Input Format The first line contains an integer, E, the number of students who have subscribed to the English newspaper. The second line contains E space separated roll numbers of those students. The third line contains F, the number of students who have subscribed to the French newspaper. The fourth line contains F space separated roll numbers of those students. Constraints Output Format Output the total number of students who have subscriptions to both English and French newspapers. Sample Input (see STDIN_SIO) Sample Output 13 """ import io STDIN_SIO = io.StringIO(""" 9 1 2 3 4 5 6 7 8 9 9 10 1 2 3 11 21 55 6 8 """.strip()) if __name__ == '__main__': #input() # discarded, not needed #e = set(map(int, input().split())) #input() # discarded, not needed #f = set(map(int, input().split())) STDIN_SIO.readline().strip() # discarded, not needed e = set(map(int, STDIN_SIO.readline().strip().split())) STDIN_SIO.readline().strip() # discarded, not needed f = set(map(int, STDIN_SIO.readline().strip().split())) print(len(e.intersection(f)))
6a1094763daefbe916a5b85faa0b40dc12594b18
AnujBalu/Matplotlib_Notes
/Ls_7_legend.py
634
4.0625
4
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0,5,10) y = x**3 fig,axes = plt.subplots(figsize=(12,3),dpi=100) axes.plot(x,y,'b',label='x&y') # 'label=' function will be plotted in graph using legend() method axes.legend() # this legend method will locate the label automatically in graph # to customize the location in legend() method # axes.legend(loc=0) # let matplotlib decide the optimal location # axes.legend(loc=1) # upper right cornor # axes.legend(loc=2) # upper left cornor # axes.legend(loc=3) # lower left cornor # axes.legend(loc=4) # lower right cornor plt.show()
1f38ebbfacbe2e03f75ebb3aa98df7b1187bf727
Mayankjh/Python_tkinter_initials
/canvas.py
268
3.625
4
#canvas from tkinter import* root = Tk() canvas = Canvas(root,width=300,height=300) canvas.pack() def createrect(x1,y1,x2,y2): canvas.create_rectangle(x1,y1,x2,y2,fill="#453423") createrect(5,50,200,70) createrect(5,5,40,200) root.mainloop()
269f54e5e5c121b6cca18cdacfbe023dfa49fec7
samwilliamsjebaraj/networkautomation
/PythonCode/lambda_functions.py
511
4.21875
4
""" File:lambda_functions.py Shows the map(),filter(),reduce() function operations using lambda """ my_list=range(1,101) #using map() on lambda print map((lambda x:x%2==0),my_list) print map((lambda x:x%2!=0),my_list) #using filter() on lambda print filter((lambda x:x%2==0),my_list) print filter((lambda x:x%2!=0),my_list) #using reduce() on lambda print "Total Values:{}".format(reduce((lambda x,y :x+y),my_list)) print "Average:{}".format(reduce((lambda x,y :x+y),my_list)/len(my_list)) print len(my_list)
a0bdcdf7f81947125b1db6c259fc5ecc8622079c
ahmednofal/DSP_Project
/steganography.py
4,683
3.671875
4
# This files contains the implementation of the Steganography effect using Phase coding # The source for the theory of the implementation will be in the external sources file. # What TO DO : # According to the source: # 1- Get audio file( supposed to be created using the audio morphing techniques) # 2- Convert audio file into continuous line of bits ( For LSB Coding)- also the audio will be typically amplified to # always account for the deterioration of the signal due to the LSB # 3- Convert the audio file into the frequency domain for it to be processed using the spread spectrum technique # 4- All audio files will be of mono type from datautils import * from enum import Enum # Global constant to be used by all functions for sync purposes quantization_bit_value = 16 # The lsb_code function is to implement the lsb coding technique for steganography, papers file include papers # explaining the theory behind the standard and the implementation # The function needs one input and produces one output # The inputs will be the message to be embedded # The output will be the rate and the amplitude values # There might be modification to the function in terms of the number of bits used to represent the signal whether it is # only one bit of more of the original amplitude # To use the LSB steganography approach u should use high amplitude signals, amplify low signals or record with high amp # from the start # Another parameter that could be added would be the factor by which the amplitude will be amplified class Method(Enum): lsb_coding = 0 phase_coding = 1 def hide(cover_audio, emb_audio, method=Method.lsb_coding): #binary_cover_message_rate, binary_cover_message = load_wav_file_in_binary(cover_audio_file) # We have the covering audio file amps in binary format # We need to convert the embedded file into binary as well #binary_emb_message_rate, binary_emb_message = load_wav_file_in_binary(emb_audio_file) if method == Method.lsb_coding: stego = lsb_code(emb_audio, cover_audio) return stego def lsb_code(binary_emb_message, cover_message): # Binary manipulation # The LSB of each array entry in the amplitude array of the cover signal will be switched to comply with the ith # bit in the embedded signal (the mask_lsb function) # A suggested scheme would be to require that the cover audio be big enough (in time) to contain the embedded signal # For the library to be usable the first scheme is used with a warning raised for the user to enter a taller(in time # length) cover audio emb_message_bits_length = len(binary_emb_message) lsb_idx = 0 # Loop over all the bits in the binary_emb_message # print(len(binary_emb_message)) # print(0%cover_message.shape[0]) current_shape = cover_message.shape[0] for k in range(emb_message_bits_length): if (float(k) / float(current_shape)) > 1: lsb_idx += 1 current_shape = 2 * k idx = k % cover_message.shape[0] #print(idx) #print(cover_message[idx]) cover_message[idx] = hide_bit(binary_emb_message[k], cover_message[idx], lsb_idx) return cover_message def hide_bit(bit, word, bit_to_be_replaced_idx): #print(bit_to_be_replaced_idx) bit_to_be_replaced_value = mask_bit(bit_to_be_replaced_idx, word) #print(int(bit)) if int(bit): if not bit_to_be_replaced_value: # The bit to be replaced is zero and the bit to be hidden is one so we add the # the value of that bit in decimal to the value of the word word = word +(2 ** bit_to_be_replaced_idx) else: if bit_to_be_replaced_value: word = word - (2 ** bit_to_be_replaced_idx) return word def mask_bit(idx, message): masker = message & (1 << idx) masker = masker >> idx return masker def recover(stego_data, emb_msg_len): # cover_data is a string list of binary numbers chunk = 15 msg = '' #print(type(stego_data)) stego_len = len(stego_data) #x_i = stego_data[:, 15] # print(x_i) lsb_lvl = emb_msg_len // stego_len data = np.array([list(x) for x in stego_data]) # print("data shape ",data.shape) for i in range(lsb_lvl): msg = msg + ''.join(data[:, chunk-i]) # print(msg) rem = emb_msg_len % (stego_len) msg = msg + ''.join(data[:rem, chunk-lsb_lvl]) chunk = 16 msg_split = [msg[i: i + chunk] for i in range(0, len(msg), chunk)] # f = open("emb_msg_rec.txt", 'w') # for i in msg_split: # f.write(i + '\n') return msg_split
84645b7abedb4075451bf6bbfaf536bb6e41c84b
peelstnac/Employee-Management-System
/parsing.py
10,335
3.625
4
""" File containing relevant REPL/AST classes and methods. """ from typing import List, Any, Optional import graph def remove_whitespace(s: str) -> str: """ Remove whitespace from a string. >>> s = ' this is a string with whitespace ' >>> remove_whitespace(s) == 'thisisastringwithwhitespace' True """ return ''.join(s.split(' ')) def tokenize(s: str) -> List[str]: """ Tokenize a string by splitting on whitespace except when contained in ()'s. If there contains a balanced bracket, split it as well. >>> s = ' i want to tokenize (this string) ' >>> tokenize(s) == ['i', 'want', 'to', 'tokenize', '(this string)'] True """ tokens = [] medium = [] j = 0 for i in range(0, len(s)): if s[i] == '(': medium.append(s[j:i]) j = i if s[i] == ')': medium.append(s[j:i + 1]) j = i + 1 if j < len(s): medium.append(s[j:]) for x in medium: x = x.strip() if len(x) == 0: continue if x[0] == '(': tokens.append(x) else: tokens.extend(x.split(' ')) return tokens class Expr: """ Expression interface for AST. """ def evaluate(self) -> Any: """ Evaluate the expression. """ raise NotImplementedError class UnOp(Expr): """ Class representing an unary operator. Instance Attributes: - company: Underlying graph structure (in this case a tree) modelling the company - op: String denoting unary operator - right: Expression that operator is acting upon """ company: graph.Tree op: str right: Expr def __init__(self, company: graph.Tree, op: str, right: Expr) -> None: self.company = company self.op = op self.right = right def evaluate(self) -> Any: """ Evaluate unary operator. """ try: if self.op == 'BOSS': self.company.add_root(self.right.evaluate()) if self.op == 'DEMOTE': self.company.demote_vertex(self.right.evaluate().uid) if self.op == 'FIRE': self.company.delete_vertex(self.right.evaluate().uid) except AttributeError: pass class BinOp(Expr): """ Class representing binary operator. Instance Attributes: - company: Underlying graph structure (in this case a tree) modelling the company - left: Expression that operator is acting upon (first input) - op: String denoting unary operator - right: Expression that operator is acting upon (second input) """ company: graph.Tree left: Expr op: str right: Expr def __init__(self, company: graph.Tree, left: Expr, op: str, right: Expr) -> None: self.company = company self.left = left self.op = op self.right = right def evaluate(self) -> Any: """ Evaluate binary operator. """ if self.op == 'ADD': potentially_new = self.left.evaluate() if not self.company.has(potentially_new.uid): self.company.add_vertex(potentially_new) self.company.add_edge(potentially_new.uid, self.right.evaluate().uid) if self.op == 'RESOLVE': lca = self.company.lca(self.left.evaluate().uid, self.right.evaluate().uid) return str(Employee(self.company, str(lca)).evaluate().uid) if self.op == 'UPDATE': self.company.update_vertex_performance(self.left.evaluate().uid, self.right.evaluate()) class Employee(Expr): """ Class representing an Employee in the company. Instance Attributes: - company: Underlying graph structure modelling the company - token: Input token used to refer to employee """ company: graph.Tree token: str def __init__(self, company: graph.Tree, token: str) -> None: self.company = company self.token = token def evaluate(self) -> graph.Vertex: """ Evaluate employee. Should always evaluate to a Vertex object. """ if self.token.isdigit(): return self.company.get(int(self.token)) else: # In the form (name, performance), where performance optional self.token = remove_whitespace(self.token) self.token = self.token.lstrip('(').rstrip(')') tokens = self.token.split(',') if len(tokens) == 1: return graph.Vertex(tokens[0], self.company.next_uid) if len(tokens) == 2: return graph.Vertex(tokens[0], self.company.next_uid, int(tokens[1])) class Num(Expr): """ Class representing a number. Instance Attributes: - token: Input token to denote this number """ token: str def __init__(self, token: str) -> None: self.token = token def evaluate(self) -> Optional[int]: """ Evaluate number. """ if not self.token.isdigit(): print(self.token + ' is not a valid integer.') return return int(self.token) class REPL: """ REPL which allows the user to interact with the program. """ # Private Instance Attributes: # - _company: Underlying graph structure to represent _company # - _buffer: Input buffer that is yet to be tokenized # - _module: AST module _company: graph.Tree _buffer: str _module: List[Expr] def __init__(self, company: graph.Tree) -> None: self._company = company self._buffer = '' self._module = [] @property def next_word(self) -> str: """ Get next token from buffer. Does not remove token. """ tokens = self._buffer.split(' ') if len(tokens) == 0: return '' return tokens[0] @property def pop_next_word(self) -> str: """ Get next token from buffer. Removes token. """ tokens = self._buffer.split(' ') if len(tokens) == 0: return '' self._buffer = self._buffer[len(tokens[0]):] self._buffer = self._buffer.strip() return tokens[0] def evaluate(self) -> None: """ Evaluate string stored in self._buffer. """ # Ignore if empty if self._buffer == '': return # Clean the buffer self._buffer = self._buffer.strip() # Determine number of arguments each operator requires operators = { 'BOSS': 1, 'ADD': 2, 'UPDATE': 2, 'RESOLVE': 2, 'DEMOTE': 1, 'FIRE': 1, 'VISUALIZE': 0, } # Determine if return None return_none = { 'BOSS': True, 'ADD': True, 'UPDATE': True, 'RESOLVE': False, 'DEMOTE': True, 'FIRE': True, 'VISUALIZE': True } # Convert to Reverse Polish Notation tokens = tokenize(self._buffer) tokens.reverse() stack = [] for token in tokens: if token in operators: new_token = '' for _ in range(0, operators[token]): new_token += stack.pop() + ' ' new_token += token stack.append(new_token) else: stack.append(token) self._buffer = stack.pop() # Evaluate tokens = tokenize(self._buffer) for token in tokens: if token in operators: # Make a backup operands = [] for _ in range(0, operators[token]): operands.append(stack.pop()) operands.reverse() if operators[token] == 0: if token == 'VISUALIZE': self._company.visualize_graph() if operators[token] == 1: expr = UnOp(self._company, token, Employee(self._company, operands[0])) if return_none[token]: expr.evaluate() else: stack.append(expr.evaluate()) if operators[token] == 2: expr = BinOp(self._company, Employee(self._company, operands[0]), token, Employee(self._company, operands[1])) # Handle the only exception if token == 'UPDATE': expr = BinOp(self._company, Employee(self._company, operands[0]), token, Num(operands[1])) if return_none[token]: expr.evaluate() else: stack.append(expr.evaluate()) else: stack.append(token) def start(self) -> None: """ Start the REPL. """ while True: line = input('BONE: ').split(' ') for i in range(0, len(line)): token = line[i] if token == 'QUIT': return if token == 'END': # This try except block is to allow # graph.py to print the errors and for # the REPL to not choke on an error try: self.evaluate() for expr in self._module: expr.evaluate() except KeyError: pass finally: self._buffer = '' self._module = [] continue self._buffer += token + ' ' if __name__ == '__main__': import doctest import python_ta doctest.testmod(verbose=True) python_ta.check_all(config={ 'max-line-length': 1000, # E9998 for IO, W0702 for try/except, E1136 R1710 for Optional[] typing, 'disable': ['E9998', 'W0702', 'E1136', 'R1710'], 'extra-imports': ['graph'], 'max-nested-blocks': 6, 'max-branches': 20 })
bd051c385037c91db25f3560462a10f190f64096
harrytsz/JianZhiOffer
/SourceCode/面试题51:数组中重复的数字3.py
736
3.90625
4
#数组中重复的数字 Edition3 # in [] def duplicate(numbers, length, duplication): if numbers == None or length <= 0: return False for item in numbers: if item < 0 or item > length - 1: return False container = [] for i in range(length): if numbers[i] in container: duplication.append(numbers[i]) else: container.append(numbers[i]) return duplication if __name__=="__main__": numbers = [2, 3, 1, 0, 2, 5, 3] length = 7 duplication = [] result = duplicate(numbers, length, duplication) if result != None: print(duplication) else: print("No Duplicate Elements!!!")
a33460b7c4d575a7bc09d59bda1c9a75111ed3ae
TheBillusBillus/snek
/taking inputs.py
631
4.375
4
#how to take different types of inputs #strings #intigers #and floats print("*******************************") print("welcome to my example program") print("*******************************") #used input function to take input name = input("what is your name? ") print ("welcome",name) age = input("how old are you? ")#all inputs are considered to be strings print ("you are "+age+" years old")#age is an integer, not a string #comp. can not calculate integers #strings must be converted to integers before being calculated int_age = int(age) int_age5 = (int_age)+5 age5 = str (int_age5) print = ("you will be "+age5+" in 5 years")
a145fd47a8b0dab28b442d2b60f6b058791c64b9
KistVictor/exercicios
/exercicios de python/Mundo Python/011.py
229
3.796875
4
altura = float(input('Qual a altura da parede? ')) largura = float(input('Qual a largura da parede? ')) area = altura*largura litros = area/2 print('A área da parede é {}\nPrecisa-se de {} litros de tinta'.format(area, litros))
1a731280980c7ca76e12e0629aec4e7b30717ebb
Wanghongkua/Leetcode-Python
/Archive/283_Move_Zeroes.py
1,697
3.609375
4
from typing import List class Solution: def moveZeroes(self, nums: List[int]) -> None: """ using array rotation in reversed method """ # def reverse(nums): # start = 0 # end = len(nums) - 1 # while end > start: # nums[end], nums[start] = nums[start], nums[end] # start += 1 # end -= 1 # return nums # count = 0 # previous = None # for index in range(len(nums)): # if nums[index] == 0: # count += 1 # if count == 1: # previous = index # continue # tmp = reverse(nums[previous:index]) # tmp[0:len(tmp)-count+1] = reverse(tmp[0:len(tmp)-count+1]) # nums[previous:index] = tmp # previous = index - count + 1 # if previous is not None and nums[previous] == 0 and count > 0: # tmp = reverse(nums[previous:index+1]) # tmp[0:len(tmp)-count] = reverse(tmp[0:len(tmp)-count]) # nums[previous:index+1] = tmp """ Try to be fast using two pointer """ count = 0 for index in range(len(nums)): value = nums[index] if value == 0: count += 1 continue if count and value: nums[index-count] = value index = len(nums) - 1 for i in range(count): nums[index - i] = 0 print(nums) if __name__ == '__main__': test = Solution() test.moveZeroes([4, 2, 4, 0, 0, 3, 0, 5, 1, 0])
f772614e8bc44d07ac8c2d4de38fb16302275776
skypea/pgmpy
/pgmpy/utils/state_name.py
7,418
3.828125
4
""" The file contains decorators to manage the user defined variable state names. It maps the internal representaion of the varibale states to the user defined state names and vice versa. """ class StateNameInit(): """ The class behaves as a decorator for __init__ methods. It adds a dictionary as an attribute to the various classes where mapping is required for the variable state names. The dictionary has the following format - {'x1': ['on', 'off']} where, 'x1' is a variable and 'on', 'off' are its correspinding states. Example ------- >>> import numpy as np >>> from pgmpy.factors import Factor >>> sn = {'speed': ['low', 'medium', 'high'], ... 'switch': ['on', 'off'], ... 'time': ['day', 'night']} >>> phi = Factor(['speed', 'switch', 'time'], ... [3, 2, 2], np.ones(12), state_names=sn) >>> print(phi.state_names) {'speed': ['low', 'medium', 'high'], 'switch': ['on', 'off'], 'time': ['day', 'night']} """ def __call__(self, f): def wrapper(*args, **kwargs): # Case, when no state names dict is provided. if 'state_names' not in kwargs: # args[0] represents the self parameter of the __init__ method args[0].state_names = None else: args[0].state_names = kwargs['state_names'] del kwargs['state_names'] f(*args, **kwargs) return wrapper class StateNameDecorator(): """ This class behaves as a decorator for the various methods that can use variable state names either in input parameters or in return values. Parameters ---------- argument: string or None The parameter that needs to be wrapped. None, if no parameter is to be wrapped. return_val: boolean True if the return value needs to be wrapped else False. """ def __init__(self, argument, return_val): self.arg = argument self.return_val = return_val self.state_names = None self.arg_formats = [self.is_list_of_states, self.is_list_of_list_of_states, self.is_dict_of_states] def is_list_of_states(self, arg): """ A list of states example - [('x1', 'easy'), ('x2', 'hard')] Returns ------- True, if arg is a list of states else False. """ return isinstance(arg, list) and all(isinstance(i, tuple) for i in arg) def is_list_of_list_of_states(self, arg): """ A list of list of states example - [[('x1', 'easy'), ('x2', 'hard')], [('x1', 'hard'), ('x2', 'medium')]] Returns ------- True, if arg is a list of list of states else False. """ if arg is None: return False return all([isinstance(arg, list), all(isinstance(i, list) for i in arg), all((isinstance(i, tuple) for i in lst) for lst in arg)]) def is_dict_of_states(self, arg): """ A dict of states example - {'x1': 'easy', 'x2':'hard', 'x3': 'medium'} Returns ------- True, if arg is dict of states else False. """ return isinstance(arg, dict) def get_mapped_value(self, arg_val): for arg_format in self.arg_formats: if arg_format(arg_val): return self.map_states(arg_val, arg_format) return None def map_states(self, arg_val, arg_format): if arg_format == self.is_list_of_states: if not isinstance(arg_val[0][1], str): # If the input parameter is consistent with the internal # state names architecture if not self.return_val: return arg_val else: return [(var, self.state_names[var][state]) for var, state in arg_val] else: return [(var, self.state_names[var].index(state)) for var, state in arg_val] if arg_format == self.is_list_of_list_of_states: if not isinstance(arg_val[0][0][1], str): # If the input parameter is consistent with the internal # state names architecture if not self.return_val: return arg_val else: mapped_arg_val = [] for elem in arg_val: mapped_elem = [(var, self.state_names[var][state]) for var, state in elem] mapped_arg_val.append(mapped_elem) else: mapped_arg_val = [] for elem in arg_val: mapped_elem = [(var, self.state_names[var].index(state)) for var, state in elem] mapped_arg_val.append(mapped_elem) return mapped_arg_val if arg_format == self.is_dict_of_states: if not any([isinstance(i, str) for i in arg_val.values()]): # If the input parameter is consistent with the internal # state names architecture if not self.return_val: return arg_val else: for var in arg_val: arg_val[var] = self.state_names[var][arg_val[var]] else: for var in arg_val: arg_val[var] = self.state_names[var].index(arg_val[var]) return arg_val def __call__(self, f): def wrapper(*args, **kwargs): # args[0] represents the self parameter of the __init__ method method_self = args[0] if not method_self.state_names: return f(*args, **kwargs) else: self.state_names = method_self.state_names if self.arg and not self.return_val: # If input parameters are in kwargs format if self.arg in kwargs: arg_val = kwargs[self.arg] kwargs[self.arg] = self.get_mapped_value(arg_val) return f(*args, **kwargs) # If input parameters are in args format else: for arg_val in args[1:]: mapped_arg_val = self.get_mapped_value(arg_val) if mapped_arg_val: mapped_args = list(args) mapped_args[args.index(arg_val)] = mapped_arg_val return f(*mapped_args, **kwargs) elif not self.arg and self.return_val: return_val = f(*args, **kwargs) mapped_return_val = self.get_mapped_value(return_val) # If the function returns only one output if mapped_return_val: return mapped_return_val # If the function returns more than one output. for ret_val in list(return_val): mapped_ret_val = self.get_mapped_value(ret_val) if ret_val: return_val[return_val.index(ret_val)] = mapped_ret_val return return_val return wrapper
9b15b9a71a2f7eb1e40993d24aeaa1ebe3617564
the-deep/DEEPL
/helpers/data_structures.py
3,185
3.8125
4
""" Collection of data structures """ class TrieNode: def __init__(self, val): self.value = val self.children = {} class Trie: def __init__(self): self.root = TrieNode(None) self.items_count = 0 def insert(self, iterable, value=None, parent=None): if len(iterable) == 0: # TODO: do something clever raise Exception("can't send empty item") if parent is None: parent = self.root if len(iterable) == 1: parent.children[iterable[0]] = TrieNode(value) return if parent.children.get(iterable[0]) is None: parent.children[iterable[0]] = TrieNode(None) self.insert(iterable[1:], value, parent.children[iterable[0]]) def preorder(self, node): lst = [] if node is None: return [] lst.append(node.value) children = node.children childkeys = list(children.keys()) if len(childkeys) == 0: rightmost = None leftones = [] elif len(childkeys) == 1: rightmost = None leftones = childkeys[0] else: rightmost = children[childkeys[-1]] leftones = childkeys[:-1] print(leftones) for each in leftones: lst.append(self.preorder(node.children[each])) lst.extend(self.preorder(rightmost)) return lst def __str__(self): return "Not yet implemented" class DictWithCounter(dict): def __init__(self, *args, **kwargs): self.__count = 0 super().__init__(*args, **kwargs) def __setitem__(self, key, value): if not self.get(key): self.__count += 1 super().__setitem__(key, value) @property def count(self): return self.__count # TODO: implement __delitem__ to reduce count class Node: def __init__(self, val): self.value = val self.left = None self.right = None class TreeWithNodeCounts: def __init__(self): self.nodes_count = 0 self.root = None def _insert_right(self, value, compareNode): if compareNode.right is None: compareNode.right = Node((value, self.nodes_count)) self.nodes_count += 1 return else: return self.insert(value, compareNode.right) def _insert_left(self, value, compareNode): if compareNode.left is None: compareNode.left = Node((value, self.nodes_count)) self.nodes_count += 1 return else: return self.insert(value, compareNode.left) def insert(self, value, compareNode=None): if not compareNode and self.root is None: self.root = Node((value, self.nodes_count)) self.nodes_count += 1 return elif not compareNode and self.root: return self.insert(value, self.root) else: # compareNode present if value >= compareNode.value[0]: return self._insert_right(value, compareNode) else: return self._insert_left(value, compareNode)
7b63a4114ee68205d25f79700ae4107544137c11
SethDeVries/My-Project-Euler
/Python/Problem007.py
296
3.90625
4
# Maximum value of the prime n = int(input("What number should I go up to? ")) # The prime p = 2 # The number of the prime x = 0 for p in range(2, n+1): for i in range(2, p): if p % i == 0: break else: x +=1 print ("#", x, "->",100 p), print ("Done")
61b67a543f0341e8f079f1e570901425d078fd5c
JoaoVarela1/Jo-oV
/Aula.py
482
3.65625
4
País=["Brasil","Holanda","Espanha","França"] print(País) del País[1] print(País) País.append("Argentina") print(País) País.remove("Brasil") print(País) País.sort() print(País) País=["Brasil","Holanda","Espanha","França"] País2=sorted(País) print(País) print(País2) País=["Brasil","Holanda","Espanha","França"] País.reverse() print(País) País=["Brasil","Holanda","Espanha","França","Luxembourg","Belgica"] print(len(País))
d6a8ebafc2c9f212147ac84bec4bc9da0c9f76fd
Cruzader20/ProjectEuler
/problem10.py
683
3.671875
4
""" rasul silva Project Euler problem 10 """ def is_prime(num): if num == 0 or num == 1: return False if num % 2 == 0: return False for value in range(2,int(num**.5) + 1): if num % value == 0: return False return True def generate_prime_list(range_top): primes = [2] for i in range(2,range_top+1): if (is_prime(i)): primes.append(i) return primes def sum_up_list(input_list): list_sum = 0 for item in input_list: list_sum = list_sum + item return list_sum if __name__ == "__main__": print(sum_up_list(generate_prime_list(1999999))) # answer is 142913828922
421b8376457f9d86e3315f6d4fa6337cd3dbe41c
arya-pv/pythonjuly2021
/flow_of_controls/conditional_statements/if_else.py
218
4.1875
4
#..if..else.. # a=int(input("enter the number")) # if a>0: # print("hi") # else: # print("hello") a=int(input("enter the number")) if a>0: print("number is positive") else: print("number is negative")
a4a27faec0a3389a1c8d974dcff05de86ad07d9e
JonNData/Python-Skills
/fundamentals/sumdiff.py
910
3.546875
4
import random """ find all a, b, c, d in q such that f(a) + f(b) = f(c) - f(d) """ #q = set(range(1, 10)) q = set(range(1, 200)) # q = (1, 3, 4, 7, 12) def f(x): return x * 4 + 6 # Your code here matches = [] # nest for loops for every combination of a and b, # them pick c and d to match? potential_lefts = {} for a in q: for b in q: potential_lefts[(f(a) + f(b))] = (a, b) # key is sum, value is index potential_rights = {} for c in q: for d in q: potential_rights[(f(c) - f(d))] = (c, d)# key is diff, val is index for ab in potential_lefts: if ab in potential_rights: left_indexes = potential_lefts[ab] right_indexes = potential_rights[ab] matches.append(left_indexes) matches.append(right_indexes) print(matches) # lesson learned: the thing you want to search quickly should be set to the keys
07ea7521b9a3e4569bed9a8d58f0caa0d45469f1
Dynamitelaw/UDC7pAPxtknuBxa8
/StockSelectionInterface.py
2,084
4.34375
4
''' Dynamitelaw Standard interface for selecting stocks to buy and sell. All selectors MUST be compatible with the methods included in this class. ''' from abc import ABC,abstractmethod class stockSelector(ABC): def __init__ (self, genericParams=[]): ''' selecetorName must be a string denoting which selector type to use. genericParams is a list where you pass the arguments needed by the constructor of your specified selector. ''' self.minimumPurchase = 2500 self.name = self.getName() #NOTE you must define a self.name attribute in your selector. It's used by the simulator @abstractmethod def selectStocksToBuy(self, maxNumberOfStocks, date=False, customTickerList=False, genricParameters=[]): ''' Selects which stocks to buy, and the proportion of funds to be allocated to each. maximumNumberOfStocks is the highest number of stocks the caller wants to select. Passing a date parameter will select stocks for the given date. Ommitting it will select stocks based on realtime data. Passing a customTickerList will only analyze tickers included in that list. Returns a list of in the following format: [ [Ticker1, RatioOfFundAllocation1], [Ticker2, RatioOfFundAllocation2], ... ] . All ratios must add up to 1. ''' @abstractmethod def selectStocksToSell(self, listOfOwnedStocks, date=False, genricParameters=[]): ''' Selects which stocks to sell. Passing a date parameter will select stocks for the given date. Ommitting it will select stocks based on realtime data. Returns a list of stocks to sell. ''' @abstractmethod def getName(self): ''' Returns the name of the selector ''' def numberOfStocksToBuy(self, funds): ''' Returns how many stocks you should buy based on your availible funds. ''' return (int(funds/self.minimumPurchase))
ba8cfaca435b6ea8d9243f3709d6cbee741c5843
562350782/simple
/ex/ex1_improve.py
2,000
3.578125
4
import IterativeSolution import Initialization import numpy as np "长度为1m,横截面积为0.01m2的圆柱型金属棒,一端横截面露出,其余部分被厚的绝热橡胶层包裹。金属棒表面均匀缠绕着热电阻丝,热电阻丝的发热总功率为20W" "将横截面露出的一端放入100℃沸腾的水池中,已知该金属材料的导热系数平均为 5w/mk,放置很长时间后求解金属棒的温度分布" "------------------------------------------Initialization--------------------------------------------------------------" lamda= 5 S=2000 n=50 l=1 detax=l/n print(detax) A = np.zeros((50, 50)) B = np.zeros((50, 1)) T = np.zeros((50, 1)) "------------------------------------------Iterative_Solution----------------------------------------------------------" # def solution(x,A,B,lamda,detax,S): for j in range(50000): for i in range(n): if i == 0: A[i, i + 1] = lamda / detax A[i, i] = 3 * lamda / detax B[i, 0] = S*detax + 200 * lamda / detax T[i, 0] = (B[i, 0] + A[i, i + 1]*T[i + 1, 0])/A[i, i] # print(A) if i == n-1: A[i, i] = lamda / detax A[i, i - 1] = lamda / detax B[i, 0] = S*detax T[i, 0] = (B[i, 0] + A[i, i - 1]*T[i - 1, 0])/A[i, i] # print(T[i, 0]) if i != 0 and i != n - 1: A[i, i] = 2 * lamda/detax A[i, i - 1] = lamda/detax A[i, i + 1] = lamda/detax B[i, 0] = S*detax T[i, 0] = (B[i, 0] + A[i, i-1]*T[i-1, 0] + A[i, i+1]*T[i+1, 0])/A[i, i] print(T) "------------------------------------------main--------------------------------------------------------------" # result = solution(x,A,B,lamda,detax,S) # slove = IterativeSolution.solution(Initialization.n, Initialization.lamda, Initialization.detax, # Initialization.T0, Initialization.A, Initialization.B, Initialization.S) # print(slove)
f95aed5af52e68d1c22fa3bd6a6be75f5ce90fca
jjbskir/AirPollutants
/src/Validation.py
4,012
3.53125
4
from PyQt4 import QtGui ''' Used for validating user inputs. ''' class Validation: # string containing the error. errors = [] ''' Called when ever a error is made. Adds the error message to a list. @param msg: Error message. string @return: False, indicating a error occured. boolean ''' def error(self, msg): self.errors.append(msg) return False ''' Used to get the errors from validation. When it is called it destroys the old errors and returns them. @return: list of errors. list(string) ''' def getErrors(self): oldErrors = self.errors self.errors = [] return oldErrors ''' Validate title. @param title: Title to validate. Must be less then or equal to 8 characters. string @return: True if no errors, false if title is greater then 8 characters, first character is not a letter, or the title has spaces. boolean ''' def title(self, title): alphabetL = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] alphabetU = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] if not title: self.error('Must enter a run title.') elif len(title) > 8: self.error('Title must be less than 9 characters.') elif title[0] not in alphabetL and title[0] not in alphabetU: self.error('Title`s first character must be letter.') elif ' ' in title: self.error('Title cannot contain spaces.') else: return True ''' Validate run codes. Make sure they selecetd a feed stock and harvest activity. @param run_codes: run codes to validate. list(string) @return: True if more then 0 run codes, false if no run codes were submitted. boolean ''' def runCodes(self, run_codes): if len(run_codes) > 0: return True else: return self.error('Must select a feed stock and activity.') ''' Validate fertilizer distribution. Must all be numbers and must sum up to 1. Or they can leave all the slots blank. @param fertDist: Fertilizer distribution the user enterd for 4 feedstocks. dict(string: list(string)) @return: True if criteria are met, false otherwise. boolean ''' def fertDist(self, fertDists): for fertDist in fertDists.values(): # if they don't enter anything, then return true. if not fertDist: return True # make sure all of the entries are numbers and sum to 1. sumDist = 0.0 try: for fert in fertDist: sumDist += float(fert) except: return self.error('Must enter a number for fertilizer distributions.') if sumDist != 1: return self.error('Distribion must sum to 1.') ''' Fertilizer validation. Should validate on it's own. Would only be set off it a bug occurs in the making of the fertilizer dictionary. @param fert: Dictionary of the four feedstocks and weather the model will account for them using fertilizers. dict(boolean) @return: True if all conditions are met, false otherswise. boolean. ''' def ferts(self, ferts): if len(ferts.values()) >= 6: return self.error('Fertilizer Error.') else: return True ''' Pesticide validation. Only to make sure pesticide dictionary was created. @param pestFeed: Pesticides name and weather it was clicked. dict(string) @return: True if conditions are met, false otherwise. boolean ''' def pest(self, pestFeed): if len(pestFeed.values()) >= 3: return self.error('Pesticide Error.') else: return True
e3a5c2ccbc3ca341d447be4f9b3024abdb4bc2d4
shivBshah/programming_practice
/Data Structures/SimplifyPath/solution.py
423
3.75
4
#use of stack def simplifyPath(path): directories = [] string_array = path.split("/") for s in string_array: if s != "" and s!= ".": if s == "..": if len(directories) != 0: directories.pop() else: directories.append(s) return "/" + "/".join(directories) def main(): print(simplifyPath("/home/a/./x/../b//c/")) main()
397bec61e5f6651b8d597ce7926b2488dc0ab0a0
Burbon13/Python
/Tidor/aha.py
570
3.625
4
dimensiune=int(input("Dati numar:")) def backRec(x, dim): el = -1 x.append(el) while (len(x) <= dim): x[-1] = el if consistent(x, dim): #if solution(x, dim): if(len(x) == dim): print(x) backRec(x, dim) el = 1 def consistent(x,dim): suma=0 for i in range(len(x)): suma+=x[i] if suma<0: return False return True def solution(x,dim): suma=0 for i in range(len(x)): suma+=x[i] return len(x)==dim and suma==0 backRec([],dimensiune)
d6741cfdeebeee96bc7d03117382e5076b58a125
VitaliiStorozh/Python_marathon_git
/4_sprint/Tasks/s4.3.py
1,277
3.90625
4
# Create a class Employee that will take a full name as argument, as well as a set of none, one or more keywords. # # Each instance should have a name and a lastname attributes plus one more attribute for each of the keywords, if any. # # Examples: # john = Employee("John Doe") # mary = Employee("Mary Major", salary=120000) # richard = Employee("Richard Roe", salary=110000, height=178) # giancarlo = Employee("Giancarlo Rossi", salary=115000, height=182, nationality="Italian") # mary.lastname ➞ "Major" # richard.height ➞ 178 # giancarlo.nationality ➞ "Italian" # john.name ➞ "John" class Employee(): def __init__(self,fullname, **kwargs): self.name = fullname.split(" ")[0] self.lastname = fullname.split(" ")[1] self.__dict__.update(kwargs) john = Employee('John Doe') print(john.lastname) mary = Employee('Mary Major', salary=120000) print(mary.salary) richard = Employee('Richard Roe', salary=110000, height=178) print(richard.salary) print(richard.height) giancarlo = Employee('Giancarlo Rossi', salary=115000, height=182, nationality='Italian') print(giancarlo.name) print(giancarlo.nationality) peng = Employee('Peng Zhu', salary=500000, height=185, nationality='Chinese', subordinates=[i.lastname for i in (john, mary, richard, giancarlo)]) print(peng.subordinates)
7537a805dac383dbe95f87e84cd3688cefd1a66e
ArthurChaigneau/dqn
/GroupOfBirds.py
1,597
3.953125
4
from random import choice from Bird import Bird class GroupOfBirds: """ Créer une ligne d'oiseau (obstacles) Le principe c'est que aléatoirement on va choisir un trou sur la hauteur de l'écran, on remplit la ligne verticale d'oiseau sauf au niveau du trou """ LENGTH_HOLE = 180 HEIGHT_BIRD = 90 WIDTH_BIRD = 85 def __init__(self, env, speed): self.birds = [] self.env = env self.speed = speed self.on_screen = True self.posYHole = choice(range(0, self.env.height - self.LENGTH_HOLE, self.LENGTH_HOLE)) # Choix du trou aléatoirement # Liste contenant toutes les positions y disponibles pour les oiseaux allThePositionPossible = [i for i in range(self.posYHole - self.HEIGHT_BIRD, - self.HEIGHT_BIRD // 2, - self.HEIGHT_BIRD)] + \ [i for i in range( self.posYHole + self.LENGTH_HOLE + 1, self.env.height, self.HEIGHT_BIRD)] for i in allThePositionPossible: if not (self.posYHole <= i <= self.posYHole + self.LENGTH_HOLE): self.birds.append(Bird(self.env, self.env.width + self.WIDTH_BIRD, i, self.speed)) def move(self) -> bool: """ Fait avancer tous les oiseaux :return: Retourne vrai si les oiseaux sont toujours sur l'écran près avoir avancé, faux sinon """ for bird in self.birds: bird.move() if bird.position[0][0] <= - self.WIDTH_BIRD: self.on_screen = False return self.on_screen
c1642f83650cf678037c8c50354174b85c5025cc
chudsonwr/python-examples
/4/example4.py
893
4.40625
4
# Ask the user which value they want to work out, distance covered or speed requireed. choice = input('To work out (D)istance enter \'d\'\nTo work out (S)peed enter \'s\'\n') # declare the variables but give them a null value, so that they can be operated on speed = None distance = None # Get the input for either distance or time depending on choice variable if choice.lower() == 'd': speed = int(input('Enter the speed: ')) elif choice.lower() == 's': distance = int(input('Enter the distance travelling: ')) else: print(f"Unrecognised option: '{choice}'") # Get the input for time as it's always required if speed or distance: time = int(input('Enter the time: ')) # Perform the relevant calculation if speed: distance = speed * time print(f"Distance covered: {distance}") elif distance: speed = distance / time print(f"Speed required: {speed}")
7a4da3886f56b2b151ffb84c25e5aba51fe99835
uhcho2020/uhcho2020
/[2021-10] 3rd/1676.py
193
3.640625
4
from math import factorial N = int(input()) fac_n = factorial(N) fac_n = str(fac_n) count = 0 for i in reversed(fac_n): if i == '0': count += 1 else: break print(count)
7025d619e8c67eabce9e44137eac20d54296c016
Herasymov/GoIT_solutions
/lesson9.2/third.py
639
3.984375
4
# class Node of binary tree class Node: def __init__(self, val, l=None, r=None): self.val = val self.left = l self.right = r def insertToNode(root, val): if not root: return Node(val) elif root.val <= val: root.right = insertToNode(root.right, val) else: root.left = insertToNode(root.left, val) return root values = [8, 3, 6, 10, 1, 14, 13, 4, 7] root = None for i in values: root =insertToNode(root, i) print(root.val) print(root.left.val, end=" ") print(root.right.val) print(root.left.left.val, end=" ") print(root.left.right.val, end=" ") print(root.right.right.val)
2ae1b6abb86bd7f9d2739411abea16c37b3d8be0
chenshl/py_study_demo
/Study_kaifaban/py_mofacanshu.py
704
3.8125
4
#!/usr/bin/python # coding:utf-8 # @author : csl # @date : 2018/04/22 22:24 # 魔法参数*args和**kwargs的用法 # *args可以捕获到所有的位置参数(非keyword参数);**kwargs可以捕获到所有的keywords参数 def args(f_arg, *args): print("first normal arg:", f_arg) for arg in args: print("another arg through *args:", arg) alist = [1, 'python1', 'helloworld1', 'test1'] atuple = (2, 'python2', 'helloworld2', 'test2') args(*alist) args(alist) args(*atuple) args(atuple) def kwargs(f_arg, **kwargs): print("NO:", f_arg) for k, w in kwargs.items(): print("%s == %s" % (k, w)) adict = {"name":"Jack", "sex":"Men", "age":"22"} kwargs(3, **adict)
1a8d108c1885a35f5c29e2ceeb6cd4ca993806dc
rogue0137/practice
/leetcode_python/easy/SOLVED-subtract-the-product-and-sum-of-digits-of-an-integer.py
783
3.765625
4
# 1281. Subtract the Product and Sum of Digits of an Integer # https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ class Solution: def subtractProductAndSum(self, n: int) -> int: n_as_list = [int(x) for x in str(n)] prod_of_digits = 1 for i in range(len(n_as_list)): prod_of_digits = prod_of_digits * n_as_list[i] sum_of_digits = sum(n_as_list) diff_btwn_prod_and_sum = prod_of_digits - sum_of_digits return diff_btwn_prod_and_sum # Runtime: 32 ms, faster than 46.62% of Python3 online submissions for Subtract the Product and Sum of Digits of an Integer. # Memory Usage: 13.7 MB, less than 75.18% of Python3 online submissions for Subtract the Product and Sum of Digits of an Integer.
85c7ab782e9a7fd2022f00760f51f972fa9e2c1a
MohdMazher23/PythonAssingment
/Day5/Max_list.py
413
4.3125
4
def max_list(list_value): """It is a funtion to find the highest value present in list""" value=max(list_value) print("THE MAXIMUM NO PRESENT IN LIST IS:" ,value) #creation a list and assinging values to id list_value=[90,40,50,60,77,98,43] #calling list funtion print(list_value) max_list(list_value) #output """ [90, 40, 50, 60, 77, 98, 43] THE MAXIMUM NO PRESENT IN LIST IS: 98 """
54fc2596708ebd8eea0d095942dd237cdf8e2538
amit8810/Python-programs
/python program 01/mygrade_marks.py
457
4.125
4
marks=int(input("enter the marks")) if(marks>=90 and marks<=100): print(" grade is excellent") elif(marks>=80 and marks<=90): print("grade is A") elif(marks>=70 and marks<=80): print("grade is B") elif(marks>=60 and marks<=70): print("grade is C") elif(marks>=50 and marks<=60): print("grade is D") elif(marks<=0 or marks<50): print("fail") else: print("please enter valid marks")
867b63a1084ecd32ac1d89e7b43d39913f579b4d
GGGGGarfield/Python_Study
/Python基础教程/Python训练营资料/Python基础训练营代码/01_basic/12-if_statement.py
2,039
3.515625
4
# coding: utf-8 # True/False # a = True # b = False # print type(a) # print type(b) # if False: # print 'success' # else: # print 'fail' # print 'finished' # a = 1 # b = 2 # if a == b: # print 'equal' # else: # print 'not equal' # username = raw_input(u'请输入用户名:'.encode('gbk')) # if username == 'zhiliao': # print u'恭喜!登录成功!' # else: # print u'抱歉,登录失败!' # blacklist = 'zhiliao' # username = raw_input(u'请输入用户名:'.encode('gbk')) # if username != 'zhiliao': # print u'您的用户是没有被加入到黑名单,可以正常使用' # else: # print u'您的用户被加入到黑名单,不能正常使用' # if username == 'zhiliao': # print u'您的用户被加入到黑名单,不能正常使用' # else: # print u'您的用户是没有被加入到黑名单,可以正常使用' # age = 17 # if age > 17: # print u'您可以进入到网吧了' # else: # print u'您年龄未满18岁,不能进入网吧' # age = 17 # if age < 18: # print u'您的年龄未满18岁,不能进入网吧' # else: # print u'您可以进入到网吧了' # age = 18 # if age >= 18: # print u'您可以进入到网吧了' # else: # print u'您的年龄未满18岁,不能进入网吧' # age = 18 # if age <= 17: # print u'您的年龄未满18岁,不能进入网吧' # else: # print u'您可以进入到网吧了' # x and y # 青年人的年龄划分:15-24 # age = raw_input(u'请您输入年龄:'.encode('gbk')) # age = int(age) # if age >= 15 and age <= 24: # print u'您是一个青年人' # else: # print u'您不是一个青年人' # age = raw_input(u'请您输入年龄:'.encode('gbk')) # age = int(age) # if age < 15 or age > 24: # print u'您不是一个青年人' # else: # print u'您是一个青年人' person1 = u'中国人' person2 = u'南非' # if person1 == u'中国人': # print u'可以上战舰' # else: # print u'不可以上战舰' if not person2 == u'中国人': print u'不可以上战舰' else: print u'可以上战舰'
d99085fb2cf4a4b7afbf736a2adea972f55fb7a5
Coderode/Python
/OOPS/init method.py
560
4.03125
4
#The __init__method #it is similar to constructors in c++ #it is run as soon as an object of a class is instantiated #useful to do any initialization you want to do with your object class Person: #init method or constructor def __init__(self,name='None'): #using bydefault name as none if not given during calling then it would result none self.name=name #any method #method-member function def fun1(self): print('Hello, my name is ',self.name) #using class p=Person('sandeep') #name as initial parameter of the class p.fun1() print(Person().fun1())
ea52e733e178170c254812aefe3acd81d33f4f25
AswiniSankar/OB-Python-Training
/Assignments/Day-2/p8.py
198
4.3125
4
# program to print the number of occurence of sub string in the given string mainstring = input("enter the main string") substring = input("enter the sub string") print(mainstring.count(substring))
5f7e810f56fb142f6d1ad68799dc8d4ef294785c
haripriya2703/KNN_Using_SmallWorldGraphs
/KNN_Classifier.py
1,155
3.71875
4
from KNN_Search import knn_search def knn_classifier(knn_graph, distance_metric, d, m, k): """ :param knn_graph: existing graph :param distance_metric: metric using which the nearest neighbors should be determined :param d: new data point :param m: number of searches to be performed :param k: number of neighbors to be searched for :return: predicted label for the data point based on k-nearest neighbors """ species_labels = ['Iris-setosa', 'Iris-virginica', 'Iris-versicolor'] labels_count = [0, 0, 0] # if data point is a vertex in the graph, get its neighbors from the adjacency list representation of the graph if d in knn_graph: return knn_graph[d].label # if data point is not a vertex, invoke knn_search to get neighbors neighbors = knn_search(knn_graph, distance_metric, d, m, k) for neighbor in neighbors: for i in range(3): if neighbor.label == species_labels[i]: labels_count[i] += 1 break label_index = labels_count.index(max(labels_count)) label = species_labels[label_index] return label_index, label
9e323728bba4374af6847d857bd3ce9a01f5f703
lillapulay/python-foundations
/return.py
621
4.34375
4
# Takes an integer and prints out its square # x = int(input("x: ")) # print(x * x) # Defining a function # Takes an input called n # In Python, we need to define the function prior to calling it, otherwise we get an error # It reads from top to bottom # def square(n): # return n * n # Using this function we can simplify the previous input method # x = int(input("x: ")) # print(square(x)) # Solution: # First defining the functions def main(): x = int(input("x: ")) print(square(x)) def square(n): return n * need # Then, calling the function # main() # Convention: if __name__ == "__main__": main()
87d53a3994f920ecb42f3a24b00b38fc7d1755c0
sumanth0892/Basic-Data-structures
/graphs.py
4,173
3.953125
4
import sys,heapq class Vertex: def __init__(self,n): #Each vertex will have a few characteristics self.name = n self.color = 'Black' self.previous = None #Set previous vertex to be none for now self.neighbours = {} self.distance = sys.maxsize def addNeighbour(self,v,weight): #Use this to add an edge to the graph if v not in self.neighbours: self.neighbours[v] = weight #Distance between two nodes return True class Graph: #A class to implement the graph vertices = {} def addVertex(self,vertex): if isinstance(vertex,Vertex) and vertex.name not in self.vertices: self.vertices[vertex.name] = vertex return True else: return False def addEdge(self,u,v,weight): #weight is the distance between two vertices #u and v are the names of the vertices if u in self.vertices and v in self.vertices: self.vertices[u].addNeighbour(v,weight) self.vertices[v].addNeighbour(u,weight) return True else: return False def resetGraph(self): #Resets the graph after applying an algorithm for v in self.vertices.keys(): if self.vertices[v].color != 'Black': self.vertices[v].color = 'Black' self.vertices[v].distance = sys.maxsize def dfs(self,vertex): #Depth First Search vertex.color = 'Red' #Mark as visited for v in vertex.neighbours: if self.vertices[v].color == 'Black': self.dfs(self.vertices[v]) vertex.color = 'Blue' def bfs(self,vertex): #Breadth first search used to find the shortest path vertex.distance = 0 vertex.color = 'Red' #Mark as visited Q = list() for v in vertex.neighbours: Q.append(v) self.vertices[v].distance = vertex.distance + vertex.neighbours[v] while len(Q): u = Q.pop(0) #Can be implemented with a heap data structure node_u = self.vertices[u] node_u.color = 'Red' #Mark as visited for v in node_u.neighbours: node_v = self.vertices[v] if node_v.color == 'Black': Q.append(v) #Rebuild the heap if unvisited if node_v.distance > node_u.distance + node_u.neighbours[v]: node_v.distance = node_u.distance + node_u.neighbours[v] def shortest(v,path): if v.previous: path.append(v.previous.name) shortest(v.previous,path) return def Djikstra(G,start): #Gets the shortest path from start to any vertex #This is together with the shortest() function written above #This is based on Breadth First search start.distance = 0 unvisitedQueue = [(G.vertices[v].distance,v) for v in G.vertices.keys()] heapq.heapify(unvisitedQueue) while len(unvisitedQueue): uv = heapq.heappop(unvisitedQueue) current = G.vertices[uv[1]] current.color = 'Red' #Mark as visited for next in current.neighbours: if G.vertices[next].color == 'Red': continue #Go to the next vertex in the heap if this is already visited newDist = current.distance + current.neighbours[next] if newDist < G.vertices[next].distance: G.vertices[next].distance = newDist G.vertices[next].previous = current #Set the previous vertex as the current vertex for the path while len(unvisitedQueue): heapq.heappop(unvisitedQueue) #pop every item #Rebuild the heap unvisitedQueue = [(G.vertices[v].distance,v) for v in G.vertices.keys() if G.vertices[v].color == 'Black'] heapq.heapify(unvisitedQueue) #Driving code for graph-based algorithms #Uncomment to test """ g = Graph() a = Vertex('a') b = Vertex('b') c = Vertex('c') d = Vertex('d') e = Vertex('e') f = Vertex('f') vertices = [a,b,c,d,e,f] for vertex in vertices: g.addVertex(vertex) g.addEdge('a', 'b', 7) g.addEdge('a', 'c', 9) g.addEdge('a', 'f', 14) g.addEdge('b', 'c', 10) g.addEdge('b', 'd', 15) g.addEdge('c', 'd', 11) g.addEdge('c', 'f', 2) g.addEdge('d', 'e', 6) g.addEdge('e', 'f', 9) for v in g.vertices: print(v) print(g.vertices[v].color) print(g.vertices[v].distance) print("\n") print("After doing a Breadth-First Search from Vertex A:") g.bfs(a) for v in g.vertices: print(v) print(g.vertices[v].color) print(g.vertices[v].distance) print("\n") #Reset the graph g.resetGraph() #Get the shortest path from a to d path = ['d'] #Rebuild from the end. Djikstra(g,a) shortest(d,path) print(path) """
154b92734fbf9f37cb90712f7f9d023296862654
MachineDragon/ReplaceVowelsWithG
/ReplaceVowelsWithg.py
271
3.921875
4
# function replaces vowels with the letter "g" def translate(phrase): new_word = "" for i in phrase: if i in "AEIOUaeiou": new_word += "g" else: new_word += i return new_word print(translate(input("enter a word: ")))
e7fd8aac55abd77ea96f67aaa59b689b9c7f4570
theovoss/BoggleSolver
/bogglesolver/load_english_dictionary.py
3,734
4.1875
4
#!/usr/bin/env python """Stores the dictionary in a linked list.""" from bogglesolver.twl06 import WORD_LIST from bogglesolver.twl06 import TEST_WORD_LIST class _dictnode: """ An element of the dictionary. Each element represents one letter in a word. Each element contains an array of potential next elements. This means that look-up time for a word depends only on the length of the word. It also means that if you have a partial word, all potential endings are further down the tree. """ def __init__(self): self.letters = {} self.word = "" def add_letter(self, word, index, word_len): """ Add a word letter by letter to the tree. :param str word: word that should be added. :param str index: current index for the letter to add. """ if word_len > index: if word[index] in self.letters.keys(): self.letters[word[index]].add_letter(word, index + 1, word_len) else: self.letters[word[index]] = _dictnode() self.letters[word[index]].add_letter(word, index + 1, word_len) else: self.word = word class Edict: """ The interface for the dictionary. Contains the root element of the dictionary. Contains helpful functions for creating, adding to, and accessing the dictionary elements. """ def __init__(self): self.dictionary_root = _dictnode() def read_dictionary(self, use_test_words=False): """ Read in the list of valid words and add them to the dictionary. :param bool use_test_words: whether to use the test words or actual words. """ words = None if use_test_words: words = TEST_WORD_LIST else: words = WORD_LIST for word in reversed(words): self.add_word(word.lower()) def is_word(self, word): """ Determine if a word is in the dictionary. Lookup in the dictionary is O(n) :param str word: word to look for in the dictionary. :returns: True if word is in dictionary. Otherwise False. """ node = self.get_last_node(self.dictionary_root, word.lower()) return node.word != "" if node else False def add_word(self, word): """ Add a word to the dictionary. This is for extending the dictionary. :param str word: word to add. """ self.dictionary_root.add_letter(word.lower(), 0, len(word)) def get_words(self, node, all_words=[]): # pylint: disable=W0102 """ Get all words from the specified node on down. If called with the root node passed in, returns all words in the dictionary. :param _dictnode node: node to get all words from. :param list all_words: list of all words found so far. :returns: all words from the node on down. """ for a_node in node.letters.keys(): all_words = self.get_words(node.letters[a_node], all_words) if node.word and node.word not in all_words: all_words.append(node.word) return all_words @staticmethod def get_last_node(node, letter): """ Determine if the letter provided is a valid path from the provided node. :param _dictnode node: node in the Edict. :param str letter: next letter. :returns: True if the node has a path for the given letter, False Otherwise """ for l in letter: if l not in node.letters.keys(): return None node = node.letters[l] return node
b8126cc93c76ed9206f18e443f6ee9f6d488fb3a
gustavogattino/Curso-em-Video-Python
/Mundo 2 - Basico/Aula12/aula12_desafio03.py
272
4.0625
4
"""Aula 12 - Desafio 03.""" n1 = int(input('Digite um valor: ')) n2 = int(input('Digite outro valor: ')) if n1 > n2: print('{} é maior que {}!'.format(n1, n2)) elif n2 > n1: print('{} é maior que {}!'.format(n2, n1)) else: print('Os valores são iguais.')
dd8164197b3e8f93784d0daa4f0050da614cd49c
tthtlc/turtle-graphics-explorer
/src/ellipse.py
427
3.640625
4
import math import turtle wn = turtle.Screen() wn.bgcolor('lightblue') PI=3.14 fred = turtle.Turtle() fred.speed(99999) fred.penup() steps=2*PI/360 R1=100 R2=50 i=0 angle=0 alpha=2*PI/8 beta=2*PI/8 while i < 360: y1 = R1*math.sin(angle+alpha)####+R1*math.sin(angle+beta) x1 = R2*math.cos(angle)####+R2*math.cos(angle) fred.goto(x1,y1) if (i==0): fred.pendown() angle += steps i+=1 wn.exitonclick()
a5cae9c3d4ae4d7d5f1aa4daa1ef837a64387fcc
emanoelmlsilva/Lista-IP
/exercicio03/exercicio15.py
377
3.578125
4
valor_reais = int(input('Valor em reais: ')) c = 100 l = 50 x = 10 v = 5 i = 1 resC = valor_reais/c valor_reais = valor_reais%c resL = valor_reais/l valor_reais = valor_reais%l resX = valor_reais/x valor_reais = valor_reais%x resV = valor_reais/v resI = valor_reais%v print('A quantidade de notas de 100 é %d, 50 é %d, 10 é %d, 5 é %d, 1 é %d'%(resC,resL,resX,resV,resI))
f0d96cbd6c2b0a090a9089c9794db74c885d4f89
gustavowl/Algorithms-Cormen
/Chapter07/quick_sort_recursive.py
1,990
4.3125
4
#The user will type a list separated by the character "space". The list will be stored in lst lst = [int(num) for num in input("Type the list. Elements are separated by space\n").split()] #prints the original list #print("The original list is: {}".format(lst)) #starts quick sort #print("\nQUICK SORT BEGIN\n") #the efficiency of quick sort depends on the chosen pivot. #For didactic reasons, an arbitrary pivot is chosen def order_pivot(lst, start, end): if (start < end): #verifies if not basis case pivot_pos = start #the first element is chosen as pivot for i in range (start + 1, end): if (lst[i] < lst[pivot_pos]): #then i-th element should be located at the left side of pivot. Swap if (i > pivot_pos + 1): #this means that the pivot_pos+1-th element should be located at #the right of the pivot; where it already is. Swap it with the i-th #element, that should be located at the left of the pivor aux = lst[pivot_pos + 1] lst[pivot_pos + 1] = lst[i] lst[i] = aux #because of the previous if, the element to be swapped with the pivot #is located right after it. aux = lst[pivot_pos + 1] lst[pivot_pos + 1] = lst[pivot_pos] lst[pivot_pos] = aux #now the pivot has moved one position to the right pivot_pos += 1 return pivot_pos #then start == end, i.e. basis case (one element) return start def quick_sort(lst, start, end): if (start < end): pivot_pos = order_pivot(lst, start, end) #pivot is already in the right position. All the elements to its left are #less than the pivot; and all elements to the right are greater or equal to it quick_sort(lst, start, pivot_pos) #sorts sublist at the left of the pivot quick_sort(lst, pivot_pos + 1, end) #sorts sublist at the right of the pivot #print("\nQUICK SORT END\n") #end of quick sort quick_sort(lst, 0, len(lst)) #prints sorted list print("The sorted list is: {}".format(lst)) f = open('output.txt', 'w') f.write(' '.join(map(str, lst)))
1eec2a5f0dd4cf98a1fa827813deaed9ee7af79f
abhinav-bapat/PythonPrac
/for_loop_example1.py
221
4.03125
4
# Write a program to add all the numbers of a list and print the result list1 =[10, 20, 30, 40, 50] sum = 0 for x in list1: sum = sum + x print(sum)
f9d131e93d0e1b0af2cd424d67c55aa5169c1959
manchenkoff/geekbrains-python-homework
/lesson04/task07.py
804
4.125
4
""" Реализовать генератор с помощью функции с ключевым словом ​yield,​ создающим очередное значение. При вызове функции должен создаваться объект-генератор. Функция должна вызываться следующим образом: f​or el in fact(n).​ Подсказка: факториал числа n — произведение чисел от 1 до n. Например, факториал четырёх 4! = 1 * 2 * 3 * 4 = 24. """ def fact(number: int): temp_result = 1 if number <= 0: yield temp_result for x in range(1, number + 1): temp_result *= x yield temp_result N = 4 for el in fact(N): print(el)
09054d28a59ecf6b845607b54c808909c884c6b7
Praharshinibujji/pythonprogrammer
/130.py
141
3.921875
4
num=int(raw_input()) reverse=0 while(num>0): remainder=num%10 reverse=reverse*10+remainder num=num//10 print reverse
e2577867074094d2550050e9d1a6612751eeace7
inaph/30DaysOfPython-inaph
/Day_03/Excercise03.py
1,624
4.03125
4
#age = 29 #height = 5.65 #cmplx = 1+5j #print(type(age)) #print(type(height)) #print(type(cmplx)) #base = int(input("Enter base: ")) #height = int(input("Enter height: ")) #area = print ("The area of triangle " , 0.5 * base * height) #side_a = int(input(" Enter side a: ")) #side_b = int(input(" Enter side b: ")) #side_c = int(input(" Enter side c: ")) #perimeter = print("Perimeter of the triangle ", side_a + side_b + side_c) #length = int(input("Enter the length of the rectangle ")) #breadth = int(input("Enter the breadth of the rectangle ")) #area_rectangle = print("Area of the Rectangle ", length * breadth ) #perimeter_rectangle = print("Perimeter of the Rectangle ", 2 * length * breadth ) #radius = int(input("Enter the radius of circle ")) #Area_circle = print("Area of Circle " , 3.14 * radius **2) #circum_of_circle = print("circumference of Circle ", 3.14 * 2 * radius) print (not(len("python") == len("jargon"))) print (("on" in 'python') and ("on" in 'jargon')) print ('jargon' in 'I hope this course is not full of jargon') print (not (("on" in 'python') and ("on" in 'dragon'))) print(type ('(float(len("python")))))')) print((type('10') == type(10))) print((int(9.8)) == 10) Hours = int(input("Enter Hours: ")) Rate = int(input("Enter rate per hour: ")) print("Your weekly earning is ", Hours * Rate ) age = int(input(" Enter number of years you have lived: ")) print("You have lived for ", age * 31536000 ) print("1 1 1 1 1") print("2 1 2 4 8") print("3 1 3 9 27") print("4 1 4 16 64") print("5 1 5 25 125") words8 = "I am enjoying this challenge. \nI just wonder what is next." print(words8)
ccf52c76638ac9197b48e3e61487fca7c11058ea
robertopc/urioj
/beginner/1001.py
155
3.5
4
#!/usr/bin/python3 # https://www.urionlinejudge.com.br/judge/pt/problems/view/1001 A = int(input()) B = int(input()) X = A + B print("X = {}".format(X))
74bbdd40c28ec27140de7fd44fdfb250d9e7957d
JasonSun/Misc
/Codeforces/61A.py
334
3.609375
4
r = '' # zip() built-in function # Using * operator to unzip for a, b in zip(raw_input(), raw_input()): if a != b: r += '1' else: r += '0' print r ''' s1 = raw_input() s2 = raw_input() s3 = '' for i in xrange(len(s1)): if s1[i] != s2[i]: s3 = s3 + '1' else: s3 = s3 + '0' print s3 '''
78cb7717811704b6f9e4c2c755dce601ac5de4b2
Markers/algorithm-problem-solving
/BLOCKGAME/cjm9236_BLOCKGAME.py
3,580
3.5625
4
# BLOCKGAME problem # Author: JeongminCha (cjm9236@me.com) cache = None strategy = [] L_block = [ [[0,0],[1,0],[1,1]], [[0,0],[0,1],[1,1]], [[0,0],[0,1],[-1,1]], [[0,0],[1,0],[0,1]] ] I_block = [ [[0,0],[1,0]], [[0,0],[0,1]] ] def initial_setting(): global strategy for row in range(5): for col in range(5): board = [0] # processing L block for shape in range(4): if L_available(board, row, col, shape): strategy.append(board[0]) L_pop(board, row, col, shape) # processing I block for shape in range(2): if I_available(board, row, col, shape): strategy.append(board[0]) I_pop(board, row, col, shape) def index(x, y): return int(2 ** (x + y*5)) def empty(board, x, y): if (x >= 0 and x < 5) and (y >= 0 and y < 5) and (board[0] & index(x,y)) == 0: return True else: return False # Checks if a 'L' block is available def L_available(board, p, q, shape): # Check the block can be put in the specified location. for i in range(3): x = q + L_block[shape][i][1] y = p + L_block[shape][i][0] if empty(board, x, y) is False: return False # Add the block (by OR operation) for i in range(3): x = q + L_block[shape][i][1] y = p + L_block[shape][i][0] board[0] |= index(x,y) return True # Checks if a 'I' block is available def I_available(board, p, q, shape): # Check the block can be put in the specified location. for i in range(2): x = q + I_block[shape][i][1] y = p + I_block[shape][i][0] if empty(board, x, y) is False: return False # Add the block (by OR operation) for i in range(2): x = q + I_block[shape][i][1] y = p + I_block[shape][i][0] board[0] |= index(x,y) return True # Pops the 'L' block def L_pop(board, p, q, shape): # Delete the block (by XOR operation) for i in range(3): x = q + L_block[shape][i][1] y = p + L_block[shape][i][0] board[0] ^= index(x,y) # Pops the 'I' block def I_pop(board, p, q, shape): # Delete the block (by XOR operation) for i in range(2): x = q + I_block[shape][i][1] y = p + I_block[shape][i][0] board[0] ^= index(x,y) # Returns True if there's a way to win in the current board condition. def check_winning_way(board): ret = cache[board[0]] if ret != -1: return ret ret = 0 # For every strategies about putting new block for new_block in strategy: # 1. new block is not overlapped with the existing blocks. # 2. failing is guranteed after the new block is added. if ((new_block & board[0]) == 0) and \ (check_winning_way([new_block | board[0]]) <= 0): ret = 1 break return ret # Returns the number meaning marked points in board def make_board(input): ret = 0 for row in range(5): for col in range(5): ret *= 2 if input[row][col] == '#': ret += 1 return ret if __name__ == "__main__": initial_setting() for _ in range(int(raw_input())): cache = [-1] * (2 ** 25) input = [] for _ in range(5): input.append(list(raw_input())) result = check_winning_way([make_board(input)]) if result > 0: print("WINNING") else: print("LOSING")
b65be1e6a9e4d24d460dcc9853019132bdb1f488
adamhammes/advent-of-code
/aoc_2021/lib.py
2,181
3.703125
4
import itertools import math import typing from typing import Iterable T = typing.TypeVar("T") def get_input(day: int) -> str: with open(f"inputs/day{day:02}.txt") as f: return f.read() def product(nums: Iterable[int]) -> int: p = 1 for n in nums: p *= n return p def window(seq: typing.Iterable[T], n=2) -> typing.Iterable[typing.Tuple[T]]: """Returns a sliding window (of width n) over data from the iterable s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... """ it = iter(seq) result = tuple(itertools.islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result class Point(typing.NamedTuple): x: int y: int def displace(self, dx, dy): return Point(self.x + dx, self.y + dy) directions4 = [[0, 1], [-1, 0], [1, 0], [0, -1]] def neighbors4(self) -> list["Point"]: return [self.displace(x, y) for x, y in self.directions4] # fmt: off directions8 = [ [-1, 1], [0, 1], [1, 1], [-1, 0], [1, 0], [-1, -1], [0, -1], [1, -1], ] # fmt: on def neighbors8(self) -> typing.List["Point"]: return [self.displace(x, y) for x, y in self.directions8] def manhattan_distance_to(self, p: "Point") -> int: dx, dy = p.x - self.x, p.y - self.y return abs(dx) + abs(dy) def times(self, n: int) -> "Point": return Point(self.x * n, self.y * n) def rotate(self, degrees: int) -> "Point": """ Rotate the point counter-clockwise around the origin the specified number of degrees. Resulting x/y coordinates will be rounded to the nearest integer. """ rads = math.radians(degrees) sin, cos = math.sin(rads), math.cos(rads) x = self.x * cos - self.y * sin y = self.x * sin + self.y * cos return Point(int(round(x)), int(round(y))) def parse_grid(raw: str) -> dict[Point, str]: points = {} for y, line in enumerate(raw.strip().splitlines()): for x, c in enumerate(line.strip()): points[Point(x, y)] = c return points
afa43e5492fab06a11935abedb24281ca8d0fedc
clementnduonyi/snbank
/back_site.py
4,120
3.8125
4
import json import os import random header= '-----Welcome to SNBANK Platform-----' print(header.upper()) def login_algorithm(): signed_in = False while True: try: login_action = input(str('Enter "login" to sign in/"close" to close the APP ')).lower() except ValueError: print('Invalid input') continue if login_action == 'close': print('App closed! Thank you.') quit() elif login_action == 'login': while not signed_in: username = str(input('Enter your registered username: ')) password = str(input('Enter your registered password: ')) with open('staff.txt') as file: user_details = json.load(file) for user in user_details: if user["Username"] == username and user["Password"] == password: signed_in = True print('Welcome! You are now signed in') break else: print('Wrong username and/password, Please try again') # Successfull sign in and read to carryout some banking operation if signed_in: is_done = False while not is_done: operation_choice = input('Press N to create a new bank A/C, C to check A/C details, L to logout ').upper() if operation_choice == 'N': print('Your are in New Acc creation environment') print('Personal Account Opening Form ') acc_name = str(input('Enter Acc name: ')).upper() opening_bal = str(input('Enter initial deposit amount: ')) acc_type = str(input('Enter Acc type ')) acc_email = str(input('Enter a valid email address ')) acc_number = "".join(str(random.randint(0, 9)) for i in range(10)) #Writting Custmers' details to the customer.txt file with open('customer.txt', 'w') as file: try: customer_data = json.load(file) except: customer_data = [] customer_data.append({ 'acc_number': acc_number, 'acc_name': acc_name, 'acc_type': acc_type, 'opening_bal': opening_bal, 'acc_email': acc_email, }) with open('customer.txt', 'w') as file: json.dump(customer_data, file) print(acc_number) elif operation_choice == 'C': #checking customers' account details customer_ban = str(input("Enter customers' acc number ")) with open('customer.txt', 'r') as file: customer_data = json.load(file) fetch = False for customer_data in customer_data: if customer_ban == customer_data['acc_number']: print('Account holder name: ', customer_data['acc_name']) print('Account Number: ', customer_data['acc_number']) print('Account type: ', customer_data['acc_type']) print('Account balance: ', customer_data['opening_bal']) print('Email address: ', customer_data['acc_email']) fetch = True if not fetch: print('Sorry no record found for this number. Try again') #Program terminated elif operation_choice == 'L': is_done = True print('You are now signed out. Thank you!') login_algorithm()
380348ed13c79da7bb488e361e79698486131b3f
yegeli/month1
/day14/skill_system.py
2,600
3.828125
4
""" 技能系统 封装:创建了DamageEffect、DizzinessEffect、LowerDeffenseEffect、SkillDeployer 继承:创建了SkillImpactEffect 隔离了SkillDeployer与具体技能影响的变化 多态:SkillDeployer调用SkillImpactEffect的impact方法 DamageEffect、DizzinessEffect、LowerDeffenseEffect重写SkillImpactEffect的impact方法 添加到SkillDeployer的都是重写后的impact 开闭原则:增加其他技能,只需要创建新类,SkillDeployer无需改变。 单一职责: SkillDeployer:技能释放器 DamageEffect:扣血技能 DizzinessEffect:眩晕技能 LowerDeffenseEffect:降低技能 依赖倒置:SkillDeployer 调用 SkillImpactEffect,没有调用具体技能效果类 组合复用:SkillDeployer 通过组合关系调用 技能效果 何处使用继承?何处使用组合? 继承:SkillImpactEffect 统一 DamageEffect、DizzinessEffect、LowerDeffenseEffect 组合:SkillDeployer 连接 技能效果 """ class SkillImpactEffect: def impact(self): pass class DamageEffect(SkillImpactEffect): def __init__(self, value=0): self.value = value def impact(self): print("扣你",self.value,"血量") class DizzinessEffect(SkillImpactEffect): def __init__(self, duration=0): self.duration = duration def impact(self): print("眩晕", self.duration, "秒") class LowerDeffenseEffect(SkillImpactEffect): def __init__(self, value=0,duration=0): self.duration = duration self.value = value def impact(self): super().impact() print("降低", self.duration, "防御力","持续", self.value, "秒") class SkillDeployer: def __init__(self, name=""): self.name = name self.__config_file = { "降龙十八掌":["DizzinessEffect(15)","DamageEffect(500)"], "六脉神剑":["LowerDeffenseEffect(100,10)","DamageEffect(500)"] } effect_names = self.__config_file[self.name] # "DizzinessEffect(15)" ----->DizzinessEffect(15) self.__effect_objects=[eval(item) for item in effect_names] # self.__effect_objects = [] # for item in effect_names: # self.__effect_objects.append(eval(item)) def deploy(self): print(self.name,"打死你") for item in self.__effect_objects: item.impact() xlsbz = SkillDeployer("降龙十八掌") xlsbz.deploy()
916ed052ed46238336cbd95773f9f02950200edc
Mayur-Debu/Datastructures
/Linked List/Basic/Exercise_3.py
1,850
4.1875
4
""" Create a method to delete any element from the linked list. """ class Node: def __init__(self, data=None, next=None): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def insertAtEnd(self, data): if self.head is None: self.head = Node(data, None) return else: iterator = self.head while iterator.next: iterator = iterator.next iterator.next = Node(data, None) def insertList(self, datalist): self.head = None for data in datalist: self.insertAtEnd(data) def lengthOfLinkedList(self): if self.head == None: print('Empty Linked List') else: count = 0 iterator = self.head while iterator: iterator = iterator.next count += 1 return count def removeElementAt(self, index): if index < 0 or index >= self.lengthOfLinkedList(): print('Invalid index number') elif index == 0: self.head = self.head.next else: iterator = self.head counter = 0 while iterator: if counter == index - 1: iterator.next = iterator.next.next iterator = iterator.next counter += 1 def print(self): if self.head is None: print('Empty Linked list') else: iterator = self.head while iterator: print(iterator.data, end=' --> ') iterator = iterator.next print(None) if __name__ == '__main__': ll = LinkedList() ll.insertList([1, 2, 3, 3, 4, 5]) ll.print() ll.removeElementAt(2) ll.print()
8810ab4c76e7c1f6a5053ec14b4935679869c91c
AlfonMnz/Python-1DAW-Programacion
/Ejercicios/Ejercicio 33.py
508
3.984375
4
'''Ejercicio 33. Escribe una función en la que le paso 2 puntos y te da la suma vectorial''' def punto(p1, p2): puntototal = p1[0] + p2[0], p1[1] + p2[1] return puntototal x1 = int(input('introduce la coordenada x del primer punto:\n')) y1 = int(input('introduce la coordenada y del primer punto:\n')) x2 = int(input('introduce la coordenada x del segundo punto:\n')) y2 = int(input('introduce la coordenada y del segundo punto:\n')) punto1 = x1, y1 punto2 = x2, y2 print(punto(punto1, punto2))
8ce37eadb03625a88363fbfe5d65dd08914af577
rafacab1/1daw-python-prog
/Primer Trimestre/04 Funciones/Ejercicios 20 a 28 (p. 148)/9_rota_izquierda_array_int.py
720
3.875
4
# -*- coding: utf-8 -*- from funciones.funciones2028 import * # Comprobación de 9_rota_izquierda_array_int print("Rota n posiciones a la izquierda los números de un array.") print("\nPrimero vamos a crear un array con enteros aleatorios...") n = int(input("Introduce la longitud del array: ")) minimo = int(input("Introduce el número mínimo a generar: ")) maximo = int(input("Introduce el número máximo a generar: ")) posiciones = int(input("\nIntroduce cuantas posiciones quieres rotar a la izquierda: ")) print("\nContenido del array") array = genera_array_int(n, minimo, maximo) print(array) print("\nContenido del array rotado") arrayrotiz = rota_izquierda_array_int(array, posiciones) print(arrayrotiz)
fdacb09e75b7b22ddf02d35ca1d9b84a6f49d167
roysegal11/Python
/Objct_exs/Bus.py
905
3.5625
4
class Bus(): def __init__(self, size): self.size = size self.num_of_passengers = 0 self.seats = ['free' for i in range(self.size)] def getOn(self, name): for i in range(self.size): if self.seats[i] == 'free': self.seats[i] = name self.num_of_passengers += 1 break else: print("the bus is full!") def getOff(self, name): for i in range(self.size): if self.seats[i] == name: self.seats[i] = 'free' self.num_of_passengers -= 1 break else: print(name + " is not on the bus!") def __str__(self): return f'size: {self.size} number of passengers: {self.num_of_passengers} seats: {self.seats}' bus = Bus(10) bus.getOn('aa') bus.getOn('bb') bus.getOff('aa') bus.getOn('cc') print(bus)
e6674bb5edadfbf78bb42f4e631f7d5d300a2806
meera-ramesh19/codewars
/homework/power-of-three.py
390
4.25
4
# This is my solution for AlgoDaily problem Power of Three # Located at https://algodaily.com/challenges/power-of-three def power_of_three(num): # fill in while(num>1): if(num%3==0): num=num//3; return True; else: break; return False; value=power_of_three(49); if value: print("power of 3"); else: print("not a power of 3");
51d447028f6aff329b4cbe758ec9c5923842f4a7
rafaelperazzo/programacao-web
/moodledata/vpl_data/27/usersdata/109/8514/submittedfiles/divisores.py
303
3.875
4
# -*- coding: utf-8 -*- from __future__ import division import math n=input('Digite o valor de n:') a=input('Digite o valor de a:') b=input('Digite o valor de b:') cont=0 x=1 while True: if (x%a)==0 or (x%b)==0: print x cont=cont+1 when cont==n: break x=x+1
8d5a61ddc62e0137254d7fe11f3307c38be85883
Tobias-rv/skole
/Python/Lab2/Oppgave4.py
234
3.8125
4
import math x = input("Skriv inn et tall:\n") y = input("Skriv inn enda et tall:\n") z = x + y y = y + x z = float(z) y = float(y) w = z * y w = math.sqrt(w) w = round(w, 2) print("Kvadrat roten av", y, "*", z, "=", w)
397fbcb970ee86e10326d3c9c0db1e57e6a611dd
shivaconceptsolution/PYTHON-12-01-Batch-Palasia
/pytraining/LoopExampleWithIfElse.py
189
4.03125
4
num = int(input("enter mobile number")) for i in range(1,11): a=num%10 num=num//10 if a%2!=0: print("square is ",a*a) print("cube is ",a*a*a)
5b4d656434311a73a5e34553c9e9588f4c8c88aa
JoshFowlkes/Sorting
/src/recursive_sorting/recursive_sorting.py
2,571
4.0625
4
# TO-DO: complete the helpe function below to merge 2 sorted arrays def merge( arrA, arrB ): elements = len( arrA ) + len( arrB ) merged_arr = [None] * elements a = 0 b = 0 for i in range(0, elements): if a >= len(arrA): merged_arr[i] = arrB[b] b += 1 elif b >= len(arrB): merged_arr[i] = arrA[a] a +=1 elif arrA[a] < arrB[b]: merged_arr[i] = arrA[a] a += 1 else: merged_arr[i] = arrB[b] b += 1 return merged_arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort( arr ): # TO-DO if len(arr) > 1: left = merge_sort(arr[0:len(arr) // 2]) right = merge_sort(arr[len(arr) // 2:]) arr = merge(left, right) return arr # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort( arr ): return arr ''' Class Notes on Recursion ''' def exponent(base, power): print(power) if power == 0: return 1 elif power == 1: return base return base * exponent(base, power-1) def exponent_iterative(base, power): total = base for i in range(power - 1): total *= base return total ''' Anything you can solve recursively, you can solve iteratively ''' # Quick Sort # 1. Pick a pivot and move it until everthing on the left is smaller, # everything on the right is greater # 2. REcursively quicksort the left half, then the right half '''def quicksort(arr): if len(arr) <= 1: return arr pivot = arr[-1] smaller = [] larger = [] for i in range(len(arr) - 1): element = arr[i] if element < pivot: smaller.append(element) else: # you have to TRUST that its returning the sorted list return quicksort(smaller) + [pivot] + quicksort(larger)''' def factorial(n): if n ==1: return 1 else: return n * factorial(n-1) def fib(n): print(f'calculating fib({n})') if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) cache = {0: 1, 1:1} def dynamic_fib(n): if n not in cache: cache[n] = dynamic_fib(n-1) + dynamic_fib(n-2) return cache[n]
83d2e85f1ccb46fb500e7848df0955e86d195cf4
djiang3/Battleship_Game
/Battleship.py
5,569
3.8125
4
# #Darrel Jiang #Professor Clair #CSCI 150 MTWF(9:00-9:50am) # #The main Battleship class. Initializes the game. # # from Board import * from Player import * from GraphicsManager import * class Battleship(): def __init__(self): """Creates a game of Battleship with either a human vs. human, human vs. computer, or computer vs. computer""" playing = True #Creates a list of player types, shows up on menu playertypenames=['Human','Computer'] #Initializes 2 lists of types of players for the menu selection, one is for the first selection and the other list is for the second selection. playertypes = [HumanPlayer(),ComputerPlayer()] othertypes = [HumanPlayer(), ComputerPlayer()] #Initializes the count needed to determine if a ship is sunk (Only for 2 players) a1 = 1 b1 = 1 s1 = 1 d1 = 1 p1 = 1 a2 = 1 b2 = 1 s2 = 1 d2 = 1 p2 = 1 #Initializes the value for turns turn = 1 #The main loop for the game of battleship. Initializes the required resources and allows for players to place ships. while playing: #The main menu that shows up when battleship is initialized. Closes after selections have been made. menu = GraphicsManager('skyblue3',1,1) p1type = menu.selectFromList('Select Player 1', playertypenames) p2type = menu.selectFromList('Select Player 2', playertypenames) menu.returnBoard().close() #Initializes the 2 players. player1 = playertypes[p1type] player2 = othertypes[p2type] #Initializes the graphics for the Ships Board and the Shots Board for both players. gShips1 = GraphicsManager() gShots1 = GraphicsManager('royalblue3') gShips2 = GraphicsManager() gShots2 = GraphicsManager('royalblue3') #Allows for both players to place their ships on the appropriate board. print 'Player 1, Please place your ships on your Ship Board (Battleship<1>)' player1.placeShips(gShips1) print 'Player 2, Please place your ships on your Ship Board (Battleship<3>)' player2.placeShips(gShips2) #Initializes the text based Ships Board and Shots Board for both players. It runs in the background of the game and cannot be seen by the players. p1ships = player1.getShipBoard() p1shots = player1.getShotBoard() p2ships = player2.getShipBoard() p2shots = player2.getShotBoard() over = False #Game loop that allows for players to fire onto boards until a player has no more ships while not over: #Allows for player 1 to choose a position to fire. print "Player 1's turn to fire, turn number: " + str(turn) player1.fire(p2ships,p1shots,gShips2,gShots1,gShips2) #---Checks if the shot sinks any of the opposing player's ships--- #Checks for the Aircraft Carrier if a1 > 0: if p2ships.isSunk(0): print "Player 2's Aircraft Carrier has been sunk!" a1 -= 1 #Checks for the Battleship if b1 > 0: if p2ships.isSunk(1): print "Player 2's Battleship has been sunk!" b1 -= 1 #Checks for the Submarine if s1 > 0: if p2ships.isSunk(2): print "Player 2's Submarine has been sunk!" s1 -= 1 #Checks for the Destroyer if d1 > 0: if p2ships.isSunk(3): print "Player 2's Destroyer has been sunk!" d1 -= 1 #Checks for the Patrol Boat if p1 > 0: if p2ships.isSunk(4): print "Player 2's Patrol Boat has been sunk!" p1 -= 1 #Checks if that shots sinks all of the last ship, if it does, the opposing player loses and the game ends if p2ships.lostGame(): result = 'Player 1 Wins!' #Displays the graphics that player 1 has won gShots1.displayResult(gShips1.returnBoard(),gShots2.returnBoard(),gShips2.returnBoard(),result) #Ends the game. over = True playing = False #Allows for player 2 to choose position to fire. print "Player 2's turn to fire, turn number: " + str(turn) player2.fire(p1ships,p2shots,gShips1,gShots2,gShips1) #---Checks if the shot sinks any of the opposing player's ships--- #Checks for the Aircraft Carrier if a2 > 0: if p1ships.isSunk(0): print "Player 1's Aircraft Carrier has been sunk!" a2 -= 1 #Checks for the Battleship if b2 > 0: if p1ships.isSunk(1): print "Player 1's Battleship has been sunk!" b2 -= 1 #Checks for the Submarine if s2 > 0: if p1ships.isSunk(2): print "Player 1's Submarine has been sunk!" s2 -= 1 #Checks for the Destroyer if d2 > 0: if p1ships.isSunk(3): print "Player 1's Destroyer has been sunk!" d2 -= 1 #Checks for the Patrol Boat if p2 > 0: if p1ships.isSunk(4): print "Player 1's Patrol Boat has been sunk!" p2 -= 1 turn += 1 #Checks if that shots sinks all of the last ship, if it does, the opposing player loses and the game ends. if p1ships.lostGame(): result = 'Player 2 Wins!' #Displays the graphics that player 1 has won gShots2.displayResult(gShips1.returnBoard(),gShots1.returnBoard(),gShips2.returnBoard(),result) #Ends the game. over = True playing = False if __name__ == '__main__': Battleship() """def player_select(): print 'Select PLayer' print '0) Human' print '1) Computer' player = None while not player: instr = raw_input('Please choose type of player: ') try: selection = int(instr) possible = [HumanPlayer(),ComputerPlayer()] player = possible[selection] except IndexError, ValueError: player = None return player Battleship(player_select(),player_select())"""
4506eca9b3b0caf2fb82f305e4e2049e85115ecb
smsxgz/euler_project
/problems/problems@201~700/problem_356/Largest_roots_of_cubic_polynomials.py
754
3.53125
4
mod = 10**8 K = 987654321 def matrix_mul(A, B): C = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for i in range(3): for j in range(3): for k in range(3): C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod return C def matrix_pow(A, k): R = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] while k: if k & 1: R = matrix_mul(R, A) k >>= 1 A = matrix_mul(A, A) return R def main(): res = 0 for i in range(1, 31): p = (2**i) % mod A = [[p, 0, -i % mod], [1, 0, 0], [0, 1, 0]] B = matrix_pow(A, K - 2) res += B[0][0] * p**2 % mod + B[0][1] * p % mod + B[0][2] * 3 % mod - 1 res %= mod print(res) if __name__ == '__main__': main()
3de6e3fa81cc12b31bc0bc51897a8202bc703a90
LeoVilelaRibeiro/opfpython
/opf.py
2,786
4.15625
4
# DEFINICOES DE CLASSES class Noh: """ Esta classe define o Nó de um grafo É instanciado com um identificador (String) e a classe pertencente """ def __init__(self, no_id, classe): self.no_id = no_id self.classe = classe self.dono = None self.distancia = 0 self.custo = 10000 self.estado = '' self.vizinhanca = [] self.foi_visitado = False def inserir_na_vizinhanca(self, adicionar): #Posso adicionar tanto um quanto uma lista de vizinhos self.vizinhanca.extend(adicionar) def print_noh(self): print(self) for colega in self.vizinhanca: print(colega) def __str__(self): return f"Nó {self.no_id} | Custo {self.custo} | Classe {self.classe}" class Colega: """ Esta classe define um vizinho que será adicionado a um Noh Recebe como parametro o No e o seu peso """ def __init__(self, noh, peso): self.noh = noh self.peso = peso self.e_melhor = False def __str__(self): if self.e_melhor: return f"Nó {self.noh.no_id}(Peso: {self.peso}) | PERTENCE AO CAMINHO MINIMO" else: return f"Nó {self.noh.no_id}(Peso: {self.peso})" # FUNCOES def get_menor_peso(coleguinhas): menor = coleguinhas[0] for colega in coleguinhas: if (not colega.noh.foi_visitado) and (menor.peso > colega.peso) : menor = colega return menor def get_menor_custo(noh_list): menor = noh_list[0] for noh in noh_list: if menor.custo > noh.custo: menor = noh return menor def add_amostra(noh_list): custos_list = [] print("Adicionando amostras de Teste") for noh in noh_list: peso = int(input(f'Qual o peso da aresta conectada a {noh.no_id}?')) if peso > noh.custo: custos_list.append(peso) else: custos_list.append(noh.custo) indice_menor = 0 for i, custo in enumerate(custos_list): if custos_list[indice_menor] > custo: indice_menor = i return noh_list[indice_menor].classe, custos_list[indice_menor] def get_melhores(grafo): nao_visitei = [] melhores = [] atual = grafo[0] ja_foi = 0 while ja_foi < len(grafo): atual.foi_visitado = True ja_foi += 1 for colega in atual.vizinhanca: if not colega.noh.foi_visitado: nao_visitei.append(colega) menor_peso = get_menor_peso(nao_visitei) menor_peso.e_melhor = True melhores.append((atual, menor_peso)) atual = menor_peso.noh ultimo = melhores[-1] melhores.append((ultimo[1].noh, None)) return melhores
cd52262c9fe8c8690741b41dff4c1eac9fd5e2ac
jeongyongwon/Algo_Coding
/swexpert/모음이보이지않는사람.py
312
3.625
4
import sys sys.stdin = open( '모음이보이지않는사람.txt' , 'r') T = int(input()) for t in range(T): text_ = input() vowels = ['a','e','i','o','u'] result = '' for i in range(len(text_)): if text_[i] not in vowels : result += text_[i] print(f'#{t+1} {result}')
1dfdcd03126a40b85e831ddd2df529eb91df1fd2
Gilbert-Gb-Li/Artificial-Intelligence
/f4_func_model/dataset_process/data_split.py
972
3.5625
4
from __future__ import print_function from sklearn.model_selection import train_test_split """============= 数据集切分 ================""" def dataset_split(X, y): """ 2. 可以调用sklearn里的数据切分函数: 参数: train_data:被划分的样本特征集 train_target:被划分的样本标签 test_size:如果是浮点数,在0-1之间,表示样本占比;如果是整数的话就是样本的数量 random_state:是随机数的种子。 返回numpy数组 """ X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, test_size=0.3, random_state=4) return X_train, X_test, y_train, y_test def manual_split(X, y): n_samples = len(X) X_train = X[:int(.9 * n_samples)] y_train = y[:int(.9 * n_samples)] X_test = X[int(.9 * n_samples):] y_test = y[int(.9 * n_samples):] return X_train, y_train, X_test, y_test
431ffdbf919d3e1ed63eb2a61ab926e5dbfe8855
shoark7/second-accountbook
/apis/help_method.py
1,399
3.59375
4
""" This file defines some helper methods for the project. It's simple. """ from datetime import datetime, date import os TODAY = datetime.today() YEAR = TODAY.year MONTH = TODAY.month DAY = TODAY.day ALL_MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] def get_weekday(year=YEAR, month=MONTH, day=DAY): """Use datetime.today to get weekday in Korean.""" WEEKDAY = ['월', '화', '수', '목', '금', '토', '일'] DATE = date(year, month, day) return WEEKDAY[DATE.weekday()] def get_month_name(month=MONTH): """Get month's full name in English""" return ALL_MONTH_NAMES[month-1] def get_path_day(year, month, day): path = os.path.join('Accountbook_project/Accountbook/dataset/{year}/{month:02}/{day:02}.json'.format( year=year, month=month, day=day) ) return path def get_path_month(year=YEAR, month=MONTH): path = os.path.join('Accountbook_project/Accountbook/dataset/{year}/{month:02}'.format( year=year, month=month, )) return path def get_path_year(year=YEAR): path = os.path.join('Accountbook_project/Accountbook/dataset/{year}'.format(year=year)) return path def max_expenditure_length(wanted_list): return len('{:,}'.format(max(wanted_list))) + 1
ae89cb878ed144d0038a33ad92d4fc0002002e72
SHE-43/Scraper-First-
/OurFirstScraper.py
709
3.625
4
from urllib.request import urlopen import requests r = requests.get("https://xkcd.com/353/") h = "" for x in r.iter_lines(): if ".png" in str(x) and "http" in str(x): h = str(x.decode("utf-8")) # change from bytes to string link_to_image = h[h.find("http"):] # We've found the link to the image. i = requests.get(link_to_image) with open("new_image.jpg", "wb") as f: # How to write an image bytes to png. f.write(i.content) print(i.status_code) # How to check code of the site you've accessed print(i.headers) # How to check https protocol headers. a = requests.session() # As a context manager a1 = a.get("http://www.facebook.com") print(a1.text[0:400])
1b54b8acd624d3f48d8bc0dd0e1eea922395dd11
RAZAKNUR/PYTHON
/queueExercise.py
603
3.71875
4
from collections import deque class Queue: def __init__(self): self.buffer = deque() def enqueue(self, val): self.buffer.appendleft(val) def dequeue(self): return self.buffer.pop() def is_empty(self): return len(self.buffer)==0 def size(self): return len(self.buffer) def front(self): return self.buffer[-1] def binary(x): qu = Queue() qu.enqueue("1") for i in range(x): print(qu.front()) qu.enqueue(qu.front() + "0") qu.enqueue(qu.front() + "1") qu.dequeue() binary(10)
a851104976bf82af835a819c9c3d67fe2fe82c6e
shubhamprkash/Python_Learning
/Day3.2.2_BMI_calv2.0.py
701
4.21875
4
weight = input("Enter your weight in kgs : "); height = input("Enter your hight in meters : "); # My Code bmi=float(weight)/(float(height)**2); covBmi=round(bmi,2); if covBmi < 18.5: print(f"Your BMI is {covBmi}, You are Underweight!"); elif covBmi >35: print(f"Your BMI is {covBmi}, You are clinically obese!"); elif covBmi > 18.5: if covBmi < 25: print(f"Your BMI is {covBmi}, You have Normal Weight!"); elif covBmi > 25: if covBmi <30: print(f"Your BMI is {covBmi}, You are Overweight!"); elif covBmi > 30: if covBmi < 35: print(f"Your BMI is {covBmi}, You are Obese!!"); else: print(f"Your BMI is {covBmi}, Invalid Entry error!!");
ef3a8b2a619f47c71891037e3f80bbbfc7c1708d
refine-P/NLP100Knock
/Mecab/question38.py
370
3.53125
4
#coding:utf-8 import matplotlib.pyplot as plt if __name__ == "__main__": freq = [] for line in open("word_freq.txt", "r", encoding='utf-8'): key, value = line.split(' ') value = int(value) freq.append(value) plt.hist(freq, bins=range(0, 21)) #20回より多く出現する単語は殆ど無いので排除 plt.xlabel("freq") plt.ylabel("word") plt.show()
7cbfee938932f8c114ef68b1a57cd8554eae2d80
RobotGyal/Generating-Fractals-with-Recursion
/recursion/recursion.pyde
293
3.828125
4
# FRACTAL TREE # KOSH CURVE # CANTOR SET # MANDELBROT SET def setup(): print("The recursive factorial is: ", factorial(4)) def draw(): pass def factorial(n): """ Calls itself to provide recursion """ if n == 1: return 1 else: return n * (factorial(n-1))
b3e54b137c4da0b4cedbf5cc98f8c813117605aa
banana-galaxy/challenges
/challenge5(ranges)/Stilton.py
1,115
4.03125
4
def erange(*args): result = [] if len(args) == 1: stop, start, step = args[0]-1, 0, 1 while start <= stop: result.append(start) start += step elif len(args) == 3: start, stop, step = args[0], args[1], args[2] if step == 0: raise Exception("Step argument needs to be bigger than 0") elif len(args) == 2: start, stop, step = args[0], args[1], 1 if not isinstance(stop, int) or not isinstance(start, int): raise Exception("Arguments need to be of type int") else: raise Exception("The function only accepts a minimum of 1 arg or maximum of 3 args") if not isinstance(stop, int) or not isinstance(start, int) or not isinstance(step, int): raise Exception("Arguments need to be of type int") if step < 0 and start > stop: while start > stop: result.append(start) start += step elif step > 0: while start < stop: result.append(start) start += step return result def numerate(iterable, start=0): result = [] for i in iterable: result.append((start, i)) start += 1 return result
961e8986559e8a869f905edf4a30fbfe70ca2adf
NathanZorndorf/cheat-sheets
/Python/Dictionary Cheat Sheet.py
654
4.21875
4
#-------------------- DICTIONARIES ---------------------# #---- Make a dict using keys from a list d.fromkeys() # Example : liquor_dict = {} liquor_dict.fromkeys(liquor_categories, None) #---- Get value from key if key in dict d.get() #---- Check if a dict has a key d.has_key() #---- Returns list of key,value pairs as tuples d.items() #---- Return a list of values in dict d.values() #---- Return a list of keys in dict\ d.keys() #---- Returns an interator over the key,value items in dict d.iteritems() #-------------- METHODS #---- sort items in a dict by returning a sorted list sorted(d.items(), key=operator.itemgetter(1), reverse=True)
1e95f6e6b7b3dcd8ef5a2b1530d994466dd577ea
Petrichorll/learn
/learn/2021/0202/single_cycle_link_list.py
2,623
3.828125
4
# -*- coding: utf-8 -*- # 单向循环链表 from single_link_list import Node class SingleLinkList(object): # 单向循环链表 def __init__(self, node=None): self.__head = node def is_empty(self): # 链表是否为空 return self.__head is None def length(self): # 链表的长度 ret = 0 cur = self.__head while (cur): cur = cur.next ret = ret + 1 return ret def travel(self): # 遍历整个链表 print("==开始遍历列表===================") cur = self.__head while (cur): print(cur.elem) cur = cur.next print("==结束遍历列表===================") def head_add(self, item): # 头部添加元素 node = Node(item) node.next = self.__head self.__head = node def append(self, item): # 尾部添加元素 node = Node(item) if (self.is_empty()): self.__head = node return cur = self.__head while (cur.next != None): cur = cur.next cur.next = node def insert(self, pos, item): # 指定位置添加元素,pos从0开始计算 if (pos <= 0): self.head_add(item) return if (pos > self.length() - 1): self.append(item) return pre = self.__head conut = 0 while (conut < (pos - 1)): pre = pre.next conut = conut + 1 node = Node(item) node.next = pre.next pre.next = node def remove(self, item): # 删除节点item,从左到右第1个,返回已删除结点的位置。 cur = self.__head pre = None pos = 0 while (cur): if (cur.elem == item): if (pre == None): self.__head = cur.next return pos pre.next = cur.next return pos pre = cur cur = cur.next pos = pos + 1 return None def sreach(self, item): # 查找节点是否存在,返回真假 cur = self.__head while (cur): if (cur.elem == item): return True cur = cur.next return False if __name__ == "__main__": listt = SingleLinkList() listt.head_add(8) print(listt.is_empty()) listt.append("222") listt.append([5, 5, 2, 4]) listt.append(3 + 3) listt.head_add(0) listt.travel() listt.insert(-5, 666) listt.travel() print(listt.remove(5646)) listt.travel()
28c50d97f9ecd89211f494a20d12eba57a859d92
PatrickKelly95/Python-Assignment-1
/database/models.py
1,765
3.671875
4
# Program Name: models # Purpose: Creates individual tables in database for each statistic from database.database import db # Create table based on age statistics class Age(db.Model): id = db.Column(db.Integer, primary_key=True) average_age = db.Column(db.Integer, unique=False) min_age = db.Column(db.Integer, unique=False) max_age = db.Column(db.Integer, unique=False) # Create table based on total number of players class TotalPlayers(db.Model): id = db.Column(db.Integer, primary_key=True) total_players = db.Column(db.Integer, unique=False) # Create table based on top 5 best players class BestPlayers(db.Model): id = db.Column(db.Integer, primary_key=True) best_players = db.Column(db.String, unique=False) # Create table based on top 5 worst players class WorstPlayers(db.Model): id = db.Column(db.Integer, primary_key=True) worst_players = db.Column(db.String, unique=False) # Create table based on average height and weight class AvgHeightWeight(db.Model): id = db.Column(db.Integer, primary_key=True) average_height = db.Column(db.String, unique=False) average_weight = db.Column(db.String, unique=False) # Create table based on correlation between different statistics in the csv file class Correlation(db.Model): id = db.Column(db.Integer, primary_key=True) age_rating_correlation = db.Column(db.Float, unique=False) age_pace_correlation = db.Column(db.Float, unique=False) pass_short_long_correlation = db.Column(db.Float, unique=False) # Create table based on variance of shooting ability class Variance(db.Model): id = db.Column(db.Integer, primary_key=True) variance = db.Column(db.String, unique=False) standard_dev = db.Column(db.String, unique=False)
b7ca9ed84d64fba692e3ad704aad410f267a33c4
GraceDurham/hackbright_challenges
/sum_list.py
243
4
4
def sum_list(lst): """Returns the number from summing all the numbers in a list""" sums = 0 for num in lst: sums = sums + num print num, print sums return sums print sum_list([5, 3, 6, 2, 1])
7c0bd089b25b06a8ef4e4180e38cea9b58824f9a
AthosFB/Exercicios-Python
/ExercícioDoCurso/067.py
302
3.796875
4
while True: print() tabuada = float(input("Qual número da tabuada deseja ver: (Qualquer número negativo para parar) ")) print() cont = 1 if tabuada < 0: break while cont != 11: print(f"{cont} * {tabuada} = {cont * tabuada:.2f}") cont += 1 print("Fim")
daa8fecbbf492b4e0eafd084572d65d681df1160
kumastry/atcoder
/arc/014/014a.py
66
3.640625
4
n = int(input()) if(n%2): print('Red') else: print('Blue')
3fc2ef8a0fba3cfd52c4e87a53d36254ab436d55
sudhanshu-jha/python
/python3/Python-algorithm/Bits/nextNumber/getNext.py
894
3.515625
4
# Given a positive number, print the next smallest and the next # largest number that have the same number of 1 bits in their # binary representation. def getNext(n): c = n # let p denote the position of first non-trailing 0 ie a zero which is followed by 1s c0 = 0 # number of zeros to right of position p c1 = 0 # number of ones to right of position p # while there are training zeros and c > 0 while (c & 1) == 0 and (c != 0): c0 += 1 c >>= 1 while (c & 1) == 1: c1 += 1 c >>= 1 # If n = 111...1100...000, then there is no bigger number with same number of 1s if c0 + c1 == 31 or c0 + c1 == 0: return -1 p = c0 + c1 n |= 1 << p # Flip rightmost non trailing zero n &= ~((1 << p) - 1) # Clear all bits to right of 1 n |= (1 << (c1 - 1)) - 1 # Insert (c1-1) ones on the right return n
7e6bf30720732ecc92d0b62301b5f262d58d434c
IdiotCirno/MFTI
/Test1/F.py
605
3.703125
4
a = int(input()) b = int(input()) while b != 0: if a < b: a, b = b, a a, b = b, a%b print(a) ''' Необходимо найти НОД двух чисел, используя алгоритм Евклида. Формат входных данных На вход подаются два натуральных числа, по числу в новой строке. Формат выходных данных Одно число - НОД входных чисел. Примеры Ввод Вывод 30 6 18 Ввод Вывод 1071 21 462 '''
5d564e1a33f76ffdba4fb1f128b08557a2cb42f1
yyHaker/PythonStudy
/algorithms/常见面试编程题(剑指offer&leetcode)/动态规划dp/5. 不同路径.py
715
3.546875
4
#!/usr/bin/python # coding:utf-8 """ @author: yyhaker @contact: 572176750@qq.com @file: 5. 不同路径.py @time: 2019/8/19 14:52 """ """ leetcode62:不同路径 思路:动态规划 """ class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ # 思路:动态规划,令d[i][j]表示机器人能够到达位置(i, j)的路径条数, # 则有d[i][j] = max(d[i-1][j], d[i][j-1]) # 时间复杂度为O(mn),空间复杂度为O(mn) d = [[1] * n for _ in range(m)] for i in range(1, m): for j in range(1, n): d[i][j] = d[i-1][j] + d[i][j-1] return d[m-1][n-1]
d4b187f1c9049d1639989587d216bc756b33d577
dty999/pythonLearnCode
/挑战python/052因子平方和.py
915
3.53125
4
"""6 的因子有 1, 2, 3 和 6, 它们的平方和是 1 + 4 + 9 + 36 = 50. 如果 f(N) 代表正整数 N 所有因子的平方和, 那么 f(6) = 50. 现在令 F 代表 f 的求和函数, 亦即 F(N) = f(1) + f(2) + .. + f(N), 显然 F 一开始的 6 个值是: 1, 6, 16, 37, 63 和 113. 那么对于任意给定的整数 N (1 <= N <= 10^8), 输出 F(N) 的值.""" N = 20 l = [] def f(n): res = [] for i in range(1,int(n/2 +1)+1): if n % i ==0: res.append(i) res.append(n//i) return set(res) def F1(N): from collections import defaultdict dic = defaultdict(int) for i in range(1,N+1): res = f(i) for i in res: dic[i] += 1 return dic def F(N): res = 0 for i in range(1,N//2 + 1): res += i**2*(N//i-1)#每个数拿出来留到后面给平方和用 res += N*(N+1)*(2*N+1)/6 return res print(int(F(6)))
e659751cb0fac10d81a80e9fd26f349603c63e0b
joanamucogllava/PythonPrograms
/max_num.py
300
3.984375
4
#This prigram will find the largest number from the given ones. #Author: Joana Mucogllava def max_num(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 print(max_num(20, 50, 40))
fda5701524c17f7e4c2b7370df1ab6db485618d5
roshan-malviya/Strings
/reverse.py
148
3.75
4
# slicing def reverse(stri): return arr[::-1] def reverse0(stri): b='' for i in stri: b=i+b return b c=input() print (reverse0(c))
93f4f937c61e2899cb3eba6ba55448630054cc22
maguedon/codingup
/2017/bug_chemin.py
2,152
3.859375
4
import math def getCoord(chemin): direction = "N" x = 0 y = 0 for char in chemin: if char == "A": if direction == "N": y += 100 if direction == "S": y -= 100 if direction == "E": x += 100 if direction == "O": x -= 100 elif char == "D": if direction == "N": direction = "E" elif direction == "S": direction = "O" elif direction == "E": direction = "S" elif direction == "O": direction = "N" elif char == "G": if direction == "N": direction = "O" elif direction == "S": direction = "E" elif direction == "E": direction = "N" elif direction == "O": direction = "S" return (x,y) def getDistance(coord): x = coord[0] y = coord[1] distance = math.sqrt(x*x + y*y) distance = round(distance, 0) return distance # chemin = "AGGAA" chemin = "ADDGAGDGGDDADDDGDADADGGGGGADGGDADAADAGGGDDADAAADGDDDDDAAAADDDDDDAGGAAAGGDAGAGADAADADAGDDDAAGGDGGAGAGDAGDGGDGAAGADGAAGDDADGDGDDGADAGAGDAGDAGDDDDGGDGGDAADDGGDAGADADGDDADAADDDAAAGGDGDGGGGADAGDGGGGADDDDDGDDDGAADGGDAAAAGDDDDADGADAGDAGDGAGAGGAADAGADADGGDADGGGGGGAGGDAGADGGADDGDAADGDGDDGDADADDDGAGGDDAGDDAAAGGAADDDGGGAAADGAGDGGAAAGAGAGGDAAAAGADDDDGAADADGDAGAAGGAADGADAGGDGAAAGGGDDAGDDDGADAAAGGAADAAADAAAGAGDDDDGAGGGGGDGGADAGAGAGAAGADADADGAGGDDGAAGGAADDDAGAAADADGAADADGGGAGAGDGGDAGDAGDGGAGGGADDDGDGAGGADDGDGA" i = 0 coordList = set() maxDistance = 0 for char in chemin: if char == "A": newChemin1 = chemin[:i] + "G" + chemin[i+1:] newChemin2 = chemin[:i] + "D" + chemin[i+1:] elif char == "D": newChemin1 = chemin[:i] + "G" + chemin[i+1:] newChemin2 = chemin[:i] + "A" + chemin[i+1:] elif char == "G": newChemin1 = chemin[:i] + "D" + chemin[i+1:] newChemin2 = chemin[:i] + "A" + chemin[i+1:] coord1 = getCoord(newChemin1) coordList.add(coord1) distance1 = getDistance(coord1) # print(newChemin1) if (distance1 > maxDistance): maxDistance = distance1 coord2 = getCoord(newChemin2) coordList.add(coord2) distance2 = getDistance(coord2) # print(newChemin2) if (distance2 > maxDistance): maxDistance = distance2 i = i + 1 # print(coordList) print(len(coordList)) print(maxDistance)
c099538833c3c4113b33299b4f9096a0c1c12778
f-fathurrahman/ffr-MetodeNumerik
/AkarPersamaan/python3/ridder.py
1,823
3.5
4
from math import sqrt def ridder(f, x1, x2, TOL=1.0e-9, verbose=False, NiterMax=100): if verbose: print("") print("Searching root with Ridder's method:") print("Interval = (%18.10f,%18.10f)" % (x1,x2)) print("TOL = %e" % TOL) print("") assert TOL >= 0.0 f1 = f(x1) if abs(f1) <= TOL: return x1, 0.0 f2 = f(x2) if abs(f2) <= TOL: return x2, 0.0 if f1*f2 > 0.0: raise RuntimeError("Root is not bracketed") # For the purpose of calculating relative error x3 = 0.0 x3_old = 0.0 if verbose: print(10*" "+"Iter Estimated f(x)") print(10*" "+"---- --------- ----") print("") for i in range(1,NiterMax+1): x3_old = x3 c = 0.5*(x1 + x2) fc = f(c) s = sqrt(fc**2 - f1*f2) if s == 0.0: raise RuntimeError("s is zero in ridder") dx = (c - x1)*fc/s if (f1 - f2) < 0: dx = -dx # new approximation of root x3 = c + dx f3 = f(x3) if verbose: print("ridder: %5d %18.10f %15.5e" % (i, x3, abs(f3))) if abs(f3) <= TOL: if verbose: print("") print("ridder: Convergence is achieved in %d iterations" % (i)) # return the result return x3, abs(x3 - x3_old) # Rebracket if fc*f3 > 0.0: if f1*f3 < 0.0: x2 = x3 f2 = f3 else: x1 = x3 f1 = f3 else: x1 = c x2 = x3 f1 = fc f2 = f3 # No root is found after NiterMax iterations if verbose: print("No root is found") return None, None
645a2330360db40d5cd7a001acbd002346b5447f
DavidJaimesDesign/MIT-IntroCS
/1-lecture/ps1c.py
1,175
3.90625
4
annual_salary = input("Your yearly salary: ") total_cost = 1000000.0 portion_down_payment = total_cost/4.0 epsilon = 100 high = 1.0 low = 0 num_steps = 0 guess = (high + low)/2 def amountSaved(guess, salary): annual_salary = salary portion_saved = guess semi_annual_rate = 0.07 months_to_save = 36 r = 0.04 total_saved = 0 for months in range(months_to_save): if months%6 == 0: annual_salary = annual_salary + annual_salary*semi_annual_rate monthly_savings = annual_salary*portion_saved/12 total_saved += monthly_savings + total_saved*r/12 #print total_saved return total_saved saved = amountSaved(guess, annual_salary) if (saved < portion_down_payment): print 'There is no way you could save enough in 3 years' else: while abs(saved - portion_down_payment) >= epsilon: if saved < portion_down_payment: low = guess else: high = guess guess = (high + low)/2.0 saved = amountSaved(guess, annual_salary) num_steps +=1 print 'Best savings rate:', round(guess,2) print 'Steps in bisection search:', num_steps