blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
dd3749681cb56f0a22f138d2373c0f1c140c8a91
xiaolongwang2015/Interview
/54螺旋矩阵.py
2,047
3.828125
4
""" 54 螺旋矩阵 难度:中等 题目描述: 给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。 示例1: 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5] 示例2: 输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 输出:[1,2,3,4,8,12,11,10,9,5,6,7] m == matrix.length n == matrix[i].length 1 <= m, n <= 10 -100 <= matrix[i][j] <= 100 题解方法: """ from itertools import product from collections import deque def spiralOrder(matrix: list) -> list: """ 按照顺时针螺旋顺序 ,返回矩阵中的所有元素 Note: 1 起始元素索引matrix[0][0] 2 :param matrix: :return: >>> spiralOrder([[1,2,3],[4,5,6],[7,8,9]]) [1, 2, 3, 6, 9, 8, 7, 4, 5] >>> spiralOrder([[1,2,3,4],[5,6,7,8],[9,10,11,12]]) [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7] """ rst = [] idx_collection = list(product(range(len(matrix)), range(len(matrix[0])))) row_idx, column_idx = 0, 0 # 起始元素索引matrix[0][0] idx_collection.remove((row_idx, column_idx)) rst.append(matrix[row_idx][column_idx]) direction = deque([[0, 1], [1, 0], [0, -1], [-1, 0]]) direction_row, direction_column = direction.popleft() direction.append([direction_row, direction_column]) while True: if not idx_collection: break if (row_idx + direction_row, column_idx + direction_column) not in idx_collection: direction_row, direction_column = direction.popleft() direction.append([direction_row, direction_column]) row_idx += direction_row column_idx += direction_column idx_collection.remove((row_idx, column_idx)) rst.append(matrix[row_idx][column_idx]) return rst def direction_gen(): directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] for direction in directions: yield direction if __name__ == '__main__': import doctest doctest.testmod()
3eaa2d83b1da5e09358e6cba4fd210a54ad70ced
Julesya/Tugas-Algoritma-dan-Pemrograman
/Python/Menghitung Panjang dan Lebar.py
254
3.703125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: panjang=float(input("ketik nilai panjang =")) lebar=float(input("ketik nilai lebar =")) keliling = 2*panjang+2*lebar luas = panjang*lebar print("keliling = ",keliling) print("luas =",luas) # In[ ]:
ddd4574041cab441d6c2a097dc0eb4ca32164699
omarsaad0/Python-Learning
/Python_Elzero/037_TypeConversion.py
1,302
4.09375
4
# Type Conversion # str() ########################################################################### a = 10 print(type(a)) print(type(str(a))) print("/|"*50) # tuple() c = "Omar" # string d = [1, 2, 3, 4, 5] # List e = {"A", "B", "C"} # Set f = {"A": 1, "B": 2} # Dict print(tuple(c)) print(tuple(d)) print(tuple(e)) # Random elements print(tuple(d)) print("/|"*50) # list() c = "Omar" # string d = (1, 2, 3, 4, 5) # Tuple e = {"A", "B", "C"} # Set f = {"A": 1, "B": 2} # Dict print(list(c)) print(list(d)) print(list(e)) # Random elements print(list(d)) print("/|"*50) # set() c = "Omar" # string d = (1, 2, 3, 4, 5) # Tuple e = ["A", "B", "C"] # Set f = {"A": 1, "B": 2} # Dict print(set(c)) # Random elements print(set(d)) # Random elements print(set(e)) # Random elements print(set(d)) # Random elements print("/|"*50) # dict() #c = "Omar" # string d = (("A", 1), ("B", 2), ("C", 3)) # To Convert Tuple to Dict make it nested tuple to take the Key + Value e = [["One", 1], ["Two", 2], ["Three", 3]] # To Convert List to Dict make it nested List to take Key + Value #f = {{"A", 1}, {"B", 2}} # Can not be converted to Dict #print(dict(c)) # Can not be Converted to Dict bec no Key + Value print(dict(d)) print(dict(e)) #print(dict(d)) # Un hashable Type 'set'
0715ab9f5fad4dbad4fbf270764b3f16cf4bfd2d
avinashyeccalluri/java
/Python/First.py
93
3.515625
4
a="WhAt! FiCK! DaMn CAke?" b=a.split(" ") print(''.join(e for e in a if e.isalnum()).lower())
2792ceb1ad68c14652de8bfbfbbaea2907769e77
ch-canaza/holbertonschool-higher_level_programming
/0x0A-python-inheritance/101-add_attribute.py
314
4.125
4
#!/usr/bin/python3 """ module 101-add_attribute contains the function add_attribute """ def add_attribute(obj, name, value): """ if possible, add a new attribute to an object """ if hasattr(obj, '__dict__'): setattr(obj, name, value) else: raise TypeError('can\'t add new attribute')
00626a76a45e6fe396a8d75b2370e3f6ea3e2440
TristaWWP/Python-programming-reference-
/Chapter-4.py
1,781
4.4375
4
""" 4-1 """ pizzas = ['beef', 'chicken', 'fruit'] for pizza in pizzas: print(pizza) for pizza in pizzas: print("I like " + pizza + "pizza") print("I really love pizza") """ 4-2 """ animals = ['dog', 'cat', 'pig'] for animal in animals: print(animal) for animal in animals: print("A " + animal + " would make a great pet") print("Any of these animals would make a great pet") """ 4-3 """ nums = list(range(1, 21)) for num in nums: print(num) """ 4-4 """ nums = list(range(1, 1000001)) for num in nums: print(num) """ 4-5 """ nums = list(range(1, 1000001)) print(min(nums)) print(max(nums)) print(sum(nums)) """ 4-6 """ nums = list(range(1, 21, 2)) for num in nums: print(num) """ 4-7 """ nums = list(range(3, 30, 3)) for num in nums: print(num) """ 4-8 """ res = [] nums = range(1, 11) for num in nums: val = num ** 3 res.append(val) print(res) """ 4-9 """ res = [] nums = range(1, 11) for num in nums: val = num ** 3 res.append(val) print(res) """ 4-10 """ pizzas = ['beef', 'chicken', 'fruit','other','pig'] for pizza in pizzas: print(pizza) print("The first thress items in the list are: ") print(pizzas[:3]) print("Thress items from the middle of the list are: ") print(pizzas[2:5]) print("The last thress items in the list are: ") print(pizzas[-3:]) """ 4-11 """ pizzas = ['beef', 'chicken', 'fruit','other','pig'] friends_pizzas = pizzas[:]#创建副本 pizzas.append("apple") friends_pizzas.append("banana") print("My favorite pizzas are: ") for pizza in pizzas: print(pizza) print("My friends favorite pizzas are: ") for friends_pizza in friends_pizzas: print(friends_pizza) """ 4-13 """ foods = ('pizza', 'cake', 'egg', 'beef') for food in foods: print(food) foods[0] = 'milk'
35bd55d9f0f2ee7c4b6fc778eeeeb3b76a68d8d0
joaovgotardo/exerciciospython
/ul1 - conceitos básicos/aula02/exemplo de try except com input.py
271
3.78125
4
v_numa = 0 v_numb = 0 v_resultado = 0 try: v_numa = int(input('Digite o primeiro número: ')) v_numb = int(input('Digite o segundo número: ')) v_resultado = (v_numa) / (v_numb) print('Resultado: ' + str(v_resultado)) except: print('Erro na operação')
81e33835b1be25ae7df897dda3e2d9d366074c00
syurskyi/Python_Topics
/065_serialization_and_deserialization/002_json/_exercises/_templates/Working With JSON Data in Python/003_A Real World Example (sort of).py
4,871
3.515625
4
# # -*- coding: utf-8 -*- # # # A Real World Example (sort of) # # For your introductory example, you’ll use JSONPlaceholder, a great source of fake JSON data for practice purposes. # # First create a script file called scratch.py, or whatever you want. I can’t really stop you. # # You’ll need to make an API request to the JSONPlaceholder service, so just use the requests package to do the heavy # # lifting. Add these imports at the top of your file: # # ______ ____ # ______ req.. # # # Now, you’re going to be working with a list of TODOs cuz like…you know, it’s a rite of passage or whatever. # # Go ahead and make a request to the JSONPlaceholder API for the /todos endpoint. If you’re unfamiliar with requests, # # there’s actually a handy json() method that will do all of the work for you, but you can practice using # # the json library to deserialize the text attribute of the response object. It should look something like this: # # # response = req__.g.. https://jsonplaceholder.typicode.com/todos # todos = ____.l.. ?.t.. # # # You don’t believe this works? Fine, run the file in interactive mode and test it for yourself. While you’re at it, # # check the type of todos. If you’re feeling adventurous, take a peek at the first 10 or so items in the list. # # # print(t.. __ r__.____ # # True # print(ty.. t.. # # <class 'list'> # print(t.. ;10 # # ... # # # See, I wouldn’t lie to you, but I’m glad you’re a skeptic. # # What’s interactive mode? Ah, I thought you’d never ask! You know how you’re always jumping back and forth between # # the your editor and the terminal? Well, us sneaky Pythoneers use the -i interactive flag when we run the script. # # This is a great little trick for testing code because it runs the script and then opens up an interactive command # # prompt with access to all the data from the script! # # All right, time for some action. You can see the structure of the data by visiting the endpoint in a browser, # # but here’s a sample # # { # "userId": 1, # "id": 1, # "title": "delectus aut autem", # "completed": False # } # # There are multiple users, each with a unique userId, and each task has a Boolean completed property. Can you determine which users have completed the most tasks? # # # # # Map of userId to number of complete TODOs for that user # todos_by_user = {} # # # # # Increment complete TODOs count for each user. # ___ todo __ t.. # __ ?["completed"] # ___ # # Increment the existing user's count. # ?|t.. "userId'|| += 1 # ____ K.. # # This user has not been seen. Set their count to 1. # ? t.. "userId"|| _ 1 # # # Create a sorted list of (userId, num_complete) pairs. # top_users = so.. ?.i.. # k.._ l___ x ? 1| re.. _ T.. # # # Get the maximum number of complete TODOs. # max_complete = ? 0 1 # # # Create a list of all users who have completed # # the maximum number of TODOs. # users = [] # ___ user, num_complete __ to.. # __ nu_c. < ma_c. # b.. # ?.ap.. st. ? # # max_users = " and ".jo.. ? # # # Yeah, yeah, your implementation is better, but the point is, you can now manipulate the JSON data as a normal # # Python object! # # I don’t know about you, but when I run the script interactively again, I get the following results: # # # s = "s" __ le. ? > 1 else "" # print(_ *user@ @m_u. completed @m_c. TODOs # # users 5 and 10 completed 12 TODOs # # That’s cool and all, but you’re here to learn about JSON. For your final task, you’ll create a JSON file that contains # # the completed TODOs for each of the users who completed the maximum number of TODOs. # # All you need to do is filter todos and write the resulting list to a file. For the sake of originality, you can call # # the output file filtered_data_file.json. There are may ways you could go about this, but here’s one: # # # # # Define a function to filter out completed TODOs # # # of users with max completed TODOS. # ___ keep todo # is_complete _ ? "completed"| # has_max_count _ st. ? "userId"|| __ u.. # r_ ? an. ? # # # # Write filtered TODOs to file. # w___ o.. filtered_data_file.json _ __ data_file # filtered_todos _ li.. fi. k.. t.. # ____.d.. ? d.. i.. _ 2 # # Perfect, you’ve gotten rid of all the data you don’t need and saved the good stuff to a brand new file! Run the script # # again and check out filtered_data_file.json to verify everything worked. It’ll be in the same directory as scratch.py # # when you run it. # # Now that you’ve made it this far, I bet you’re feeling like some pretty hot stuff, right? Don’t get cocky: humility is # # a virtue. I am inclined to agree with you though. So far, it’s been smooth sailing, but you might want to batten down # # the hatches for this last leg of the journey.
ceb2d0d80dc8d444b53c29984ab5a51d35a180fc
XxdpavelxX/Python-Projects
/Simple,Useful Python Projects/mindstorms.py
810
4.09375
4
import turtle # used to draw import math def draw_square(some_turtle): for i in range(1,5): some_turtle.forward(100) # brad moves forward and draws for 100 units some_turtle.right(90) #brad makes a 90 degree turn def draw_art(): window=turtle.Screen() window.bgcolor("red") # Create a red colored background brad=turtle.Turtle() #grabs the turtle and names it brad brad.shape("turtle") brad.color("yellow") brad.speed(2) for i in range(1,37): draw_square(brad) brad.right(10) angie=turtle.Turtle() angie.color("blue") angie.shape("arrow") angie.circle(100) joe=turtle.Turtle() joe.color("green") joe.shape("turtle") joe.speed(2) joe.forward(100) joe.right(135) joe.forward(math.sqrt(20000)) joe.right(135) joe.forward(100) window.exitonclick() draw_art()
7e9e15be6cb1c8fc014449c381f3d6bf287cd9ca
LingB94/Target-Offer
/58翻转字符串.py
481
3.828125
4
def reverse(s): if(not s): return False l = [] for i in s.split(): l.append(i) result = '' for i in l[::-1]: result += (i + ' ') return result[:-1] def leftRotate(s, k): if(not s or k <=-1 or k >= len(s)): return False result = '' result = s[k:]+s[:k] return result if __name__ == '__main__': l = "I am a student." print(reverse(l)) s = 'abcdefg' print(leftRotate(s,0))
7957de396b130198cbb6f7e4cb5e5afd430770e9
manish-jain-py/general_programs
/ccti/ctci_selected/coin_change.py
614
3.6875
4
def find_coins_count(amount, currency_list): min_coins_dict = {} for i in range(1, amount+1): coins_list = [] for currency in currency_list: if i >= currency: diff = i - currency if diff in min_coins_dict: coins_list.append(min_coins_dict[diff]) else: coins_list.append(diff) min_coins = min(coins_list) + 1 min_coins_dict[i] = min_coins #print min_coins_dict return min_coins amount = 98 currency_list = [1,2,5,10] print find_coins_count(amount, currency_list)
b28caa83ae1f35b4a67783a22f8a66ef9a03c092
kadarsh2k00/python-exercise
/Python GitHub/Q48.py
207
3.59375
4
##def even(n): ## if n%2==0: ## return True ##l=[] ##for i in range(1,21): ## l.append(i) ##x=filter(even,l) x=(filter(lambda x:x%2==0,range(1,21))) for i in x: print(i)
3728ba89bd50793c8c889f1ced668f9c886e445c
Alokpatek2392/Fibonacci
/Fibonacci.py
533
3.90625
4
def F(n): a=0 b=1 print(a) print(b) for i in range(1,n): c=a+b a=b b=c if(c%3==0 and c%5!=0): print('Buzz') elif(c%5==0 and c%3!=0): print('Fizz') elif(is_prime_number(c)): print('BuzzFizz') else: print(c) def is_prime_number(x): if x >= 2: for y in range(2,x): if not ( x % y ): return False else: return False return True
40a6e07a3248fec62c2e47217f6d439b5a037500
phlalx/algorithms
/leetcode/685.redundant-connection-ii.py
3,958
3.671875
4
# # @lc app=leetcode id=685 lang=python3 # # [685] Redundant Connection II # # https://leetcode.com/problems/redundant-connection-ii/description/ # # algorithms # Hard (31.14%) # Likes: 619 # Dislikes: 184 # Total Accepted: 30.3K # Total Submissions: 94.9K # Testcase Example: '[[1,2],[1,3],[2,3]]' # # # In this problem, a rooted tree is a directed graph such that, there is # exactly one node (the root) for which all other nodes are descendants of this # node, plus every node has exactly one parent, except for the root node which # has no parents. # # The given input is a directed graph that started as a rooted tree with N # nodes (with distinct values 1, 2, ..., N), with one additional directed edge # added. The added edge has two different vertices chosen from 1 to N, and was # not an edge that already existed. # # The resulting graph is given as a 2D-array of edges. Each element of edges # is a pair [u, v] that represents a directed edge connecting nodes u and v, # where u is a parent of child v. # # Return an edge that can be removed so that the resulting graph is a rooted # tree of N nodes. If there are multiple answers, return the answer that # occurs last in the given 2D-array. # Example 1: # # Input: [[1,2], [1,3], [2,3]] # Output: [2,3] # Explanation: The given directed graph will be like this: # ⁠ 1 # ⁠/ \ # v v # 2-->3 # # # Example 2: # # Input: [[1,2], [2,3], [3,4], [4,1], [1,5]] # Output: [4,1] # Explanation: The given directed graph will be like this: # 5 2 # ⁠ ^ | # ⁠ | v # ⁠ 4 # # Note: # The size of the input 2D-array will be between 3 and 1000. # Every integer represented in the 2D-array will be between 1 and N, where N is # the size of the input array. # # # https://leetcode.com/problems/redundant-connection-ii/discuss/254733/Python-Union-Find-Clear-Logic # TAGS super hard # As the problem states, there is one and only one edge that violates the definition of tree. Therefore, there are three possible cases: # a. There is no cycle in the graph, but there exist two edges pointing to the same node; # b. There is a cycle, but there do not exist two edges pointing to the same node; # c. There is a cycle, and there exist two edges pointing to the same node. # Use UF on the undirected graph + case analysis based on which node has two parents # @lc code=start class UF: def __init__(self, n): self.p = list(range(n)) self.r = [0] * n def find(uf, i): if i == uf.p[i]: return i res = find(uf, uf.p[i]) uf.p[i] = res return res def union(uf, i, j): i, j = find(uf, i), find(uf, j) if i == j: return True if uf.r[i] > uf.r[j]: uf.p[j] = i else: uf.p[i] = j uf.r[j] = max(uf.r[j], 1 + uf.r[i]) return False from collections import defaultdict class Solution: def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]: n = len(edges) parent = defaultdict(list) cand1 = None cand2 = None for v1, v2 in edges: parent[v2].append(v1) for u, v in parent.items(): if len(v) == 2: cand1 = [v[0], u] cand2 = [v[1], u] print(cand1, cand2) # Three cases # Case 1 - No cycle # return e1 # Case 2 - Cycle - two parents # return edge in cycle # Case 3 - Cycle - no two parents # return first edge that forms cycle (like 684) uf = UF(n) if cand2 is None: # Case 3 for v1, v2 in edges: if union(uf, v1 - 1, v2 - 1): return [v1, v2] else: for v1, v2 in edges: if [v1, v2] == cand2: continue if union(uf, v1 - 1, v2 - 1): # Case 1 return cand1 # Case 2 return cand2 # @lc code=end
e2af911c9968275e6545d73e6f7b26d14b30a914
leoren6631/Learning-Python
/lab2.py
10,314
4.125
4
#Problem 1: The calculate_grade() function you have just written is part of problem 1. Write 3 more assertEqual() tests to test the function calculate_grade(). In other words, pick three sets of lab scores and test scores, and then calculate (with a calculator if you like) what you think calculate_grade() should return for those lab scores and test scores. Run your script. If any of the assertEqual() tests fail, figure out what is wrong with your program or your assertEqual() tests and correct the error(s). This process is called debugging. (Don’t forget to print out the problem number.) from cisc106_34 import * def calculate_grade(lab_score, test_score): #calculate and return the grade grade = (lab_score + test_score) / 200 return grade assertEqual(calculate_grade(41.5, 132.5), 0.87) assertEqual(calculate_grade(49.2, 120.4), 0.848) assertEqual(round(calculate_grade(45.5, 133.2), 2), 0.89) #Problem 2: Write a function named calculate_trapezoid_area() that calculates the area of a trapezoid. (You MUST name your function calculate_trapezoid_area(). The function calculate_trapezoid_area() should have three parameters: the trapezoid’s two bases and the trapezoid’s height (in that order). The function should return the area of the trapezoid. The function header and doc string should look like this: def calculate_trapezoid_area(base_1, base_2, height): area = (base_1 + base_2) * height / 2 return area assertEqual(calculate_trapezoid_area(1, 3, 2), 4) assertEqual(calculate_trapezoid_area(32.0, 0.0, 4.0), 64.0) assertEqual(round(calculate_trapezoid_area(0.14, 15.07, 21.20), 2), 161.23) #Problem 3: Write a function called calculate_cylinder_volume(). The function has 2 parameters: radius and height (in that order). calculate_cylinder_volume() should calculate the volume of a cylinder. from math import pi def calculate_cylinder_volume(radius, height): circle_area = pi * (radius ** 2) volume = circle_area * height return volume assertEqual(round(calculate_cylinder_volume(2, 2), 2), 25.13) assertEqual(round(calculate_cylinder_volume(4, 5), 2), 251.33) assertEqual(round(calculate_cylinder_volume(3.2, 9.9), 2), 318.48) #Problem 4: #x = 'bbb', y = 'a' def make_string_strata(x, y): output = x+'|'+y+'|'+x return output #print (make_string_strata(x, y)) assertEqual(make_string_strata('bbb', 'a'), 'bbb|a|bbb') assertEqual(make_string_strata('1', '23'), '1|23|1') assertEqual(make_string_strata('Z', ''), 'Z||Z') #Problem 5: ''' An Internet service provider charges for megabytes (MB) transferred according to a sliding scale. Transfers up to and including 500 MB are charged a flat rate (hereinafter called the base). Transfers over 500 MB up to and including 2500 MB are charged 1.25 times the base, plus an additional $0.01/MB for each MB over 500 MB. Transfers over 2500 MB up to and including 12500 MB are charged 3.75 times the base, plus an additional $0.025/MB for each MB over 2500 MB. Transfers over 12500 MB are charged 30 times the base. Program the function bill_amount(), which takes in an amount of data transferred and a base rate (in that order), and computes the total charge (in dollars). The amount of data transferred should be in MB, and the base rate in dollars). Write 4 assertEqual() tests for 145 MB, 920.8 MB, 8607 MB and 15025 MB, using a base rate of $10.00. Write 3 other assertEqual()() tests using a base rate and data transfer amount of your choosing. ''' def bill_amount(data, base): if data <= 500: total_charge = base elif 500 < data <= 2500: total_charge = base * 1.25 + 0.01 * (data - 500) elif 2500 < data <= 12500: total_charge = base * 3.75 + 0.025 * (data - 2500) else: total_charge = base * 30 return total_charge ''' print(round(bill_amount(145, 10.00),2)) print(round(bill_amount(920.8, 10.00), 2)) print(round(bill_amount(8607, 10.00), 2)) print(round(bill_amount(15025, 10.00), 2)) ''' assertEqual(round(bill_amount(145, 10.00), 2), 10.00) assertEqual(round(bill_amount(920.8, 10.00), 2), 16.71) assertEqual(round(bill_amount(8607, 10.00), 2), 190.18) assertEqual(round(bill_amount(15025, 10.00), 2), 300.00) #Problem 6: ''' First write a function called time_calculator() that takes one parameter – an integer number of seconds. time_calculator() should output (i.e. print) the equivalent number of days, hours, minutes, and seconds. For example, if the user inputs 200000, the output should say something such as “200000 seconds equals 2 days, 7 hours, 33 minutes, 20 seconds”. Your function must accomplish its task by manipulating the input numerically, not with string manipulations. Note that time_calculator() does NOT ask for any input. Next write Python code which prompts the user to input a number of seconds, and then calls your time_calculator() function with the specified number of seconds. Note that the time_calculator() function does not return any value, so assertEqual() tests cannot be used to test its functionality. Test the function in your own way. ''' def time_calculator(time): second = minute = hour = day =0 if time < 60: second = time elif 60 <= time < 60**2: minute = int(time / 60) second = (time - minute*60) elif 60**2 <= time < 24*60**2: hour = int(time / 60**2) minute = int ((time - hour*60**2) / 60) second = time - hour*60**2 - minute*60 else: day = int(time / (24*60**2)) hour = int((time - day*24*60**2) / 60**2) minute = int((time - day*24*60**2 - hour*60**2) / 60) second = time - day*24*60**2 - hour*60**2 - minute*60 print (time, 'seconds equals', day,'days,',hour, 'hours,', minute, 'minutes,', second, 'seconds.') time_calculator(200000) #Problem 7: ''' Write a function called swap_2_of_3(), which takes an integer value in the range [0, 999], swaps the tens digit and hundreds digit, and returns the result. As tests, swap_2_of_3(326) should return 236, swap_2_of_3(930) should return 390, swap_2_of_3(20) should return 200, and swap_2_of_3(7) should return 7. Include these four tests, and write three additional assertEqual() tests for your function. N.B. The argument to swap_2_of_3() should not begin with a zero (e.g., 041), because Python 3.4 considers that to be a syntax error. ''' def swap_2_of_3(num): if 0<= num < 10: pass elif 10 <= num < 100: num = int(num/10)*100 + num % 10 elif 100<= num < 1000: num = int(num/100)*10 + int((num - int(num/100)*100)/10)*100 + num % 10 else: num = 'Error input' return num assertEqual(swap_2_of_3(326), 236) assertEqual(swap_2_of_3(930), 390) assertEqual(swap_2_of_3(20), 200) assertEqual(swap_2_of_3(7), 7) print (swap_2_of_3(-2)) #Problem 7 Extra Credit: ''' Extend your function to work for integers values in the larger range [-999 to 999]. Include at least 2 additional assertEqual() tests for negative values. ''' def swap_2_of_3_extend(num): if -10< num < 10: pass elif 10 <= abs(num) < 100: if num > 0: num = int(num/10)*100 + num % 10 else: num = abs(num) num = int(num/10)*100 + num % 10 num = -1*num elif 100<= abs(num) < 1000: if num > 0: num = int(num/100)*10 + int((num - int(num/100)*100)/10)*100 + num % 10 else: num = abs(num) num = int(num/100)*10 + int((num - int(num/100)*100)/10)*100 + num % 10 num = -num else: num = 'Error input' return num assertEqual(swap_2_of_3_extend(326), 236) assertEqual(swap_2_of_3_extend(930), 390) assertEqual(swap_2_of_3_extend(20), 200) assertEqual(swap_2_of_3_extend(7), 7) assertEqual(swap_2_of_3_extend(-7), -7) assertEqual(swap_2_of_3_extend(-20), -200) assertEqual(swap_2_of_3_extend(-326), -236) #Problem 8: ''' You are tasked with writing a function named mortgage_approval(), to decide whether or not to approve a mortgage loan. The function should return ‘yes’, ‘no’ or ‘maybe’. The function is given 6 pieces of information about a mortgage applicant, in the following order: the loan amount s/he is applying for, her/his current salary, her/his current cash in accounts, her/his estimated non-cash assets, her/his numerical credit score, and her/his last name. The following business rules determine whether or not to approve the loan: CISC106, Spring 2016 1. No mortgage will be approved if an applicant has less than 15% of the loan amount as cash in accounts (i.e., if less than 15%, the mortgage decision is “no”). 2. No mortgage will be approved if an applicant has a credit score less than 590. 3. For applicants with credit scores in the range [590 – 700) (the value 590 is included, but the value 700 is not included), current cash in accounts must be greater than or equal to 25% of the loan amount. 4. All applicants must have a current salary greater than one-third of the balance of the loan amount, which is considered to be the loan amount minus the cash in accounts. 5. Any applicant with the last name Doe must have at least $750,000 in non-cash assets or the loan is declined. 6. Any applicant that made it past rules 1 – 5 and has more cash in accounts than the loan amount is automatically approved (i.e., the mortgage decision is “yes”). Otherwise, the applicant must come to the bank for a personal interview (i.e., the mortgage decision is “maybe”.) Write a minimum of 9 assertEqual() tests that test these rules, making sure that each rule is tested at least once. Organize your tests so that they follow the business rules in the order they are given. ''' def mortgage_approval(loan_amount, salary, cash, non_cash_assets, credit_score, last_name): if cash < loan_amount*0.15 or credit_score < 590: result = 'No' elif 590 <= credit_score < 700 and cash < 0.25*loan_amount: result = 'No' elif salary <= (loan_amount-cash)/3: result = 'No' elif last_name == 'Doe' and non_cash_assets < 750000: result = 'No' else: if cash > loan_amount: result = 'Yes' else: result = 'Maybe' return result assertEqual(mortgage_approval(100000, 50000, 100000*0.25-1, 500000, 699, 'Do'), 'No')
502156045ff13f951952874a3ffcd238e733116a
ingRicardo/Neurons
/tools.py
2,654
3.71875
4
""" This module consists of some helper functions for creating neuronal networks. """ import numpy as np def poisson_homogenous(lam, timesteps): """ Generate a poisson spike train for a single neuron using a homogenous poisson distribution. .. image:: _images/homogenous_plot.png :alt: Homogenous Poisson spike train :width: 400px :Example: The spike train of the image above was generated by following function: >>> poisson_homogenous(0.4, 200) :param lam: lambda value :type lam: Float :param timesteps: total length of spike train :type timesteps: Int """ size = (1, timesteps) spiketrain = np.random.poisson(lam=lam, size=size) spiketrain = np.array(spiketrain, dtype=bool) return spiketrain def poisson_inhomogenous(lambdas, timesteps): """ Generate a poisson spike train for a single neuron using an inhomogenous poisson distribution. .. image:: _images/inhomogenous_plot.png :alt: Inhomogenous Poisson spike train :width: 400px :Example: The spike train of the image above was generated by following function: >>> poisson_inhomogenous((0.5, 0.25, 0, 0, 1, 0.5, 0, 0, 0.25, 0.5), 200) :param lambdas: Lambda values :type lambdas: List or Tuple :param timesteps: total length of the spike train :type timesteps: Int """ if timesteps % len(lambdas) != 0: raise ValueError("Cannot divide the %d mu's on the %d timesteps equally." % (len(lambdas), timesteps)) spiketrain = np.zeros((1, timesteps), dtype=bool) bucketsize = timesteps // len(lambdas) for i, lam in enumerate(lambdas): startindex = i*bucketsize spiketrain[0, startindex:startindex+bucketsize] = np.random.poisson(lam=lam, size=bucketsize) return spiketrain def sound(timesteps, midpoint, maximum, variance): """ Generates a spike train with a peak at *midpoint*. .. image:: _images/sound_plot.png :alt: Sound Plot :width: 400px :Example: The spike train of the image above was generated by following function: >>> sound(280, 150, 0.4, 50) :param timesteps: :param midpoint: central peak :param maximum: Lambda value at peak :param variance: Variance around peak :return: """ mu = np.arange(timesteps) mu = maximum * np.exp(-((mu - midpoint ) ** 2) / variance ** 2) s = poisson_inhomogenous(mu, timesteps) return s if __name__ == '__main__': s = poisson_homogenous(0.4, 200) from neurons import plotting psth = plotting.PSTH(s, binsize=25) psth.show_plot() plotting.show()
5eacaec6f4dcf9bbe786b09da123765ee5a2bae9
nbolzoni/Train_Dispatcher
/frame.py
2,454
3.5625
4
# Import tkinter for gui and time for train movement and refreshing functions. """ from tkinter import * import time """ # Create gui interface """ tk = Tk() tk.title("Train Dispatcher") tk.resizable(0,0) tk.wm_attributes("-topmost",1) canvas = Canvas(tk,width=1500,height=800,bd=0,highlightthickness=0,bg='black') canvas.pack() tk.update() """ class Track: def __init__(): # Initialize each track segment and relevant attributes pass def occupied(): # Determines what initial display color the segment should use depending on train presence pass def checkOccupancy(self): # Refreshes the color depending on train presence pass class Switch(Track): def __init__(): # Initialize each track switch segment and relevant attributes pass def actuateSwitch(): # Changes the switch position to "normal" or "diverging" if user clicks the switch pass def occupied(): # Determines what initial display color the segment should use depending on train presence pass def checkOccupancy(): # Refreshes the color depending on train presence pass class Train: def __init__(): # Initialize each train and its relevant attributes pass def movement(): # Determines how the train "moves" from east to west or west to east based on signal status and switch position pass class ABS_Signal: def __init__(): # Initialize each track automatic signal and relevant attributes pass def block_occupancy(): # Checks if track is clear to the next signal and grants clearance to proceed if so pass class Controlled_Signal: def __init__(): # Initialize each "manually" controlled signal and relevant attributes pass def block_occupancy(): # Checks if track is clear to the next signal also considering switch position, does not grant automatic clearance pass def setRoute(): # Grants manual clearance for train movement through switches and protected track pass class End_Signal: def __init__(): # Initialize each track automatic signal at boundary of route and relevant attributes pass def block_occupancy(): # Checks if the end segment is clear and grants clearance to proceed if so pass def globalMovement(): # Runs the functions above by taking the input of lists of trains, tracks, and signals and refreshing the GUI every second pass
9cb857562131f489db6abe0bf51d138292414ea1
greenfox-velox/szemannp
/week-03/day-3/10.py
228
3.734375
4
def draw_triangle(lines): position = lines - 1 stars = 1 for dots in range(1, lines + 1): print ((" " * position) + ("*" * stars)) stars += 2 position -= 1 return print(draw_triangle(8))
38365c8d7ab1ada30e608b2a1ff399e9d52e8961
glangetasq/FundClustering_Fall2020
/Tools/Labeling/define_levels.py
401
3.625
4
def define_levels(array): """returns High/ Mid/ Low categories based on 33%, 66%, 100% percentiles""" low_thresh = array.quantile(1/3) mid_thresh = array.quantile(2/3) temp = list() for i in array: if i <= low_thresh: temp.append('Low') elif i<= mid_thresh: temp.append('Mid') else: temp.append('High') return temp
db3c66bb453428d822b5347639fbf02778225a1a
victorpma/LFA-automatofinito
/src/main.py
1,278
3.765625
4
import json from automato import Automato def main(): def readAutomato(): with open('InsiraSeuAutomatoAqui/automato.json') as file: automatoJson = json.load(file) alphabet = automatoJson["alfabeto"] stateInitial = automatoJson["estadoInicial"] stateEnd = automatoJson["estadoFinal"] transictions = automatoJson["transicoes"] newAutomato = Automato(alphabet, stateInitial, stateEnd, transictions) newAutomato.populateTransictions() return newAutomato while True: print("----------------- MENU -----------------") print("ATENÇÃO: Antes de iniciar os testes, insira seu autômato na pasta 'InsiraSeuAutomatoAqui', lá possui um exemplo, mas caso queira testar com o exemplo base, fique à vontade ;)") print("\n1- Testar Autômato\n2- Finalizar") optionInput = int(input("\nEscolha uma opção acima: ")) if optionInput == 1: optionWordTest = input( "\nInforme uma palavra para testar o autômato: ") automato = readAutomato() automato.testAutomato(optionWordTest) else: print("Opção inválida, tente novamente!") break if __name__ == "__main__": main()
e7cff9523c64adeafe486178df10fed5540b45f3
asmuth444/NPTEL-Data-Structure-and-Algorithms-in-Python
/Week2/divide_check.py
139
3.859375
4
def divides(m,n): if m%n==0: return True else: return False m,n = map(int, raw_input("Enter Two Nos.:").split()) print divides(m,n)
ce4fd0be6b6f56c1db009bae3e229f15b9b27696
Pedro-Neiva/URI
/Extremely Basic/1020.py
279
3.84375
4
age = int(input()) year = 0 month = 0 day = 0 while age >= 365: age = age - 365 year = year + 1 while age >= 30: age = age - 30 month = month + 1 while age > 0: age = age - 1 day = day + 1 print("%i ano(s)\n%i mes(es)\n%i dia(s)" %(year, month, day))
e4b807dafe8be9069a0f2d5a9e9b69aee6523053
anidh/python-udemy
/starMeta.py
353
3.6875
4
import re def starMetacharacter(): pattern=r"eggs(bacon)*" string="eggsbaconbaconbacon" print(re.findall(pattern,string)) starMetacharacter() def groupsInRegex(): pattern="[A-z]([A-z])+[0-9]" string="AA8" if re.search(pattern,string): print("Match Found") else: print("Match Not Found") groupsInRegex()
d48541c08f897ad44183748b8ed6f3a0d5b4ca1d
moofarry/data-science-course
/introduccion_python/tipos_estructurados/tuplas.py
393
4.0625
4
#se cuencia inmutables de objetos my_tuple = () type(my_tuple) my_tuple = (1, 'dos', True) #print(my_tuple[1]) my_tuple1= (1) print(type(my_tuple1)) my_tuple1= (1,) print(type(my_tuple1)) #reaccinando my_other_tuple = (2,3,4) my_tuple1 += my_other_tuple print(my_tuple1) #reempaquetar x,y,z = my_other_tuple print(x,'\n') def coordenadas(): return (5,4) x,y= coordenadas() print(x,y)
a1e4d653985b184538a634e3bc97bba3c913cc36
daniemart5/PythangMan
/2Dlists.py
579
4.03125
4
# matrix = [ # [1,2,3], # [4,5,6], # [7,8,9] # ] # print(matrix[2][1]) # matrix[2][1] = 20 # print(matrix[2][1]) # for row in matrix: # for item in row: # print(item) #list methods # numbers = [5,2,1,5,7,4] # print(numbers) # #adds 20 to the end # numbers.append(20) # #adds 10 at the 0 index # numbers.insert(0,10) # #removes 2 # numbers.remove(2) # #Returns true or false if number is present in list # print(7 in numbers) # #returns how many times 5 occurs # print(numbers.count(5)) # print(numbers) # #deletes values in list # numbers.sort() # print(numbers)
6f20a0f1cbb48ed0d127b32532ef61c5e98bcc2e
cassandrakane/Class-Selection-Sort
/ClassSelectionSort.py
5,172
4.15625
4
# Class Selection Sort Program import csv class Student: # constants for class size range MAX_CLASS_SIZE = 16 MIN_CLASS_SIZE = 10 # constants for class score calculations FIRST_IMPORTANCE = 40 SECOND_IMPORTANCE = 30 GENDER_IMPORTANCE = 20 LARGE_CLASS_IMPORTANCE = -100 SMALL_CLASS_IMPORTANCE = 40 NOT_SELECETD_CLASS_IMPORTANCE = -100 NO_PREFERENCE_IMPORTANCE = 0 def __init__(self, name, gender, first, second, third): self.name = name self.gender = gender self.first = first self.second = second self.third = third def is_male(self): return self.gender == 'Male' def is_female(self): return self.gender == 'Female' def is_other_gender(self): return (not self.is_male() and not self.is_female()) def calculate_class_score(self, klass, klass_name): score = 0 # prioritize class size if len(klass) > self.MAX_CLASS_SIZE: # deprioritize large class return self.LARGE_CLASS_IMPORTANCE if len(klass) < self.MIN_CLASS_SIZE: # prioritize small class score += self.SMALL_CLASS_IMPORTANCE score += 2 * (self.MAX_CLASS_SIZE - len(klass))**2 # prioritize smaller classes within range # prioritize first/second/third choice if klass_name == self.first: # prioritize first choice score += self.FIRST_IMPORTANCE elif klass_name == self.second: # prioritize second choice score += self.SECOND_IMPORTANCE elif self.first == "No Preference" or self.second == "No Preference" or self.third == "No Preference": # no prioritization for no preference score += self.NO_PREFERENCE_IMPORTANCE elif klass_name != self.third: # deprioritize non choice return self.NOT_SELECETD_CLASS_IMPORTANCE # prioritize gender balance males = len([1 for student in klass if student.is_male()]) # number of males females = len([1 for student in klass if student.is_female()]) # number of females if males > females: if self.is_male(): score -= self.GENDER_IMPORTANCE # deprioritize males in male-heavy class else: score += self.GENDER_IMPORTANCE # prioritize females in male-heavy class elif females > males: if self.is_male(): score += self.GENDER_IMPORTANCE # prioritize males in female-heavy class else: score -= self.GENDER_IMPORTANCE # deprioritize females in female-heavy class return score # get data from csv firstLine = True students = [] with open('ClassSelectionData.csv', newline='') as f: reader = csv.reader(f) for student_row in reader: if firstLine: # skip first line (labels) firstLine = False continue students.append(Student(student_row[1], student_row[2], student_row[3], student_row[4], student_row[5])) # count classes klass_names = [] for student in students: klass_names.extend([student.first, student.second, student.third]) for klass_name in klass_names: if klass_name == "No Preference": klass_names.remove(klass_name) klass_names_final = list(set(klass_names)) # first sort klasses = [] for class_name in klass_names_final: klasses.append([]) for student in students: scores = [] for i, klass in enumerate(klasses): scores.append(student.calculate_class_score(klass, klass_names_final[i])) # get scores for each student in each class klasses[scores.index(max(scores))].append(student) # choose class with highest score for student in class # resort (rearrange students and reevaluate scores) for i in range(100): for klass_out in klasses: temp_class = klass_out[:] for t,student in enumerate(temp_class): klass_out.pop(0) scores = [] for i,klass in enumerate(klasses): scores.append(student.calculate_class_score(klass, klass_names_final[i])) klasses[scores.index(max(scores))].append(student) # print classes in output file outfile = open("classes_output.txt", "w") # clear previous text outfile.close() outfile = open("classes_output.txt", "a") outfile.write("SORTED CLASSES (M/F/O)") for i, klass in enumerate(klasses): outfile.write("\n\n\n{} ({}/{}/{})\n".format(klass_names_final[i], len([1 for student in klass if student.is_male()]), len([1 for student in klass if student.is_female()]), len([1 for student in klass if student.is_other_gender()]))) for student in klasses[i]: student_choice = 0 if student.first == klass_names_final[i] or student.first == "No Preference": student_choice = 1 elif student.second == klass_names_final[i] or student.second == "No Preference": student_choice = 2 elif student.third == klass_names_final[i] or student.third == "No Preference": student_choice = 3 outfile.write("\n" + student.name + " (" + student.gender + ") - " + str(student_choice)) outfile.write("\n\n") outfile.close()
edb0b8978dbc60c27acd9f164f0a763c1c953cd5
macknilan/Cuaderno
/Python/ejemplos_ejercicios/poo_abstract_base_classes_ejem_01.py
818
4.15625
4
# abstract base classes import abc class Vehicle(abc.ABC): """ Declaracion de la clase abstracta """ @abc.abstractmethod def go(self): pass @abc.abstractmethod def stop(self): pass class Car(Vehicle): """ Clase heredada de -Vehicle- """ def go(self): print("You drive the car") def stop(self): print("This car is stopped") class Motorcycle(Vehicle): """ Clase heredada de -Vehicle- """ def go(self): print("You ride the motorcycle") def stop(self): print("This motorcycle is stopped") # vehicle = Vehicle() car = Car() motorcycle = Motorcycle() # vehicle.go() car.go() motorcycle.go() # vehicle.stop() car.stop() motorcycle.stop()
964929a375cc16aa56a6716c533dcee8a63abf19
mirandaday16/intent_chatbot
/time_zones.py
1,632
4.03125
4
# This file is used to get time zone data for the user # Using Amdoren API: https://www.amdoren.com/time-zone-api/ import requests import json from formatting import cap_first_letters api_key = "vGSiWG7aTLBXuL2W9hPbxMU94u9Vb5" base_url = "https://www.amdoren.com/api/timezone.php" # Takes a string entered by the user and converts it into a usable format for the API call def get_location_code(location): code = cap_first_letters(location) code = code.replace(" ", "+") return code # Converts military time and date to more readable format # Example of API timestamp result:"2016-11-04 23:18:46" def convert_time_format(timestamp): # remove date and seconds time = timestamp[11:16] # check for military time (PM) if int(time[:2]) > 12: hour = time[:2] converted_hour = int(hour) - 12 minutes = time[2:] new_time = str(converted_hour) + minutes + " PM" else: new_time = time + " AM" return str(new_time) # Gets local time in user-entered location using API # Location should be a city def get_time(location): location_code = get_location_code(location) complete_url = base_url + "?api_key=" + api_key + "&loc=" + location_code response = requests.get(complete_url) # JSON method of response object x = response.json() if x["error"] == 0: # store time data time = x["time"] converted_time = convert_time_format(time) reply = "Right now in " + cap_first_letters(location) + " it is " + converted_time + "." else: print(x) reply = "Sorry, I couldn't find the time for that location." return reply
bb5442f847a0169b830400b9c672f9aeac58ff8b
educardenas97/python_project
/app/Core/Class/Transporte.py
1,950
3.796875
4
import datetime class Transporte(): """ Clase Transporte Parametros: argumento1(Date): fecha de salida del transporte argumento2(int): capacidad de cargo. En Kg argumento3(int): precio del transporte por Kg. En $ argumento4(Date): fecha de llegada. (opcional) """ def __init__(self, fecha_salida, capacidad, precio_por_kg, fecha_llegada=datetime.datetime.now(),): self.fecha_salida = fecha_salida self.fecha_llegada = fecha_llegada self.capacidad = capacidad self.precio_por_kg = precio_por_kg self.paquetes = [] self.capacidad_utilizada = Transporte.sumar_paquetes(self.paquetes) self.capacidad_disponible = self.capacidad - self.capacidad_utilizada def sumar_paquetes(paquetes): """ Sumatoria del peso de todos los paquetes Parametros: argumento(Paquete): objeto del tipo paquete Retorna: (int) peso total """ total = 0 for paquete in paquetes: total += paquete.peso return total def agregar_paquete(self, paquete): """ Funcion que agrega un paquete al transporte Parametros: argumento(Paquete): objeto de tipo paquete que se quiere agregar Retorna: (bool) True en caso de agregarse de manera satisfactoria """ if self.capacidad_utilizada+paquete.peso < self.capacidad: self.paquetes.append(paquete) self.capacidad_utilizada += paquete.peso return True else: return False def calcular_costo(self): return self.capacidad_utilizada * self.precio_por_kg def __str__(self): return "fecha_salida: {}, fecha_llegada: {}, capacidad: {}, precio_por_kg: {}, capacidad_utilizada: {}".format(self.fecha_salida, self.fecha_llegada, self.capacidad, self.precio_por_kg, self.capacidad_utilizada)
ff4bf7429737887966134a628f26b199a855e039
nhoxbypass/100days-algorithm
/day45_binary_search_tree/bst.py
7,769
3.671875
4
import random # A Python class that represents an individual node # in a Binary Tree INT_MAX = 4294967296 INT_MIN = -4294967296 class Node: def __init__(self,key): self.left = None self.right = None self.val = key def __str__(self): res = "Val: " + str(self.val) if self.haveLeftChild(): res = res + ". Left: " + str(self.left.val) if self.haveRightChild(): res = res + ". Right: " + str(self.right.val) return res def haveLeftChild(self): if self.left is None: return False return True def haveRightChild(self): if self.right is None: return False return True class BinarySearchTree: def __init__(self): self.root = None # A utility function to insert a new node with the given key def insertTo(self, parent, node): if parent.val > node.val: if parent.haveLeftChild(): self.insertTo(parent.left, node) else: parent.left = node elif parent.val < node.val: if parent.haveRightChild(): self.insertTo(parent.right, node) else: parent.right = node # Method to for quick use without give the tree root node def insert(self, value): # If the tree is empty if self.root is None: self.root = Node(value) else: self.insertTo(self.root, Node(value)) def search(self, value): return self.searchAt(self.root, value) def searchAt(self, parent, value): # Base Cases: parent node is null or key is present at parent node if parent == None: return None if parent.val == value: return parent if parent.val > value: # Key is smaller than root's key return self.searchAt(parent.left, value) elif parent.val < value: # Key is greater than root's key return self.searchAt(parent.right, value) # Search without recursion def search_iteratively(key, node): current_node = node while current_node is not None: if key == current_node.key: return current_node if key < current_node.key: current_node = current_node.left else: # key > current_node.key: current_node = current_node.right return current_node # Given a binary search tree and a key, this function # delete the key and returns the new root def deleteAt(self, parent, value): # Base Case if parent is None: return parent # If key is same as root's key, then this is the node # to be deleted if parent.val == value: # Node with only one child or no child if parent.haveLeftChild() and not parent.haveRightChild(): # If there is only left child temp = parent.left parent = None return temp if not parent.haveLeftChild() and parent.haveRightChild(): # If there is only right child temp = parent.right parent = None return temp if not parent.haveLeftChild() and not parent.haveRightChild(): # No child node parent = None return None else: # Node with two children: Get the inorder successor # (smallest in the right subtree) # Because the min node in the right subtree is bigger than every node in the left subtree # And it is smaller than the rest node in the right subtree # So it suitable to be new parent node temp = self.minValueNode(parent.right) # Copy the inorder successor's content to this node # Instead if swap entire node, we copy value parent.val = temp.val # Delete the temp node # Use parent.right as the parent node to avoid delete current parent node # Because we've just copy the same value from temp node to parent parent.right = self.deleteAt(parent.right , temp.val) if value < parent.val: # If the key to be deleted is similiar than the root's # key then it lies in left subtree parent.left = self.deleteAt(parent.left, value) elif value > parent.val: # If the kye to be delete is greater than the root's key # then it lies in right subtree parent.right = self.deleteAt(parent.right, value) return parent def delete(self, value): return self.deleteAt(self.root, value) # Display the BST in increasing order def display(self): self.displayAt(self.root) def displayAt(self, node): if node is not None: self.displayAt(node.left) print(" " + str(node)) self.displayAt(node.right) # Given a non-empty binary search tree, return the node # with minum key value found in that tree. Note that the # entire tree does not need to be searched def minValueNode(self, node): current = node # loop down to find the leftmost leaf while(current.left is not None): current = current.left return current #generate 20 number from 0-17 def generate_input(): random_array = random.sample(range(17), 17) return random_array def sort(array): tree = BinarySearchTree() # Create tree for i in range(0, len(array)): tree.insert(array[i]) array.clear() get_inorder_traversal(array, tree.root) def get_inorder_traversal(array, parent): if parent is not None: get_inorder_traversal(array, parent.left) array.append(parent.val) get_inorder_traversal(array, parent.right) def storeBSTNodes(array, parent): if parent is not None: storeBSTNodes(array, parent.left) array.append(parent) storeBSTNodes(array, parent.right) # This functions converts an unbalanced BST to a balanced BST def balanceTree(node): # Store nodes of given BST in sorted order nodes = [] storeBSTNodes(nodes, node) n = len(nodes) return balanceTreeUtil(nodes, 0, n - 1) # Recursive function to construct binary tree def balanceTreeUtil(nodes, start, end): if start > end: return None # Get the middle element and make it root mid = (start + end) // 2 node = nodes[mid] # Using index in Inorder traversal, construct left and right subtress node.left = balanceTreeUtil(nodes, start, mid - 1) node.right = balanceTreeUtil(nodes, mid + 1, end) return node # TEST # Returns true if the given tree is a binary search tree # (efficient version) def isBST(node): return (isBSTUtil(node, INT_MIN, INT_MAX)) # Retusn true if the given tree is a BST and its values # >= min and <= max def isBSTUtil(node, mini, maxi): # An empty tree is BST if node is None: return True # False if this node violates min/max constraint if node.val < mini or node.val > maxi: return False # Otherwise check the subtrees recursively # tightening the min or max constraint return (isBSTUtil(node.left, mini, node.val -1) and isBSTUtil(node.right, node.val + 1, maxi)) # Running # Driver program to test above functions # Let us create following BST # 8 # / \ # 4 12 # / \ / \ # 2 6 10 14 # / \ / \ / \ / # 1 3 5 7 9 11 13 # Uncomment if you want to use random dynamic value # tree = generate_input() # tree = BinarySearchTree() # for item in random_array: # tree.insert(item) # # return tree tree = BinarySearchTree() tree.insert(8) tree.insert(4) tree.insert(2) tree.insert(1) tree.insert(3) tree.insert(6) tree.insert(5) tree.insert(7) tree.insert(12) tree.insert(10) tree.insert(9) tree.insert(11) tree.insert(14) tree.insert(13) print(" - Display: ") tree.display() check = isBST(tree.root) print(" - Check: " + str(check)) node = tree.search(6) print(" - Find 6: " + str(node)) tree.delete(1) print(" - Delete 1: ") tree.display() tree.delete(14) print(" - Delete 14: ") tree.display() tree.delete(4) print(" - Delete 4: ") tree.display() print(" - Random array: ") array = generate_input() print(array) sort(array) print(" - Sorted: ") print(array) print(" - Unbalanced BST: ") array.clear() array = generate_input() tree = BinarySearchTree() for item in array: tree.insert(item) print(" - Display: ") tree.display() print(" - Balance: ") tree.root = balanceTree(tree.root) tree.display()
cd80df887291e4dada90d579bebec4bc460c35fd
Guirguis87/CountWordss.py
/Count_words_from_file.py
2,723
4.25
4
while True: user_text = input (r" Please Enter your file path : ") user_text_file = str(user_text) exceptions_counting = ["?" , "," , "." , "!", "/" , "_", "@"] # Creating dynamic input for user to put the required path in dynamic way myfile = open(user_text_file , "r") myfile.seek(0) myfile.readlines() myfile.seek(0) # create myfile2 variable to can do splitting operation myfile2=myfile.read() myfile.seek myfile3= myfile2.split(" ") myfile.seek(0) # for more details, creating that list to identify no of letters will not be counted ! removed_letters = [] # creating that loop to iterate all words in file , and remove exceptions mentioned for i in myfile3 : if i in exceptions_counting: removed_letters.append(i) myfile3.remove(i) print(len(myfile3)) # creating Summary report if len(myfile3) > 0 : report = open(r"D:\Courses - Trainings\Programming\Projects\Count words in String\repot.txt","w+") finalevaluation= report.write(f"For the file in path {user_text_file} , no of words are {len(myfile3)} words ,Exluded letters are {removed_letters} No of Excluded letters {len (removed_letters)} ") report.close() print(f"For the file in path {user_text_file} , no of words are {len(myfile3)} words , No of Excluded letters {len (removed_letters)} ") user_decision = input ("Would you like to continue with another file: (y/n)") if user_decision == "y" : continue else: break # for i in myfile.readlines() : # if i in exceptions_counting: # myfile2= open(r"D:\Courses - Trainings\Programming\Projects\Count words in String\test.txt",w+) # myfile. # continue # print(len(myfile.readlines())) # for i in user_words : # if i in exceptions_counting: # user_words.remove(i) # continue # print(len(user_words)) # newfile= file.read() # newfile.replace(","," ") # newfile.replace("!"," ") # print(newfile) # newfile.split(" ") # # print(newfile.split(" ")) # # from os import replace # file = open(r"D:\Courses - Trainings\Programming\Projects\Count words in String\Words to be counted.txt", "w+") # file.seek(0) # # for i in file: # # if i == (",") or ("!") or ("?"): # # newfile= open(r"D:\Courses - Trainings\Programming\Projects\Count words in String\Words to be counted2.txt", "w+") # # replace(i, " ") # # newfile.close() # # print(newfile.readlines()) # newfile = open(r"D:\Courses - Trainings\Programming\Projects\Count words in String\Words to be counted2.txt","w+") # for i in file : # if i == "?" :
78072bb7fa904449382f0789886e0b248cb9d5b3
XixinSir/PythonKnowledgePoints
/XPath/lxml库的使用.py
1,102
3.640625
4
# 导入lxml库的etree模块 from lxml import etree ''' 使用之前,首先要确保安装好lxml库. 下面为使用XPath对网页进行解析的过程 ''' # 声明一段HTML文本 text = ''' <div> <ul> <li class="item-0"><a href="link1.html">first item</a></li> <li class="item-1"><a href="link2.html">second item</a></li> <li class="item-inactive"><a href="link3.html">third item</a></li> <li class="item-1"><a href="link4.html">fourth item</a></li> <li class="item-0"><a href="link5.html">fifth item</a> </ul> </div> ''' # 调用HTNL类进行初始化,构造一个XPath解析对象 html = etree.HTML(text) # HTML文本中最后一个li节点是没有闭合的,但是etree模块可以自动修正HTML文本 # 调用tostring()方法即可输出修正后的HTML代码,但是结果是bytes类型。调用decode()方法将其转成str类型 result = etree.tostring(html) print(type(result)) print(result.decode("utf-8")) # 经过上步的处理之后,li节点标签被补全,并且还自动添加了body、html节点。
86e769e59660181e815fc9175949f6e2d78d4fbd
malyshusness/random-python
/photo_organizer.py
6,485
3.984375
4
import shutil, os, platform import exifread def convert_month_to_number(month): '''Receives a string month and returns the number equivalent For example, October as input will return 10 ''' if month.lower() == 'january': return "1" elif month.lower() == 'february': return "2" elif month.lower() == 'march': return "3" elif month.lower() == 'april': return "4" elif month.lower() == 'may': return "5" elif month.lower() == 'june': return "6" elif month.lower() == 'july': return "7" elif month.lower() == 'august': return "8" elif month.lower() == 'september': return "9" elif month.lower() == 'october': return "10" elif month.lower() == 'november': return "11" elif month.lower() == 'december': return "12" def setup_photos(): '''Examines folders in current directory and looks for folders containing a month. Will create a new empty folder for any folder that has a month and year name but not formatted year-month (2016-11) Returns a list of folders to extract photos from. ''' for folder in folders: folder = folder.lower() photo_file_check = 0 if os.path.isdir(folder): for month_name in month_list: if month_name in folder: photo_file_check = 1 if photo_file_check == 1: month = folder.strip(",").split()[0].lower() if month not in month_list: parts = folder.split() for part in parts: if part.lower() in month_list: month = part.lower() month = convert_month_to_number(month) try: year = folder.split()[-1].lower() except IndexError: continue if not year.startswith('2'): print("Please make sure each folder ends with a year") exit() photo_folders.append(folder) foldername_format = ("{}-{}".format(year, month)) folder_names.append(foldername_format) new_folder_names = (set(folder_names)) for new_folder in new_folder_names: if new_folder not in folders: print("Creating folder: {}".format(new_folder)) os.mkdir(new_folder) return photo_folders def move_photos(photo_folders): '''Takes a list of folders, copies the photos in the folders, and saves them to the newly created photos. ''' for photo_folder in photo_folders: parts = photo_folder.split() if parts[0] in month_list: month = parts[0] month = convert_month_to_number(month) year = parts[-1] dest_folder = "{}-{}".format(year, month) files = os.listdir(photo_folder) print("Copying files from {} to {}...".format(photo_folder, dest_folder)) for file in files: full_name = os.path.join(photo_folder, file) if(os.path.isfile(full_name)): shutil.copy(full_name, dest_folder) else: for part in parts: if part in month_list: month = part month = convert_month_to_number(month) year = parts[-1] dest_folder = "{}-{}{}{}".format(year, month, sep, photo_folder) try: print('Copying folder {} to {}...'.format(photo_folder, dest_folder)) shutil.copytree(photo_folder, dest_folder) except FileExistsError: print("Duplicate files...doing nothing") def get_exif_time(file_path): '''Takes a file path as input, extracts EXIF data, and returns the data ''' img = open(file_path, 'rb') tags = exifread.process_file(img, details=False) try: timestamp = str(tags['EXIF DateTimeOriginal']).replace(':','-') except KeyError: try: timestamp = str(tags['EXIF DateTimeDigitized']).replace(':','-') except KeyError: print('Unable to find EXIF time. Leaving filename.') return return timestamp def rename_files(): '''Examines files in folders (that start with '20'), calls get_exif_time(), and renames the files to the EXIF time, if possible ''' dirs = os.listdir() for dir in dirs: if dir.startswith('20'): for foldername, subfolders, filenames in os.walk(dir): print('Checking files in folder {}...'.format(foldername)) for subfolder in subfolders: print('Checking files in {} in {}...'.format(subfolder, foldername)) for filename in filenames: if not filename.startswith('20'): print('Checking EXIF timestamp for {}...'.format(os.path.join(foldername, filename))) file_path = os.path.join(foldername, filename) new_name = get_exif_time(file_path) print(new_name) if new_name != None: ext = filename.split('.')[-1] new_name = "{}.{}".format(new_name, ext) new_file_path = os.path.join(foldername, new_name) try: shutil.move(file_path, new_file_path) except PermissionError as e: print('Unable to rename file: {}'.format(file_path)) print(e) continue if __name__ == '__main__': if platform.system() == 'Windows': sep = '\\' else: sep = '/' folders = os.listdir() folder_names = [] photo_folders = [] month_list = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] pic_folders_to_move = setup_photos() move_photos(pic_folders_to_move) rename_files()
7b3a2082ef0f5fca03e39cd25891cc9ba0320bde
rishabhchopra1096/Python_Crash_Course_Code
/Chapter_7_User_Input_And_While_Loop/Practice2/greeter.py
270
4.03125
4
# name = raw_input("Please enter your name. ") # print("Hello " + name.title() + "!") prompt = "If you tell us who you are , we can personlaize the message you see." prompt += "\nWhat is your first name? " name = raw_input(prompt) print("Hello " +name.title() + "!")
202c631a7a1b493c8f5e54f78207681e4f9d531c
Samrany/practice_problems
/fit-to-width.py
1,169
4.625
5
""" Write a function that prints a string, fitting its characters within char limit. It should take in a string and a character limit (as an integer). It should print the contents of the string without going over the character limit and without breaking words. For example: >>> fit_to_width('hi there', 50) hi there Spaces count as characters, but you do not need to include trailing whitespace in your output: >>> fit_to_width('Hello, world! I love Python and Hackbright', ... 10) ... Hello, world! I love Python and Hackbright Your test input will never include a character limit that is smaller than the longest continuous sequence of non-whitespace characters: >>> fit_to_width('one two three', 8) one two three """ def fit_to_width(string, limit): """Print string within a character limit.""" # create an empty string # loop over each word and add to string # only if length doesn't go over 10 (count how many chars left in line) # once hit 10, print string and start again if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print('\n✨ ALL TESTS PASSED!\n')
05ab1e291a3ec246b03b2ad0112068cf4ab07838
juliancomcast/100DaysPython
/Module1/Day06/day06_lists.py
2,710
4.4375
4
#creating an empty list list_1 = [] list_2 = list() print("List 1 Type: {}\nList 2 Type: {}".format(type(list_1), type(list_2))) print("break") print(f"List 1 Type: {type(list_1)}\nList 2 Type: {type(list_2)}") #list function created a list where each character is a seperate entry text = "Luggage Combination" print(list(text)) #.sort() method is used to sort a list luggage = [1, 3, 5, 2, 4] luggage.sort() print(luggage) #if a sort is applied to a variable created from a list, the sort is also applied to the original numbers = [1, 2, 3, 4, 5] numbers_sorted = numbers numbers_sorted.sort(reverse=True) print(f"numbers: {numbers}\n numbers_sorted: {numbers_sorted}") #in order to create a new version, a function needs to be called to the original list numbers = [1, 2, 3, 4, 5] numbers_sorted = list(numbers) numbers_sorted.sort(reverse=True) print(f"numbers: {numbers}\n numbers_sorted: {numbers_sorted}") #lists are easily combined odd = [1, 3, 5] even = [2, 4] luggage = odd + even print(luggage) luggage = [1, 3, 5] even = [2,4] luggage.extend(even) print(luggage) print(f"Unsorted list: {luggage}") print(f"Using the sorted() function: {sorted(luggage)}") luggage.sort() print(f"Using the .sort() method: {luggage}") #items can be added by also using the .append() method lines = [] lines.append("They told me to comb the desert, so I'm combing the desert") lines.append("YOGURT! I hate Yogurt! Even with strawberries") lines.append("We'll meet again Spaceballs 2: The Quest for More Money") print(lines) #the index of a requested item can be obtained using the .index() method, use the count method to obtain frequency of an iteam luggage = [1, 2, 3, 4, 5] print(luggage.index(2)) quote = list("YOGURT! I hate Yogurt! Even with strawberries") print(quote.count("r")) #using the .insert(index, item) method can be used to add a new item to the list at a specific position luggage = [1, 2, 4, 5] luggage.insert(2, 3) print(luggage) #the .pop(i) method is used to remove and return the final element, or from a specific index i luggage = [1, 2, 3, 3, 4, 5, 6] luggage.pop() print(luggage) luggage.pop(2) print(luggage) #the .remove(i) method eliminates a specific item (i) from the list rng = list(range(1,13)) rng.remove(7) print(rng) #the .reverse() method reverses the order of the items countdown = [5, 4, 3, 2, 1] countdown.reverse() print(countdown) #python can conduct transformations to a list while declaring a new list sample = list(range(1,13)) times_12 = [i * 12 for i in sample] print(times_12) #a list can be cleared luggage.clear() print(luggage) #since lists are mutable, items can be changed luggage = [2, 2, 3, 4, 5] luggage[0] = 1 print(luggage)
385fede71146ed571445c11c341376fb9403dbc6
AparnaKuncham/Python-Code
/PycharmProjects/untitled/venv/Scripts/new.py
132
3.6875
4
import re test_string="sphain" pattern='^s...n$' res=re.findall(pattern,test_string) if res: print("Yes") else: print("No")
ef46fb8f34e7c26dbb22b7bc5aadd5cdcc0bc2d8
daodinhngoc/pythonZerotoHero
/Fortnight_1/SRC/Day2/leap.py
187
3.875
4
""" Author: Jashan Date: 2018-May-30 Git: github.com/jashangunike """ Year = int(input("Please Enter Year")) is_leap = (Year %4 ==0 and Year &100 !=0 or Year%400 ==0) print(is_leap)
94af91b678c0c6bd086e296b682bdad529741575
he44/Practice
/aoc_2020/21/p1.py
2,677
3.828125
4
def main(): in_fname = "i1_eg.txt" in_fname = "i1.txt" lines = open(in_fname).read().strip().split('\n') ingreds, allers = grab_all(lines) print(ingreds) print(allers) ingred_to_aller = {key:[val for val in allers] for key in ingreds} print(ingred_to_aller) # for each food, if allerge A there, but ingredient B there # then B cannot contain A for line in lines: p1, p2 = line.split(' (contains ') fings = set(p1.split(' ')) falls = set(p2[:-1].split(', ')) for ing in ingred_to_aller: if ing in fings: continue else: for aller in falls: if aller in ingred_to_aller[ing]: ingred_to_aller[ing].remove(aller) impossible = [] for ing in ingred_to_aller: if len(ingred_to_aller[ing]) == 0: impossible.append(ing) print("impossible ingredients are {}".format(impossible)) ans = 0 for ing in impossible: ans += ingreds[ing] print("answer is {}".format(ans)) # build a new list after removing all impossible ones for ing in impossible: del ingred_to_aller[ing] print(ingred_to_aller) num_sols = len(ingred_to_aller) solved = dict() print("We should have {} pairs".format(num_sols)) while len(solved) != num_sols: sol_ing = set() sol_all = set() for ing in ingred_to_aller: # find a solution if len(ingred_to_aller[ing]) == 1: solved[ing] = ingred_to_aller[ing][0] ans = ingred_to_aller[ing][0] sol_ing.add(ing) sol_all.add(ans) # remove those matched for ing in sol_ing: del ingred_to_aller[ing] for ing in ingred_to_aller: for ans in sol_all: if ans in ingred_to_aller[ing]: ingred_to_aller[ing].remove(ans) # print the answer out properly ans = list([(key, solved[key]) for key in solved]) print(ans) ans.sort(key = lambda x: x[1]) print(ans) print("Formatted") ans_ids = [x[0] for x in ans] print(','.join(ans_ids)) def grab_all(lines): ingreds = dict() allers = set() for line in lines: p1, p2 = line.split(' (contains ') print(p1) print(p2) for ing in p1.split(' '): if ing in ingreds: ingreds[ing] += 1 else: ingreds[ing] = 1 for alle in p2[:-1].split(', '): allers.add(alle) return ingreds, allers if __name__ == "__main__": main()
46830e4faba8d17b5107eccc3642dab43c83f43f
ScottMerrill/Airminecodetest
/Great_Circle_Distance.py
2,716
3.765625
4
#!/usr/bin/python3 import sys import csv import random import math DEGREES_IN_RADIAN = 57.29577 MEAN_EARTH_RADIUS_KM = 6371 filename = 'places.csv' ############################################### Generate Data ############################################### # Read in command line argument or from places.csv and initilize dataset if len(sys.argv) == 2: # If command line input is given #TODO: Check that input is int # print('Randomly generating', sys.argv[1], 'data points') n = int(sys.argv[1]) D = [] # Initialize Data into a list for i in range(n): # Add n number of random locations to list loc = 'Random Loc ' + str(i) lat = round(random.uniform(-90, 90), 5) lon = round(random.uniform(-180, 180), 5) temp = (loc,lat,lon) D.append(temp) # print(*D, sep = "\n") # print(D[1]) elif len(sys.argv) == 1: # Using place.csv file for data # print ('Using places.csv') D = [] with open(filename,'r') as data: # Add each row from places.csv to Dictionary csv_reader = csv.reader(data) next(csv_reader) # Skip first line of .csv file for line in csv_reader: D.append(line) # print(*D, sep = "\n") else: print ('Error: Incorrect input') sys.exit(0) ############################################### Calculate the air distance ############################################### results = [] i = 0 average = 0 while i < len(D): j = i + 1 while j < len(D): loc1, lat1, lon1 = D[i] loc2, lat2, lon2 = D[j] # Convert degrees to radians lat1 = math.radians(float(lat1)) lon1 = math.radians(float(lon1)) lat2 = math.radians(float(lat2)) lon2 = math.radians(float(lon2)) # Haversine formula # https://medium.com/python-in-plain-english/calculating-great-circle-distances-in-python-cf98f64c1ea0 dlon = abs(lon2 - lon1) dlat = abs(lat2 - lat1) a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2)**2 c = 2 * math.asin(math.sqrt(a)) # convert from radians to km dist = round(c * MEAN_EARTH_RADIUS_KM, 5) # Store results average += dist temp = (loc1,loc2,dist) results.append(temp) #print(loc1,loc2,dist) j += 1 i += 1 ############################################### Sort and Print results ############################################### sorted_results = sorted(results, key=lambda tup: tup[2]) for row in sorted_results: print("{: <25} {: <25} {: <25}".format(*row)) print("Average distance:",average/len(sorted_results), "km. Closest pair:", sorted_results[0][0] , "–", sorted_results[0][1], sorted_results[0][2], "km.")
bd21748bcc6709684487a7993fee2442c05c608e
mtan22/CPE101
/projects/project3/solver.py
1,136
3.734375
4
#Michelle Tan #11/2/2020 #Project 3 import unittest from solverFuncs import* def main(): #Uses a for loop to create the general format of the puzzle first puzzle = [] cages=get_cages() for index in range(5): puzzle.append(5*[0]) index = 0 checks = 0 backtracks = 0 #Uses a while loop to iterate through the check functions in solverFuncs and counts the backtracks and checks in the loop while index < 25: puzzle[index//5][index%5] += 1 checks=checks+1 if check_valid(puzzle,cages) and puzzle[index//5][index%5] <= 5: index=index+1 elif puzzle[index//5][index%5] <= 4: pass else: puzzle[index//5][index%5] = 0 index=index-1 backtracks=backtracks+1 print() print ('---Solution---') print() #After the checks, the solution is made and the for loop displays the finished solution for index in range(len(puzzle)): print (' '.join(map(str, puzzle[index]))) print( '\nchecks: ' + str(checks) +' backtracks: ' + str(backtracks)) if __name__ == "__main__": main()
b83d2c8683d951e1964a4cd52a20adccc653d640
aldahirSealtiel/Hangman
/Problems/Checking email/task.py
267
3.625
4
def check_email(string): if ' ' not in string and '@' in string and '.' in string: index_symbol = string.index('@') index_dot = string.find('.', index_symbol) if -1 < index_dot > index_symbol + 1: return True return False
1f35c934efc48ea742157bcf16b9fdc636c64b08
Avvacuum/cources
/test04.py
524
3.96875
4
# TODO: dictionary with values inventory = { 'gold': 500, 'pouch': ['flint', 'twine', 'gemstone'], 'backpack': ['xylophone', 'dagger', 'bedroll', 'breadloaf'] } # TODO: add key_pocket and values to dictionary inventory["pocket"] = ['seashell', 'strange berry', 'lint'] # TODO: ( .sort()) elements in backpack and print inventory['backpack'].sort() print(inventory) # TODO: del dagger from list inventory['backpack'].remove('dagger') # TODO: add 50 gold and print results inventory['gold'] += 50 print(inventory)
37fb27602b7925bd479e87610be3c6adaeb5fb7a
charles-debug/learning_record
/96-函数说明文档.py
324
3.875
4
# help(len) help函数的作用就是查看函数的说明文档 def sum_num(a,b): """ 求和函数 """ return a + b help(sum_num) # 说明文档的高级使用 def sum_num1(a,b): """ 求和函数sum_num param a: param b: return: """ return a + b help(sum_num1)
a198cfcc18d389e98e7b2254a951c23e15370811
log2timeline/l2tdevtools
/l2tdevtools/versions.py
1,244
4
4
# -*- coding: utf-8 -*- """Functions to handle package versions.""" def CompareVersions(first_version_list, second_version_list): """Compares two lists containing version parts. Note that the version parts can contain alpha numeric characters. Args: first_version_list (list[str]): first version parts. second_version_list (list[str]): second version parts. Returns: int: 1 if the first is larger than the second, -1 if the first is smaller than the second, or 0 if the first and second are equal. """ first_version_list_length = len(first_version_list) second_version_list_length = len(second_version_list) for index in range(0, first_version_list_length): if index >= second_version_list_length: return 1 try: first_version_part = int(first_version_list[index], 10) second_version_part = int(second_version_list[index], 10) except ValueError: first_version_part = first_version_list[index] second_version_part = second_version_list[index] if first_version_part > second_version_part: return 1 if first_version_part < second_version_part: return -1 if first_version_list_length < second_version_list_length: return -1 return 0
add04089f0100e8268461f90737e09b99b9bbadb
fredrik84/AoC2017
/day3/part1/find.py
837
3.71875
4
#!/usr/bin/python3 import time with open("input") as f: data = int(f.readline().strip()) def move_right(x,y): return x+1, y def move_down(x,y): return x,y-1 def move_left(x,y): return x-1,y def move_up(x,y): return x,y+1 def gen_points(end): from itertools import cycle _moves = cycle(moves) n = 1 pos = 0,0 times_to_move = 1 yield n,pos while True: for _ in range(2): move = next(_moves) for _ in range(times_to_move): if n >= end: return pos = move(*pos) n+=1 yield n,pos times_to_move+=1 moves = [move_right, move_down, move_left, move_up] grid = list(gen_points(int(data))) if grid[data-1][1][0] < 0: x = -1*grid[data-1][1][0] else: y = grid[data-1][1][0] if grid[data-1][1][1] < 0: y = -1*grid[data-1][1][1] else: y = grid[data-1][1][1] print("%s" % str(int(x)+int(y)))
3d69c6c6bb2cee1b2f5747930915f014e45d791e
Shiv2157k/leet_code
/amazon/design/snake_game.py
2,715
4.28125
4
from typing import List from collections import deque class SnakeGame: """ W - Width, H - Height, N - no. of food items Time Complexity: - move method : O(1) - calculate bite itself: O(1) using dictionary - add and remove element from queue: O(1) Space Complexity: - O(W * H + N) - O(N) - food data structure - O(W * H) used by snake and snake grid. """ def __init__(self, width: int, height: int, food: List[List[int]]): """ Initialize data structure here. :param width: - screen width. :param height: - screen height. :param food: - a list of food position. eg: food = [[1,1], [1,0]] """ # initially snake is at origin or front self.snake = deque([(0, 0)]) self.snake_grid = {(0, 0): 1} self.height = height self.width = width self.food_index = 0 self.food = food self.movement = {"U": [-1, 0], "L": [0, -1], "R": [0, 1], "D": [1, 0]} def move(self, direction: str) -> int: """ Move the snake. :param direction: - "U" = up, "L" = left, "R" = right, "D" = down :return: game's score after move. -1 if game over snake crosses screen boundary or bites itself. """ # build the new head provided the direction new_head = (self.snake[0] + self.movement[direction][0], self.snake[1] + self.movement[direction][1]) # boundary conditions height_boundary_crossed = new_head[0] < 0 or new_head[1] >= self.height width_boundary_crossed = new_head[1] < 0 or new_head[1] >= self.width # bites itself bites_itself = new_head in self.snake_grid and new_head != self.snake[-1] # check the boundary conditions if height_boundary_crossed or width_boundary_crossed or bites_itself: return -1 # note food list could be empty next_food_item = self.food[self.food_index] if self.food_index < len(self.food) else None # if there is an available food item it is on cell occupied by snake after the move, eat it if self.food_index < len(self.food) and next_food_item[0] == new_head[0] and next_food_item[1] == new_head[1]: self.food_index += 1 else: # time to pop the tail and remove it from snake grid tail = self.snake.pop() del self.snake[tail] # add the new head self.snake.appendleft(new_head) # add it to the snake grid for tracking self.snake_grid[new_head] = 1 return len(self.snake) - 1
aabbf2e2d57a7208cda008e2c28f09b4803418cc
gevishahari/mesmerised-world
/dice2.py
207
3.890625
4
import random while True: x=int(input("press 1 to roll the dice and 0 to quit")) if(x==1): print(random.randint(1,6)) elif(x==0): print("bye!") break else: print("press either 1 or 0")
09d80c11216e021e63432295c322bc7f68e05d77
btemovska/ListsAndTuples
/Tuples_Intro.py
981
4.25
4
t = "a", "b", "c" print(t)#('a', 'b', 'c') <= this is tuples name = "Biljana" age = 10 print(name, age, "Python", 2020) #Biljana 10 Python 2020 print((name, age, "Python", 2020)) #('Biljana', 10, 'Python', 2020) welcome = "Welcome to the Nightmare", "Alice Cooper", 1975 bad = "Bad Company", "Bad Company", 1974 budgie = "Nightflight", "Budgie", 1981 imelda = "More Mayhem", "Emilda May", 2011 metallica = "Ride the Lightning", "Metallica", 1984 print(metallica) #('Ride the Lightning', 'Metallica', 1984) print(metallica[0]) #Ride the Lightning print(metallica[1]) #Metallica print(metallica[2]) #1984 #NOTE, they are immutable, thus you can't change what is in index 1 or 2 or 0, etc... #Lists are mutable #Tuples are immutable #if you want to change the data of tuples, create a list, than change it metallica2 = list(metallica) print(metallica2) #['Ride the Lightning', 'Metallica', 1984] metallica2[0] = "Master of Puppets" print(metallica2) #['Master of Puppets', 'Metallica', 1984]
7afd871d97f9602ce48cb76febdd51520aff47a3
park950414/python
/第三章/程序练习题/4.py
133
3.875
4
x=input("请输入一个5位数字:") if x==x[::-1]: print("这是一个回文数") else: print("这不是一个回文数")
18328f6032234a20a249f23136c8ed8dfbeca2e0
jamesfallon99/CA116
/lab_week05/pw-login-shell.py
316
3.6875
4
#!/usr/bin/env python s = raw_input() while s != "end": i = 0 while i < len(s) and s[len(s) - i - 1] != ":": i = i + 1 if i < len(s): j = 0 while j < len(s) and s[j] != ":": j = j + 1 if j < len(s): print s[:j], s[(len(s) - i):] s = raw_input()
04d0dd3c8f8f0b36926f97e23bc8d377c029b6b3
XiancaiTian/Leetcode
/q124.py
1,261
3.828125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # should consider every node as a new start # should return the better path in each recursion # Note: there is no need to reach the leaf # better path is selected from # (self + left, self + right, self only, self + left + right) # return path is selected from # (self + left, self + right, self only) # edge case, what if the tree looks like [-5] class Solution: def maxPathSum(self, root: TreeNode) -> int: self.maxi_sum = root.val self.dfs(root) return self.maxi_sum def dfs(self, root): if root: left_path = self.dfs(root.left) right_path = self.dfs(root.right) three_options = max(root.val, root.val + left_path, root.val + right_path) self.maxi_sum = max(self.maxi_sum, three_options, root.val + left_path + right_path) return three_options else: return 0
391976dc68ef9e144f66478807581a8a8f8052c4
gorillacodes/HelloWorld-
/Stone Paper Scissors.py
1,315
3.859375
4
from random import randint print ("Stone = 1\nPaper = 2\nScissors = 3\n") u_score = 0 c_score = 0 def game(): u_input = int(input("Your move? ")) c_input = randint(1, 4) if u_input == c_input: print("Tie") elif u_input == 1 and c_input == 2: print("Computer showed Paper \nComputer won") c_score += 1 elif u_input == 1 and c_input == 3: print("Computer showed Scissors \nYou won") u_score += 1 elif u_input == 2 and c_input == 1: print("Computer showed Stone \nYou won") u_score += 1 elif u_input == 2 and c_input == 3: print("Computer showed Scissors \nComputer won") c_score += 1 elif u_input == 3 and c_input == 1: print("Computer showed Stone \nComputer won") c_score += 1 elif u_input == 3 and c_input == 2: print("Computer showed Paper \nYou won") u_score += 1 else: print("Please enter a valid option") game() def stats(): print ("Computer Score = ",c_score) print ("Your Score = ",u_score) continue_input = int(input("\nDo you want to play again?\nYes = 1\nNo = 2\nStats = 3\n")) while continue_input == 1: game() stats()
76c50e58fb799403bc277b10c96eee8f0c625bff
Peterquilll/interview_questions
/chapter5/pairwise_swap.py
321
3.75
4
def pairwise_swap(a): mask = 0xAAAAAAAA even = a & mask odd = a & mask >> 1 even_shift = even >> 1 odd_shift = odd << 1 swap = even_shift | odd_shift return bin(swap) def main(): a = 0x66 result = pairwise_swap(a) print(bin(a), result) if __name__ == '__main__': main()
97a35f1f05a46138655e3b63066395d65fa4808f
KandyKad/Python-3rd-Sem
/Lab4/A4_3_py.py
115
3.5
4
l1 = [int(i) for i in input("Enter a list of numbers: ").split()] l2 = [int(i) for i in l1 if i%2==0] print(l2)
7eb947fdb2363b56d974062ea658766909155308
malker97/CS494ChatRoomProj
/Class/list.py
457
3.578125
4
#!/usr/bin/python3 # creat rooms import Room def creatlotsroom(arr_room,num): for i in range(num): arr_room.append(Room.creatchatroom('Room-'+str(i),i,'Test Uesr')) # return arr_room # show all infomation def listrooms(arr_room): str_roomlist = '' for i in range(len(arr_room)): str_roomlist += str(arr_room[i].name+'\n') return str_roomlist # rooms = [] # creatlotsroom(rooms,20) # print(listrooms(rooms))
be361903de9d0d9b9d190cccb6ff81c63dbb7373
Randeepk1/NLP
/NLP_W2S_W2W_STEMMER_LEMME.py
1,421
3.625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import nltk # nltk.download() from nltk.stem import PorterStemmer,WordNetLemmatizer from nltk.corpus import stopwords # In[2]: Pharagraph = 'Paragraphs are the building blocks of papers. Many students define paragraphs in terms of length: a paragraph is a group of at least five sentences, a paragraph is half a page long, etc. In reality, though, the unity and coherence of ideas among sentences is what constitutes a paragraph. A paragraph is defined as “a group of sentences or a single sentence that forms a unit” (Lunsford and Connors 116). Length and appearance do not determine whether a section in a paper is a paragraph. For instance, in some styles of writing, particularly journalistic styles, a paragraph can be just one sentence long. Ultimately, a paragraph is a sentence or group of sentences that support one main idea. In this handout, we will refer to this as the “controlling idea,” because it controls what happens in the rest of the paragraph' # In[3]: sentents = nltk.sent_tokenize(Pharagraph) # In[4]: sentents # In[5]: word = nltk.word_tokenize(Pharagraph) word # In[6]: stemmer = PorterStemmer() for i in range(len(sentents)): words = nltk.word_tokenize(sentents[i]) words = [stemmer.stem(word) for word in words if word not in set(stopwords.words('english'))] sentents[i]= ' '.join(words) # In[ ]:
5434aa8f584d09832687d48e3b9c0ea984fbb003
leandro-alvesc/estudos_python
/guppe/exercicios/secao_06/ex009.py
200
4.03125
4
# Ler um número inteiro N e depois imprima os N primeiros numeros naturais impares n = int(input('Digite um número inteiro N: ')) for num in range(1, n + 1): if num % 2 == 1: print(num)
c54d360c9798a7c5243f4e18c1072ff0f284bc52
SiyiGuo/Titan-V
/AlphaHalfGo-Zero/HalfGo/PubgArena.py
3,867
3.5625
4
import numpy as np class Arena(): """ An Arena class where any 2 agents can be pit against each other. """ def __init__(self, player1, player2, game, display=None): """ Input: player 1,2: two functions that takes board as input, return action game: Game object display: a function that takes board as input and prints it (e.g. display in othello/OthelloGame). Is necessary for verbose mode. see othello/OthelloPlayers.py for an example. See pit.py for pitting human players/other baselines with each other. """ self.player1 = player1 self.player2 = player2 self.game = game self.display = display def playGame(self, initBoard, verbose=False): """ Executes one episode of a game. player: lambda board, turn: np.argmax(pmcts.getActionProb(board, turn, temp=0) Returns: 1 white win -1 black win 0.001 draw """ # # For recors of a single game # self.boards = [] # self.turns = [] # self.pis = [] # self.curPlayers = [] players = [self.player2, None, self.player1] curPlayer = 1 board = initBoard turn = 0 #turn indicator curPlayer = 1 #WHite first #game start while self.game.getGameEnded(board, curPlayer, turn)==0 :# or turn < 256: #this should == trun < 24 if verbose: assert(self.display) print("Turn ", str(turn), "Player ", str(curPlayer)) self.display(board) #curPlayer = White = 1, curPlayer +1 = 2 -> players[2] = self.player1 #curPlayer = Black = -1, curPlayer + 1 = 0 -> players[0] = self.player2 canonicalBoard = self.game.getCanonicalForm(board, curPlayer) action = players[curPlayer+1](canonicalBoard, turn) # valids = self.game.getValidMoves(self.game.getCanonicalForm(board, curPlayer), curPlayer) valids = self.game.getValidMoves(canonicalBoard, 1) #as cannonical board convert to white if action != None and action != self.game.getActionSize(): if valids[action]==0: print("\n player: %s"%curPlayer) print(action) print(board) a = input() # #Recording the data # self.boards.append(canonicalBoard) # pis = [0] * self.game.getActionSize() # pis[action] = 1 # self.pis.append(pis) # self.turns.append(turn) # self.curPlayers.append(curPlayer) #update board, curPlayer, turn at the end, as developmet guide indeicated board, curPlayer = self.game.getNextState(board, curPlayer, action, turn) turn+=1 if verbose: assert(self.display) print("Game over: Turn ", str(turn), "Result ", str(self.game.getGameEnded(board, 1, turn))) self.display(board) #As get Game wnded return a player won or not #here we want white or balck wwin or not #so we passs object board, with 1 as player result = self.game.getGameEnded(board, 1, turn) # Continus print("Object board:\n%s"%np.array(board).reshape(8,8)) print("Player:%s won"%result) print("Tuen:%s"%turn) # # recording the data # for i in range(len(self.turns)): # canonicalBoard = self.boards[i] # pis = self.pis[i] # turn = self.turns[i] # curPlayer = self.curPlayers[i] # self.records.append((canonicalBoard, pis, result*((-1)**(curPlayer!=1)), turn)) return result
75f5aadd6ca332f0c30a5fbfc39ecc6f1ba4250d
jinurajan/Datastructures
/educative.io/coding_patterns/topological_sort/course_schedule_II.py
1,226
4.03125
4
""" Let’s assume that there are a total of n courses labeled from 0 to n-1. Some courses may have prerequisites. A list of prerequisites is specified such that if prerequisities=a,b , you must take course b before course a Given the total number of courses n and a list of the prerequisite pairs, return the course order a student should take to finish all of the courses. If there are multiple valid orderings of courses, then the return any one of them. Note: There can be a course in the 0 to n-1 range with no prerequisites. """ from collections import defaultdict from collections import Counter def find_order(n, prerequisites): graph = defaultdict(list) indegrees = {i: 0 for i in range(n)} for a, b in prerequisites: graph[b].append(a) indegrees[a] += 1 sources =[k for k,v in indegrees.items() if v == 0] sorted_order = [] while sources: # queue hence pop(0) subject = sources.pop(0) sorted_order.append(subject) for prereq in graph[subject]: indegrees[prereq] -= 1 if indegrees[prereq] == 0: sources.append(prereq) if len(sorted_order) != n: return [] return sorted_order
29d5280f271606bd6379a45b768e035d27c57473
k-young-passionate/Baekjoon
/python_version/p1747.py
645
3.859375
4
from math import sqrt def ispalindrome(num): n = str(num) front = n[:len(n)//2] if len(n)%2 == 0: addition = 0 else: addition = 1 back = n[len(n)//2+addition:] back = back[::-1] if front == back: return True else: return False def isprime(num): if num == 1: return False s = int(sqrt(num)) for i in range(2, s+1): if num % i == 0: return False return True n = int(input()) i = n prime = [] while True: flag = True if ispalindrome(i): if isprime(i): print(i) break i += 1 # print(prime)
c05186bdfd761d1b80706062d24a8006250b33e7
shruti280401/python
/project-data_analysis_udemycourses.py
1,334
3.8125
4
import pandas as pd data = pd.read_csv('7. Udemy Courses.csv') print(data.head()) #printing data for different subjects which udemey is offering courses print(data.subject.unique())#returns only unique element #######print(pd.Series(data.subject)) #printing data for which subject has maximum no of courses print(data.subject.value_counts()) #printing data for courses which are free of courses myvar = data[data.is_paid == False] ########print(myvar.to_string()) #showing data for all courses which r paid myvar = data[data.is_paid == True] print(myvar) #showing data for top selling courses print(data.sort_values('num_subscribers',ascending=False)) #least selling courses print(data.sort_values('num_subscribers')) #all courses of graphic design where price is below 100 print(data[(data.price > '100') & (data.subject == 'Graphic Design') ]) #filtering #all coursesrelated to python print(data[data.course_title.str.contains('Python')]) #courses published in yr 2015 data['published_timestamp'] = pd.to_datetime(data.published_timestamp) data['Year'] = data['published_timestamp'].dt.year print(data[data.Year == 2015]) #max no of suscriber for each level of courses data.level.unique() print(data.groupby('level')['num_subscribers'].max()) print(data.groupby('level').max())
e1f74711235a4d613c05dfbd559f4717267e3850
ternura001/store
/猜字游戏.py
819
3.78125
4
#任务:开始金币有5个金币,每猜一次减一个为0就退出(or充钱)猜错3次也退出 import random randint=random.randint(10, 20)#随机生成数字的范围:int [] print(randint) i=3 a=5 while i>=1: print("您还有机会%d次"%i) print("您还有金币%d个"%a) num=int(input("请输入您猜的数字")) if num==randint: print("恭喜你猜对了") a=a+3 randint = random.randint(10, 20) print(randint) i=3 continue elif num>randint: print("猜大了,再来一次") elif num<randint: print("猜小了,再来一次") else: print("再来一次") i=i-1 a=a-1 print("金币剩余%d"%a) if i == 0: a = a - 3 i = i + 1 if a<=0: break
3c98897a6108d5b492a506e3237935c7975e5ac3
alirezaghey/leetcode-solutions
/python/remove-duplicates-from-sorted-array-ii.py
376
3.734375
4
from typing import List # Time complexity: O(n) where n is the length of nums # Space complexity: O(1) # Two pointer approach class Solution: def removeDuplicates(self, nums: List[int]) -> int: left = 2 for i in range(2, len(nums)): if nums[left-2] != nums[i]: nums[left] = nums[i] left += 1 return left
f5d3a057ddba1ebd47141433c7e05acad24539d5
fumokmm/language-examples
/Python/0009_isnumber.py
1,016
3.53125
4
# 半角数値 s1 = "1234567890" assert s1.isdecimal() == True assert s1.isdigit() == True assert s1.isnumeric() == True # 全角文字 s2 = "1234567890" assert s2.isdecimal() == True assert s2.isdigit() == True assert s2.isnumeric() == True # 2乗を表す上付き数字² pow2 = "²" assert pow2.isdecimal() == False # decimalではFalse assert pow2.isdigit() == True assert pow2.isnumeric() == True # 分数 fraction = "½" assert fraction.isdecimal() == False assert fraction.isdigit() == False assert fraction.isnumeric() == True # ローマ数字 roman = "Ⅶ" assert roman.isdecimal() == False assert roman.isdigit() == False assert roman.isnumeric() == True # 漢数字 kanji1 = "一二三四五六七八九〇" kanji2 = "壱億参阡萬" assert kanji1.isdecimal() == False assert kanji1.isdigit() == False assert kanji1.isnumeric() == True assert kanji2.isdecimal() == False assert kanji2.isdigit() == False assert kanji2.isnumeric() == True
3b7895d1b1b2934805c390bab2dc3d7d99d65050
ccoleman19/Analytic-Avengers
/SalesTaxCalculator.py
974
3.9375
4
# from calcTax import calculateTax def calculateTax(price): tax = round(price*.06,2) total = round(price + tax,2) return tax, price, total def runningTotal(): lastItem = True total = 0 while lastItem == True: price = float(input("Cost of item: ")) if price > 0: total = round(price + total,2) elif price == 0: lastItem = False return total def redo(): option = input("\n\nWould you like to perform another conversion? (y/n): ").lower() if option == "y": main() else: print("\nThanks, bye!") def main(): print("Sales Tax Calculator\n\n") print("ENTER ITEMS (ENTER 0 TO END)") tax, price, total = calculateTax(runningTotal()) print(f"Total: {price}") print(f"Sales Tax: {tax}") print(f"Total After Tax: {total}") redo() if __name__ == '__main__': main()
bbfafb340cc3dde0857724fe60cffa0d83b8d416
jhiltonsantos/ADS-Algoritmos-IFPI
/Atividade_Fabio_02a_Condicionais/fabio_02a_19_imc.py
368
3.890625
4
def main(): altura = float(input('Altura (em metros): ')) peso = float(input('Peso (em quilogramas): ')) calc_imc = peso / (altura**2) if calc_imc < 25: print('Peso Normal') elif 25 <= calc_imc <= 30: print('Obeso') elif calc_imc > 30: print('Obesidade morbida') if __name__ == '__main__': main()
d514c75601121d623c7a24de1a6ce6bbd3068ee9
emirbuckun/CS50-Problems
/Problem6/Cash/cash.py
498
3.75
4
def main(): amount = get_amount() print(change(amount * 100)) def change(cents): return round(cents // 25 + (cents % 25) // 10 + ((cents % 25) % 10) // 5 + ((cents % 25) % 10) % 5) def get_amount(): while True: try: n = float(input("Change owed: ")) if n >= 0: break except: print("INVALİD") return n main()
15c61272e7a72c3cac14453fc3d2447711c99f68
shengchaohua/shiyanlou-solution
/classic-algorithm-in-action/classic-algorithm-solution-in-python/FactorialTrailingZeroes.py
689
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 5 18:47:34 2018 @problem: leetcode 172. & lintcode 2. Factorial Trailing Zeroes @author: sheng """ class Solution: def trailingZeroes(self, n): """ :type n: int :rtype: int """ # loop if n < 0: return -1 count = 0 while n > 0: n //= 5 # 计算因子 5 的个数 count += n return count def trailingZeroes2(self, n): # recursive if n < 0: return -1 if n == 0: return 0 else: return n // 5 + self.trailingZeroes2(n // 5)
57d8727e405c699116a2c052a3072dd1fbffd2ca
marnovo/ml
/ast2vec/token_parser.py
2,466
3.546875
4
import re import Stemmer class TokenParser: """ Common utilities for splitting and stemming tokens. """ NAME_BREAKUP_RE = re.compile(r"[^a-zA-Z]+") #: Regexp to split source code identifiers. STEM_THRESHOLD = 6 #: We do not stem splitted parts shorter than or equal to this size. MAX_TOKEN_LENGTH = 256 #: We cut identifiers longer than thi value. def __init__(self, stem_threshold=STEM_THRESHOLD, max_token_length=MAX_TOKEN_LENGTH): self._stemmer = Stemmer.Stemmer("english") self._stemmer.maxCacheSize = 0 self._stem_threshold = stem_threshold self._max_token_length = max_token_length def process_token(self, token): for word in self.split(token): yield self.stem(word) def stem(self, word): if len(word) <= self._stem_threshold: return word return self._stemmer.stemWord(word) def split(self, token): token = token.strip()[:self._max_token_length] prev_p = [""] def ret(name): r = name.lower() if len(name) >= 3: yield r if prev_p[0]: yield prev_p[0] + r prev_p[0] = "" else: prev_p[0] = r for part in self.NAME_BREAKUP_RE.split(token): if not part: continue prev = part[0] pos = 0 for i in range(1, len(part)): this = part[i] if prev.islower() and this.isupper(): yield from ret(part[pos:i]) pos = i elif prev.isupper() and this.islower(): if 0 < i - 1 - pos <= 3: yield from ret(part[pos:i - 1]) pos = i - 1 elif i - 1 > pos: yield from ret(part[pos:i]) pos = i prev = this last = part[pos:] if last: yield from ret(last) def __getstate__(self): state = self.__dict__.copy() del state["_stemmer"] return state def __setstate__(self, state): self.__dict__ = state self._stemmer = Stemmer.Stemmer("english") class NoTokenParser: """ One can use this class if he or she does not want to do any parsing. """ def process_token(self, token): return [token]
57a714dfc0e8946ded0339c71c584f2ead344108
gi4nchi/HW03
/MagicMaze.py
1,017
3.8125
4
import random def life_counter(errors, lives): if errors < 10: errors += 1 elif errors == 10: print("You lost one life") lives += 1 errors = 0 if lives == 3: print("You lost") exit() return errors, lives counter = 0 errors = 0 lives = 0 directions=['N','S','E','W'] random.shuffle(directions) #print(directions)# to know the password in advance print( end= "Welcome to de magic maze, which way do you want to go? ") while True: guess= input("N,S,E,W?\n") if guess in directions: #print(directions[counter])#try to get what gets from the list each turn if(guess==directions[counter]): print("Well done") counter+=1 if(counter==len(directions)): print("You Win") exit() else: print("Wrong answer") errors,lives=life_counter(errors,lives) else: print("Not a valid answer") errors,lives=life_counter(errors,lives)
8ee9efa2cc92269d2bebc7ea41b31de359da6687
tedbennett/data-structures
/dequeue.py
3,565
3.703125
4
from simple_queue import CircularQueue import unittest class Deque(CircularQueue): def __init__(self, length): super().__init__(length) def add_first(self, item): if self.len >= self.max_size: raise Exception("Deque is full") self.zero_index -= 1 if self.zero_index < 0: self.zero_index = self.max_size + self.zero_index self._queue[self.zero_index] = item self.len += 1 def add_last(self, item): super().enqueue(item) def remove_first(self): return super().dequeue() def remove_last(self): if self.len == 0: raise Exception("Dequeue is empty") index = (self.zero_index + self.len - 1) % self.max_size # finds end of queue, checks if needs to wrap around item = self._queue[index] self._queue[index] = None self.len -= 1 return item def first(self): return super().first() def last(self): if self.len == 0: raise Exception("Deque is empty") return self._queue[self.zero_index + self.len - 1] def resize(self, length): super().resize(length) def is_empty(self): return super().is_empty() def __len__(self): return super().__len__() class DequeTest(unittest.TestCase): def test_init(self): """ Tests deque initialises correctly, and checks head() raises and exception correctly :return: """ queue = Deque(20) self.assertEqual(queue.len, 0) self.assertEqual(len(queue._queue), 20) with self.assertRaises(Exception): queue.first() with self.assertRaises(Exception): queue.last() def test_add(self): queue = Deque(20) for i in range(10): queue.add_last(i) for i in range(10, 20): queue.add_first(i) with self.assertRaises(Exception): queue.add_last(1) def test_remove(self): queue = Deque(20) for i in range(10): queue.add_last(i) self.assertEqual(len(queue), 10) self.assertEqual(queue.remove_first(), 0) self.assertEqual(len(queue), 9) self.assertEqual(queue.first(), 1) self.assertEqual(queue.remove_last(), 9) self.assertEqual(queue.last(), 8) def test_wraparound(self): """ Tests that adding extra elements will cause the deque to wraparound the array :return: """ queue = Deque(10) for i in range(10): queue.add_last(i) self.assertEqual(queue.zero_index, 0) queue.remove_first() self.assertEqual(queue.zero_index, 1) queue.add_last(11) # should be at array index 0 for i in range(8): queue.remove_first() self.assertEqual(queue.zero_index, 9) queue.remove_first() self.assertEqual(queue.zero_index, 0) self.assertEqual(queue.first(), 11) def test_resize(self): queue = Deque(5) for i in range(5): queue.add_last(i) queue.remove_first() self.assertEqual(queue.zero_index, 1) self.assertEqual(len(queue), 4) queue.resize(10) self.assertEqual(len(queue._queue), 10) self.assertEqual(queue.zero_index, 0) self.assertEqual(len(queue), 4) for i in range(4): queue.enqueue(i) with self.assertRaises(Exception): queue.resize(3) if __name__ == "__main__": unittest.main()
24f0cb316a1bfe1de86c59aaad465f66a039078c
1987617587/lsh_py
/basics/day5/lzt/parameter_test.py
5,700
3.75
4
# author:lzt # date: 2019/11/12 14:20 # file_name: parameter_test # 参数的定义 # 形参:a,b def add(a: int, b: int): """ 为a和b求和 :param a: 数据a :param b: 数据b :return: 两个数据的和 """ return a + b # 函数执行 # c = "a" # d = "b" # # 实参:c,d # print(add(c, d)) # 1.写一个函数根据用户的按键不同角色播放不同的动画。 def doaction(key): """ 根据key做出不同的动画效果 :param key:用户的按键 :return:None """ # 根据按键做动画播放 if key == "w": print("播放前进动画") elif key == "d": print("播放右移动画") elif key == "a": print("左移动画") elif key == "s": print("后退动画") else: print("不支持该按键!") # while 1: # doaction(input("请按键")) # 2.写一个函数,传入攻击者的攻击力,技能加成系数,被攻击者的防御力,计算出伤害值。 def hurt(atk, sk_per, h_def, dis_per): """ 计算伤害值并返回 :param atk:主动攻击方的攻击力 :param sk_per:本次的技能伤害 :param h_def:被攻击方的防御力 :param dis_per:防御力的抵伤系数 :return:本次的真实伤害值 """ hurt = atk * sk_per - h_def * dis_per return 1 if hurt < 0 else hurt # 测试伤害函数 # e_atk = 1500 # e_sk_per = 2 # e_h_def = 1200 # e_dis_per = 0.2 # print(f"本次伤害值为:{hurt(e_atk, e_sk_per, e_h_def, e_dis_per)}") # print(f"本次伤害值为:{hurt(2000, 1.7, 1800, 0.3)}") # 位置参数:按次序摆放的形参 def print_nums(arg1, arg2, arg3): """ 输出传入的参数 :param arg1:第一个参数 :param arg2:第二个参数 :param arg3:第三个参数 :return:None """ print(arg1) print(arg2) print(arg3) # 实参传入并执行 # print_nums(1, 2, 3) # print_nums(2, 1, 3) # print_nums(3, 1, 2) # 位置参数可以按照名字来传参 # print_nums(arg2=10, arg3=5, arg1=6) # print_nums(1, arg3=2, arg2=1) # 银行的开卡 # 以默认值的方式写的参数 可以免于传递 def create_card(name, pid, gender="男", tel="123456", addr=None, b_g=None): """ 为开卡输入用户数据 :param name:真实姓名 :param pid:身份证号 :param gender:性别 :param tel:电话号码 :param addr:住址 :param b_g:男女朋友 :return:None """ print(f"开卡的用户{name} 身份证号:{pid} 性别:{gender} 电话:{tel} 住址:{addr} 有没有朋友:{b_g}") # 进行单据的填写 # create_card("002", "1234") # create_card("002", "12345", "女") # create_card("002", "123456", "女", "12312312312") # create_card("001", "121xxxxxxx", "男", "16666666xxx") # create_card(pid="123123", name="123", gender="女") # 命名关键字参数:* def print_args(arg1, arg2, *, arg3, arg4): print(arg1, arg2, arg3, arg4) # print_args(1, 2, 3, 4) # print_args(1, 2, arg4=4, arg3=3) # def be_hurt(): # print("未命中目标") # # # def be_hurt(player1): # print("未命中目标") # # # def be_hurt(player1, player2): # print("未命中目标") # 可变参数列表 # 1. 可变参数列表是否可以和其他参数形式混杂 # def be_hurt(player, *args): # """ # 减掉AOE释放技能伤害的角色的血量值 # :param player:主动攻击的角色 # :param args:被命中的角色 # :return:None # """ # # 查看一下args的类型 # print(type(args)) # # 遍历args这个容器 查看被打中的角色 # for i in range(len(args)): # print(f"{player}击中了{args[i]}!") # be_hurt("悟空") # be_hurt("悟空", "阿珂") # be_hurt("悟空", "阿珂", "嬴政") # be_hurt("悟空", "阿珂", "嬴政", "妲己") # 2.可变参数列表一般情况下位于目前参数的末尾 def be_hurt(*args, player): """ 减掉AOE释放技能伤害的角色的血量值 :param player:主动攻击的角色 :param args:被命中的角色 :return:None """ # 查看一下args的类型 print(type(args)) # 遍历args这个容器 查看被打中的角色 for i in range(len(args)): print(f"{player}击中了{args[i]}!") # be_hurt("1", "2", "3", player="4") # 3.可变参数列表和*是互不见面的状态 # def be_hurt(*, args1, arg2, *args): # pass # be_hurt(args1=1,arg2=2,a="1",b="2") # 参数的打包和解包 # 参数的打包:*args **args方式来完成打包 # def nums(*args): # pass # nums(1, 2, 3, 4, 5, 6, 7, 8) # 参数的解包 nums = [1, 2, 3, 4, 5, 6, 7] def show_nums(a, b, c, d, e, f, g): print(a, b, c, d, e, f, g) # show_nums(*nums) # 函数内的修正对实参有无影响? # def swap(a, b): # a, b = b, a # print(f"a={a} b={b}") # c = 1 # d = 2 # swap(c, d) # print(f"c={c} d={d}") # def swap(arr): # # 交换列表中0和1位置 # arr[0], arr[1] = arr[1], arr[0] # print(f"函数内的列表:{arr}") # pass # # # arr_obj = [1, 2] # swap(arr_obj) # print(arr_obj) # 可变和不可变类型 # str1 = "bcd" # print(id(str1)) # str1 = "abc" # print(id(str1)) # 不可变类型的传参 def change(str1, num, bool1): str1 = "1111" num = 1234 bool1 = False # 传入不可变类型的实参:函数内的修改不会影响实参 # s1 = "ok" # num1 = 123 # bool11 = True # change(s1, num1, bool11) # print(s1, num1, bool11) # 可变类型的传参:影响的程度:1.若可变类型的下属的值发生改变 可以影响到实际参数 2.若整体发生了改变 不影响实参 def change_list(arr): # arr[3] = 10 arr = [100, 1000] arr2 = [1, 2, 3, 4] change_list(arr2) print(arr2)
544346359175959e4525f48ede467b184a05d878
kabu1zhan/training
/kursOOP/Refactoring.py
5,922
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pygame import random import math SCREEN_DIM = (800, 600) class Vec2d(): def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return type(self)(self.x + other.x, self.y + other.y) def __sub__(self, other): return type(self)(self.x - other.x, self.y - other.y) def __mul__(self, k): return type(self)(self.x * k, self.y * k) def int_pair(self): return (self.x, self.y) def __len__(self): return int(math.sqrt(self.x ** 2 + self.y ** 2)) def __str__(self): return str(self.int_pair()) def __repr__(self): return str(self.int_pair()) class Polyline(): def __init__(self): self.points = [] self.speeds = [] def add_point(self, point): self.points.append(Vec2d(point[0], point[1])) self.speeds.append(Vec2d( random.random() * 2, random.random() * 2 )) def get_point(self, points, alpha, deg=None): if deg is None: deg = len(points) - 1 if deg == 0: return points[0] return points[deg] * alpha + self.get_point(points, alpha, deg - 1) * (1 - alpha) def get_points(self, points): alpha = 1 / self.count res = [] for i in range(self.count): res.append(self.get_point(points, i * alpha)) return res def set_points(self): """функция перерасчета координат опорных точек""" for p in range(len(self.points)): self.points[p] = self.points[p] + self.speeds[p] if self.points[p].x > self.dim[0] or self.points[p].x < 0: self.speeds[p] = Vec2d(-self.speeds[p].x, self.speeds[p].y) if self.points[p].y > self.dim[1] or self.points[p].y < 0: self.speeds[p] = Vec2d(self.speeds[p].x, -self.speeds[p].y) def draw_points(self, game, display, style="points", width=3, color=(255, 255, 255)): """функция отрисовки точек на экране""" if style == "line": points = self.get_knot() for p_n in range(-1, len(points) - 1): game.draw.line(display, color, (int(points[p_n].x), int(points[p_n].y)), (int(points[p_n + 1].x), int(points[p_n + 1].y)), width) elif style == "points": for p in self.points: game.draw.circle(display, color, (int(p.x), int(p.y)), width) def draw_help(game, display, steps): """функция отрисовки экрана справки программы""" display.fill((50, 50, 50)) font1 = game.font.SysFont("courier", 24) font2 = game.font.SysFont("serif", 24) data = [] data.append(["F1", "Show Help"]) data.append(["R", "Restart"]) data.append(["P", "Pause/Play"]) data.append(["Num+", "More points"]) data.append(["Num-", "Less points"]) data.append(["", ""]) data.append([str(steps), "Current points"]) game.draw.lines(display, (255, 50, 50, 255), True, [ (0, 0), (800, 0), (800, 600), (0, 600)], 5) for i, text in enumerate(data): display.blit(font1.render( text[0], True, (128, 128, 255)), (100, 100 + 30 * i)) display.blit(font2.render( text[1], True, (128, 128, 255)), (200, 100 + 30 * i)) class Knot(Polyline): def __init__(self, count, dim): super().__init__() self.count = count self.dim = dim def get_count(self): return self.count def set_count(self, count): if count > 0: self.count = count def get_knot(self): if len(self.points) < 3: return [] res = [] for i in range(-2, len(self.points)-2): ptn = [] ptn.append((self.points[i] + self.points[i+1])*0.5) ptn.append(self.points[i+1]) ptn.append((self.points[i+1] + self.points[i+2])*0.5) res.extend(self.get_points(ptn)) return res if __name__ == "__main__": pygame.init() gameDisplay = pygame.display.set_mode(SCREEN_DIM) pygame.display.set_caption("MyScreenSaver") steps = 35 working = True show_help = False pause = True knot = Knot(steps, SCREEN_DIM) hue = 0 color = pygame.Color(0) while working: for event in pygame.event.get(): if event.type == pygame.QUIT: working = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: working = False if event.key == pygame.K_r: knot = Knot(steps) if event.key == pygame.K_p: pause = not pause if event.key == pygame.K_KP_PLUS: knot.set_count(knot.get_count()+1) if event.key == pygame.K_F1: show_help = not show_help if event.key == pygame.K_KP_MINUS: steps = knot.get_count() knot.set_count(steps-1 if steps > 1 else 0) if event.type == pygame.MOUSEBUTTONDOWN: knot.add_point(event.pos) gameDisplay.fill((0, 0, 0)) hue = (hue + 1) % 360 color.hsla = (hue, 100, 50, 100) knot.draw_points(pygame, gameDisplay) knot.draw_points(pygame, gameDisplay, style="line", width=3, color=color) if not pause: knot.set_points() if show_help: Knot.draw_help(pygame, gameDisplay, knot.get_count()) pygame.display.flip() pygame.display.quit() pygame.quit() exit(0)
d1c02a5bebe070d0394e5fcf4c5ed8303ddd18f6
zy924/Algo
/insertion1.py
567
4.21875
4
""" Insert a number into a sorted array, the number will in the rightmost cell. Print the array every time a number is shifted. For example: Input: 2 3 4 1 Output: 2 3 4 4 2 3 3 4 2 2 3 4 1 2 3 4 """ #input A = [2,3,4,5,1] def insertion1(ar): m = len(ar) e = ar[-1] for i in xrange(m-2,-1,-1): if ar[i]<=e: ar[i+1]=e print " ".join(map(str,ar)) break else: ar[i+1]=ar[i] print " ".join(map(str,ar)) if e<ar[0]: #Be careful when you down to the 0 index ar[0]=e print " ".join(map(str,ar)) return if __name__ == "__main__": insertion1(A)
cd6b854695b73229b635fe15de3bdea5e1cdff79
maximkavm/ege-inf
/15/Числовые отрезки/Решение.py
311
3.5
4
P = range(2, 10+1) Q = range(6, 14+1) def F(x, An, Ak): A = range(An, Ak+1) return ((x in A) <= (x in P)) or (x in Q) max_len = 0 for An in range(1, 99): for Ak in range(An+1, 100): OK = all(F(x, An, Ak) for x in range(1000)) if OK: max_len = max(max_len, Ak - An) print(max_len) # Ответ: 12
ca367ff37ad0b77d61b84f11c6d6b17156e81c54
side-projects-42/DS-Bash-Examples-Deploy
/CONTENT/DS-n-Algos/ALGO/__PYTHON/word_count.py
432
3.71875
4
file=open("sample.txt","r") d=dict() for lines in file: lines=lines.strip() lines=lines.lower() words=lines.split(" ") for word in words: if word in d: d[word]=d[word]+1 else: d[word]=1 find=str(input("enter the word to count: ")) find=find.lower() if find in list(d.keys()): print(f"{find} : "+ str(d.get(find))) else: print("word not present!! ")
7f5a6b975822e91f1c7368d7fae4082e444d4f2e
mikeodf/Python_Line_Shape_Color
/ch5_prog_6_line_randomize_1.py
3,990
4.21875
4
""" ch5 No.6 Program name: line_randomize_1.py Objective: Draw two segmented sets of lines with a confined but random (Gaussean)components. Keywords: random vertical, distribution ============================================================================79 Comments: We draw a set of segmented line with partially random vertical components using the function line_randomize_vertical(...). We also draw a set of segmented line with partially random vertical as well as horizontal components using the function line_randomize_xy(...). A gaussean random distribution is used. Tested on: Python 2.6, Python 2.7.3, Python 3.2.3 Author: Mike Ohlson de Fine """ from Tkinter import * #from tkinter import * # For Python 3.2.3 and higher. from random import * root = Tk() root.title(" Randomize lines.") cw = 750 # canvas width ch = 500 # canvas height canvas_1 = Canvas(root, width=cw, height=ch, background="white") canvas_1.grid(row=0, column=1) def line_randomize_vertical(xy_line, x_delta, standard_deviation): """ Draw a segmented line with randomized vertical component added. """ num_steps = int((xy_line[2] - xy_line[0])/x_delta) xy_list = [] for i in range(num_steps): y_randomized = xy_line[1] + gauss(mean, standard_deviation) x_next = xy_line[0] + i * x_delta xy_list.append(x_next) xy_list.append(y_randomized) canvas_1.create_line(xy_list, width = 3) def line_randomize_xy(xy_line, x_delta, standard_deviation): """ Draw a segmented line with randomized vertical component added. """ num_steps = int((xy_line[2] - xy_line[0])/x_delta) xy_list = [] line_randomize_1.py for i in range(num_steps): y_randomized = xy_line[1] + gauss(mean, standard_deviation) x_randomized = xy_line[0] + i * x_delta + gauss(mean, standard_deviation) xy_list.append(x_randomized) xy_list.append(y_randomized) canvas_1.create_line(xy_list, width = 3) # Execute and Demonstrate. # ========================== x_delta = 2.0 mean = 1.0 standard_deviation = 2.0 xy_line = 100.0, 50.0, 300.0, 50.0 line_randomize_vertical(xy_line, x_delta, standard_deviation) standard_deviation = 4.0 xy_line = 100.0, 100.0, 300.0, 100.0 line_randomize_vertical(xy_line, x_delta, standard_deviation) standard_deviation = 6.0 xy_line = 100.0, 150.0, 300.0, 150.0 line_randomize_vertical(xy_line, x_delta, standard_deviation) standard_deviation = 8.0 xy_line = 100.0, 200.0, 300.0, 200.0 line_randomize_vertical(xy_line, x_delta, standard_deviation) standard_deviation = 10.0 xy_line = 100.0, 250.0, 300.0, 250.0 line_randomize_vertical(xy_line, x_delta, standard_deviation) standard_deviation = 12.0 xy_line = 100.0, 320.0, 300.0, 320.0 line_randomize_vertical(xy_line, x_delta, standard_deviation) standard_deviation = 16.0 xy_line = 100.0, 400.0, 300.0, 400.0 line_randomize_vertical(xy_line, x_delta, standard_deviation) standard_deviation = 2.0 xy_line = 500.0, 50.0, 700.0, 50.0 line_randomize_xy(xy_line, x_delta, standard_deviation) standard_deviation = 4.0 xy_line = 500.0, 100.0, 700.0, 100.0 line_randomize_xy(xy_line, x_delta, standard_deviation) standard_deviation = 6.0 xy_line = 500.0, 150.0, 700.0, 150.0 line_randomize_xy(xy_line, x_delta, standard_deviation) standard_deviation = 8.0 xy_line = 500.0, 200.0, 700.0, 200.0 line_randomize_xy(xy_line, x_delta, standard_deviation) standard_deviation = 10.0 xy_line = 500.0, 250.0, 700.0, 250.0 line_randomize_xy(xy_line, x_delta, standard_deviation) standard_deviation = 12.0 xy_line = 500.0, 320.0, 700.0, 320.0 line_randomize_xy(xy_line, x_delta, standard_deviation) standard_deviation = 16.0 xy_line = 500.0, 400.0, 700.0, 400.0 line_randomize_xy(xy_line, x_delta, standard_deviation) root.mainloop()
703ca0d2e67f5a6b8146ad8f7e117f157c967bf1
s-rokade/Student-Management
/studenassig_main.py
785
3.78125
4
'''Create a student management application. Create a student table with columns - id, name and marks Create python functions to - 1)show students 2)update student marks with id 3)Insert new student 4)Delete student''' from studenassig import Student #from student import Student while True: print("***********Welcome To Student Management Application*************") print("Press any keys....") print("\t1.Show Students\n\t2.Update marks\n\t3.Add student\n\t4.Delete student") ch = int(input("Enter your choice:")) e = Student() if ch ==1: e.show_stu() elif ch ==2: e.update_mark() elif ch ==3: e.create_table() e.insert_into() elif ch ==4: e.delete() else: break
15cda0a33628bab338fc72c9076eaa0838dc0a9e
JhonesBR/python-exercises
/9- Python Set Exercise/ex06.py
210
4.03125
4
# Return a set of all elements in either A or B, but not both # Solution: https://github.com/JhonesBR set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} set3 = set1.symmetric_difference(set2) print(set3)
044c6032baa0271635feba335720cc316f5c04f1
MRS88/python_basics
/week_2_if_n_while/sum_of_sequence.py
544
4.03125
4
''' Определите сумму всех элементов последовательности, завершающейся числом 0. Формат ввода Вводится последовательность целых чисел, оканчивающаяся числом 0 (само число 0 в последовательность не входит, а служит как признак ее окончания). ''' n = int(input()) res = 0 lst = [] while n != 0: lst.append(n) n = int(input()) print(sum(lst))
eed9422ed66d956fa1d71634aed8ea7a767c01ea
intaschi/Python-course
/Estruturas de repetição/Ex048.py
264
3.75
4
s = 0 cont = 0 for n in range(0, 501): if n % 2 == 1 and n % 3 == 0: cont = cont + 1 s += n print('A soma de todos os {} resulta da soma {}'.format(cont, s)) #for n in range(0, 500, 3): # if n % 2 == 1: # print(n, end = ' ')
214687e64823aa9fd309f215f4a895574213b600
meng-z/leetcode
/278_first_bad_version/v1.py
709
3.671875
4
# The isBadVersion API is already defined for you. # @param version, an integer # @return a bool # def isBadVersion(version): ''' Runtime: 24 ms, faster than 84.54% of Python3 online submissions for First Bad Version. Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for First Bad Version. ''' class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ # binary search for first bad version lo, hi = 1, n while lo < hi: middle = (lo + hi) // 2 if isBadVersion(middle): hi = middle else: lo = middle + 1 return lo
708d1e24564b94e1d85b3227ce712cf60156a84e
thiagocmota/python
/exercicio9.py
608
3.921875
4
#9) Faça um programa que calcule o aumento de um salário. Ele deve solicitar o #valor do salário e a porcentagem de aumento. Mostre o valor do aumento e do #novo salário. salario_inicial = float(input("Digite o valor do salario do fuincionario: ")) porcentagem_aumento = float(input("Digite somento o valor da porcentagem que deve ser aumentado no salario: ")) valor_aumento = salario_inicial * (porcentagem_aumento / 100) salario_atualizado = salario_inicial + valor_aumento print(f"O valor do aumento foi: {valor_aumento}") print(f"O novo salario do funcionario é: {salario_atualizado}")
e45319948b48665763b6b65dc6fe0f7d458a6096
zhangweichina111/RPi-snake
/linkList.py
3,413
3.9375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def test(): print "Hello,this is list operator class that prepare for snake's body." class Node(object): def __init__(self,x,y,p=0): self.cur_x = x self.cur_y = y # self.cur_dir = dir self.next = p class LinkList(object): def __init__(self): self.head = 0 def __getitem__(self, key): if self.is_empty(): print 'linklist is empty.' return elif key <0 or key > self.getlength(): print 'the given key is error' return else: return self.getitem(key) def __setitem__(self, key, item): if self.is_empty(): print 'linklist is empty.' return elif key <0 or key > self.getlength(): print 'the given key is error' return else: self.delete(key) return self.insert(key) def initlist(self,data): self.head = Node(data[0].cur_x,data[0].cur_y) p = self.head for i in data[1:]: node = Node(i.cur_x,i.cur_y) p.next = node p = p.next def getlength(self): p = self.head length = 0 while p!=0: length+=1 p = p.next return length def is_empty(self): if self.getlength() ==0: return True else: return False def clear(self): self.head = 0 def append(self,item): q = Node(item.cur_x,item.cur_y) if self.head ==0: self.head = q else: p = self.head while p.next!=0: p = p.next p.next = q def getitem(self,index): if self.is_empty(): print 'Linklist is empty.' return j = 0 p = self.head while p.next!=0 and j <index: p = p.next j+=1 if j ==index: return p else: print 'target is not exist!' def insert(self,index,item): if self.is_empty() or index<0 or index >self.getlength(): print 'Linklist is empty.' return if index ==0: q = Node(item.x,item.y,self.head) self.head = q p = self.head post = self.head j = 0 while p.next!=0 and j<index: post = p p = p.next j+=1 if index ==j: q = Node(item.x,item.y,item.dir,p) post.next = q q.next = p def delete(self,index): if self.is_empty() or index<0 or index >self.getlength(): print 'Linklist is empty.' return if index ==0: q = Node(item.x,item.y,item.dir,self.head) self.head = q p = self.head post = self.head j = 0 while p.next!=0 and j<index: post = p p = p.next j+=1 if index ==j: post.next = p.next def index(self, value): if self.is_empty(): print 'Linklist is empty.' return p = self.head i = 0 while p.next!=0 and not p.x == value: p = p.next i+=1 if p.x == value: return i else: return -1
b997b080fb541e3744378e0be20df1cf029f4991
VANITHAVIJAYA/codekata
/day.py
202
4
4
day={'monday':'working day','tuesday':'working day','wednesday':'working day','thursday':'working day','friday':'working day','saturday':'holiday','sunday':'holiday'} d=input("Enter day") print(day[d])
1db6e5837f61897bcd50144bdf677d31d2b6721d
tejaswisunitha/teja
/85.py
143
3.65625
4
c= raw_input().rstrip() evenB = oddB = '' for j, k in enumerate(c): if j & 1 == 0: evenB += k else: oddB += k print(evenB + " " + oddB)
0ff96e3f446d52fb31699558be76f5f5269b1c6f
YinhaoHe/LeetCode
/interviews/interviewQuestions/slidingWindowMax(SegmentHackerRank).py
1,073
4.1875
4
''' Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window. Find maximum of minimum for every window size in a given array https://www.geeksforgeeks.org/find-the-maximum-of-minimums-for-every-window-size-in-a-given-array/ Given an integer array of size n, find the maximum of the minimum’s of every window size in the array. Note that window size varies from 1 to n. ''' from collections import deque def segment(x, arr): # Write your code here def maxSlidingWindow(nums, k): d = deque() out = [] for i, n in enumerate(nums): while d and nums[d[-1]] < n: d.pop() d += i, if d[0] == i - k: d.popleft() if i >= k - 1: out += nums[d[0]], return out res = maxSlidingWindow(list(map(lambda x: -x, arr)), x) return -min(res)
c6554ff18c23a61d3694e73b808f44c96f9a19c4
bwalsh0/100DaysOfPython
/lc_338.py
488
3.640625
4
class Solution: def countBits(self, num: int) -> List[int]: total = [] for i in range(num + 1): counter = bin(i).count('1') # for j in bin(i): # if j == '1': # counter += 1 total.append(counter) return total # bin(i).count('1') is the easy way to do it with built in functions # for loop to search each char in the returned string is slower
fe01b00decfbf0ce1e7f16e81454e2221bbd6785
here0009/LeetCode
/Python/1673_FindtheMostCompetitiveSubsequence.py
2,168
3.890625
4
""" Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5. Example 1: Input: nums = [3,5,2,6], k = 2 Output: [2,6] Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive. Example 2: Input: nums = [2,4,3,3,5,4,9,6], k = 4 Output: [2,3,3,4] Constraints: 1 <= nums.length <= 105 0 <= nums[i] <= 109 1 <= k <= nums.length """ from typing import List import heapq class Solution: def mostCompetitive(self, nums: List[int], k: int) -> List[int]: length = len(nums) lst = [(v,i) for i,v in enumerate(nums[:length-k+1])] # print(lst) heapq.heapify(lst) res = [heapq.heappop(lst)] for i in range(length-k+1, length): v = nums[i] heapq.heappush(lst, (v,i)) while lst[0][1] < res[-1][1]: heapq.heappop(lst) res.append(heapq.heappop(lst)) while len(res) < k: while lst[0][1] < res[-1][1]: heapq.heappop(lst) res.append(heapq.heappop(lst[0])) return [v for v, _ in res] from typing import List import heapq class Solution: def mostCompetitive(self, nums: List[int], k: int) -> List[int]: stack = [] length = len(nums) for i,v in enumerate(nums): while stack and v < stack[-1] and len(stack) + length - i > k: stack.pop() if len(stack) < k: stack.append(v) return stack S = Solution() nums = [3,5,2,6] k = 2 print(S.mostCompetitive(nums, k)) nums = [2,4,3,3,5,4,9,6] k = 4 print(S.mostCompetitive(nums, k))
1b7601b03e331ce8072dc38703aa7525558572c8
ajaykumar011/python-course
/classes/inheritance1.py
634
4.0625
4
# Inheritance allows us to define a class that inherits all the methods and properties from another class. # Parent class is the class being inherited from, also called base class. # Child class is the class that inherits from another class, also called derived class. class Person: #Parent Class def __init__(self,fname,lname): self.firstname=fname self.lastname=lname def welcome(self): print("Welcome to Home " + self.firstname , self.lastname) class Student(Person): #child class of Parent 'Person' pass p1 = Person("Ajay", "Kumar") p1.welcome() p2= Student("Sushil", "Kumar") p2.welcome()
2d10c663cad9404f941dae4088808da0ebef70a9
thisisvikasmourya/DS
/Practical1a.py
157
3.96875
4
arr1=[12,35,42,22,1,6,54] arr2=['hello','world'] arr1.index(35) print(arr1) arr1.sort() print(arr1) arr1.extend(arr2) print(arr1) arr1.reverse() print(arr1)
fca0a1e74b22adc9eb88b784df61ae51c08a70c5
JianxiangWang/LeetCode
/33 Search in Rotated Sorted Array/solution.py
1,377
3.78125
4
#encoding: utf-8 # 4 5 6 7 0 1 2 # binary search, always ! # low-mid or mid-high 之间始终有一个是有序的, 所以每一次都可以判断是target 在 low-mid 还是 high-mid 之间 ! class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ n = len(nums) low = 0 high = n - 1 found = -1 while low <= high: print low, high mid = (low + high) >> 1 if nums[mid] == target: found = mid break if nums[mid] > target: if nums[low] <= nums[mid]: if target >= nums[low]: high = mid - 1 else: low = mid + 1 if nums[mid] < nums[high]: high = mid - 1 if nums[mid] < target: if nums[low] <= nums[mid]: if target >= nums[low]: low = mid + 1 if nums[mid] < nums[high]: if target <= nums[high]: low = mid +1 else: high = mid - 1 return found if __name__ == '__main__': print Solution().search([4,5,6,7,8,0,1,2,3], 5)
2f56e0320156ddf592ec5e73a2f083ba55da7187
Sorabh-Singh/HackerRank
/DS/No Idea.py
649
3.515625
4
''' Input Format The first line contains integers and separated by a space. The second line contains integers, the elements of the array. The third and fourth lines contain integers, and , respectively. Output Format Output a single integer, your total happiness. Sample Input 3 2 1 5 3 3 1 5 7 Sample Output 1 ''' n,m = map(int,input().split()) N = list(map(int,input().split())) A = set(map(int,input().split())) B = set(map(int,input().split())) happiness_level= 0 for i in N: if i in A: happiness_level = happiness_level + 1 elif i in B: happiness_level = happiness_level - 1 print(happiness_level)
271027b140627bc9195ef00b50518b703ed70f00
zNIKK/Exercicios-Python
/Python_3/DEF/MÓDULOS/Moedas--COMPLETO/pacotes/Strings/__init__.py
1,711
3.5625
4
from pacotes import Numeros def erros(txt): v=False while not v: entrada=str(input(txt)) if entrada.isalpha(): if ',' in entrada: re = f'{entrada}'.replace(',', '.') return float(re) print(f'\033[0;31mERRO \"{entrada}\" é um preço invalido\033[m') else: v=True return float(entrada) def moeda(n=0,m='R$'): return f'{m}{n:.2f}'.replace('.',',') def resumo(n=0,p1=10,p2=10,formato=False): if formato==True: print('——'*15) print(f'{"RESUMO DO VALOR":^30}') print('——'*15) print(f'Preço analizado: \tR${moeda(n):>3}') print(f'Dobro do preço: \tR${Numeros.dob(n,True):>3}') print(f'Metade do preço: \tR${Numeros.metade(n,True):>3}') print(f'{p1}% de Aumento: \t\tR${Numeros.porc(n, p1, True)}' if len(str(p1))==1 else f'{p1}% de Redução: \tR${Numeros.dim(n, p1, True)}') print(f'{p2}% de Redução: \t\tR${Numeros.dim(n, p2, True)}' if len(str(p2))==1 else f'{p2}% de Redução: \tR${Numeros.dim(n, p2, True)}') print('——'*15) else: print('——' * 15) print(f'{"RESUMO DO VALOR":^30}') print('——' * 15) print(f'Preço analizado: \tR${n}') print(f'Dobro do preço: \tR${Numeros.dob(n)}') print(f'Metade do preço: \tR${Numeros.metade(n)}') print(f'{p1}% de Aumento: \tR${Numeros.porc(n, p1)}' if len(str(p1))==1 else f'{p1}% de Redução: \tR${Numeros.dim(n, p1)}') print(f'{p2}% de Redução: \t\tR${Numeros.dim(n, p2)}' if len(str(p2))==1 else f'{p2}% de Redução: \tR${Numeros.dim(n, p2)}') print('——' * 15)
de18e9b676934ba8591c8a85b2ee0e7fec73581d
cjb5799/DSC510Fall2020
/KOSMICKI_DSC510/cable_install.py
954
4.1875
4
#DSC 510 #Week 2 #Programming Assignment Week 2 #Author Sherry Kosmicki #09/7/2020 #factor used to calculate cost cablefactor = .87 print('Welcome to my invoice generator!') #Prompt user for their name username = input('Please enter your name\n') #Prompt user for company name usercompany = input ('Enter your company name\n') #Prompt user for number of feet of cable to be installed to calculate cost userfeet = input('How many feet of cable will be installed?\n') #Calculate userfeet prompt times cablefactor variable cost = (int(userfeet) * cablefactor) #Generate Invoice print('') print('Please print invoice below - due in 30 days') print('==================================================') print('INVOICE') print('TO:',username) print('COMPANY:',usercompany) print('') print('Amount of cable installed =',userfeet) print('Cost per feet =',cablefactor) print('Total Due= $',round(cost,2)) print('==================================================')
e8f9a2e98b7d68ea5f0a353c9b575aec15414ace
SagarikaNagpal/Python-Practice
/QuesOnOops/A-3.py
73
3.8125
4
import math a=int(input("num is: ")) print("squre of a: ",math.pow(a,2))
6d29f4046d736a3891911e00b185e2670ca59d94
Minji0h/Introduce-at-CCO-with-python
/Semana4/exercicio1.py
226
3.765625
4
# Escreva um programa que receba um número natural n n n na entrada e imprima n! n! n! (fatorial) na saída. n = int(input("Digite o valor de n: ")) fator = 1 while(n > 0): fator = fator * n n = n - 1 print(fator)
f79a817bf0c4dac50e28c5b17417d623015e67af
anoy1729/NSL-RAShip-Program
/python-basic/Basic Data Types/Lists.py
700
3.75
4
if __name__ == '__main__': N = int(input()) lst = [] for i in range(N): arr = list(map(str, input().strip().split(' '))) if(len(arr)==2): arr[1] = int(arr[1]) elif(len(arr)==3): arr[1] = int(arr[1]) arr[2] = int(arr[2]) if(arr[0]=='insert'): lst.insert(arr[1],arr[2]) if(arr[0]=='print'): print(lst) if(arr[0]=='remove'): lst.remove(arr[1]) if(arr[0]=='append'): lst.append(arr[1]) if(arr[0]=='sort'): lst.sort() if(arr[0]=='pop'): lst.pop() if(arr[0]=='reverse'): lst.reverse()
64573dcc450cda37d8dac46f9f4a346cb5ab0b97
harshitpoddar09/HackerRank-Solutions
/30 Days of Code/Day 3- Intro to Conditional Statements.py
307
3.875
4
#!/bin/python3 import math import os import random import re import sys n = int(input()) if n%2!=0 : print("Weird") elif n==2 or n==4 : print("Not Weird") elif n%2==0 and n>=6 and n<=20: print("Weird") elif n%2==0 and n>=20 and n<=100: print ("Not Weird")