blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c727aa9bfd09cbb68e1132994a48eab4a74e2cd4
jp-tran/dsa
/problems/top_k_elements/rearange_string.py
1,506
3.953125
4
import heapq """ Given a string, find if its letters can be rearranged in such a way that no two same characters come next to each other. Time complexity: O(N * log(N)) Space complexity: O(N) """ def rearrange_string(str): charFrequencyMap = {} for char in str: charFrequencyMap[char] = charFrequencyMap.get(char, 0) + 1 maxHeap = [] # add all characters to the max heap for char, frequency in charFrequencyMap.items(): heapq.heappush(maxHeap, (-frequency, char)) # alternate between appending different letters by using a previousChar # variable to track which letter you just appended previousChar, previousFrequency = None, 0 resultString = [] while maxHeap: frequency, char = heapq.heappop(maxHeap) # add the previous entry back in the heap if its frequency is greater than zero if previousChar and -previousFrequency > 0: heapq.heappush(maxHeap, (previousFrequency, previousChar)) # append the current character to the result string and decrement its count resultString.append(char) previousChar = char previousFrequency = frequency+1 # decrement the frequency # if we were successful in appending all the characters to the result string, return it return ''.join(resultString) if len(resultString) == len(str) else "" def main(): print("Rearranged string: " + rearrange_string("aappp")) print("Rearranged string: " + rearrange_string("Programming")) print("Rearranged string: " + rearrange_string("aapa")) main()
510a6747e279df236f68b08edc67d6fd976b4767
ibinibenny/Sample1
/ass2_listbims.py
887
4.0625
4
#Write a program to implement all built-in methods of list. tup=[1,2,3,4,5,6,6,7,7,8,8,9] print(tup[0]) print(tup[:5]) print(tup[5]+tup[6]) tupl=['hello','HAAI',' spect '] print(tupl*3) print('hello'in tupl) print(len(tup)) print(tupl[1].lower()) print(tupl[0].upper()) print(tupl[0].title()) print(tupl[0].capitalize()) print(tupl[2].strip()) print(tupl[1].startswith('H')) print(tupl[1].endswith('I')) print("--------------------------") print(tup) print("count of 8=",tup.count(8)) print("appending 10") tup.append(10) print(tup) print("inserting 11 @5th index",tup.insert(5,11)) print("removing 1") tup.remove(10) print(tup) print("sorting..") tup.sort() print(tup) print("min and max values in the list are:",min(tup),max(tup)) print("list after popping...") print(tup.pop()) tup.reverse() print("list reversed=",tup) tup.clear() print("clearing the list",tup)
f58e32f5773c3231139212a3123691792c0eab5f
DyogoBendo/URI-Python
/iniciante/2779.py
174
3.5
4
if __name__ == "__main__": n = int (input()) m = int(input()) lista = set() for i in range(m): lista.add(int(input())) print(n - len(lista))
3ca377d237c2244084ba29847e790ee2b5deba0e
apuya/python_crash_course
/Part_2_Projects/Project_1_Alien_Invasion/Chapter_13_Aliens/exercise13_2.py
513
3.625
4
# Python Crash Course: A Hands-On, Project-Based Introduction To Programming # # Name: Mark Lester Apuya # Date: # # Chapter 13: ALiens! # # Exercise 13.2 Better Stars: # You can make a more realistic star pattern by introducing randomness when you place each star. Recall that you can get a random # num- ber like this: # # from random import randint # random_number = randint(-10, 10) # # This code returns a random integer between −10 and 10. Using your code in Exercise 13-1, adjust each star’s position by a random
1c12807e0e6e49c24c6212b6c6a9c5d698e5c895
takayg/algorithm
/Python/Data Structure/Union Find/Union find(class).py
725
3.546875
4
class UnionFind: def __init__(self,N): self.parent = [i for i in range(N)] self.rank = [0] * N self.count = 0 def root(self,a): if self.parent[a] == a: return a else: self.parent[a] = self.root(self.parent[a]) return self.parent[a] def is_same(self,a,b): return self.root(a) == self.root(b) def unite(self,a,b): ra = self.root(a) rb = self.root(b) if ra == rb: return if self.rank[ra] < self.rank[rb]: self.parent[ra] = rb else: self.parent[rb] = ra if self.rank[ra] == self.rank[rb]: self.rank[ra] += 1 self.count += 1
ef9b6475662f307c1f5fbf24f0f7f8104f9be4e3
Linuxea/hello_python
/src/basic/bigLoop.py
66
3.53125
4
sum = 0 for x in range(101): sum += x print("sum = %s" % sum)
cc294369f1bbf48e88e070a6f07952e6abfb0bbe
programmer-anvesh/Hacktoberfest2021
/BinarySearchTree/sort_arr_to_bst.py
565
3.765625
4
#The main task here is to convert a sorted array into a Balanced Binary Search Tree ''' Made by: Ansh Gupta(@ansh422) Date: 03/10/2021 ''' class TreeNode: def __init__(self,val=0,left=None,right=None): self.val=val self.left=left self.right=right def sortedArrayToBST(nums): if not nums: return None mid=len(nums)//2 root=TreeNode(nums[mid]) root.left=sortedArrayToBST(nums[:mid]) root.right=sortedArrayToBST(nums[mid+1:]) return root if __name__ == "__main__": nums=list(map(int,input().split())) root=sortedArrayToBST(nums)
18dbba52155a6b2b44c0615573ceedaba5b7ae43
aikaos/loops
/venv/Flip number.py
120
3.8125
4
# flip numbers n = int(input("Enter any number: ")) m = 0 while n > 0: m = m * 10 + n % 10 n = n // 10 print(m)
ee610a4257cd6556b089ea082a89fc3b30aaaf98
chenguiyuan/Leetcode
/1twosum.py
451
3.640625
4
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ map = {} for i, num in enumerate(nums): if target - num in map: return([map[target - num], i]) else: map[num] = i solution = Solution() nums = [2, 8, 7, 11, 5, 9] target = 11 print(solution.twoSum2(nums, target))
8143cfade544a1b663f8b7923296418c0ba81897
jsmith09/ChopATweet
/TweetQueryGUI.py
3,670
3.65625
4
#TweetQueryGUI Class #Programmed by: Jesse Smith #Course: CIS225E-HYB1 #Description: GUI driver for ReadTweets, WriteTweets and Query Class. #This allows a search, get an average, and display tweets #for a user-searched word in the tweets.txt file.(Improvement for Assignment 5) import tkinter from read import ReadTweets from write import WriteTweets from find import Query class TweetQueryGUI: def __init__(self): self.main_window = tkinter.Tk() #Create frames self.top_frame = tkinter.Frame() self.upper_frame = tkinter.Frame() self.middle_frame = tkinter.Frame() self.bottom_frame = tkinter.Frame() #Create Labels self.prompt_label = tkinter.Label(self.top_frame, \ text="Tweet Query System") self.search_entry = tkinter.Entry(self.upper_frame, width=20) self.results_label = tkinter.Label(self.bottom_frame, text="") #Create Buttons self.search_button = tkinter.Button(self.middle_frame,\ text='Search',\ command=self.searchQuery) self.display_button = tkinter.Button(self.middle_frame, text ='Display' ,\ command=self.tweetDisplay) self.average_button = tkinter.Button(self.middle_frame, \ text = 'Average', \ command=self.average) self.quit_button = tkinter.Button(self.middle_frame, \ text='Quit', \ command=self.main_window.destroy) #Show labels and buttons self.prompt_label.pack(side='left') self.search_entry.pack(side='left') self.results_label.pack(side='left') self.quit_button.pack(side='right') self.search_button.pack(side='left') self.display_button.pack(side='left') self.average_button.pack(side='left') #Show frames self.top_frame.pack() self.upper_frame.pack() self.middle_frame.pack() self.bottom_frame.pack() #Method that is called when clicked by search_button def searchQuery(self): filename = 'tweets.txt' tweets = WriteTweets(filename) tweets.writetweets() searchWord = str(self.search_entry.get()) if searchWord == "": self.results_label['text'] = "Please search for a word" else: find = Query(filename, "listtweets.txt", searchWord) self.results_label['text'] = find.query() #Method that called when clicked by display_button def tweetDisplay(self): filename = 'tweets.txt' tweets = WriteTweets(filename) tweets.writetweets() searchWord = str(self.search_entry.get()) if searchWord == "": self.results_label['text'] = "Please search for a word" else: find = Query(filename, "listtweets.txt", searchWord) self.results_label['text'] = find.displayTweets() #Method that called when clicked by average_button def average(self): filename = 'tweets.txt' tweets = WriteTweets(filename) tweets.writetweets() searchWord = str(self.search_entry.get()) if searchWord == "": self.results_label['text'] = "Please search for a word" else: find = Query(filename, "listtweets.txt", searchWord) self.results_label['text'] = find.average() #Main method called TweetQueryGUI()
7812fef1e15b71cb44e39b2843d4de0f2e1a6b96
Adamsdurga/Python
/python31.py
102
3.75
4
string = "hello" c = 0 for i in range (len(string)): if (string [i]!=''): c = c+1 print (c)
da7ae155d25de771be41cac6c0f0ff2d6854db1d
klq/euler_project
/euler14.py
1,914
3.859375
4
def euler14(): # Problem: """ The following iterative sequence is defined for the set of positive integers: n -> n/2 (n is even) n -> 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. """ # Solve: (fast method) N = 1000001 longest_steps = [0]*N longest_steps[1] = 1 for i in range(1,N): temp = [] j = i # keeping looking for the next one while: while (j>=N) or longest_steps[j] == 0 : temp.append(j) j = collatz_walk(j) found_steps = longest_steps[j] # pop the elements from the temp list: count = 1 while temp: j = temp.pop() if j < N: longest_steps[j] = found_steps + count count += 1 max_index = max( (v, i) for i, v in enumerate(longest_steps) )[1] return max_index def collatz_walk(n): if n%2==0: n = n/2 else: n = 3*n+1 return n def count_steps(n): # chain start at 1 steps = 1 if n == 1: return steps while (n>1): n = collatz_walk(n) steps += 1 return steps def main(): # slow method: longest_steps = [0]*1000001 for i in range(1000001): longest_steps[i] = count_steps(i) max_index = max( (v, i) for i, v in enumerate(longest_steps) )[1] print max_index, longest_steps[max_index] print euler14() #837799
ca311cb5fe1cd6063ab2133bbc93e7b5393cad29
miguel007TMM2/final_mini_project
/crupier.py
2,465
3.71875
4
import os from cards import Deck class Crupier(): values_cards_crupier = 0 def __init__(self, deck_of_cards): #Each time the class is called this will be executed by granting the dealer 2 cards self.deck_of_cards = deck_of_cards self.cards = self.deck_of_cards.list_of_cards self.crupier_current_hand = [] self.crupier_iterator = 0 self.crupiers_two_cards() def mutation_of_as(self, index, put_list, addition): #This method changes the value of the As mutation = put_list [index].value = 1 addition += mutation addition -= 1 def set_mutation_of_as(self, index, enter_list, sum_value): #This method calls the mutation of the As if the value of the cards in total does not exceed 10 points for index in range(len(enter_list)): if enter_list[index].value == 11: if sum_value >= 11: self.mutation_of_as(index, enter_list, sum_value) def get_cards(self): if len(self.cards) == 1: self.cards.generator_of_cards() card = self.cards.pop() return card def get_two_cards(self): two_cards = [] for card in range(2): two_cards.append(self.get_cards()) return two_cards def get_card_for_crupier(self, index): #this method takes care of passing a card to the dealer by passing the value of the card to a variable self.crupier_current_hand.append(self.deck_of_cards.list_of_cards.pop()) self.set_mutation_of_as(self.crupier_iterator, self.crupier_current_hand, self.values_cards_crupier) self.values_cards_crupier += self.crupier_current_hand[index].value def crupiers_two_cards(self): #it takes two cards for dealer just calling the method that takes one card twice for self.crupier_iterator in range(0, 2): self.get_card_for_crupier(self.crupier_iterator) def Keep_holding_cards(self):#This method continues taking dealer cards until reaching 16 points or going over self.set_mutation_of_as(self.crupier_iterator, self.crupier_current_hand, self.values_cards_crupier) while self.values_cards_crupier <= 16: self.crupier_iterator += 1 self.get_card_for_crupier(self.crupier_iterator) def reset_crupier_data(self): self.crupier_current_hand = [] self.values_cards_crupier = 0 self.deck_of_cards.generator_of_cards()
15b025c0c7ebfe4ee67d3f479f852d3d372253f6
Sheretluko/LearnPython_homeworks
/lesson2/11_while_1.py
366
4.0625
4
# Напишите функцию hello_user(), которая с помощью функции input() # спрашивает пользователя “Как дела?”, пока он не ответит “Хорошо” def hello_user(): answer = '' while answer.lower() != 'хорошо': answer = input('Как дела? ') hello_user()
56a7259e9ec3ae779d563b045859615ac22c4fe3
backmay/tisco_exam
/test_1.py
438
3.609375
4
input_a = '9876543' input_b = [ '3467985', '7865439', '8743956', '3456789', ] def is_same_ditgit_in_same_index(input_a, input_b): for index in range(len(input_a)): if input_a[index] == input_b[index]: print('{} : is Invalid'.format(input_b)) return print('{} : is Valid'.format(input_b)) for index in range(len(input_b)): is_same_ditgit_in_same_index(input_a, input_b[index])
cbea2286d9c3d24b5e791fc05f8b393b116092c3
dsibars/PythonTutorialsAndSamples
/labs/test/friendclass/test_002.py
1,037
3.75
4
import unittest from labs.Friend import Friend # EXERCISE: # Create a new function in friend, that allows you to change the name. # Tests will check that after changing the name, the salutate method has the new name. class TestFriend002(unittest.TestCase): def setUp(self): self.test_name = 'patata' self.test_friendof = 'cebolla' self.test_level = 5 self.target = Friend(self.test_name, self.test_friendof, self.test_level) def test_change_name(self): # Test change name functionality test_new_name = 'petete' # Set a new name self.target.set_name(test_new_name) # Expected result expected_result = 'hello! I am ' + test_new_name # Generate the result result = self.target.present_yourself() # Restore the name self.target.set_name(self.test_name) # Check if the expected result and result are the same self.assertEquals(result, expected_result) if __name__ == '__main__': unittest.main()
0791a9047c221132071e1d2eddc16f5e24c07bf6
a844810597/python_code
/primary/learn_class/class_turtle_and_fish.py
4,448
3.875
4
import random # 行走区域 legal_x = [0, 10] legal_y = [0, 10] class Turtle: def __init__(self, name='小乌龟'): global legal_x global legal_y self.__pos_x = random.randint(*legal_x) # 初始化乌龟生成的位置 self.__pos_y = random.randint(*legal_y) self.energy = 100 self.name = name def __getDirection(self): return random.choice(['up', 'down', 'left', 'right']) def __getStep(self): return random.randint(1, 2) # 乌龟的步长为1-2 def getPositon(self): return (self.__pos_x, self.__pos_y) def getEnergy(self): print('%s 还剩 %d 点体力' % (self.name, self.energy)) def move(self): global legal_x global legal_y direction = self.__getDirection() # 获取走的方向 step = self.__getStep() # 获取走的步长 if direction == 'right': self.__pos_x += step if self.__pos_x > legal_x[1]: # 如果向右越界则向左掉头行走 self.__pos_x = legal_x[1] + (legal_x[1] - self.__pos_x) elif direction == 'left': self.__pos_x -= step if self.__pos_x < legal_x[0]: # 如果向左越界则向右掉头行走 self.__pos_x = legal_x[0] + (legal_x[0] - self.__pos_x) elif direction == 'up': self.__pos_y += step if self.__pos_y > legal_y[1]: # 如果向上越界则向下掉头行走 self.__pos_y = legal_y[1] + (legal_y[1] - self.__pos_y) else: self.__pos_y -= step if self.__pos_y < legal_y[0]: # 如果向下越界则向上掉头行走 self.__pos_y = legal_y[0] + (legal_y[0] - self.__pos_y) self.energy -= 1 # 每移动一次,体力减少1 def eat(self): self.energy += 20 if self.energy > 100: self.energy = 100 class Fish: def __init__(self, name='小鱼'): global legal_x global legal_y self.__pos_x = random.randint(*legal_x) # 初始化鱼生成的位置 self.__pos_y = random.randint(*legal_y) self.name = name self.__step = 1 def __getDirection(self): return random.choice(['up', 'down', 'left', 'right']) def getPositon(self): return (self.__pos_x, self.__pos_y) def move(self): global legal_x global legal_y direction = self.__getDirection() # 获取走的方向 step = self.__step if direction == 'right': self.__pos_x += step if self.__pos_x > legal_x[1]: # 如果向右越界则向左掉头行走 self.__pos_x = legal_x[1] + (legal_x[1] - self.__pos_x) elif direction == 'left': self.__pos_x -= step if self.__pos_x < legal_x[0]: # 如果向左越界则向右掉头行走 self.__pos_x = legal_x[0] + (legal_x[0] - self.__pos_x) elif direction == 'up': self.__pos_y += step if self.__pos_y > legal_y[1]: # 如果向上越界则向下掉头行走 self.__pos_y = legal_y[1] + (legal_y[1] - self.__pos_y) else: self.__pos_y -= step if self.__pos_y < legal_y[0]: # 如果向下越界则向上掉头行走 self.__pos_y = legal_y[0] + (legal_y[0] - self.__pos_y) turtle = Turtle() fish = [] for i in range(10): new_fish = Fish('小鱼_'+str(i)) fish.append(new_fish) while True: if not len(fish): print('鱼儿都被吃完啦,游戏结束!') break if not turtle.energy: print('乌龟没有体力抓鱼啦,游戏结束!') break turtle.move() turtle_pos = turtle.getPositon() print('小乌龟爬到了 (%d, %d)' % turtle_pos) for each_fish in fish[ : ]: each_fish.move() each_fish_pos = each_fish.getPositon() print('%s爬到了 (%d, %d)' % (each_fish.name, *each_fish_pos)) if each_fish_pos == turtle_pos: turtle.eat() print('%s 被吃掉咯~' % each_fish.name) fish.remove(each_fish)
1600708d81d73d2077aca5ce1acf27d7ecd4d508
Basma23/data-structures-and-algorithms-python
/data_structures_and_algorithms/data_structures/stacks_and_queues/stacks_and_queues.py
2,429
3.890625
4
class Node(): def __init__(self, info): self.info = info self.next = None class Stack(): def __init__(self): self.top = None self.items = [] def push(self, info): if self.top == None: self.top = Node(info) self.items.append(info) else: new_node = Node(info) self.top.next = new_node self.top = new_node self.items.append(new_node.info) def pop(self): if self.top: popped = self.top self.top = self.top.next return popped.info else: return f'the stack is empty' def peek(self): try: return self.top.info except AttributeError as error: return 'the stack is empty' def is_empty(self): if self.top == None: return True else: return False class Queue(): def __init__(self): self.front = None self.rear = None self.items = [] def enqueue(self, info): new_node = Node(info) if not self.front and not self.rear: self.front = new_node self.rear = new_node self.items.append(new_node.info) return old_rear = self.rear self.rear = new_node self.items.append(new_node.info) def dequeue(self): try: temp = self.front self.front = temp.next if self.front == None: self.rear = None self.items.pop(0) return temp.info except AttributeError as e: return 'the queue is empty' def peek(self): try: return self.front.info except AttributeError as error: return 'the queue is empty' def is_empty(self): if not self.front: return True else : return False if __name__ == '__main__': fruites = Stack() fruit = Queue() # fruites.push('Orange') # fruites.push('Pineapple') # fruites.push('Berry') # print(fruites.items) # # print(fruites.peek()) # print(fruites.pop()) # print(fruites.items) fruit.enqueue('Mango') fruit.enqueue('Strawberry') fruit.enqueue('Peach') print(fruit.items) print(fruit.front.info) print(fruit.rear.info) print(fruit.peek()) print(fruit.dequeue())
3ad3d860bdccbf13d02d48744b1734f6724cafae
nicknii29/first_hirst_painting
/main.py
1,214
3.53125
4
from turtle import Turtle, Screen import random timmy = Turtle() timmy.speed(3) timmy.hideturtle() timmy.penup() timmy.goto(x=-125, y=-125) screen = Screen() screen.setup(500, 500) screen.colormode(255) color_list = [(238, 246, 244), (249, 243, 247), (1, 12, 31), (54, 25, 17), (218, 127, 106), (9, 104, 160), (242, 213, 68), (150, 83, 39), (216, 86, 63), (156, 6, 24), (165, 162, 30), (158, 62, 102), (207, 73, 103), (10, 64, 33), (11, 96, 57), (95, 6, 20), (175, 134, 162), (7, 173, 217), (1, 61, 145), (2, 213, 207), (158, 32, 23), (8, 140, 85), (144, 227, 217), (121, 193, 147), (220, 177, 216), (100, 218, 229), (251, 198, 1), (116, 170, 192)] def draw_dots(): for _ in range(10): timmy.color(random.choice(color_list)) timmy.dot(15) timmy.penup() timmy.forward(30) def turn_left(): timmy.left(90) timmy.penup() timmy.forward(30) timmy.left(90) timmy.forward(30) def turn_right(): timmy.right(90) timmy.penup() timmy.forward(30) timmy.right(90) timmy.forward(30) for _ in range(5): draw_dots() turn_left() draw_dots() turn_right() screen.exitonclick()
4eba9d749aa84b4d6e37d2547c4183e1795f3b34
Sejopc/ScriptingEthicalHackers
/Python/Semana5/user.py
84
3.546875
4
#!/usr/bin/env python3 name = input("Cual es su nombre? \n") print("Hello,", name)
0198675adadf90de44988f4ba7094578b571c1e5
nambroa/Algorithms-and-Data-Structures
/arrays/M_total_time_covered_by_intervals/algorithm.py
2,655
4.0625
4
""" Given a list of arrays of time intervals, write a function that calculates the total amount of time covered by the intervals. For example: input = [(1,4), (2,3)] return 3 input = [(4,6), (1,2)] return 3 input = {{1,4}, {6,8}, {2,4}, {7,9}, {10, 15}} return 11 QUESTIONS TO ASK (with example answers to guide the solution): + Can the list of arrays be None or empty? Yes, both. + Is the list of arrays sorted? No, it can come in any order. + Can I use additional memory? Yes. + Can I modify the list of arrays? No, you can't. """ # We start by getting the starting times and the ending times of the intervals separately. Then, we sort those. # The main point here is to iterate them at the same time with indexes i and j. # If the current starting times is smaller than the current ending times, it means that you could potentially start # there. So we remember this decision and advance the i. If, in the next iteration, the current starting times is # still smaller, we WONT take that as a potential starting time. This is because the array is sorted, so the # starting_times[i+1] will always be higher than starting_times[i]. And, as such, it's total time would be lower. # In order to achieve this, we have a "current_count" that increases each time we find a starting time and # decreases each time we find an ending time. Only when "current_count" is zero, we will take a new starting_time. # If the current ending times is smaller, we have to check "current_count". # If it isnt zero, it means that you can search further. # If it is zero, this is the best ending time to form the interval def get_the_total_time_covered_by_the_intervals(intervals): _validate_empty_or_none_intervals(intervals) starting_times = [interval[0] for interval in intervals] ending_times = [interval[1] for interval in intervals] starting_times.sort() ending_times.sort() total_time = current_starting_time = current_count = i = j = 0 while i < len(starting_times) and j < len(ending_times): if starting_times[i] <= ending_times[j]: if current_count == 0: current_starting_time = starting_times[i] current_count += 1 i += 1 else: current_count -= 1 if current_count == 0: total_time += ending_times[j] - current_starting_time j += 1 total_time += (ending_times[len(ending_times) - 1] - current_starting_time) # Last iteration. return total_time def _validate_empty_or_none_intervals(intervals): if intervals is None or len(intervals) == 0: raise ValueError("Intervals is None or empty.")
b2861bed82a654da12ab2aee8846b2136dd2fcc5
globalfranck/banking_interface
/main.py
3,212
4.8125
5
# Bank project # Creating a menu: new customer, existing customer and exit the program bank_logo = " -------------------- \n --- Bank and Co. --- \n -------------------- \n " menu = "1) New customer \n 2) Existing customer \n 3) Exit program \n Enter your choice : " hyphens = " -------------------- \n" # Bank data, used to store bank details data = {} # Standard required information in a bank account represented as a list standard_bank_info =["Name", "Adress", "Phone number", "Gov ID", "Account Type", "Amount"] # Creating a function that takes data from user and stores it for new customer def store_data(): # We create a new account number using the customer input account_number = input("Enter your account number: ") # We loop over the standard banking info list and prompt the user to give us the required details to open an account and then add this information for i in standard_bank_info : user_details.append(input(f"Enter {i}: ")) # STORING DATA # We store the info into a dictionary using the zip function to map and combine standard bank info with user details data[account_number] = dict(zip(standard_bank_info, user_details)) print(f"Account n° {account_number} was created.") print(hyphens) return # Creating a function that ask an existing customer the options he'd like to choose def other_options(): print(hyphens) customer_option = int(input("1. Check Balance \n2. Withdraw\n3. Deposit\nEnter choice: ")) # User wants to see the current balance if customer_option == 1: print("Current balance available: ", data[account_number]["Amount"]) print(hyphens) # User wants to withdraw money elif customer_option == 2: withdraw_amount = int(input("Enter amount to withdraw: ")) # Converting the amount in the dictionary into a number data[account_number]["Amount"] = int(data[account_number]["Amount"]) data[account_number]["Amount"] -= withdraw_amount print(hyphens) print("Withdraw successful") print("New balance is: ", data[account_number]["Amount"]) print(hyphens) # User wants to deposit money else: deposit_amount = int(input("Enter amount to deposit: ")) # Converting the amount in the dictionary into a number data[account_number]["Amount"] = int(data[account_number]["Amount"]) data[account_number]["Amount"] += deposit_amount print(hyphens) print("Deposit successful") print("New balance is: ", data[account_number]["Amount"]) print(hyphens) while True: # We will store into this list the input details from the client user_details = [] # Showing menu and asking for the user choice user_choice = int(input(bank_logo + menu)) # New customer if user_choice == 1 : store_data() # Existing customer elif user_choice == 2 : account_number = input("Enter your account number: ") if account_number in data: print("Record found.") # Showing options to the user other_options() else: print("Record not found.") else: break
56b585c38222657678c3b95cff17beb52bcb17d8
cypaul85/HelloCoding
/quickSort.py
388
4.0625
4
def quickSort(arr): if len(arr) < 2: return arr else: pivot = arr[0] less = [i for i in arr[1:] if i< pivot] greater = [i for i in arr[1:] if i > pivot] return quickSort(less)+[pivot]+quickSort(greater) print(quickSort([10,5,2,3])) arr = [1,2,3,4,5,6,7,8,9,10] less = [element for element in arr[5:] if element > 2] print(less)
46a9bc3ea75408707f049c3fd25412edfbd935fc
LukasPol/URI_Online_Judge
/python/1005 - Média 1.py
91
3.5
4
A = float(input()) B = float(input()) print('MEDIA = {:.5f}'.format(((A*3.5)+(B*7.5))/11))
f922591dbc8d2580959740951a213918d2746113
santhoshkumar22101999/python-programs-29-01-2020-
/Numberguessing.py
295
3.9375
4
import random a=int(input("enter a value within 10")) b= random.randrange(0,10) if(a==b): print("winner",a,b) else: print("better luck next time") ''' SAMPLE OUTPUT: enter a value 2 better luck next time ---------------------------------- enter a value 1 ('winner', 1, 1) '''
1392aba8a70102b8e7bdd56f85b83aea6a2875fb
Ziaeemehr/miscellaneous
/ictp_workshop/euler/17.py
967
3.78125
4
#!/usr/bin/env python from sys import exit, argv num_dict={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six', 7:'seven',8:'eight',9:'nine',11:'eleven',12:'twelve', 13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen', 17:'seventeen',18:'eighteen',19:'nineteen', 10:'ten',20:'twenty',30:'thirty',40:'forty', 50:'fifty',60:'sixty',70:'seventy',80:'eighty',90:'ninety', 100:'onehundred',1000:'onethousand'} def f(num): if num in num_dict: return len(num_dict[num]) elif num>100: hun = num/100 rem = num%100 #print hun,rem return len(num_dict[hun]+'hundred') + ((f(rem)+3) if rem else 0) else: tens = num/10 rem = num % 10 return len(num_dict[tens*10])+(f(rem) if rem else 0) #elif num/1000: # th = num/1000 # return len(num_dict[th]+'thousand')+f(num%1000) letters = 0 print f(int(argv[1])) for i in range(1,1001): #print i,f(i) letters += f(i) print letters
a375c1710040b8cad8ed00f8fb7a9fe600680a7d
shivakrshn49/python-concepts
/bound_vs_unbound_methods.py
1,584
3.765625
4
#https://stackoverflow.com/questions/13348031/python-bound-and-unbound-method-object #Whenever you look up a method via instance.name (and in Python 2, class.name), the method object is created a-new. #Python uses the descriptor protocol to wrap the function in a method object each time. #So, when you look up id(C.foo), a new method object is created, you retrieve its id (a memory address), #then discard the method object again. Then you look up id(cobj.foo), a new method object created that re-uses the now freed memory #address and you see the same value. The method is then, again, discarded (garbage collected as the reference count drops to 0). #Next, you stored a reference to the C.foo unbound method in a variable. Now the memory address is not freed #(the reference count is 1, instead of 0), and you create a second method instance by looking up cobj.foo which has to use a new memory #location. Thus you get two different values. #Two objects with non-overlapping lifetimes may have the same id() value python class D(object): def f(self, x): return x def g(self, x): return x d = D() print D.__dict__['f'], id(D.__dict__['f']) print D.f, id(D.f), '<<<D.f' print d.f, id(d.f), '<<<d.f' print '*************' # print D.__dict__['g'], id(D.__dict__['g']) # print D.g, id(D.g), '<<<D.g' # print d.g, id(d.g), '<<<d.g' # print '**************' assigned = d.f again_assigned = D.f print id(assigned) print id(again_assigned) print d.f, id(d.f), '<<<d.f<<<<<<' print D.f, id(D.f), '<<<D.f' # print [id(x) for x in (d.f, d.f, D.f, D.f)]
52718d92b2ede7d3662451e04da18a26bb7a383b
signalwolf/Leetcode_by_type
/Facebook习题/dasd.py
4,336
3.8125
4
class LinkedListNode(object): def __init__(self, key, count): self.count = count self.key = [key] self.prev = None self.next = None class AllOne(object): def __init__(self): """ Initialize your data structure here. """ self.count = {} self.min = LinkedListNode('min', 0) self.max = LinkedListNode('max', 0) self.min.next = self.max self.max.prev = self.min def inc(self, key): """ Inserts a new key <Key> with value 1. Or increments an existing key by 1. :type key: str :rtype: void """ if key not in self.count: if self.min.next == self.max or self.min.next.count != 1: newNode = LinkedListNode(key, 1) newNode.prev = self.min newNode.next = self.min.next self.min.next.prev = newNode self.min.next = newNode self.count[key] = newNode else: self.min.next.key.append(key) else: currNode = self.count[key] # case1: need to add new node if currNode.next == self.max or currNode.next.count != currNode.count + 1: # case1.1: currnode only have 1 key: if len(currNode.key) == 1: currNode.count += 1 # case1.2: currNode have more than 1 key else: currNode.key.remove(key) newNode = LinkedListNode(key, 1) newNode.prev = currNode newNode.next = currNode.next currNode.next.prev = newNode currNode.next = newNode self.count[key] = newNode else: # currNode.next != self.max and currNode.next.count == currNode.count + 1 currNode.key.remove(key) currNode.next.key.append(key) self.count[key] = currNode.next self.printlinkedlist() def dec(self, key): """ Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. :type key: str :rtype: void """ if key not in self.count: return currNode = self.count[key] if currNode.count == 1: # only have one element, remove the node: if len(currNode.key) == 1: self.min.next = currNode.next currNode.next.prev = self.min else: currNode.key.remove(key) else: if currNode.prev == self.min or currNode.prev.count != currNode.count - 1: if len(currNode.key) == 1: currNode.count -= 1 else: currNode.key.remove(key) newNode = LinkedListNode(key, 1) newNode.next = currNode newNode.prev = currNode.prev currNode.prev.next = newNode currNode.prev = newNode self.count[key] = newNode else: currNode.key.remove(key) currNode.prev.key.append(key) self.count[key] = currNode.prev self.printlinkedlist() def printlinkedlist(self): if self.min.next == self.max: return None else: curr = self.min.next res = [] while curr != self.max: print curr.count, curr.key res.append([curr.count, curr.key]) curr = curr.next def getMaxKey(self): """ Returns one of the keys with maximal value. :rtype: str """ if self.max.prev == self.min: return '' else: return self.max.prev.key def getMinKey(self): """ Returns one of the keys with Minimal value. :rtype: str """ if self.max.prev == self.min: return '' else: return self.min.next.key # return self.min.next.key # Your AllOne object will be instantiated and called as such: # obj = AllOne() # obj.inc(key) # obj.dec(key) # param_3 = obj.getMaxKey() # param_4 = obj.getMinKey()
10ce42e1d632f53facf32c950a45b7cc10a97341
pyplusplusMF/202110_68
/_68semana05clase15Numpy.py
3,202
3.734375
4
# clase miercoles 2 de junio # linea de comando para instalar numpy # py -m pip install numpy (conda) (En windows) # https://numpy.org/install/ import numpy as np arreglo = np.array([1,2,3]) print (arreglo) # [1 2 3] arreglo1D = np.array ( [1, 2, 3] ) print ('arreglo1D = ', arreglo1D) # [1 2 3] print ('type = ', type (arreglo1D)) # <class 'numpy.ndarray'> print ('Ndim = ', arreglo1D.ndim) # 1 print ('shape = ', arreglo1D.shape) # shape = (3,) print ('Size = ', arreglo1D.size) # 3 print ('dtype = ', arreglo1D.dtype) # int32 print ('nbytes = ', arreglo1D.nbytes) #12 arreglo2D = np.array ( [ [1, 2], [3, 4], [5,6] ] ) print ('arreglo2D = \n', arreglo2D) print ('type = ', type (arreglo2D)) #<class 'numpy.ndarray'> print ('Ndim = ', arreglo2D.ndim) # 2 print ('shape = ', arreglo2D.shape) # (3, 2) print ('Size = ', arreglo2D.size) # 6 print ('dtype = ', arreglo2D.dtype) # int32 print ('nbytes = ', arreglo2D.nbytes) # 24 arreglo1D = np.array([1, 2, 3], dtype=np.int) print ('arreglo1D = ', arreglo1D) # [1 2 3] print ('arreglo1D dType = ', arreglo1D.dtype) # int32 arreglo1D = np.array([1, 2, 3], dtype=np.float) print ('\narreglo1D = ', arreglo1D) # [1. 2. 3.] print ('arreglo1D dType = ', arreglo1D.dtype) # float64 arreglo1D = np.array([1, 2, 3], dtype=np.complex) print ('\narreglo1D = ', arreglo1D) # [1.+0.j 2.+0.j 3.+0.j] print ('arreglo1D dType = ', arreglo1D.dtype) # complex128 print ('Parte Real = ', arreglo1D.real) # [1. 2. 3.] print ('Parte Imaginaria = ', arreglo1D.imag) # [0. 0. 0.] lista = [1,2,3,4] array1D = np.array (lista) print ('array1D = ', array1D) # [1 2 3 4] print ('ndim = ', array1D.ndim) # 1 print ('shape = ', array1D.shape) # (4, ) listaAnidada = [[1,2],[3,4]] array2D = np.array (listaAnidada) # [[1 2] # [3 4]] print ('array2D = \n', array2D) print ('ndim = ', array2D.ndim) # 2 print ('shape = ', array2D.shape) # (2, 2) # Generar un array con valores constantes # 1. Array de ceros arrayDeCeros = np.zeros( (2,3) ) print ('arrayDeCeros 2D = \n', arrayDeCeros) # [[0. 0. 0.] # [0. 0. 0.]] print ('dtype = ',arrayDeCeros.dtype ) # float64 # Conversion al tipo de dato entero 64 arrayDeCeros = np.zeros( (2,3) , dtype = np.int64) print ('\narrayDeCeros 2D = \n', arrayDeCeros) # [[0 0 0] # [0 0 0]] print ('dtype = ',arrayDeCeros.dtype ) # int64 # 2. Array de unos arrayDeUnos = np.ones ( (4) ) print ('\narrayDeUnos 1D = ', arrayDeUnos) # [1. 1. 1. 1.] # Se genero un arreglo de unos multiplicado po 5.4 x1 = 5.4 * np.ones(10) print ('x1', x1) # x1 [5.4 5.4 5.4 5.4 5.4 5.4 5.4 5.4 5.4 5.4] # se genero un arreglo de 10 posiciones con valor de 5.4 # full recibe dos argumentos y evita la multiplicacion x2 = np.full(10, 5.4) print ('x2', x2) # x1 [5.4 5.4 5.4 5.4 5.4 5.4 5.4 5.4 5.4 5.4] arreglo1D = np.empty(5) arreglo1D.fill (10) print ('arreglo1D = ', arreglo1D) arreglo1D = np.full (5, 8.0) print ('arreglo1D = ', arreglo1D) # Usando arange arreglo1D = np.arange (0.0, 10, 1) print ('arreglo1D = ', arreglo1D) arreglo1D = np.linspace (0, 10, 11) print ('arreglo1D = ', arreglo1D) x = np.array ([-1, 0 , 1]) y = np.array([-2, 0, 2]) print ('x + y = ', np.meshgrid(x + y) ) z = (x + y) ** 2 print ('z = ', z)
552143bf089381f164f484f27167500f3148a99f
EugeneBad/Office_Space_Allocation
/PERSON/fellow_test.py
1,018
3.625
4
import unittest from PERSON.person import Person, Fellow class FellowTest(unittest.TestCase): def setUp(self): self.in_fellow = Fellow('Scott', 'Y') self.out_fellow = Fellow('Aretha', 'N') def test_Fellow_inherits_Person(self): self.assertTrue(issubclass(Fellow, Person), msg='Fellow should inherit Person') def test_Fellow_type(self): self.assertEqual(self.in_fellow.type, 'fellow', msg='Fellow type should be fellow') self.assertEqual(self.out_fellow.type, 'fellow', msg='Fellow type should be fellow') def test_Fellow_name(self): self.assertEqual(self.in_fellow.name, 'Scott', msg='Fellow name is wrong') self.assertEqual(self.out_fellow.name, 'Aretha', msg='Fellow name is wrong') def test_Fellow_accommodation(self): self.assertEqual(self.in_fellow.accommodation, 'Y', msg="Fellow's accommodation status is wrong") self.assertEqual(self.out_fellow.accommodation, 'N', msg="Fellow's accommodation status is wrong")
3c8bdfe4f883e137f0e79ba5042d6e7debcc63ae
homeworkofgit/gitdemo
/cal.py
169
3.890625
4
#calculator created by Gat Jiarui a=int(input()) b=int(input()) x=input() if(x=='+') print(a+b) if(x=='-') print(a-b) if(x=='*') print(a*b) if(x=='/' and b!=0) print(a/b)
7941990da85aebcaaeed452c3be51ec0c3077cb0
All3yp/Daily-Coding-Problem-Solutions
/Solutions/303.py
1,182
4.40625
4
""" Problem: Given a clock time in hh:mm format, determine, to the nearest degree, the angle between the hour and the minute hands. Bonus: When, during the course of a day, will the angle be zero? """ HOUR_ANGLE = { 1: (1 / 12) * 360, 2: (2 / 12) * 360, 3: (3 / 12) * 360, 4: (4 / 12) * 360, 5: (5 / 12) * 360, 6: (6 / 12) * 360, 7: (7 / 12) * 360, 8: (8 / 12) * 360, 9: (9 / 12) * 360, 10: (10 / 12) * 360, 11: (11 / 12) * 360, 12: (12 / 12) * 360, } def get_displaced_hour_angle(mm: int) -> float: return (mm / 60) * (360 / 12) def get_minutes_angle(mm: int) -> float: return (mm / 60) * 360 def get_angle_between_arms(time: str) -> int: hh, mm = [int(elem) for elem in time.split(":")] hour_angle = (HOUR_ANGLE[hh] + get_displaced_hour_angle(mm)) % 360 minute_angle = get_minutes_angle(mm) return round(abs(hour_angle - minute_angle)) if __name__ == "__main__": print(get_angle_between_arms("12:20")) print(get_angle_between_arms("12:00")) print(get_angle_between_arms("6:30")) print(get_angle_between_arms("3:45")) """ SPECS: TIME COMPLEXITY: O(1) SPACE COMPLEXITY: O(1) """
25877630b3fa068a15946cea4692a619b17a900c
cybo-neutron/DS-and-Algo
/BinarySearch/ugly_number_iii.py
642
3.53125
4
import math def lcm2(a,b,c): return (a*lcm(b,c))//math.gcd(a,lcm(b,c)) def lcm(a,b): return (a*b)//math.gcd(a,b) def check(n,a,b,c,m): num=0 num=m//a + m//b + m//c - m//lcm(a,b) - m//lcm(b,c) - m//lcm(a,c) + m//lcm2(a,b,c) return num>=n class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: l=min(a,b,c)-1 r=n*min(a,b,c) while(r-l>1): m=l+(r-l)//2 if(check(n,a,b,c,m)): r=m else: l=m; return r
611ac587fdb32648bd10eeb7f90013671344fdd3
gitHirsi/PythonNotes
/001基础/015lambda表达式/04列表内字典数据排序.py
608
4.0625
4
""" @Author:Hirsi @Time:2020/6/9 20:49 """ students = [ {'name': 'DD', 'age': 20}, {'name': 'CC', 'age': 30}, {'name': 'BB', 'age': 18}, {'name': 'AA', 'age': 21} ] # sort(key=lambda... , reverse=bool) # name key对应的值 升序排序 students.sort(key=lambda x: x['name']) print(students) # name key对应的值 降序排序 students.sort(key=lambda x: x['name'], reverse=True) print(students) # age key对应的值 升序排序 students.sort(key=lambda x:x['age']) print(students) # age key对应的值 降序排序 students.sort(key=lambda x:x['age'],reverse=True) print(students)
01933effba34a27fc9b06f397f2f65be18b7e5c2
RyanKruegel/FileDialogDemo.GUI
/filedialogdemo.py
1,240
3.6875
4
""" Program: filedialogdemo.py Author: Ryan K Date: 10/19/20 """ from breezypythongui import EasyFrame import tkinter.filedialog class FileDialogDemo(EasyFrame): # demonstrated the use of a file dialog. def __init__(self): # sets up the window and the widget EasyFrame.__init__(self, title = "File Dialog Demo") self.outputArea = self.addTextArea(text = "", row = 0, column = 0, width = 80, height = 15) self.addButton(text = "Open", row = 1, column = 0, command = self.openFile) # event handling method def openFile(self): # pops up an open file dialog, and if a file is selected, displays its text in the text are and its path name in the title bar of the window. fList = [("Python files", "*.py"), ("Text files", "*.txt")] fileName = tkinter.filedialog.askopenfilename(parent = self, filetypes = fList) # if the filename is NOT just an empty string, open the file contents, set the text of the text area and update the title of the window if fileName != "": file = open(fileName, "r") text = file.read() file.close() self.outputArea.setText(text) self.setTitle(fileName) # definition of the main() function def main(): FileDialogDemo().mainloop() main()
c3c549d68da0db3fb06ac40b718d0a46d66b5298
Adasumizox/ProgrammingChallenges
/codewars/Python/3 kyu/MakeASpiral/spiralize_test.py
1,374
3.53125
4
from spiralize import spiralize import unittest class TestMakeASpiral(unittest.TestCase): def test(self): def solution(size): if size == 1: return [[1]] spiral = [] # Fill top row with '1's and rest with '0's for i in range(size): spiral.append([1 if i == 0 else 0] * size) # Locations and directions row, col = 0, size-1 hor, ver = 0, 1 # Loop for the length of the spiral's arm for n in range(size-1, 0, -2): # Loop for the number of arms of this length for m in range(min(2, n)): # Loop for each '1' in this arm for i in range(n): row += ver col += hor spiral[row][col] = 1 # Change direction hor, ver = -ver, hor return spiral for size in range(5,10): self.assertEqual(spiralize(size), solution(size), "Failed for size %i" % size) for size in range(11,50): self.assertEqual(spiralize(size), solution(size), "Failed for size %i" % size) self.assertEqual(spiralize(100), solution(100), "Failed for size 100") if __name__ == '__main__': unittest.main()
b4cfe73b139d6af0f9305b2c420566fac84fc9ff
dixitomkar1809/Coding-Python
/GFG/String/removeAdjacentDuplicatesString.py
1,354
3.65625
4
# Author: Omkar Dixit # Email: omedxt@gmail.com ''' Given a string s, recursively remove adjacent duplicate characters from the string s. The output string should not have any adjacent duplicates. ''' # Time Complexity: O(n) class Solution: def removeDups(self, s, lastRemoved): if len(s) == 0 or len(s) == 1: return s if s[0] == s[1]: lastRemoved = ord(s[0]) while len(s) > 1 and s[0] == s[1]: s = s[1:] s = s[1:] return self.removeDups(s, lastRemoved) rem_str = self.removeDups(s[1:], lastRemoved) if len(rem_str) != 0 and rem_str[0] == s[0]: lastRemoved = ord(s[0]) return rem_str[1:] if len(rem_str) == 0 and lastRemoved==ord(s[0]): return rem_str return s[0] + rem_str if __name__ == '__main__': str1 = "geeksforgeeg" str2 = "azxxxzy" str3 = "caaabbbaac" str4 = "gghhg" str5 = "aaaacddddcappp" str6 = "aaaaaaaaaa" str7 = "qpaaaaadaaaaadprq" str8 = "acaaabbbacdddd" sol = Solution() print(sol.removeDups(str1, 0)) print(sol.removeDups(str2, 0)) print(sol.removeDups(str3, 0)) print(sol.removeDups(str4, 0)) print(sol.removeDups(str5, 0)) print(sol.removeDups(str6, 0)) print(sol.removeDups(str7, 0)) print(sol.removeDups(str8, 0))
7baae670f50e97f5cd03300a53d66251c501e96b
varshachary/MyPracticeProblems
/unique_n_integers_add_upto0.py
355
3.609375
4
""" Given an integer n, return any array containing n unique integers such that they add up to 0. #leetcode """ class Solution: def sumZero(self, n: int) -> List[int]: arr=list(range(1,n)) return arr+[-(sum(arr))] """ Input: n = 5 Output: [-7,-1,1,3,4] Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4]. """
ed9822e4abe55ae42bdcade9ab12e349e008893f
toshihikoyanase/optuna
/optuna/_hypervolume/hssp.py
1,667
3.5
4
from typing import List import numpy as np import optuna def _solve_hssp( rank_i_loss_vals: np.ndarray, rank_i_indices: np.ndarray, subset_size: int, reference_point: np.ndarray, ) -> np.ndarray: """Solve a hypervolume subset selection problem (HSSP) via a greedy algorithm. This method is a 1-1/e approximation algorithm to solve HSSP. For further information about algorithms to solve HSSP, please refer to the following paper: - `Greedy Hypervolume Subset Selection in Low Dimensions <https://ieeexplore.ieee.org/document/7570501>`_ """ selected_vecs: List[np.ndarray] = [] selected_indices: List[int] = [] contributions = [ optuna._hypervolume.WFG().compute(np.asarray([v]), reference_point) for v in rank_i_loss_vals ] hv_selected = 0.0 while len(selected_indices) < subset_size: max_index = int(np.argmax(contributions)) contributions[max_index] = -1 # mark as selected selected_index = rank_i_indices[max_index] selected_vec = rank_i_loss_vals[max_index] for j, v in enumerate(rank_i_loss_vals): if contributions[j] == -1: continue p = np.max([selected_vec, v], axis=0) contributions[j] -= ( optuna._hypervolume.WFG().compute(np.asarray(selected_vecs + [p]), reference_point) - hv_selected ) selected_vecs += [selected_vec] selected_indices += [selected_index] hv_selected = optuna._hypervolume.WFG().compute(np.asarray(selected_vecs), reference_point) return np.asarray(selected_indices, dtype=int)
5f94a72331002185e23a3a0839954e6865cc2744
SurajPatil314/Leetcode-problems
/shortestcompletingword.py
1,657
4.125
4
''' Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said to complete the given string licensePlate Here, for letters we ignore case. For example, "P" on the licensePlate still matches "p" on the word. It is guaranteed an answer exists. If there are multiple answers, return the one that occurs first in the array. The license plate might have the same letter occurring multiple times. For example, given a licensePlate of "PP", the word "pair" does not complete the licensePlate, but the word "supper" does. ''' class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: ans1=[] ans3=[] if(len(licensePlate) ==0 or len(words)==0): return None for char1 in licensePlate: if char1.isalpha(): ans1.append(char1.lower()) print(ans1) for litem in words: ans2=[] ans2 = ans1.copy() for litemchar in litem: if litemchar.isalpha(): if litemchar.lower() in ans2: ans2.remove(litemchar.lower()) if len(ans2)==0: ans3.append(litem) print("ans3::") print(ans3) if len(ans3)==0: return None else: len1= len(ans3[0]) fans= ans3[0] for qw in ans3: if len(qw)<len1: fans=qw len1= len(qw) return fans
72657c084eb68561cfda42a8c1920ddb0e04801c
jgam/hackerrank
/sorting/bubblesort.py
611
3.546875
4
def countSwaps(a): num_swap = 0 if a == sorted(a): print('Array is sorted in', num_swap, 'swaps.') print('First Element:', a[0]) print('Last Element:', a[-1]) return 0 else: for i in range(1,len(a)): for j in range(len(a)-i): if a[j] > a[j+1]: first_num, second_num = a[j+1], a[j] a[j+1] = second_num a[j] = first_num num_swap += 1 print('Array is sorted in', num_swap, 'swaps.') print('First Element:', a[0]) print('Last Element:', a[-1])
47de073c40eecb3a1fadf8ee409193ba4b989092
Dawrld/student-python-introduction-qadr98
/loops-for/arrayLoop.py
101
3.515625
4
def insert_squares(arr, num): arr1 = arr + [i ** 2 for i in range(1, num + 1)] return arr1
d076b02566d759ffb6124532e0909deea51fbf39
serdaraltin/Freelance-Works-2020
/202003161131 - alaca (Java - Soru-Cevap)/example-code/advent_of_code_2018-master/estomagordo-python3/1b.py
250
3.53125
4
def solve(d): count = 0 reached = set([0]) while True: for line in d: count += int(line) if count in reached: return count reached.add(count) with open('input_1.txt') as f: data = [line.rstrip() for line in f] print(solve(data))
49bc0217670a611c8a049f587f8dd0a215b6145d
lancekindle/pysolation
/RobotBoard.py
6,815
3.84375
4
import Game import random import BoardAnalyzer class RandomBot(object): """ controller for any non-humanControlled playing tokens. Using a board-representation, it can decide where to move, and what tiles to remove. Calls to the RandomBot must be made for each moving-or-removing turn. Future inheriting classes, should they fail in taking a turn, should call super() on their take_move_player_turn and take_remove_tile_turn, since these base functions will take any possible turn. """ def __init__(self, game, board, player): self.game = game # keep reference of game for tracking success of move (game.turnSuccessfull) self.board = board # keep reference to the board and player for calculations self.player = player def take_move_player_turn(self, move_player_fxn): """ move player token to a random nearby tile """ x, y = self.player.x, self.player.y tiles = self.board.get_landable_tiles_around(x, y) target = random.choice(tiles) move_player_fxn(target.x, target.y) def take_remove_tile_turn(self, remove_tile_fxn): """ remove a random tile from the board """ removableTiles = list(self.board.get_all_open_removable_tiles()) # all removable tiles target = random.choice(removableTiles) remove_tile_fxn(target.x, target.y) class TileRemoveBot(RandomBot): def take_remove_tile_turn(self, remove_tile_fxn): """ remove a random tile around a random player (that isn't MY player). If that isn't possible, remove a random tile that's not around my player. If that isn't possible, remove a random tile. """ tilesAroundOpponents = [] for player in self.board.players: if not player == self.player: x, y = player.x, player.y nearbyTiles = self.board.get_removable_tiles_around(x, y) tilesAroundOpponents.extend(nearbyTiles) tilesAroundOpponents = set(tilesAroundOpponents) x, y = self.player.x, self.player.y tilesAroundMe = set(self.board.get_removable_tiles_around(x, y)) # tiles around controlled player (me) safelyAroundOpponents = list(tilesAroundOpponents - tilesAroundMe) # tiles around opponents but not around me removableTiles = set(self.board.get_all_open_removable_tiles()) # all removable tiles safelyRemovable = list(removableTiles - tilesAroundMe) # all removable tiles except those around me try: if safelyAroundOpponents: target = random.choice(safelyAroundOpponents) elif tilesAroundOpponents: # likely that I'm next to other player. I'll have to remove a tile available for both of us target = random.choice(list(tilesAroundOpponents)) else: # no open spots to remove around players can only happen if solid unremovable tiles exist target = random.choice(safelyRemovable) except IndexError: # this error will catch if last else statement possibly triggered it super(TileRemoveBot, self).take_remove_tile_turn(remove_tile_fxn) return remove_tile_fxn(target.x, target.y) class MoveBot(TileRemoveBot): """ MoveBot moves toward open, escapable tiles. It calculates the best location(s) on a board by looking at the # of open neighboring tiles for all tiles -- twice. It chooses to move towards a tile that has the most desireable neighboring tiles """ def take_move_player_turn(self, move_player_fxn): x, y = self.player.x, self.player.y grid_gen_fxn = self.board.to_number_grid sweetspotter = BoardAnalyzer.SweetSpotGrid(grid_gen_fxn) grid = sweetspotter.originalGrid try: x, y = sweetspotter.get_next_move_toward_sweet_spot(grid, x, y) except IndexError: super(MoveBot, self).take_move_player_turn(move_player_fxn) return move_player_fxn(x, y) class RobotGameBoard(Game.GameBoard): """ allow defining robots in board """ def set_num_robot_players(self, numRobots): if numRobots < 1: return numPlayers = len(self.players) n = int(numPlayers / numRobots) # n is a ratio for player in self.players[::n]: # every nth player is a robot, so we sample every nth player if numRobots: # stop once numRobots has been reached player.humanControlled = False numRobots -= 1 class RobotGame(Game.Game): """ game handles adding robots to gameplay """ def setup(self, numPlayers=2, shape=(9,9), numRobots=0): self.board = self.GameBoard() self.board.Player = self.Player # set up proper inheritance self.board.Tile = self.Tile self.board.setup(shape) self.board.add_players(numPlayers + numRobots) self.robots = dict() self.setup_robots(numRobots) self.turnType = self.MOVE_PLAYER # first player's turn is to move self.get_active_player().active = True def setup_robots(self, numRobots): """ set up robots to handle appropriate number player token """ self.board.set_num_robot_players(numRobots) for player in self.board.players: if not player.humanControlled: robot = MoveBot(self, self.board, player) self.robots[player] = robot def robot_takes_turn(self): """ if active player is robot (AI), will guide robot into taking part of its turn (remove-tile or move-player) """ activePlayer = self.get_active_player() if activePlayer.humanControlled: return activeRobot = self.robots[activePlayer] if self.turnType == self.REMOVE_TILE: remove_tile_fxn = super(RobotGame, self).player_removes_tile activeRobot.take_remove_tile_turn(remove_tile_fxn) elif self.turnType == self.MOVE_PLAYER: move_player_fxn = super(RobotGame, self).player_moves_player activeRobot.take_move_player_turn(move_player_fxn) elif self.turnType == self.GAME_OVER: pass # game over, we do nothing else: raise # problem with our logic def player_removes_tile(self, x, y): """ if active player is human, carry out function. Otherwise exit """ activePlayer = self.get_active_player() if activePlayer.humanControlled: super(RobotGame, self).player_removes_tile(x, y) def player_moves_player(self, x, y): """ if active player is human, carry out function. Otherwise exit """ activePlayer = self.get_active_player() if activePlayer.humanControlled: super(RobotGame, self).player_moves_player(x, y)
8491effdf9af4f995f507106744610a6d256709f
shankar-jasti/AIND
/Sudoku/solution.py
5,418
3.640625
4
assignments = [] rows = 'ABCDEFGHI' cols = '123456789' def cross(A, B): return [s+t for s in A for t in B] boxes = cross(rows,cols) row_units = [cross(r, cols) for r in rows] col_units = [cross(rows, c) for c in cols] diag_units = [[m+str(n) for m,n in zip(rows,cols)],[m+str(n) for m,n in zip(rows,cols[::-1])]] square_units = [cross(rs,cs) for rs in (rows[:3],rows[3:6],rows[6:]) for cs in (cols[:3],cols[3:6],cols[6:])] unitlist = row_units+col_units+diag_units+square_units units = dict((s, [u for u in unitlist if s in u]) for s in boxes) def assign_value(values, box, value): """ Please use this function to update your values dictionary! Assigns a value to a given box. If it updates the board record it. """ # Don't waste memory appending actions that don't actually change any values if values[box] == value: return values values[box] = value if len(value) == 1: assignments.append(values.copy()) return values def naked_twins(updated_values): """ The logic followed in this function is 1. loop through each unit in unitlist to find naked twins in that unit 2. Once naked twins found then remove all naked twins digits from all other boxes in that unit 3. Any update can possibly produce a naked twins in the same unit or other units 4. Then break the loop and go to step 1 to find naked twins formed by this function """ updated = True """While loop keep running as long as long as a box is updated""" while(updated): updated = False """This loop covers logic of going through each unit in unitlist""" for u in unitlist: if updated is True: break twins = {} unit_values = {k:updated_values[k] for k in u if len(updated_values[k]) == 2} """ This loop groups all two digit boxes by box values, Sample shown below. sample-> this loop produces {'11':['A1','A7'],'12':['A2'],'56':['A8']} """ for k,v in sorted(unit_values.items()): twins.setdefault(v, []).append(k) twins = {v:kl for v,kl in twins.items() if len(kl)>1} """This loop goes through dict of twins produced by above loop Note: This can be improved by updating all peers instead of updating peers in unit""" for value,keylist in twins.items(): for box in list(set(u) - set(keylist)): oldVal = updated_values[box] table = str.maketrans(dict.fromkeys(value)) updatedVal = updated_values[box].translate(table) """ Blow two lines along with while loop covers new naked twins formed by the update""" if oldVal != updatedVal: updated = True updated_values = assign_value(updated_values,box,updatedVal) return updated_values # Find all instances of naked twins # Eliminate the naked twins as possibilities for their peers def grid_values(grid): value_list = [x.replace('.',cols) for x in grid] grid_dict = dict(zip(boxes,value_list)) return grid_dict def display(values): width = 1+max(len(values[k]) for k in boxes) line = '+'.join(['-'*(width*3)]*3) for r in rows: print(''.join(values[r+c].center(width)+('|' if c in '36' else '') for c in cols)) if r in 'CF': print(line) return def eliminate(values): for key,data in values.items(): if len(data) == 1: for unit in (u for u in unitlist if key in u): for element in (e for e in unit if key!=e): values[element] = values[element].replace(data,'') return values def only_choice(values): for unit in unitlist: for key in (k for k in unit if len(values[k])>1): unit_val = [values[k] for k in unit if k!=key] for data in list(values[key]): if not(any(data in v for v in unit_val)): values[key] = data break return values def reduce_puzzle(values): stalled = False while not stalled: solved_values_before = len([box for box in values.keys() if len(values[box]) == 1]) values = eliminate(values) values = only_choice(values) values = naked_twins(values) solved_values_after = len([box for box in values.keys() if len(values[box]) == 1]) stalled = solved_values_before == solved_values_after if len([box for box in values.keys() if len(values[box]) == 0]): return False return values def search(values): values = reduce_puzzle(values) if values: # Choose one of the unfilled squares with the fewest possibilities unSolVals = {ke:len(vl) for ke,vl in values.items() if len(vl)>1} if len(unSolVals) > 0: fewestValKey = min(unSolVals,key=unSolVals.get) # Now use recursion to solve each one of the resulting sudokus, and if one returns a value (not False), return that answer! for data in values[fewestValKey]: newValues = values.copy() newValues = assign_value(newValues,fewestValKey,data) newValues = search(newValues) if newValues: return newValues else: return values else: return False def solve(grid): gridDict = grid_values(grid) return search(gridDict) if __name__ == '__main__': diag_sudoku_grid = '9.1....8.8.5.7..4.2.4....6...7......5..............83.3..6......9................' # diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3' display(solve(diag_sudoku_grid)) try: from visualize import visualize_assignments visualize_assignments(assignments) except SystemExit: pass except: print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')
7d75401857437af4eb57a927645de55bdcf40936
jasonsahl/UGAP
/igs/threading/channels.py
1,806
3.890625
4
## # Channels provide a means of communicatin between threads from Queue import Queue class Channel: """ A channel is a unidirectional form of communication between threads. A channel allows for the following actions: send - Send an object over the channel sendError - Sends an error, the object should be an exception. It will get raised on the otherside when they do a receive receive - Receive an object from a channel, this blocks unless a timeout is set NOTE - One thread should only be send'ing and the other thread only receive'ing. Channels unidirectional sendWithChannel - Send an object and create a receive channel, and return it. The object will be sent as a tuple (object, Channel). This is useful if you want to send a task to perform and get a result back, the channel is almost like a 'future' but not quite. There is no sendErrorWithChannel. """ def __init__(self): self.queue = Queue() def send(self, obj): """Send 'obj' through the channel""" self.queue.put_nowait((True, obj)) def sendError(self, err): """Send an error""" self.queue.put_nowait((False, err)) def sendWithChannel(self, obj): """Send 'obj' as well as a new channel through this channel and return the new channel""" ch = Channel() self.send((obj, ch)) return ch def receive(self, timeout=None): """ Receive an object from the channel. Blocks unless a timeout is specified. Give a timeout of 0 to poll """ block = True ok, item = self.queue.get(block, timeout) self.queue.task_done() if not ok: raise item return item
1be18deb0efcc552010a944cd8aeb1301ecac7bb
alebreux/iot
/moteur2.py
1,038
3.5
4
import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BOARD) Motor1A = 16 Motor1B = 18 Motor1E = 22 GPIO.setup(Motor1A,GPIO.OUT) GPIO.setup(Motor1B,GPIO.OUT) GPIO.setup(Motor1E,GPIO.OUT) print ("Going forwards") GPIO.output(Motor1A,GPIO.HIGH) GPIO.output(Motor1B,GPIO.LOW) GPIO.output(Motor1E,GPIO.HIGH) sleep(3) print ("Going backwards") GPIO.output(Motor1A,GPIO.LOW) GPIO.output(Motor1B,GPIO.HIGH) GPIO.output(Motor1E,GPIO.HIGH) sleep(3) print ("Going forwards") GPIO.output(Motor1A,GPIO.HIGH) GPIO.output(Motor1B,GPIO.LOW) GPIO.output(Motor1E,GPIO.HIGH) sleep(3) print ("Going backwards") GPIO.output(Motor1A,GPIO.LOW) GPIO.output(Motor1B,GPIO.HIGH) GPIO.output(Motor1E,GPIO.HIGH) sleep(5) print ("Going forwards") GPIO.output(Motor1A,GPIO.HIGH) GPIO.output(Motor1B,GPIO.LOW) GPIO.output(Motor1E,GPIO.HIGH) sleep(3) print ("Going backwards") GPIO.output(Motor1A,GPIO.LOW) GPIO.output(Motor1B,GPIO.HIGH) GPIO.output(Motor1E,GPIO.HIGH) sleep(3) print ("Now stop") GPIO.output(Motor1E,GPIO.LOW) GPIO.cleanup()
cd858b51e939cde7ea878deae2077f7030a09706
peng00bo00/optlearningcontrol
/Project/infrastructure/sumtree.py
1,951
3.5625
4
import numpy as np class SumTree: """ A sum-tree data structure for prioritized replay buffer. """ def __init__(self, capacity): """ Initialize sum-tree with given capacity. """ ## self.data is used to store data self.data = np.zeros(capacity, dtype=object) ## self.tree is used to record weights self.tree = np.zeros(2*capacity-1) self.capacity = capacity ## self.position is used to record data index self.position = 0 def _propogate(self, idx, change): """ Update the weights recursively from bottom up. """ parent = (idx - 1) // 2 self.tree[parent] += change if parent != 0: self._propogate(parent, change) def _retrieve(self, idx, s): """ Traverse the tree recursively from top down. Return the leaf index in the tree. """ left = 2*idx + 1 right = 2*idx + 2 ## return idx if it's already leaf if left >= len(self.tree): return idx ## traverse recursively if s <= self.tree[left]: return self._retrieve(left, s) else: return self._retrieve(right, s-self.tree[left]) def push(self, data, p): """ Add a new node into the tree. """ idx = self.position + self.capacity - 1 self.data[self.position] = data self.update(idx, p) self.position += 1 if self.position >= self.capacity: self.position = 0 def update(self, idx, p): change = p - self.tree[idx] self.tree[idx] = p self._propogate(idx, change) def get(self, s): idx = self._retrieve(0, s) dataIdx = idx - (self.capacity - 1) return idx, self.tree[idx], self.data[dataIdx] @property def total(self): return self.tree[0]
80da32d74fe931426b1e9297724d93f47c256c4c
PedroLSF/PyhtonPydawan
/6b - CHALLENGE ADV/6.2.3_MoreFrequentItem.py
449
3.875
4
# We have a conveyor belt of items where each item is represented by a different number. #We want to know, out of two items, which one shows up more on our belt def more_frequent_item(lst, item1, item2): new_lst1 = lst.count(item1) new_lst2 = lst.count(item2) if new_lst1 >= new_lst2: return item1 else: return item2 #Uncomment the line below when your function is done print(more_frequent_item([2, 3, 3, 2, 3, 2, 3, 2, 3], 2, 3))
25d4b161df40ed5b5b375140f97b72fc51b08596
koder-ua/python-classes
/examples/rational_3.py
1,001
3.53125
4
def nod(x, y): x = abs(x) y = abs(y) return _nod(max(x, y), min(x, y)) def _nod(x, y): if y == 0: return x return nod(y, x % y) class BasicRational(object): "basic rational number" def __init__(self, num, denom): self.num = num self.denom = denom def __add__(self, y): nd = self.denom * y.denom nn = self.num * y.denom + y.num * self.denom return self.__class__(nn, nd) def __neg__(self): return self.__class__(-self.num, self.denom) def __sub__(self, y): return self + (-y) def __str__(self): return "{}/{}".format(self.num, self.denom) def __repr__(self): return str(self) class AutoSimpl(BasicRational): "Auto simplified rational number" def __init__(self, num, denom): cur_nod = nod(num, denom) self.num = num / cur_nod self.denom = denom / cur_nod b1 = AutoSimpl(1, 2) b2 = AutoSimpl(1, 3) b3 = b2 - b1 - b1 print b1, b2, b3
af7c4f92decc61a9a69565593923c87926d36f3d
HarryKT/LCD-Display
/example/single_custom-4-bit.py
745
4.09375
4
## PRINTING A SINGLE CUSTOM CHARACTER ''' Take a look at this code, which prints a single smiley face character to the display: ''' from RPLCD import CharLCD, cleared, cursor # This is the library which we will be using for LCD Display from RPi import GPIO # This is the library which we will be using for using the GPIO pins of Raspberry PI # Initializing the LCD Display lcd = CharLCD(numbering_mode=GPIO.BOARD, cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23]) smiley = ( 0b00000, 0b01010, 0b01010, 0b00000, 0b10001, 0b10001, 0b01110, 0b00000, ) lcd.create_char(0, smiley) lcd.write_string(unichr(0)) # Always Clean Up the GPIO after using the code GPIO.cleanup()
b66882851b3f8d42c3b6e3b49d20c7715f6844a8
wupai/myFirst
/judgeprime.py
554
4.03125
4
''' 题目:判断101-200之间有多少个素数,并输出所有素数。 程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除, 则表明此数不是素数,反之是素数。 ''' import math def jdprime(n): for i in range( 2, int(math.sqrt(n)+1)): if n%i==0: return False return True sum=0 for i in range(1,200+1): if jdprime(i): sum+=1 print('%6d'%i, end='' ) if sum%10==0: print() print() print("总共有%d个素数"%sum)
46a4df21932f5b4499c0335698fd6dc024bc7b7c
dbahsa/python_algoBunch
/tri_selection/main.py
954
3.953125
4
import random # tri par sélection # l = [5, 8, 1, 4] # V # [1, 5, 8, 10, 2] # sorted / unsorted # V # [1, 2, 5, 8, 10] # V # [1, 2, 5, 8, 10] # O(N^2) # print("UNSORTED:", l) # generate_random_list(n, min, max) 3, 0, 10 [7, 10, 5] # selection_sort(l) def generate_random_list(n, min, max): l = [] for i in range(n): e = random.randint(min, max) l.append(e) return l def selection_sort(l): for unsorted_index in range(0, len(l)-1): min = l[unsorted_index] min_index = unsorted_index for i in range(unsorted_index+1, len(l)): if l[i] < min: min = l[i] min_index = i # V m l[min_index] = l[unsorted_index] # [5, 8, 10, 2, 5] l[unsorted_index] = min # [1, 8, 10, 2, 5] l = generate_random_list(100, -1000, 1000) print("UNSORTED:", l) selection_sort(l) print("SORTED: ", l)
723b762f929afe151eed62520cf91b4063846a24
jmnelmar/LeetCodeChallengues
/Python/PlusOne.py
1,555
4
4
''' Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself. Example 1: Input: digits = [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Example 2: Input: digits = [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321. Example 3: Input: digits = [0] Output: [1] Constraints: 1 <= digits.length <= 100 0 <= digits[i] <= 9 ''' def plusOne(digits): n = len(digits) -1 carry = 0 while(n >= 0): if n == len(digits) - 1: digits[n] += 1 if carry > 0: digits[n] += carry carry = 0 if digits[n] > 9: carry = 1 digits[n] -= 10 #print(f'{digits}, carry: {carry}, n: {n}') n -= 1 if carry > 0: digits.insert(0,1) print(digits) ''' for i in range(n): print(digits[-i]) if carry > 0: digits[-i] += carry digits[-i] += 1 if digits[-i] > 9: carry = 1 digits[-i] -= 10 ''' #[ 9, 9, 0] carry = 1 digits = [9,9,9] plusOne(digits) digits = [8,9,9,9] plusOne(digits)
977884ee193e0d6a43ab9dfd82cc4cd9caae757d
mhiro216/atcoder_abc_python
/abc/162_C.py
229
3.8125
4
""" gcd(a,b,c) = gcd(a, gcd(b,c)) """ K = int(input()) from math import gcd ans = 0 for i in range(1,K+1): for j in range(1, K+1): for k in range(1, K+1): ans += gcd(i, gcd(j,k)) print(ans)
e3f4e2950867374e895f78e47644d147c43e98d7
robsonshockwave/poo-python
/algoritmos_sort/bublue_e_quick.py.py
2,150
4.15625
4
# -*- coding: utf-8 -*- from random import randint from random import seed import timeit import time #Implemente uma função que receba uma lista de inteiros e ordena essa lista utilizando o Bubble Sort def bubblesort(l): for _ in range(len(l)): for j in range(len(l) - 1): if l[j] > l[j+1]: l[j], l[j+1] = l[j+1], l[j] #Escreva um programa que gere uma lista com 10.000 números inteiros # (gerados randomicamente no intervalo entre 1 e 10.000) def gerarListaAleatoria(l): seed(1) for _ in range(10000): value = randint(1, 10000) l.append(value) #Implementação do Quick Sort def partition(l, inicio, fim): pivot = l[inicio] menor = inicio + 1 maior = fim while True: while menor <= maior and l[maior] >= pivot: maior = maior - 1 while menor <= maior and l[menor] <= pivot: menor = menor + 1 if menor <= maior: l[menor], l[maior] = l[maior], l[menor] else: break l[inicio], l[maior] = l[maior], l[inicio] return maior def quicksort(l, inicio, fim): if inicio >= fim: return p = partition(l, inicio, fim) quicksort(l, inicio, p-1) quicksort(l, p+1, fim) l = [] #gerarListaAleatoria(l) #print('lista com números aleatórios preenchidos: ') #print(l) #bubblesort(l) #print('lista com números ordenados usando bubble sort: ') #print(l) #quicksort(l, 0, len(l) - 1) #print('lista com números ordenados usando quick sort: ') #print(l) #Computar o tempo gasto para ordenar a lista usando o Bubble sort gerarListaAleatoria(l) inicio_bubble = timeit.default_timer() bubblesort(l) fim_bubble = timeit.default_timer() #Imprimir os resultados obtidos, em milisegundos print('Tempo gasto em Bubble Sort foi de:', (fim_bubble - inicio_bubble) * 1000, 'milisegundos') #Computar o tempo gasto para ordenar a lista usando o Quicksort gerarListaAleatoria(l) inicio_quick = timeit.default_timer() quicksort(l, 0, len(l) - 1) fim_quick = timeit.default_timer() #Imprimir os resultados obtidos, em milisegundos print('Tempo gasto foi em Quick Sort de:', (fim_quick - inicio_quick) * 1000, 'milisegundos')
0313ffe8611cbca38c4f3ae829a5e57465aa7c21
WangYoudian/Useful-Toolkit
/A算法竞赛问题/模拟除法.py
864
3.828125
4
# 立华奏在学习初中数学的时候遇到了这样一道大水题: # “设箱子内有 n 个球,其中给 m 个球打上标记,设一次摸球摸到每一个球的概率均等,求一次摸球摸到打标记的球的概率” # “emmm...语言入门题” # 但是她改了一下询问方式:设最终的答案为 p ,请输出 p 小数点后 K_1 到 K_2 位的所有数字(若不足则用 0 补齐) def fastPower(base, power, MOD): res = 1 while power > 0: if power&1: res = res*base%MOD power >>= 1 base = base*base%MOD return res T = int(input()) for _ in range(T): m, n, k1, k2 = map(int, input().split()) kth_digit = (m%n * fastPower(10, k1-1, n))%n while k1 <= k2: kth_digit *= 10 print(kth_digit//n, end='') kth_digit %= n k1 += 1 print()
fe74fa4ce8cc10ece9323dfffe45cd395119feeb
18sg/recipeGrid
/recipeGrid/generator/serves.py
199
3.59375
4
import re serves_regex = re.compile("(serves?|for|makes) (?P<num>\d+)") def interpret(english): match = serves_regex.search(english) return int(match.group("num")) if match is not None else None
1ac8cbf6e3b872651909839822fcdb923bb3349f
ahdahddl/cytoscape
/csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/tags/rs_Python_Pack090515/General_Packages/Data_Struct/ListList.py
2,692
3.71875
4
#!/usr/bin/env python class ListList: def __init__(self, ilists = None): if ilists is None: self.slists = [] else: self.slists = ilists def add_list(self, ilist): self.slists.append(ilist) def add_lists(self, ilists): self.slists += ilists def empty_lists(self, num): self.slists = [] for ct in range(num): self.slists.append([]) def nth_elems(self, nth): ret = [] for slist in self.slists: if nth < len(slist): ret.append(slist[nth]) return ret def nth_nums(self, nth): ret = [] for slist in self.slists: if (nth < len(slist) and (type(slist[nth]) == int or type(slist[nth]) == float)): ret.append(slist[nth]) return ret def nth_nums_all_valid(self, nth): ret = [] for slist in self.slists: if (nth >= len(slist) or (type(slist[nth]) != int and type(slist[nth]) != float)): return False else: ret.append(slist[nth]) return ret def num_lists(self): return len(self.slists) def max_length(self): max = 0 for slist in self.slists: if max < len(slist): max = len(slist) return max def get_all_lists(self): return self.slists def to_single_list(self): single_list = [] for i in range(self.max_length()): nth = self.nth_nums(i) if nth: single_list.append(1.0*sum(nth)/len(nth)) else: single_list.append(None) return single_list def append_all(self, ilist): if len(ilist) != len(self.slists): raise "List size length mismatch" for ct in range(len(ilist)): self.slists[ct].append(ilist[ct]) def append_all_same(self, elem): for elist in self.slists: elist.append(elem) def change_every(self, ilist, nth): if len(ilist) != len(self.slists): raise "List size length mismatch" for ct in range(len(ilist)): self.slists[ct][nth] = ilist[ct] if __name__ == "__main__": ll = ListList([[2,9,8]]) ll.add_list([1,3,5,"Rin",9]) ll.add_list([4,6,8]) ll.add_list([4,5,7,4,7,8]) print ll.get_all_lists() print ll.max_length() print ll.nth_nums(2) print ll.nth_nums_all_valid(2) print ll.to_single_list() print ll.num_lists() ll = ListList() print ll.slists ll.empty_lists(3) print ll.get_all_lists() ll.append_all(["A", "B", "C"]) ll.append_all_same("XXX") print ll.get_all_lists() ll = ListList() ll.add_lists([[1,2,3],[4,5,6],[7,8,9]]) ll.change_every(["A", "B", "C"], 1) print ll.get_all_lists()
99020ae9a2442bf65129790a4d58b5184b75e9c9
beddingearly/LMM
/125_Valid_Palindrome.py
649
3.953125
4
# coding=utf-8 import string class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ # s = s.translate(string.maketrans("",""), string.punctuation) # 去标点符号 exclude = set(string.punctuation) s = ''.join(ch for ch in s if ch not in exclude) s = ''.join(s.split()) # 去句中空格 s = s.lower() # 转化小写 ss = s[::-1] if s == ss: return True else: return False if __name__ == '__main__': a = Solution() s = "A man, a plan, a canal: Panama" print a.isPalindrome(s)
0f83d07991ff8835c6697d499e9971c86ac3eb36
hhongjoon/TIL
/etc/pycharm/day2_problem/min_max.py
643
3.515625
4
import sys sys.stdin = open("sample_input.txt") def min_max(data, a, z): if a < z : copy = list(data) mid = int(a + z)/2 # min_max(copy[:mid+1],0,mid) # min_max(copy[mid+1:],mid+1,len(copy)-1) min_max(copy, 0, mid) min_max(copy, mid + 1, len(copy) - 1) merge(copy,a,mid,z) def merge(data, l, mid, r): result = [] if data[l] > data[r]: data[l], data[r] = data[r],data[l] def main(): case = int(input()) num = int(input()) nums = list(map(float, input.split())) for i in nums: print(f"#{i + 1} {}") if __name__ == "__main__": main()
efbe07cfed9320597ebf131ae146d11817e8c419
LoboCgv/Tutorial-Python
/PruebaPython/Mascota.py
294
3.625
4
class Mascota: def __init__(self,raza,nombreMascota,peso,color): self.raza=raza self.nombreMascota=nombreMascota self.peso=peso self.color=color def __str__(self): print(self.raza+" "+self.nombreMascota+" "+str(self.peso)+" "+self.color)
b5293f52e17755bc070840491a345fa9451dd79f
Chandler/planet_app
/utils/create_tables.py
1,422
3.71875
4
import sqlite3 from os import sys # use as a script: # python utils/create_tables.py planet.db def create_tables(db_name): conn = sqlite3.connect(db_name) # "userid" comes from the specification # if this project were continued I would probably # switch it out for uuid "user_id" and a user defined # "user_name" conn.execute( """ CREATE TABLE users ( pkey INTEGER PRIMARY KEY, userid varchar(200) NOT NULL UNIQUE, first_name varchar(200) NOT NULL, last_name varchar(200) NOT NULL ) """ ) conn.execute( """ CREATE TABLE groups ( pkey INTEGER PRIMARY KEY, name text UNIQUE ) """ ) # this join table models group membership # # using the text fields userid and group_name # in the join table would probably not be a great # decision in a large application, but for a small # app like this it simplifies things # and the join table becomes human readable conn.execute( """ CREATE TABLE user_group_join ( pkey INTEGER PRIMARY KEY, userid varchar(200) NOT NULL, group_name varchar(200) NOT NULL, UNIQUE(userid, group_name) ) """ ) conn.commit() if __name__ == '__main__': db_name = sys.argv[1] create_tables(db_name)
f4b55ff90ad210ceaefe26c0d93446993381f8ac
challeger/leetCode
/每日一题/2020_10_04_两数相加.py
1,290
3.59375
4
""" day: 2020-10-04 url: https://leetcode-cn.com/problems/add-two-numbers/ 题目名: 两数相加 给出两个 非空 的链表用来表示两个非负的整数. 其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和. 您可以假设除了数字 0 之外,这两个数都不会以 0 开头. 思路: 同时遍历两个链表,定义一个进位carry来判断下一次相加是否需要进位即可 """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: node = ListNode(0) # 用来建立新链表的节点 head = node # 最终返回的结果 carry = 0 # 进位 while l1 or l2: x = l1.val if l1 else 0 y = l2.val if l2 else 0 foo = x + y + carry carry = foo // 10 node.next = ListNode(foo % 10) node = node.next if l1: l1 = l1.next if l2: l2 = l2.next if carry: node.next = ListNode(carry) return head.next
23a31ed469a1bee059f5572478fa9e09876a7b38
Jan-zou/LeetCode
/python/String/67_add_binary.py
883
3.828125
4
# !/usr/bin/env python # -*- coding: utf-8 -*- ''' Description: Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". Tags: Math, String Time: O(n) Space: O(1) ''' class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ result = '' carry, val = 0, 0 n = max(len(a), len(b)) for i in xrange(n): val = carry if i < len(a): val += int(a[-(i+1)]) if i < len(b): val += int(b[-(i+1)]) carry, val= val / 2, val % 2 result += str(val) if carry: result += str(carry) return result[::-1] if __name__ == '__main__': print Solution().addBinary('11', '1')
37d959edf740464ebade95b257fdc78945b2a1d9
shubhamgg1997/pyspark
/excersise/list.py
262
3.546875
4
'''Write a program which take a list of list and give result of # all list''' from pyspark import SparkContext sc = SparkContext("local", "list app") list1=[[1,2,3],[4,5,6],[7,8,9]] list2=sc.parallelize(list1) list3=list2.reduce(lambda x,y: x+y) print(list3)
49c5e9b6859f86f8101f965e3365dfbfbd9cafcb
lfteixeira996/Coding-Bat
/Python/List-2/sum67.py
907
3.90625
4
import unittest ''' Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 7 (every 6 will be followed by at least one 7). Return 0 for no numbers. sum67([1, 2, 2]) -> 5 sum67([1, 2, 2, 6, 99, 99, 7]) -> 5 sum67([1, 1, 6, 7, 2]) -> 4 ''' def sum67(nums): flag = True sum = 0 for item in nums: if (item == 6): flag = False if(flag == True): sum += item if(item == 7): flag = True return sum class Test_sum67(unittest.TestCase): def test_1(self): self.assertEqual(sum67([1, 2, 2]), 5) def test_2(self): self.assertEqual(sum67([1, 2, 2, 6, 99, 99, 7]), 5) def test_3(self): self.assertEqual(sum67([1, 1, 6, 7, 2]), 4) if __name__ == '__main__': unittest.main()
13c6d7124de8b0e3d261fded9113266911c9a0ee
TrevorBagels/nomorediscordcreeps
/dev/program/utils.py
1,850
3.640625
4
from datetime import datetime, timezone, timedelta def now() -> datetime: return datetime.now().astimezone(timezone.utc) def long_ago() -> datetime: return datetime(1990, 1, 1).astimezone(timezone.utc) def hms(seconds): """Returns h:m:s from seconds """ seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 return "%d:%02d:%02d" % (hour, minutes, seconds) def dhms(seconds): """Returns d days, h:m:s from seconds """ days = seconds // 86400 seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 return f"{days} day(s), " + "%d:%02d:%02d" % (hour, minutes, int(seconds)) def time_elapsed(seconds): if seconds < 60: return f"{'%02d' % seconds}s" minutes = seconds // 60 if minutes < 60: return f"{'%02d' % minutes}m {'%02d' % (seconds - minutes*60)}s" return hms(seconds) def pluralize(word, value, plural=None, include_value=True): if include_value: word = str(value) + " " + word if plural == None: plural = word + "s" if float(value) == 1.0: return word return plural def time_elapsed_1(seconds): if seconds < 60: return pluralize("second", int(seconds)) minutes = seconds // 60 if minutes < 60: return f"{'%02d' % round(minutes + seconds/60, 1)} minutes" hours = minutes // 60 if hours < 24: return f"{'%02d' % round(hours + minutes/60, 1)} hours" days = hours // 24 return f"{pluralize('day', days)}, " + f"{'%02d' % round(hours + minutes/60, 1)} hours" def round_seconds_datetime(dt: datetime) -> datetime: if dt.microsecond >= 500_000: dt += timedelta(seconds=1) return dt.replace(microsecond=0) def round_seconds_delta(dt: timedelta) -> timedelta: if dt.microseconds >= 500_000: dt += timedelta(seconds=1, microseconds=-dt.microseconds) return dt
e9cc5eb16fd308d1f904bc6efc6541277120ebc3
AlonsoDo/ensayosenpython
/EjemplosNivelMedio/ejercicio1.py
222
3.734375
4
#!/usr/bin/env python anchura = int(input("Anchura del rectangulo: ")) altura = int(input("Altura del rectangulo: ")) for i in range(altura): for j in range(anchura): print("* ", end="") print()
0fda81fbc2fc4911bfbfd19a846370c5a6ed9555
skinder/Algos
/PythonAlgos/Done/Kth_Largest_Element_in_an_Array.py
797
4.09375
4
''' https://leetcode.com/problems/kth-largest-element-in-an-array/ Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Example 1: Input: [3,2,1,5,6,4] and k = 2 Output: 5 Example 2: Input: [3,2,3,1,2,4,5,5,6] and k = 4 Output: 4 ''' class Solution(object): def findKthLargest(self, nums, k): nums.sort() return nums[-k] def find3dmax(self, nums): st = list(set(nums)) st.sort() if len(st) >= 3: return st[-3] else: return st[-1] a = Solution() print a.findKthLargest([3,2,3,1,2,4,5,5,6], 4) print a.findKthLargest([3,2,1,5,6,4], 2) print a.find3dmax([1,2]) print a.find3dmax([3, 2, 1]) print a.find3dmax([2, 2, 3, 1])
88839bbb94816f1d470c06dfae72fe0890903dc8
justinba1010/CSCE557
/proj3-retry/point.py
3,855
4
4
""" Justin Baum 21 October 2020 point.py Points on an elliptic curve """ from utils import multiplicative_inverse as m_inv class Point: """ Point Module Represents points in affine form on some curve """ def __init__(self, x, y, curve): """ Construct a point on some curve """ self.x = x self.y = y self.curve = curve @staticmethod def infinity(): """ Return point at infinity """ point = Point(0,0,None) point.infinity = True return point def copy(self): """ Return a deep copy """ return Point(self.x, self.y, self.curve) def double(self): """ Returns a new point that is: p + p """ if self.infinity: return self # 3x_1^2 + a m_slope = (3 * pow(self.x, 2, self.curve.modulus)) + self.curve.a m_slope *= m_inv(2 * self.y, self.curve.modulus) m_slope %= self.curve.modulus # m^2 - 2x1 x_3 = pow(m_slope, 2, self.curve.modulus) + self.curve.a x_3 %= self.curve.modulus # m(x_3 - x_1) + y_1 y_3 = m_slope * (x_3 - self.x) + self.y y_3 *= -1 y_3 %= self.curve.modulus return Point(x_3, y_3, self.curve) def multiply(self, k): """ Returns new point using p1 * k """ point = self.copy() while k > 1 and not point.infinity: if k & 1 == 1: point += point if not point.infinity: point += self else: # Loop around return self.multiply((k >> 1) + 1) else: point += point return point def add(self, other): """ Returns a new poin that is: p1 + p2 """ if self.infinity: return self if other.infinity: return other if self == other: return self.double() if self.x == other.x: # Geometrically this is the point at infinity return Point.infinity() # (y_2 - y_1) * (x_2 - x_1)^-1 m_slope = (other.y - self.y) m_slope *= m_inv((other.x - self.x) % self.curve.modulus, self.curve.modulus) m_slope %= self.curve.modulus # m^2 - x_1 - x_2 x_3 = pow(m_slope, 2, self.curve.modulus) - self.x - other.x x_3 %= self.curve.modulus # m(x_3 - x_1) + y_1 y_3 = m_slope * (x_3 - self.x) + self.y y_3 %= self.curve.modulus y_3 *= -1 y_3 %= self.curve.modulus return Point(x_3, y_3, self.curve) def def order_multiplication(self): return [] def order_exponentiation(self): return [] def __add__(self, other): """ Allows the use of + """ return self.add(other) def __iadd__(self, other): """ Allows the use of += """ return self + other def __mul__(self, k): """ Allows the use of * """ return self.multiply(k) def __imul__(self, k): """ Allows the use of *= """ return self * k def __eq__(self, other): """ Allows the use of == """ return ( self.x == other.x and self.y == other.y and self.curve == other.curve or (self.infinity and other.infinity) ) def __str__(self): """ Returns a pretty print of the point """ return "<{}, {}>".format(self.x, self.y) def __hash__(self): """ Allows the use of sets """ return hash(0) if self.infinity else hash((self.x, self.y, self.curve.__str__()))
b0d276a316f8f383bf55f81dcfe4ed2f83b391d5
rafaelperazzo/programacao-web
/moodledata/vpl_data/22/usersdata/71/11766/submittedfiles/av1_2.py
187
3.890625
4
# -*- coding: utf-8 -*- from __future__ import division import math a=input("a: ") b=input("b: ") c=input("c: ") d=input("d: ") if a==c or b==d: print("V") else: print("F")
fd5c82689e02b697f9ab341c7c0c5057e04b75e5
Cccmm002/my_leetcode
/378-kth-smallest-element-in-a-sorted-matrix/kth-smallest-element-in-a-sorted-matrix.py
1,073
3.875
4
# -*- coding:utf-8 -*- # Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. # # # Note that it is the kth smallest element in the sorted order, not the kth distinct element. # # # Example: # # matrix = [ # [ 1, 5, 9], # [10, 11, 13], # [12, 13, 15] # ], # k = 8, # # return 13. # # # # Note: # You may assume k is always valid, 1 ≤ k ≤ n2. class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ import heapq height = len(matrix) width = len(matrix[0]) heap = [] for i in range(width): heapq.heappush(heap, (matrix[0][i], 0, i)) for i in range(k - 1): cur = heapq.heappop(heap) if cur[1] + 1 >= height: continue heapq.heappush(heap, (matrix[cur[1] + 1][cur[2]], cur[1] + 1, cur[2])) r = heapq.heappop(heap) return r[0]
068ceb20671a7d62204d40ef4e6eac177744a136
lim1202/LeetCode
/Dynamic Programming/unique_paths.py
3,056
4.15625
4
'''Unique Paths''' # Unique Path # A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). # The robot can only move either down or right at any point in time. # The robot is trying to reach the bottom-right corner of the grid # (marked 'Finish' in the diagram below). # How many possible unique paths are there? def unique_paths(cols, rows): '''Unique paths''' dp_list = [[1 for i in range(cols)] for i in range(rows)] for i in range(1, rows): for j in range(1, cols): dp_list[i][j] = dp_list[i - 1][j] + dp_list[i][j - 1] return dp_list[rows - 1][cols - 1] # Unique Path II # Now consider if some obstacles are added to the grids. How many unique paths would there be? # An obstacle and empty space is marked as 1 and 0 respectively in the grid. def unique_paths_with_obstacles(grid): '''Unique path with obstacles''' if not grid or not grid[0]: return 0 rows = len(grid) cols = len(grid[0]) dp_list = [[1 for i in range(cols)] for i in range(rows)] dp_list[0][0] = 1 if grid[0][0] == 0 else 0 for i in range(1, rows): dp_list[i][0] = 1 if dp_list[i - 1][0] == 1 and grid[i][0] == 0 else 0 for j in range(1, cols): dp_list[0][j] = 1 if dp_list[0][j - 1] == 1 and grid[0][j] == 0 else 0 for i in range(1, rows): for j in range(1, cols): if grid[i][j] == 0: dp_list[i][j] = dp_list[i - 1][j] + dp_list[i][j - 1] else: dp_list[i][j] = 0 return dp_list[rows - 1][cols - 1] # Minimum Path Sum # Given a m x n grid filled with non-negative numbers, # find a path from top left to bottom right which minimizes the sum of all numbers along its path. # Note: You can only move either down or right at any point in time. def min_path_sum(grid): '''Minimum path sum''' if not grid or not grid[0]: return 0 rows = len(grid) cols = len(grid[0]) dp_list = [[1 for i in range(cols)] for i in range(rows)] dp_list[0][0] = grid[0][0] for i in range(1, rows): dp_list[i][0] = dp_list[i - 1][0] + grid[i][0] for j in range(1, cols): dp_list[0][j] = dp_list[0][j - 1] + grid[0][j] for i in range(1, rows): for j in range(1, cols): dp_list[i][j] = min(dp_list[i - 1][j], dp_list[i][j - 1]) + grid[i][j] return dp_list[rows - 1][cols - 1] if __name__ == '__main__': print('Unique paths') print('2 x 2:', unique_paths(2, 2)) print('3 x 3:', unique_paths(3, 3)) print('3 x 4:', unique_paths(3, 4)) print('4 x 4:', unique_paths(4, 4)) print('Unique paths with obstacles') GRID2 = [[0, 1], [0, 0]] print('grid:', GRID2) print('paths:', unique_paths_with_obstacles(GRID2)) GRID3 = [[0, 0, 0], [0, 1, 0], [0, 0, 0]] print('grid:', GRID3) print('paths:', unique_paths_with_obstacles(GRID3)) print('Minimum path sum') GRID22 = [[0, 1], [2, 3]] print('grid:', GRID22) print('sum:', min_path_sum(GRID22))
c46c0f32d0ba6590200f8f09a54a7e8b345ccc83
flfelipelopes/Python-Curso-em-Video
/ex039.py
1,630
4.03125
4
#Um programa que leia se uma pessoa está na idade de alistamento militar ou não, #se já está em tempo de se alistar ou se já passou da época de alistamento. from datetime import date atual = date.today().year print('X'*10, '{}ANALISADOR DE ALISTAMENTO MILITAR{}' .format('\033[1m', '\033[m'), 'X'*10) print('') print('Para fazer a análise do candidato, insira o ano de nascimento abaixo.') nascimento = int(input('Ano de nascimento: ')) idade = (atual - nascimento) print('') print('Quem nasceu em {} tem {} anos em {}'.format(nascimento, idade, atual)) print('') print('Considerando a informação acima: ') if idade == 18: print('Você já está na idade de se alistar! Procure a junta mauis próxima de sua residência.') elif idade < 18: print('Não se preocupe, você ainda não está na idade de se alistar.\n' 'Mas, deverá fazê-lo daqui a {} anos'.format(18 - idade)) elif idade > 18: verificacao = int(input('Você já se apresentou em uma junta militar? ' '\n[1] {}SIM{} [2] {}NÃO{}: '.format('\033[1m', '\033[m', '\033[1m', '\033[m'))) print('') if verificacao == 1: print('Então não se preocupe. Você está em dia com a sua obrigação militar.') else: print('Você já passou da idade de se alistar e deverá fazê-lo imediatamente.\n' 'Procure a junta militar mais próxima de sua residência.') else: print('Dados incorretos. Tente novamente.') print('') print('Obrigado por colaborar com o Exército Brasileiro. Tenha um ótimo dia!') #função quebrada em elif verificacao == não. debuggar.
0ca9f2ce8c1a06349351b878e590a57d2f01965f
dshinzie-zz/exercism
/python/pig-latin/pig_latin.py
529
3.53125
4
def translate(word_list): words = [] for word in word_list.split(): if word[0:3] in ['squ','thr','sch']: words.append(word[3:] + word[0:3] + "ay") elif word[0:2] in ['ch','qu','th']: words.append(word[2:] + word[0:2] + "ay") elif word[0:2] in ['yt', 'xr']: words.append(word + "ay") elif word[0] in ['a','e','i','o','u']: words.append(word + "ay") else: words.append(word[1:] + word[0] + "ay") return ' '.join(words)
a87dd3e4a1ce10f98b87db1c7c96fb970ca0f459
kemingy/daily-coding-problem
/src/reduce.py
974
3.921875
4
# reduce (also known as fold) is a function that takes in an array, a combining # function, and an initial value and builds up a result by calling the # combining function on each element of the array, left to right. For example, # we can write sum() in terms of reduce: # def add(a, b): # return a + b # def sum(lst): # return reduce(lst, add, 0) # This should call add on the initial value with the first element of the # array, and then the result of that with the second element of the array, # and so on until we reach the end, when we return the sum of the array. # Implement your own version of reduce. def reduce(lst, func, init): ans = init for item in lst: ans = func(ans, item) return ans def add(a, b): return a + b def time(a, b): return a * b if __name__ == '__main__': print(reduce(range(1, 101), add, 0)) print(reduce([str(x) for x in range(1, 10)], add, '')) print(reduce(range(1, 100), time, 1))
dedd0012be11d9185387662f52fe6562ea9286ec
harrisrf/IAB_SA_EM
/sample_rotation.py
2,320
4
4
import sqlite3 import sys #Create our in-memory database object db = sqlite3.connect(':memory:') #Iterator to pull in the necessary data def importer(yyyymm): with open('D:\\Users\\F3879852\\Documents\\Telmar\\Demographics\\data_demo_c1_' + str(yyyymm) +'0100_30') as demo: for line in demo: yield yyyymm, line[0: 31] demo.close() #Function to initialise the demographics table in the database def init_db(cur): cur.execute('''CREATE TABLE demographics ( Month INTEGER, ID TEXT)''') #Function to populate the demographics table def populate_db(cur, monthy): cur.executemany(''' INSERT INTO demographics (Month, ID) VALUES (?,?)''', list(importer(monthy))) db.commit() #Main program if __name__ == '__main__': cur = db.cursor() #Create our db cursor object for use in the functions init_db(cur) #Create our demographics table if not sys.argv[1]: month1 = input("Please enter the first month you'd like to compare in the numeric format YYYYMM: ") #Get the first month we want to compare else: month1 = sys.argv[1] if not sys.argv[2]: month2 = input("Please enter the second month you'd like to compare in the numeric format YYYYMM: ") #Get the second month we want to compare else: month2 = sys.argv[2] populate_db(cur, month1) #Load the first month's data into the db populate_db(cur, month2) #Load the second month's data into the db #Three SQL queries to extract IDs per each month and then to extract the total common IDs between those months cur.execute(''' select "Total demographics in " || ?, count(distinct ID) from demographics where month = ? union all select "Total demograhpics in " || ?, count(distinct ID) from demographics where month = ? union all select "Common demographics between " || ? || " and " || ? , count(*) from ( (select id from demographics where month = ?) as t1 inner join (select id from demographics where month = ?) as t2 on t1.id = t2.id )''', [str(month1), month1, str(month2), month2, str(month1), str(month2), month1, month2]) for row in cur: print(row) #Print out the three queries' results db.close() #Close up the db connection
ce73aaecebce0fa506dcec0ba2bab70601d7785d
somasan/projectone
/three/three9.py
427
3.9375
4
import turtle import math turtle.shape('turtle') def oct(n, R): turtle.begin_fill() turtle.left(90 - (360/(2*n))) for i in range(n): turtle.left(360/n) turtle.forward(R * 2 * math.sin(math.pi/n)) turtle.end_fill() turtle.right(90 - (360 / (2 * n))) turtle.penup() turtle.forward(15) turtle.pendown() if n == 10: input() else: oct(n+1, R+15) oct(3, 30)
ba437ee1bc0ed8239635c918024848b48fb173cc
KeerthikaRajvel/T9Hacks
/map/authentication.py
858
3.53125
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 8 03:20:52 2020 @author: matth """ class authentication: def __init__(self): # Go to http://apps.twitter.com and create an app # The consumer key and secret will be generated for you after #Twitter Credentials self.consumer_key = 'Xsm1PSWiJYFkn0Rmoi53Mm8pU' self.consumer_secret = 'DzckZZPyAKPQZdCtUWVshUhczjGMOeST53FmR1q41r2oqOWjuL' # Create an access token under the "Your access token" section self.access_token = '1082567145395937280-10ARA8VBNprf6TzT0o1QDjBojIA9oV' self.access_token_secret = '0g84r99NYhYY9Pt69OYKrgr5VeBGh2X6nCAt6oHikdSKO' def getconsumer_key(self): return self.consumer_key def getconsumer_secret(self): return self.consumer_secret def getaccess_token(self): return self.access_token def getaccess_token_secret(self): return self.access_token_secret
0d46264e9ae28e252fb8be7ef15786a14edb7245
Julioc10/CursoPython
/palindrome.py
121
3.84375
4
palavra = input('Palavra:') palindrome = palavra == palavra[::-1] print(f'{palavra} é palindrome?') print('palindrome')
bc4cd7187486acef7eff8bb0fd7244f33ae4d0b3
marchelleboid/adventofcode
/2016/day10/day10a.py
2,663
3.703125
4
class Instruction: def __init__(self, output, number): self.output = output self.number = number def __repr__(self): return str(self.__dict__) class Bot: def __init__(self, low_instruction, high_instruction): self.value1 = -1 self.value2 = -1 self.low_instruction = low_instruction self.high_instruction = high_instruction def add_value(self, value): if self.value1 == -1: self.value1 = value elif self.value2 == -1: self.value2 = value else: print("AHHHHHHH!") def has_two(self): return self.value1 != -1 and self.value2 != -1 def get_low(self): return min(self.value1, self.value2), self.low_instruction def get_high(self): return max(self.value1, self.value2), self.high_instruction def is_winner(self): return (self.value1 == 61 and self.value2 == 17) or (self.value1 == 17 and self.value2 == 61) def reset(self): self.value1 = -1 self.value2 = -1 def __repr__(self): return str(self.__dict__) bots = {} outputs = {} with open('input') as f: for line in f: line = line.strip() if line.startswith('bot'): bot = int(line.split(' ')[1]) low_number = int(line.split(' ')[6]) low_output = line.split(' ')[5] == 'output' high_number = int(line.split(' ')[-1]) high_output = line.split(' ')[-2] == 'output' low_instruction = Instruction(low_output, low_number) high_instruction = Instruction(high_output, high_number) bots[bot] = Bot(low_instruction, high_instruction) with open('input') as f: for line in f: line = line.strip() if line.startswith("value"): value = int(line.split(' ')[1]) bot = int(line.split(' ')[-1]) bots[bot].add_value(value) while True: ready_bots = [] for k, v in bots.items(): if v.has_two(): ready_bots.append(k) for ready_bot in ready_bots: bot = bots[ready_bot] if bot.is_winner(): print(ready_bot) exit() low_value, low_instruction = bot.get_low() if low_instruction.output: outputs[low_instruction.number] = low_value else: bots[low_instruction.number].add_value(low_value) high_value, high_instruction = bot.get_high() if high_instruction.output: outputs[high_instruction.number] = high_value else: bots[high_instruction.number].add_value(high_value) bot.reset()
6620169ce013282bc4602f63a40de682aa0d77de
Momo227/PracticeAlgorithm
/FullSearch/found_mini.py
320
3.5625
4
def main(): N = int(input()) min = int(20000000) data = [] for i in range(N): a = int(input()) data.append(a) min_value = min for i in range(N): if(data[i] < min_value): min_value = data[i] print(min_value) if __name__ == '__main__': main()
7dd205fd51c837b6f31bcd544ea60f1c9c49ceaf
Kaecchi/mroczko_python
/2/zadanie11.py
186
3.5625
4
# -*- coding: utf-8 -*- n = int(input('Podaj n')) wart = 0 for i in range(2, n-1): if n % i == 0: wart = 1 if wart == 1: print('Złożona') else: print('Pierwsza')
7ae18bb53b77f3b272ea244887d3d75f565205aa
readxia/basketball_stats
/BasketballStats.py
5,114
3.9375
4
from Player import Player """ player=Player("Read") player.shoot(3, True) player.shoot(2, False) player.shoot(2, False) player.shoot(2, True) player.rebound(False, 2) player.rebound(True, 1) player.print_stats() """ user_input = ""; player_list = []; def help_me(): #list commands here print "\n \nList of commands: \n1) EXIT: exits the program \n2) DONE: finishes adding players \n3) ADDPLAYER: allows adding players" def str2bool(v): return v.lower() in ("true") while(user_input != "EXIT"): stat_sheet=open("stat_sheet.txt", "w") user_input = raw_input("Enter a command (HELP for list of commands): ").upper() print user_input #lists the commands if(user_input == "HELP"): help_me() # input the players on the team if(user_input == "ADDPLAYER"): while(user_input != "DONE"): user_input = raw_input("Enter a player: ").upper() if(user_input == "DONE"): break player = Player(user_input) player_list.append(player) # command to print stats of a singular player if(user_input.find("PRINT") != -1): #splits at all the spaces if not player_list: print "No players added in list" break; #"user_input formatting example: print leo" #"values example: [print, read]" try: values = user_input.split(); for p in player_list: if(p.name == values[1]): p.print_stats() except: print "invalid input, use the format 'print [name]'" # command to shoot the ball if(user_input.find("SHOOT") != -1): #splits at all the spaces if not player_list: print "No players added in list" break; #"user_input formatting example: shoot leo 1 true" #"values example: [shoot, leo, 1, true]" try: values = user_input.split(); shot_type = int(values[2]) make = str2bool(values[3]) for p in player_list: if(p.name == values[1]): p.shoot(shot_type, make) print "shot recorded" except: print "invalid input, use the format 'shoot [name] [shot type] [true or false]'" # command to add rebounds if(user_input.find("REBOUND") != -1): #splits at all the spaces if not player_list: print "No players added in list" break; #"user_input formatting example: rebound read true 1" #"values example: [rebound, leo, true, 1]" try: values = user_input.split(); offensive = str2bool(values[2]) amount = int(values[3]) for p in player_list: if(p.name == values[1]): p.rebound(offensive, amount) print "rebound recorded" except: print "invalid input, use the format 'rebound [name] [offensive true or false] [amount]'" # command to add assists if(user_input.find("ASSIST") != -1): #splits at all the spaces if not player_list: print "No players added in list" break; #"user_input formatting example: assist leo 1" #"values example: [assist, leo, 1]" try: values = user_input.split(); amount = int(values[2]) for p in player_list: if(p.name == values[1]): p.assist(amount) print "assist recorded" except: print "invalid input, use the format 'assist [name] [amount]'" # command to add steals if(user_input.find("STEAL") != -1): #splits at all the spaces if not player_list: print "No players added in list" break; #"user_input formatting example: steal leo 1" #"values example: [steal, leo, 1]" try: values = user_input.split(); amount = int(values[2]) for p in player_list: if(p.name == values[1]): p.steal(amount) print "steal recorded" except: print "invalid input, use the format 'steal [name] [amount]'" # command to add blocks if(user_input.find("BLOCK") != -1): #splits at all the spaces if not player_list: print "No players added in list" break; #"user_input formatting example: block leo 1" #"values example: [block, leo, 1]" try: values = user_input.split(); amount = int(values[2]) for p in player_list: if(p.name == values[1]): p.block(amount) print "block recorded" except: print "invalid input, use the format 'block [name] [amount]'" # command to add turnover if(user_input.find("TURNOVER") != -1): #splits at all the spaces if not player_list: print "No players added in list" break; #"user_input formatting example: turnover leo 1" #"values example: [turnover, leo, 1]" try: values = user_input.split(); amount = int(values[2]) for p in player_list: if(p.name == values[1]): p.turnover(amount) print "turnover recorded" except: print "invalid input, use the format 'turnover [name] [amount]'" # command to add fouls if(user_input.find("FOUL") != -1): #splits at all the spaces if not player_list: print "No players added in list" break; #"user_input formatting example: foul leo 1" #"values example: [foul, leo, 1]" try: values = user_input.split(); amount = int(values[2]) for p in player_list: if(p.name == values[1]): p.foul(amount) print "foul recorded" except: print "invalid input, use the format 'foul [name] [amount]'" for p in player_list: p.write_stats(stat_sheet) stat_sheet.close()
fba3c13b38ea7753480b18ffaf8228ed5c4fdde8
abnerlourenco/Aprendendo_python3
/seçao 3/funcao.py
430
3.96875
4
# -*- coding utf: -8 -*- def chamar(): print("Bem vindo a declaração de uma função") chamar() # a função tambem pode receber parametros, com isso podemos inserir dentro do escopo da função def soma(x,y): resultado = x + y print(resultado) soma(8, 9) # o objetivo da função é retornar algum valor def subtração(a,b): return a - b resultado = subtração(19, 9) print(resultado)
01f273f0acc05f7af7a5e72c817f244fcc73a34b
klknet/geeks4geeks
/datastructure/array/sum_of_all_primes.py
414
4.03125
4
""" Sum of all the prime numbers with the count of digits <= D. """ def sum_of_prime(d): n = 10 ** d prime = [True] * n for i in range(2, n): m = i*i if prime[i]: while m < n: prime[m] = False m += i s = 0 for i in range(2, n): if prime[i]: s += i return s print(sum_of_prime(2)) print(sum_of_prime(3))
ee6c768e39a186746c8adf4dcc520d7a4d8cb342
772766964/Python
/Variable.py
239
3.90625
4
# python会根据赋予的类型来决定该变量的类型 # char(),str(),int()...可以进行强制转型 counter = 100 # 赋值整型变量 miles = 1000.0 # 浮点型 name = "John" # 字符串 print counter print miles print name
d465365c9c6bfdad459e68a4bc1887eebed35185
KonstantinMyachin/HSEPython
/ru/myachin/homework/sixth/main.py
13,664
3.5625
4
import pandas as pd # ### Задача 1 (1 балл) # В датафрейме `df` находится информация об успеваемости студентов: в столбцах `First Name` и `Last Name` — имя и # фамилия, а в следующих столбцах — оценки за разные курсы по пятибальной системе (целые числа от 0 до 5). # Напишите функцию `get_grade(df, lastname, firstname, course)`, возвращающую оценку данного студента по данному курсу. # Предполагается, что не бывает студентов, у которых совпадали бы одновременно фамилия и имя. # # **Пример:** # # Входная таблица # # ``` # Last Name First Name Algebra Calculus Music Law # 0 Doe John 4 5 3 5 # 1 Smith Alice 5 4 2 4 # ``` # записывается в виде # # ```python # df = pd.DataFrame( # [ # ['Doe', 'John', 4, 5, 3, 5], # ['Smith', 'Alice', 5, 4, 2, 4] # ], # columns=['Last Name', 'First Name', 'Algebra', 'Calculus', 'Music', 'Law'] # ) # ``` # Для неё функция `get_grade(df, 'Doe', 'John', 'Algebra')` должна вернуть число `4`. # # **Подсказка.** Не забудьте превратить результат в целое число (`int`)! def get_grade(df, lastname, firstname, course): return int(df[(df['Last Name'] == lastname) & (df['First Name'] == firstname)][course]) # ### Задача 2 (1 балл) # В датафрейме `df` задана некоторая таблица. Написать функцию `get_rows_after_5(df, n)`, возвращающую датафрейм, в # котором записано `n` строк, начиная с пятой сверху (включая 5-ю). Например, `get_row_after_5(df, 1)` должна # вернуть только пятую строку, а `get_row_after_5(df, 2)` — 5-ю и 6-ю. # # **Внимание!** Индексами (именами строк) могут быть не числа, а что угодно. def get_rows_after_5(df, n): return df[4: 4 + n] # ### Задача 3 (1 балл) # В датафрейме `df` задана некоторая таблица, её индексами являются целые числа, не обязательно идущие по порядку. # Написать функцию `between(df, n, m)`, возвращающую все строки этой таблицы, расположенные между строками с # индексами `n` и `m`, включая строки с индексами `n` и `m`. Гарантируется, что строка с индексом `n` встречается # раньше строки с индексом `m`. def between(df, n, m): return df.loc[n: m] # ### Задача 4 (1 балл) # В датафрейме `grades` находится таблица с оценками разных студентов по разным формам контроля (студент — строка, # форма контроля — столбец, имена студентов записаны в `index` по строкам и не являются частью таблицы). # В series `weights` находятся веса, с которыми каждая форма контроля входит в итоговую оценку. # (Сумма весов равна 1.) Напишите функцию `weight_grades(grades, weights)`, которая возвращает series, в котором # указано, какой студент какую итоговую оценку получил. # # **Подсказка.** Вам пригодится метод `.dot` для датафрейма, который делает матричное умножение # (аналог функции `SUMPRODUCT` в табличных процессорах) — умножает каждый элемент строки на соответствующий вес, # а потом всё складывает. # # Примеры входных и выходных данных см. в тесте. def weight_grades(grades, weights): return grades.dot(weights) # ### Задача 5 (2 балла) # Написать функцию `mean_by_gender(grades, genders)`, принимающую на вход два series одинаковой длины: в grades # записаны оценки некоторых студентов, а в genders — их пол в виде строк male или female. Требуется вернуть словарь, # ключами которого будут строки `"male"` и `"female"`, а записями — среднее арифметическое оценок студентов # соответствующего пола. # # Например, если `grades = pd.Series([5, 4, 3, 5, 2])` и # `genders = pd.Series(["female", "male", "male", "female", "male"])`, функция должна вернуть # словарь `{'male': 3.0, 'female': 5.0}`. # # **Подсказка.** Вы уже решали похожую задачу в прошлом задании с помощью `numpy`. Подумайте, как это более изящно # сделать с помощью `pandas`. Можно, конечно, создать два отдельных series, в один поместить оценки всех юношей, # а в другой — всех девушек, но есть решение и поизящнее: создать датафрейм, столбцами которого являются наши # series, а затем применить метод `groupby`. Кстати, у series есть метод `to_dict()`. # # Чтобы создать датафрейм с заданными столбцами можно передать `pd.DataFrame` на вход словарь: # # pd.DataFrame({'column1': [1, 2, 3], 'column2': [4, 5, 6]}) def mean_by_gender(grades, genders): df = pd.DataFrame() df['Grade'] = grades df['Gender'] = genders df = df.groupby('Gender').mean() return df['Grade'].to_dict() # ### Задача 6. (2 балла) # В датафрейме `df` находится информация об успеваемости студентов. Написать функцию `gpa_top(df)`, принимающую # на вход датафрейм `df` и модифицирующую его следующим образом: # # - Добавить в `df` столбец с именем `'GPA'`, содержащим среднюю оценка студента. Разные студенты могут брать # разный набор курсов, поэтому среди оценок студентов может встречаться `NaN` (это означает, что студент не # брал соответствующий курс). Среднее считается среди тех курсов, которые студент брал. # # - Отсортировать датафрейм по убыванию `GPA`. # # - Вернуть только те строчки датафрейма, в которых `GPA` не меньше `4` баллов. # # **Подсказки:** # # 1. Для сортировки датафрейма нужно использовать метод `sort_values()`. # 2. Метод `mean()` игнорирует строки и `NaN`'ы. # # В следующих ячейках приведено два примера. # входной датафрейм def gpa_top(df): df['GPA'] = df.mean(axis=1) df.sort_values(by='GPA', ascending=False, inplace=True) return df[df['GPA'] >= 4] # ### Задача 7 (2 балла) # В таблице `df` записана информация о покупках товаров в некотором магазине. Пример: # # Покупатель Товар Количество Цена # 0 Иван Петрович Макароны 4 120 # 1 Лариса Ивановна Плюшки 10 100 # 2 Иван Петрович Плюшки 1 100 # 3 Петя Леденцы 5 20 # # Один и тот же товар может продаваться по разным ценам. # # Вам нужно написать функцию `check_table(df)`, возвращающую кортеж из двух словарей: в первом должно быть указано, # сколько денег оставил в магазине каждый покупатель, а во втором — сколько удалось выручить за продажу каждого # товара. Например, для приведенной выше таблицы должно быть возвращено # # ``` # ({'Иван Петрович': 580, 'Лариса Ивановна': 1000, 'Петя': 100}, # {'Леденцы': 100, 'Макароны': 480, 'Плюшки': 1100}) # ``` # # **Подсказки:** # # 1. Сначала создайте столбец, в котором будет указано, во сколько обошлась каждая покупка (с учётом количества # товара и его цены). Одномерные элементы *pandas* (например, столбцы и строки датафреймов — их тип # называется `pd.DataSeries`) ведут себя как `np.array()`, то есть операции с ними производятся поэлементно. # 2. Вам поможет метод `groupby()`. # 3. У элементов типа `pd.DataSeries` есть метод `to_dict()`, превращающий их в словари. def check_table(df): df['Total'] = df['Количество'] * df['Цена'] return (df.groupby('Покупатель')['Total'].sum().to_dict(), df.groupby('Товар')['Total'].sum().to_dict()) # ### Задача 8 (4 балла) # В некотором царстве, некотором государстве, раз в четыре года на земском соборе проходят выборы царя. # Царство имеет федеративную структуру и состоит из земель. Каждая земля имеет право направить на съезд # определённое число делегатов, чьи голоса и определят президента… ой, то есть царя. У разных земель разное число # делегатов. По традиции, каждая земля на своей территории проводит выборы самостоятельно, после чего подводится их # итог и определяется победитель в данной земле. Делегаты, которых отправляют на собор, обязаны проголосовать за того # кандидата, который набрал в их земле большинство голосов («победитель получает всё»). Царём становится тот кандидат, # который набрал большинство голосов делегатов. Разные земли имеют разное число делегатов. # # Требуется написать функцию `winner_votes(results)`, возвращающую двухэлементный кортеж: первый элемент — победитель, # второй — число голосов делегатов, которые он набрал. Функция принимает на вход таблицу (`pd.DataFrame`), # выглядящую примерно так: # # state electors Arya Stark Tyrion Lannister Deineris Targarien # 0 Winterfell 3 0.6 0.3 0.1 # 1 Riverrun 5 0.3 0.2 0.5 # 2 Vaes Dothrak 2 0.2 0.3 0.5 # # В первом столбце указано название земли, во втором — число делегатов от этой земли, в остальных столбцах — доля # голосов жителей, которые набрал данный кандидат в данной земле. # # Например, для приведенной выше таблицы победителем в `Winterfell` будет `Arya Stark`, в остальных двух # землях — `Deineris Targarien`. Арья наберёт 3 голоса делегатов, Дейнерис — 7 голосов. Победителем будет Дейнерис. # Функция должна вернуть `("Deineris Targarien", 7)`. # # Как обычно, запрещено использовать циклы. # # В случае, если два кандидата набирают равное число голосов, то побеждает тот, кто идёт первым по алфавиту. # # **Подсказка.** Вам пригодится метод `.idxmax()`. И ещё `.sort_index()`. def winner_votes(results): print("don't complete")
03a3bb2c109e0b5d609cb21950566254bb610159
priyankasomani9/basicpython
/Assignment13/basic13.2_matrix.py
250
4.09375
4
import numpy as np x=int(input("enter values of how many rows you want")) y=int(input("enter values of how many column you want")) matrix=[] for i in range(x): for j in range(y): matrix.append(i*j) matrix = np.array(matrix).reshape(x, y)
2317756811d89bfe16020e90071c4266339b448d
yuanzhi0515/guandan-ai
/client/utils.py
4,722
3.578125
4
# ---------------------------------------------------------- # Representation String # ---------------------------------------------------------- def suit_to_str(suit): map = ['♠', '♥', '♣', '♦'] return map[suit] def card_to_str(card): if card[1] == 'PASS': return 'PASS' if card[1] == 'JOKER': return '{}{}'.format(card[0], card[1]) return '{}{}'.format(suit_to_str(card[0]), card[1]) def cards_to_str(cards): return ','.join([card_to_str(card) for card in cards]) def action_to_str(action): return '({}) {}'.format(action['type'], cards_to_str(action['action'])) # ---------------------------------------------------------- # Player Utilities # ---------------------------------------------------------- def prev_player(player): return (player + 3) % 4 def next_player(player): return (player + 1) % 4 def ally_player(player): return (player + 2) % 4 # ---------------------------------------------------------- # Compare Order # ---------------------------------------------------------- def rank_order(rank): map = { '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14, 'JOKER': 15, 'PASS': 0 } return map[rank] def rank_cmp(rank_l, rank_r): order_l = rank_order(rank_l) order_r = rank_order(rank_r) return order_l - order_r def card_type_order(card_type): map = { 'Single': 0, 'Pair': 1, 'Trips': 1, 'ThreePair': 3, 'TripsPair': 3, 'ThreeWithTwo': 5, 'Straight': 6, 'StraightFlush': 7, 'Bomb': 8, 'JOKER': 9, 'PASS': 10, 'tribute': 10, 'back': 10, 'anti': 10 } return map[card_type] def card_type_cmp(card_type_l, card_type_r): order_l = card_type_order(card_type_l) order_r = card_type_order(card_type_r) return order_l - order_r # ---------------------------------------------------------- # Miscellaneous # ---------------------------------------------------------- card_types = [ 'Single', 'Pair', 'Trips', 'ThreePair', 'ThreeWithTwo', 'TripsPair', 'Straight', 'StraightFlush', 'Bomb', 'JOKER' ] card_ranks = [ '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A', 'JOKER_0', 'JOKER_1' ] def is_fire_card(card_type): return card_type in ['StraightFlush', 'Bomb', 'JOKER'] def _attr_init_and_append(obj, attr, val): if attr not in obj: obj[attr] = [] obj[attr].append(val) def pass_action(): return {'type': 'PASS', 'rank': 'PASS', 'action': [[0, 'PASS']]} # ---------------------------------------------------------- # Statistics # ---------------------------------------------------------- def count_hand_cards(hand_cards): '''Return a map: rank -> cards with this rank.''' counter = dict() for hand_card in hand_cards: rank = hand_card[1] _attr_init_and_append(counter, rank, hand_card) return counter def gen_bucket(counter): '''Return a bucket where bucket[i] gathers all i tuples of cards with the same rank except JOKER''' bucket = dict([(size, []) for size in range(1, 9)]) ordered_rank = list(counter.keys()) ordered_rank.sort(key=rank_order) for rank in ordered_rank: if rank != 'JOKER': cards = counter[rank] bucket[len(cards)].append(cards) return bucket def partition(hand_cards): counter = count_hand_cards(hand_cards) bucket = gen_bucket(counter) result = dict() for single in bucket[1]: _attr_init_and_append(result, 'Single', single) for trips in bucket[3]: if len(bucket[2]) > 0: pair = bucket[2].pop(0) _attr_init_and_append(result, 'ThreeWithTwo', trips + pair) else: _attr_init_and_append(result, 'Trips', trips) for pair in bucket[2]: _attr_init_and_append(result, 'Pair', pair) for size in range(4, 9): for bomb in bucket[size]: _attr_init_and_append(result, 'Bomb', bomb) if 'JOKER' in counter: jokers = counter['JOKER'] if len(jokers) == 4: _attr_init_and_append(result, 'Bomb', jokers) else: # TODO: handle joker pair for joker in jokers: _attr_init_and_append(result, 'Single', joker) return result if __name__ == "__main__": hand_cards = [[0, '2'], [1, '2'], [0, '2'], [0, '3'], [3, '4'], [1, '4'], [0, '7'], [3, '10'], [0, '10'], [3, 'J'], [0, 'K'], [3, 'A'], [3, '5'], [0, '5'], [0, 'JOKER']] partition(hand_cards)
cd60c3eaa61424ac3082beaef3c42f9771cdc220
lbarthur/bing
/zhuce.py
716
3.671875
4
f = open("/reboot/user.txt", "a+") username="" password="" while True: username=input("please input your username(quit):").strip() password = input("please input your password:").strip() repass = input("please confirm your password:").strip() if username =="": print ("user name is null, please register again ") continue elif password =="": print ("password is null, please register again ") continue elif repass =="" or repass != password: print ("password is not same,please register again") continue else : print ("Congratulation !~") break f.write("%s:%s\n" %(username,password)) f.close()
7a943c6b4345ad6d9613f7903e51b165d94aeb49
ITlearning/ROKA_Python
/2021_03/03_12/CH04/014_Reversed_For02.py
134
3.9375
4
# 반대로 반복하기(2) for i in reversed(range(5)) : print("현재 반복 변수 : {}".format(i)) # reversed() 사용하기
adcc18ea2a893f049fb50e45f0a038f1fb81febf
poojaGit95/DataStructures-Algorithms-Python
/Graphs/BellmanFordAlgorithm.py
1,249
3.578125
4
class Graph: def __init__(self, vertices): self.vertices = vertices self.nodes = [] self.graph = [] def addNode(self, node): self.nodes.append(node) def add_edge(self, src, dest, dist): self.graph.append([src, dest, dist]) def distanceFromSource(self, dist): for node, wgt in dist.items(): print("Distance of vertex", node, "is", wgt) def BellmanFord(self, src): dist = {} for i in self.nodes: dist[i] = float("inf") dist[src] = 0 for i in range(1, self.vertices): for s,d,w in self.graph: if dist[s]!=float("inf") and dist[d]>dist[s]+w: dist[d] = dist[s]+w for s, d, w in self.graph: if dist[s] != float("inf") and dist[d] > dist[s] + w: print("graph has negative cycle") return self.distanceFromSource(dist) g = Graph(5) g.addNode("A") g.addNode("B") g.addNode("C") g.addNode("D") g.addNode("E") g.add_edge("A", "C", 6) g.add_edge("A", "D", 6) g.add_edge("B", "A", 3) g.add_edge("C", "D", 1) g.add_edge("D", "C", 2) g.add_edge("D", "B", 1) g.add_edge("E", "B", 4) g.add_edge("E", "D", 2) g.BellmanFord("E")
ce24094b2dc93793a2126aca18ba696b21ed75fa
NianchenGuo/myproject
/weiwei_pro/weiwei_pro3/file_reader.py
884
3.703125
4
# coding=utf-8 """ 作者:郭伟伟 简介: 从文件中读取数据 日期:2019-12-10 """ with open("pi_digits.txt") as file_object: """ 函数open() 接受一个参数:要打开的文件的名称 """ contents = file_object.read() print(contents.rstrip()) # 绝对路径读取文件 file_path = "C:\\my\\MyProject\\myproject\\weiwei_pro\\weiwei_pro3\\pi_digits.txt" with open(file_path) as file_object: contents = file_object.read() print(contents.rstrip()) #  逐行读取 filename = "pi_digits.txt" with open(filename) as file_object: for line in file_object: print(line.rstrip()) # 创建一个包含文件各行内容的列表 filename = "pi_digits.txt" with open(filename) as file_object: lines = file_object.readlines() pi_string = " " for line in lines: pi_string += line.strip() print(pi_string) print(len(pi_string))
0042af4cde7dd06de6b5f2d931493a54fc76ed7a
btke/CS61A-Fall-2016
/lab/lab11/lab11.py
1,537
3.875
4
def countdown(n): """ >>> for number in countdown(5): ... print(number) ... 5 4 3 2 1 0 """ "*** YOUR CODE HERE ***" val=n while val>=0: yield val val-=1 def trap(s, k): """Return a generator that yields the first K values in iterable S, but raises a ValueError exception if any more values are requested. >>> t = trap([3, 2, 1], 2) >>> next(t) 3 >>> next(t) 2 >>> next(t) ValueError >>> list(trap(range(5), 5)) ValueError """ assert len(s) >= k "*** YOUR CODE HERE ***" val=0 while val<k: yield s[val] val+=1 raise ValueError("It's a trap!") def repeated(t, k): """Return the first value in iterator T that appears K times in a row. >>> s = [3, 2, 1, 2, 1, 4, 4, 5, 5, 5] >>> repeated(trap(s, 7), 2) 4 >>> repeated(trap(s, 10), 3) 5 >>> print(repeated([4, None, None, None], 3)) None """ assert k > 1 "*** YOUR CODE HERE ***" count=0 list_el=None for el in t: if el == list_el: count+=1 if count==k: return el else: count=1 list_el=el def hailstone(n): """ >>> for num in hailstone(10): ... print(num) ... 10 5 16 8 4 2 1 """ "*** YOUR CODE HERE ***" i = n while i != 1: yield i if i % 2 == 0: i //=2 else: i=i*3+1 yield i
3eb69f257265bd083fff31758a8143b0caef73ff
RahulRwt125/Classwork
/UPPERLIST.py
70
3.65625
4
n=input("Enter a string please: ") a=[i for i in n.upper()] print(a)
9aeb74f45630b5c5fee5371b6c9e81fa626b2860
Demoleas715/PythonWorkspace
/Unit4Objects/Encryptor.py
1,193
4.21875
4
class Encryptor(object): def __init__(self, file_name): self.file_name=file_name self.e_dict={} self.d_dict={} text_file=open(file_name, "r") for line in text_file: line=line.strip().split("\t") self.e_dict[line[0]]=line[1] self.d_dict[line[1]]=line[0] ''' Initializes a new encryption object, using the cipher from the specified file. This method sets the properties e_dict and d_dict. ''' def encryptMessage (self, msg): self.msg=msg str="" for letter in msg: letter=self.e_dict.get(letter.upper(), letter) str+=letter return str ''' Encrypts the string msg. Note this method DOES NOT print to The screen. Instead, it returns the encrypted message as a string. ''' def decryptMessage (self, msg): self.msg=msg str="" for letter in msg: letter=self.d_dict.get(letter.upper(), letter) str+=letter return str ''' Performs the inverse action to encryptMessage. '''
b48f510412b93341d0312385eb07c65de7216c70
nicolasduran25/Python-Daw
/practica 3/practica3ej6.py
186
3.671875
4
Precio = int(input("precio del producto:")) Producto = input("nombre del producto:") IVA = Precio*0.21 Total = Precio + IVA print ("el producto",Producto ,"vale en total",Total,"euros")
303ce88fb36a2454fbd5bd3e20a72531073c2514
ZainQasmi/LeetCode-Fun
/gcd.py
178
3.546875
4
# def gcd(a,b): # if b==0: # return a # else: # return gcd(b,a%b) # print gcd(2,4) def ajeeb(n,k,i): if k<n: print i-1 else: print i+(k%n)-1 ajeeb(3,5,1) #1