blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
c8b2f991f2127ea1b2de3133b4b4ff625c2b6d6f
kelpasa/Code_Wars_Python
/6 кю/Error correction #1 - Hamming Code.py
965
4.46875
4
''' Background information The Hamming Code is used to correct errors, so-called bit flips, in data transmissions. Later in the description follows a detailed explanation of how it works. In this Kata we will implement the Hamming Code with bit length 3, this has some advantages and disadvantages: ✓ Compared to other versions of hamming code, we can correct more mistakes ✓ It's simple to implement x The size of the input triples https://www.codewars.com/kata/5ef9ca8b76be6d001d5e1c3e/train/python ''' def encode(string): return ''.join(['{0:08b}'.format(i) for i in [ord(i) for i in string]]).replace('1','111').replace('0','000') def decode(bits): res = list(map(''.join, zip(*[iter(bits)]*3))) lst = [] for i in res: if i.count('1')>i.count('0'): lst.append('1') else: lst.append('0') return ''.join([chr(i) for i in [int(i,2) for i in list(map(''.join, zip(*[iter(''.join(lst))]*8)))]])
0f3a0986eca10bd23af88c452f467053d670078e
SevenWen/OSCP
/AllHex.py
124
3.515625
4
# !/usr/bin/python hex=0x00 f=open("Allhex","w") while(hex<=0xff): f.write("\\x"+format(hex, '02x')) hex+=1; f.close()
5ab6c31ba152486e5a688db77a2496e3257b0cd6
cloud-cloudbooks/Python_2018
/Python_2017_summer/Study_Day3/D3_07_for_turtle.py
115
3.609375
4
import turtle as t t.shape("turtle") for i in [1, 2, 3, 4, 5] : t.forward(100) t.left(72) t.done()
6deb6991fc53c91c7e710acfbc947cddf56faa5e
jbischof/algo_practice
/epi2/heap_test.py
514
3.5
4
import unittest import heap class HeapTest(unittest.TestCase): def testMergedSortedLists(self): lists = [[1, 4, 7], [2, 4, 6], [5, 9, 10]] self.assertEqual(heap.merge_sorted_lists(lists), [1, 2, 4, 4, 5, 6, 7, 9, 10]) def testContainerWithMedian(self): a = [1, 0, 3, 5, 2, 0, 1] expect_medians = [1, 0.5, 1, 2, 2, 1.5, 1] cwm = heap.ContainerWithMedian() for i in range(len(a)): cwm.append(a[i]) self.assertEqual(cwm.median(), expect_medians[i])
22bbf836f90ff2c327c71e69dfd5157e17775ec3
bhusalashish/DSA-1
/Data/Binary Search/Peak Element/Maximum element in a Bitonic Array.py
1,274
3.703125
4
''' #### Name: Maximum element in a Bitonic Array Link: [youtube](https://www.youtube.com/watch?v=BrrZL1RDMwc&list=PL_z_8CaSLPWeYfhtuKHj-9MpYb6XQJ_f2&index=18) **Brute**: Use linear search to get the answer in O(n) Finding peak element (But bitonic array will have single peak element) ''' def max_elem(arr): n = len(arr) low = 0 high = n-1 if n == 1: # If there is only one element in the array return 0 while low <= high: mid = (low + high)//2 if mid > 0 and mid < n-1: # If mid is not last element or first element if arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]: return mid elif arr[mid+1] > arr[mid]: low = mid+1 elif arr[mid-1] > arr[mid]: high = mid - 1 elif mid == 0: # if mid ever reaches to the first element if arr[mid] > arr[mid+1]: # Reverse Sorted array return mid else: return mid+1 elif mid == n-1: # If mid ever reaches to the first element if arr[mid] > arr[mid-1]: # Sorted Array return mid else: return mid-1 arr = [1, 4, 5, 7, 8, 6, 3, 2] print(max_elem(arr))
5bf8d3a6c7f5e102e6ec5f95ab138ea48d82ec3d
abhinavashok/practice-lang
/python/b1.py
298
4.5
4
# Learning Arrays ##Declare an array a=[3,4,5,6] #Iterate over the array using for loop for item in a: print(item) # Print using indices print("a[3]=",a[3]) # using negative indices,when we put negative indice it goes to 0-(indice) meaning the other side of the array. print("item=",a[-1])
e6a0395d36420031180227839b80062b8703b777
martinmeagher/UCD_Exercises
/Module9_Intermediate_Data_Visualization_with_Seaborn/1c_Regression_Plots_in_Seaborn.py
646
3.953125
4
# Create a regression plot of premiums vs. insurance_losses sns.regplot(data=df, x="insurance_losses", y="premiums") # Display the plot plt.show() # Create an lmplot of premiums vs. insurance_losses sns.lmplot(data=df, x="insurance_losses", y="premiums") # Display the second plot plt.show() # Create a regression plot using hue sns.lmplot(data=df, x="insurance_losses", y="premiums", hue="Region") # Show the results plt.show() # Create a regression plot with multiple rows sns.lmplot(data=df, x="insurance_losses", y="premiums", row="Region") # Show the plot plt.show()
ff5e4962b1330f5f7e606687ebf489bf3323a5f2
LuciferCoder/Python_Learn_2019
/day2/demo05.py
1,639
4.09375
4
""" 关系运算符: == != > < >= <= 左边 运算符 右边 --> bool True False == : 比较的是内容, 返回值是True| False is:比较的是地址, 可以通过id(变量)获取地址 逻辑运算符: """ a1 = 9 a2 = 9 print(a1 < a2) print(a1 > a2) print(a1 == a2) # 恒等于的判断 True print(a1 != a2) # False b1 = 10000 b2 = 10000 print(b1 == b2) # 比较的是内容 print(b1 is b2) # 比较的是地址 在交互式中,这个语句是False,因为交互式窗口是逐行编译结束,所以不相等;而在py文件中,是逐行加载,前者被后者复用,所以相等; print(id(b1), id(b2)) ''' 是False的情况有哪些? 0 '' None ''' print(not 3 + 5) print(5 + False) # 5 False参与算数运算的时候就变成了0 print(5 + True) # 6 True参与算数运算的时候就便车给了 print(5 > True) # True True与算数进行比较运算时,True表示的数字为1 # and or ''' and: 与 两边同时为真时结果才为真 T and T = T T and F = F F and T = F F and F = F 验证用户成功:用户名True and passwd True --> 登陆成功 or: 或 已有一边为True 或者两边都是是True T and T = T T and F = T F and T = T F and F = F 验证登录:(用户名and密码) or (手机号and验证码) --> 登陆成功 ''' number = input('请输入一个整型数字:') print(type(number), number) # 类型转化吧:str-->int number = int(number) # print(8 > 5 and 5 != number) print(8 > 5 and 5 == number) # print(8 > 5 and 5 == number)
17d82dc51c8bda8bfa4ae1da614b35d6eae9b63b
Liav8/Games.cards
/DeckOfCards.py
876
3.6875
4
from Card import * from random import * # מחלקה שיוצרת חבילת קלפים מסודרת (52) class DeckOfCards: def __init__(self): self.cards = cards = [] names = {1: "Diamond", 2: "Spade", 3: "Heart", 4: "Club"} for number in range(1, 14): for suit in names.values(): cards.append(Card(number, suit)) #פעולה שמדפיסה את החבילה def show(self): return f"This deck's cards are: {self.cards}" #פעולה שמדפיסה את החבילה def __repr__(self): return f"This deck's cards are: {self.cards}" # פעולה שמערבבת חפיסת קלפים def shuffle(self): shuffle(self.cards) # פעולה שמחזירה קלף רנדומלי מהחבילה def deal_one(self): return self.cards.pop(randint(0, len(self.cards)-1))
ab3f7c15d89d3a19dd09d222974b40681419425a
m-ox/python_course
/homework/4-19-21_wallet.py
4,713
3.96875
4
""" - Must include 1 class - Must have some sort of main menu and accept user input to route logic flow - Needs to have the following functionality: - Check Balance - Deposit - Withdrawal - Exit - Must manage balance accurately (balance should reflect transactions). """ class Wallet(): def squiggly(self): print('\n.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:._.:*~*:.\n') def main_menu(self): Wallet.squiggly(self) menu_select = input('What would you like to do?\n\n (1) Check Balance | (2) Deposit | (3) Withdrawal | (4) Exit | >>> ').lower() #print(menu_select) # for debugging - remove before submission if menu_select == '4' or menu_select == 'exit': Wallet.leave_menu(self) # important to self reference elif menu_select == '1' or menu_select == 'check balance' or menu_select == 'balance': Wallet.check_balance(self) elif menu_select == '2' or menu_select == 'deposit': Wallet.deposit(self) elif menu_select == '3' or menu_select == 'withdraw' or menu_select == 'withdrawal': Wallet.withdrawal(self) else: print('Something else happened...') exit() def balance_query(self): balance_object = open('wallet_data.py', 'r+') data = balance_object.read() data = float(data) print_data = str(format(data, '.2f')) deposit_question = '\nYour balance: $' + print_data balance_object.close() return deposit_question def balance_data(self): balance_object = open('wallet_data.py', 'r+') data = float(balance_object.read()) balance_object.close() return data def check_balance(self): data = Wallet.balance_data(self) if data == 0: print('\nDude, you\'re just broke.') Wallet.main_menu(self) if data > 0 and data < .01: print('\nYou are close to broke: $' + str(format(data, '.2f'))) Wallet.main_menu(self) elif data > 1e+46: print('\nYou have a grossly large amount of money: $' + str(format(data, '.2f'))) Wallet.main_menu(self) else: print(self.balance_query()) Wallet.main_menu(self) Wallet.squiggly(self) print(result) balance_object.close() print('\n*\n*\n*\n') Wallet.main_menu(self) def deposit(self): # oh no I broke my deposit print(self.balance_query()) data = Wallet.balance_data(self) deposit_request = input('\nHow much would you like to deposit? | >>> $') try: val = round(float(deposit_request), 2) if val < 0: print('\nThis is not a valid deposit amount, my dude.') Wallet.squiggly(self) Wallet.deposit(self) elif val >= 0: new_balance = data + val file = open('wallet_data.py', 'r+') file.write(str(new_balance)) print('\nYou deposited: $' + str(format(val, '.2f'))) file.close() print(self.balance_query() + '\n') Wallet.main_menu(self) else: print(self.balance_query()) Wallet.main_menu(self) except ValueError: print("Input was not a valid number.") Wallet.deposit(self) balance_object.close() def withdrawal(self): print(self.balance_query()) data = Wallet.balance_data(self) deposit_request = input('\nHow much would you like to withdraw? | >>> $') try: val = round(float(deposit_request), 2) if val > data: print('\nYou don\'t have enough money to withdraw that much!') Wallet.withdrawal(self) elif val < 0: print('\nThis is not a valid withdrawal amount, my dude.') Wallet.squiggly(self) Wallet.deposit(self) elif val >= 0: new_balance = data - val file = open('wallet_data.py', 'r+') file.write(str(new_balance)) print('\nYou withdrew: $' + str(format(val, '.2f'))) file.close() print(self.balance_query() + '\n') Wallet.main_menu(self) else: print(self.balance_query()) Wallet.main_menu(self) except ValueError: print("Input was not a valid number.") Wallet.deposit(self) balance_object.close() def leave_menu(self): print('\n*closes wallet*\n') exit() def __str__(self): heredoc = f''' A simple Python-powered wallet. '''.strip() def __init__(self): print('\nHello, PyWallet here.') Wallet.main_menu(self) Wallet()
67b133fa7d41ff1d4add2d75652d03044f9e7b8d
jungwonkkim/swexpert
/boj14624.py
257
3.671875
4
cmd = int(input()) if cmd%2: string = '*' * cmd + '\n' string +=' '*(cmd//2) + '*' + '\n' for i in range(1, cmd//2+1): string += ' ' * (cmd//2-i) + '*' + ' '*(2*i-1) + '*' + '\n' print(string) else: print('I LOVE CBNU')
c78637914601bccf2ec3a5f1d0c47020e78b5c2e
richasharma3101/-100--Days-of-Code
/code/Day-5/cp.py
272
3.90625
4
def compound_interest(P,R,T): CI = P * (pow((1 + R / 100), T)) print("Compound interest is", CI) P=float(input("Enter the value of principle")) R=float(input("Enter the value of rate")) T=float(input("Enter the value of time")) compound_interest(P,R,T)
359d00700518521574c8305121781ca4c9aea4db
mateusziwaniak/Python-course-M.Dowson-book---tutorial
/Rozdzial 5/zadanie rozdzial5.py
1,149
3.96875
4
scores = [] choice = None while choice != "0": print( """ Najlepsze wyniki 0 - zakończ 1 - pokaż wyniki 2 - dodaj wynik 3 - usuń wynik 4 - posortuj wyniki """ ) choice = input("Twoj wybor to: ") if choice == "1": for entry in scores: score, name = entry print("\n", name, score) elif choice == "2": name = input("Dla którego gracza chcesz wprowadzić wynik?: ") score = int(input("\nJaki wynik chcesz dodać? ")) entry = (score, name) scores.append(entry) scores.sort(reverse=True) scores = scores[:5] elif choice == "3": score = int(input("\nKtóry wynik chcesz usunąć? ")) if score in scores: scores.remove(score) else: print(score, "nie ma takiego wyniku") elif choice == "4": scores.sort() elif choice == "0": print("Koniec") input("\nNaciśnij ENTER aby zakończyć") break else: print("Niestety błędny wybór!")
e6976c940de948634f7ebb4a4913e0ddee6948b9
ChenxiiCheng/Python-LC-Solution
/Q3-Longest Substring Without Repeating Characters-Medium.py
1,298
3.8125
4
''' Question: 3. Longest Substring Without Repeating Characters Descrition: Given a string, find the length of the longest substring without repeating characters. Examples: 1.Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. 2.Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. 3.Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. ''' #Python3 Code: class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ #Soltuion 2 dic, start, ans = {}, 0, 0 for i in range(len(s)): if s[i] not in dic or dic[s[i]] < start: ans = max(ans, i - start + 1) else: start = dic[s[i]] + 1 dic[s[i]] = i return ans #Solution dic, start, ans = {}, 0, 0 for i, v in enumerate(s): if v in dic and start <= dic[v]: start = dic[v] + 1 else: ans = max(ans, i - start + 1) dic[v] = i return ans
f7b7940bdc1c2e30f4e81b41256c5bde20674910
capeman1/Lessons_for_egor
/example_OOP.py
3,111
3.84375
4
class biological_class: def __init__ (self, name, height, weight , age, gender ,organism=bool): self.name = name self.height = height self.weight = weight self.age = age self.gender = gender self.organism = organism from random import randint if randint(0,1) == 0: self.organism = False else: self.organism = True print('У нас новое существо. Имя :',self.name ) def hello (self): print('Знакомтесь, Имя : {0}. Рост {1} см. Вес {2} кг. Возвраст {3} лет. Пол {4}. Организм: {5}.'.format(self.name, self.height, self.weight , self.age, self.gender ,self.organism),end=' ' ) def evolve(self): from random import randint print('эволюция для существа с именем : ',self.name, ', составила:',randint(60,100)) def jump(self): print(self.name, "Совершает прыжок на ", 0.35*(self.height)) class Human(biological_class): def __init__(self, name, height, weight , age, gender ,organism, profession , salary ): biological_class.__init__(self, name, height, weight , age, gender ,organism) self. profession = profession self.salary = salary print('В ходе эволюции создался человек : ', self.name) def hello(self): biological_class.hello(self) print('Должность : {0} , Зарплата : {1} .'.format(self. profession ,self.salary)) class Monkey(biological_class): def __init__(self, name, height, weight , age, gender ,organism, lovely_food, location ): biological_class.__init__(self, name, height, weight , age, gender ,organism) self.lovely_food = lovely_food self.location = location print('В ходе эволюции создалась обезьяна : ', self.name) def hello(self): biological_class.hello(self) print('Любимое лакомство : {0}. Место нахождение {1} '.format(self.lovely_food,self.location)) egor=Human(name ='Егор',height = 180,weight=70,age= 26,gender= "мужской",profession= 'инженер', salary=10000000,organism=bool) print(' ') igor=Human(name ='игорь',height = 180,weight=150,age= 26,gender= "мужской",profession= 'милитари-дентист',salary=9999999999,organism=bool) print(' ') lili=Monkey(name ='Лили',height = 90,weight=34,age= 12,gender= 'Женский',lovely_food='банан',location= 'зоопарк',organism=bool) print(' ') Garu=Monkey(name ='Гару',height = 120,weight=55,age= 12,gender= 'мужской',lovely_food='банан',location= 'джунгли',organism=bool) print(' ') count =[egor,igor,lili,Garu] for spec in count: spec.hello() spec.evolve() spec.jump() print(' ') print('igor lax ') print('igor lax ') print('igor lax ')
7aebaed21d42448c0a66866247916ffe3c0371bc
JJ-Woods/Euler
/Python/pe009.py
628
3.53125
4
#Author - Jamie Woods #https://projecteuler.net/problem=9 import math TARGET = 1000 def main(): answer = findProductOfTriplet() print("The solution to problem 9 is " + str(answer)) def findProductOfTriplet(): for a in range(1, TARGET): for b in range(1, TARGET): aSquared = a ** 2 bSquared = b ** 2 cSquared = aSquared + bSquared c = math.sqrt(cSquared) sumOfTriplet = a + b + c if sumOfTriplet == 1000: productOfTriplet = a * b * c return int(productOfTriplet) if __name__ == "__main__": main()
67795d31809deb054cdc2e520ed8c5805beca481
Alekceyka-1/algopro21
/part1/LabRab/labrab-02/02.py
163
3.625
4
def get_count_div(num): count = 0 for i in range(2, num): if num % i == 0: count += 1 return count n = 12 print(get_count_div(n))
c45623b4662563adeb72e52f2386f83f0d0b2691
KFranciszek/pylove-training
/1.1/Excersise_1_7.py
264
3.5625
4
def odwazniki(a,b): ab = a * b aa = a bb = b while bb != 0 : cc = bb bb = aa % bb aa = cc ab = ab / aa return (int(ab/a),int(ab/b)) print(odwazniki(2, 8)) # 4, 1 print(odwazniki(4, 6)) # 3, 2 print(odwazniki(6, 4))
fb34eb8ca6b3892e237f63aef15af77c3e834c25
hoyasmh/PS
/boj/02001-03000/2083.py
123
3.796875
4
s=input().split() while s[0]!='#': print(s[0],['Junior','Senior'][int(s[1])>17 or int(s[2])>79]) s=input().split()
f3e9ffa43dec8739a25bacf9c97f2c13b5dcc46b
whuybrec/MiniGamesBot
/minigames/blackjack.py
4,068
3.765625
4
import random # https://gist.github.com/getmehire/013c6157eb0ddb26eb7a3965b5f58ae4 suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = { 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5, 'Six': 6, 'Seven': 7, 'Eight': 8, 'Nine': 9, 'Ten': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11 } class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def __str__(self): return self.rank + " of " + self.suit class Deck: def __init__(self): self.deck = [] for suit in suits: for rank in ranks: self.deck.append(Card(suit, rank)) # appending the Card object to self.deck list def __str__(self): composition = '' # set the deck comp as an empty string for card in self.deck: composition += '\n' + card.__str__() # Card class string representation return "The deck has: " + composition def shuffle(self): random.shuffle(self.deck) # grab the deck attribute of Deck class then pop off card item from list and set it to single card def deal(self): card = self.deck.pop() return card class Hand: def __init__(self): self.cards = [] # start with 0 cards in hand def add_card(self, card): self.cards.append(card) def get_value(self): a = b = 0 for card in self.cards: if card.rank == 'Ace': a += 1 b += 11 else: a += values[card.rank] b += values[card.rank] if b > 21: b = a return a, b class Blackjack: def __init__(self): self.player_turn = True self.deck = Deck() self.deck.shuffle() self.player_hands = [Hand()] self.player_hands[0].add_card(self.deck.deal()) self.player_hands[0].add_card(self.deck.deal()) self.dealer_hand = Hand() self.dealer_hand.add_card(self.deck.deal()) self.dealer_hand.add_card(self.deck.deal()) def can_split(self): return self.player_hands[0].cards[0].rank == self.player_hands[0].cards[1].rank def split_hand(self): self.player_hands.append(Hand()) card = self.player_hands[0].cards[0] self.player_hands[1].cards.append(card) self.player_hands[0].cards.remove(card) def hit(self, hand=0): self.player_hands[hand].add_card(self.deck.deal()) def stand(self): self.dealer_turn() def is_player_busted(self): busted = True for hand in self.player_hands: if hand.get_value()[0] <= 21 or hand.get_value()[1] <= 21: busted = False return busted def is_dealer_busted(self): return self.dealer_hand.get_value()[0] > 21 and self.dealer_hand.get_value()[1] > 21 def dealer_turn(self): self.player_turn = False while self.dealer_hand.get_value()[0] < 17 or self.dealer_hand.get_value()[1] < 17: self.dealer_hand.add_card(self.deck.deal()) def get_game_result(self): if self.is_player_busted() and self.is_dealer_busted(): return "DRAW" elif self.is_player_busted(): return "LOSE" elif self.is_dealer_busted(): return "WIN" max_hand_value = 0 for hand in self.player_hands: if max_hand_value < max(hand.get_value()) <= 21: max_hand_value = max(hand.get_value()) if max(self.dealer_hand.get_value()) < max_hand_value: return "WIN" if max(self.dealer_hand.get_value()) == max_hand_value: return "DRAW" return "LOSE" def has_ended_in_draw(self): result = self.get_game_result() return result == "DRAW" def has_player_won(self): result = self.get_game_result() return result == "WIN"
239648424bcfe928a1e543e0d51583e23c6434e2
mshukuno/Library-Utilities
/test/true-locations.py
5,638
4.0625
4
"""Make a list of locations of true values in a boolean 2-D array. Usage: python {this-script} [ {input-file} ] This script reads a text file with the data for a 2-dimensional boolean array. The format of the file is the one used by the Read2DimArray method in the Bool class of the Landis utility library (Landis.Util.Bool.Read2DimArray). Blank lines and comment lines are ignored in the file. A blank line is either an empty line (has no characters), or has just whitespace. A comment line is a line where the first non-whitespace character is "#". Any other line is considered a data line. The first data line in the file specifies the list of characters which will indicate true elements in the array. In this example, true-chars =Tt1Yy any of the 5 characters -- upper and lowercase letters "T" and "Y" and the digit 1 -- may indicate a true element in the array. All the characters that follow the "=" represent the list of true-value characters. This list may be empty, in which case, all the elements in the array will be false. The remaining data lines in the file are of the form: row {#} ={data for row} The {#} is an optional row number: one or more digits. This row number is not used by this script; it can used a visual aid for users reading the file. The data for the row is 0 or more characters, one character per column in the array. If the character for a column is in the list of true characters, then the corresponding element in the array is true. Othewise, the element is false. Each row in the array must have the same number of columns. It is acceptable to have 0 columns in each row, or to have no rows (i.e., there are no data lines with the "row" keyword). The script writes to standard output a list of locations of the true elements in the array. One location is written per line in the format: {row} {column} The locations were written in row-major order. If no input file is specified, the script reads the file data from standard input. """ #------------------------------------------------------------------------------ import re import sys #------------------------------------------------------------------------------ def main(): try: filename = process_cmd_line() array = read_array(filename) write_true_locations(array) return 0 except ProgramError, err: print >>sys.stderr, err.message return 1 #------------------------------------------------------------------------------ def process_cmd_line(): if len(sys.argv) == 1: return '-' if len(sys.argv) == 2: return sys.argv[1] raise ProgramError("Usage: python %s [ file ]" % sys.argv[0]) #------------------------------------------------------------------------------ class ProgramError: def __init__(self, message): self.message = message def __str__(self): return message #------------------------------------------------------------------------------ def read_array(filename): input_file = InputFile(filename) # Read list of true characters line = input_file.read_line() pattern = re.compile(r"^\s*true-chars\s*=(.*)") match = pattern.match(line) if not match: raise input_file.error('Expected line starting with "true-chars ="') true_chars = match.group(1) # Read row data pattern = re.compile(r"^\s*row\s*\d*\s*=(.*)") expectedLen = None array = [] while True: line = input_file.read_line() if line is None: break match = pattern.match(line) if not match: raise input_file.error('Expected line starting with "row [#] ="') row = match.group(1) if expectedLen is None: expectedLen = len(row) elif expectedLen != len(row): raise input_file.error('Expected %d character%s after the "="' % expectedLen, (expectedLen != 1 and "s" or "")) array.append([ch in true_chars for ch in row]) return array #------------------------------------------------------------------------------ class InputFile: def __init__(self, filename): self.filename = filename if filename == "-": self.filename = "standard input" self.file = sys.stdin else: self.file = file(filename, 'r') self.line_number = 0 def read_line(self): if self.file is None: return None while True: line = self.file.readline() if line == "": self.file = None self.line_number = None return None self.line_number += 1 line = re.sub(r'\s+', '', line) if line == "": continue if re.match(r'\s*#', line): continue return line def error(self, message): if self.line_number is None: location = 'end of' else: location = 'line %d in' % self.line_number return ProgramError('At %s %s:\n %s' % (location, self.filename, message)) #------------------------------------------------------------------------------ def write_true_locations(array): for row in range(0, len(array)): for column in range(0, len(array[0])): if array[row][column]: print row+1, column+1 #------------------------------------------------------------------------------ if __name__ == "__main__": main()
ad9b97e96133ed28b9014ab0d7fcf8cb679430f9
MDGSF/JustCoding
/python-leetcode/sw_58_2.py
365
3.59375
4
class Solution: def reverseLeftWords(self, s: str, n: int) -> str: n = n % len(s) a = list(s) self.reverse(a, 0, n - 1) self.reverse(a, n, len(a) - 1) self.reverse(a, 0, len(a) - 1) return ''.join(a) def reverse(self, a, left, right): while left < right: a[left], a[right] = a[right], a[left] left += 1 right -= 1
15c090827cf86829b4e735f26cd22e4a1a5b2a6e
xjwhhh/TensorflowTutorial
/LearnAndUseML/TextClassification.py
5,314
3.5625
4
# 电影评论分类 import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt print(tf.__version__) # Download the IMDB dataset imdb = keras.datasets.imdb # 训练集,测试集 (train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000) # Explore the data 数据全部是数字 print("Training entries: {}, labels: {}".format(len(train_data), len(train_labels))) print(train_data[0]) # 不同评论的长度可能不同 len(train_data[0]), len(train_data[1]) # Convert the integers back to words 可以使用配套字典将数字转化为评论文字 # A dictionary mapping words to an integer index word_index = imdb.get_word_index() # The first indices are reserved word_index = {k: (v + 3) for k, v in word_index.items()} word_index["<PAD>"] = 0 word_index["<START>"] = 1 word_index["<UNK>"] = 2 # unknown word_index["<UNUSED>"] = 3 reverse_word_index = dict([(value, key) for (key, value) in word_index.items()]) def decode_review(text): return ' '.join([reverse_word_index.get(i, '?') for i in text]) print(decode_review(train_data[0])) print(decode_review(train_data[1])) # Prepare the data # 必须把数组转化成tensor,有两种方法 # 方法一:将数组转化成0,1向量,比如[3,5]转化成一万维的向量,除了索引3,5处为1,其余为0,但是这种方法是内存密集型的,需要num_words * num_reviews的矩阵 # 方法二:填充数组,使它们都有相同长度,然后创建一个大小为max_length * num_reviews的整形张量 # 在这个教程中,使用第二个方法,首先处理数据,标准化长度 train_data = keras.preprocessing.sequence.pad_sequences(train_data, value=word_index["<PAD>"], padding='post', maxlen=256) test_data = keras.preprocessing.sequence.pad_sequences(test_data, value=word_index["<PAD>"], padding='post', maxlen=256) # 此时长度均为256,结尾原来无数据处填0 print(len(train_data[0]), len(train_data[1])) print(train_data[0]) # Build the model # input shape is the vocabulary count used for the movie reviews (10,000 words) vocab_size = 10000 model = keras.Sequential() # The first layer is an Embedding layer. This layer takes the integer-encoded vocabulary and looks up the embedding vector for each word-index. # These vectors are learned as the model trains. The vectors add a dimension to the output array. The resulting dimensions are: (batch, sequence, embedding). model.add(keras.layers.Embedding(vocab_size, 16)) # Next, a GlobalAveragePooling1D layer returns a fixed-length output vector for each example by averaging over the sequence dimension. # This allows the model can handle input of variable length, in the simplest way possible. model.add(keras.layers.GlobalAveragePooling1D()) # This fixed-length output vector is piped through a fully-connected (Dense) layer with 16 hidden units. model.add(keras.layers.Dense(16, activation=tf.nn.relu)) # The last layer is densely connected with a single output node. Using the sigmoid activation function, this value is a float between 0 and 1, representing a probability, or confidence level. model.add(keras.layers.Dense(1, activation=tf.nn.sigmoid)) print(model.summary()) # Hidden units # 隐藏层,更多的隐藏层可以进行更复杂的学习 # Loss function and optimizer # loss——损失函数 # metrics——监测训练集和测试集 # optimizer——决定数据如何更新 model.compile(optimizer=tf.train.AdamOptimizer(), loss='binary_crossentropy', metrics=['accuracy']) # Create a validation set 验证集,从训练集中划分出来 x_val = train_data[:10000] partial_x_train = train_data[10000:] y_val = train_labels[:10000] partial_y_train = train_labels[10000:] # Train the model history = model.fit(partial_x_train, partial_y_train, epochs=40, batch_size=512, validation_data=(x_val, y_val), verbose=1) # Evaluate the model results = model.evaluate(test_data, test_labels) print(results) # Create a graph of accuracy and loss over time history_dict = history.history print(history_dict.keys()) acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(acc) + 1) # "bo" is for "blue dot" plt.plot(epochs, loss, 'bo', label='Training loss') # b is for "solid blue line" plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() plt.clf() # clear figure acc_values = history_dict['acc'] val_acc_values = history_dict['val_acc'] plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show()
158d6d323cfdb15fbe1bcce604de96900a642e12
Python-Repository-Hub/Learn-Online-Learning
/Python-for-everyone/02_Data_Structure/10_Tuple/03_adventage.py
357
3.984375
4
(x, y) = (4, 'fred') print(y) # fred (a, b) = (99, 98) print(a) # 99 def t() : return (10, 20) x, y = t() print(x, y) # 10 20 # () is recognized as a tuple, even if it is not used. x, y = 1, 10 print(x, y) # 1 10 x, y = y, x print(x, y) # 10 1
429ab48b9cf07f2b51ee9eb9493991c66bfc5b91
jorgemira/codewars
/katas/5kyu/kata8.py
296
3.609375
4
""" Codewars 5 kyu kata: Multiples By Permutations II URL: https://www.codewars.com/kata/5ba178be875de960a6000187/python """ def find_lowest_int(k): n = 1 while True: if sorted(str(k * n)) == sorted(str((k + 1) * n)): return n else: n += 1
dd7b263d4fee276498e0b7954e1fe82e8c0410aa
ariayukin/python_study
/fishc No6.py
2,011
3.96875
4
-3 ** 2 3 ** -2 #and not or not True not 0 not 1 3 < 4 < 5 #优先级 幂运算 < 正负号 < 算术操作符 < 比较操作符 < 罗技运算符 #测试题: #0. Python 的 floor 除法现在使用 “//” 实现,那 3.0 // 2.0 您目测会显示什么内容呢? #1.0 #1. a < b < c 事实上是等于? #(a < b) and (b < c) #2. 不使用 IDLE,你可以轻松说出 5 ** -2 的值吗? #0.04 #幂运算操作符比其左侧的一元操作符优先级高,比其右侧的一元操作符优先级低。 #3. 如何简单判断一个数是奇数还是偶数? # n % 2 == 0 否则为奇数 #4. 请用最快速度说出答案:not 1 or 0 and 1 or 3 and 4 or 5 and 6 or 7 and 8 and 9 #4 #5. 还记得我们上节课那个求闰年的作业吗?如果还没有学到“求余”操作,还记得用什么方法可以“委曲求全”代替“%”的功能呢? 动动手: 0. 请写一个程序打印出 0~100 所有的奇数。 i = 100 while i >= 0: if i % 2 != 0: print (i,end=" ") i -= 1 else: i -= 1 1. 我们说过现在的 Python 可以计算很大很大的数据,但是......真正的大数据计算可是要靠刚刚的硬件滴,不妨写一个小代码,让你的计算机为之崩溃? print(2 ** 2 ** 32) # 一般很多机子都会在一会儿之后:Memory Overflow,内存不够用。 # 设计到幂操作,结果都是惊人滴。 2. 爱因斯坦的难题 爱因斯坦曾出过这样一道有趣的数学题:有一个长阶梯,若每步上2阶,最后剩1阶;若每步上3阶,最后剩2阶;若每步上5阶,最后剩4阶;若每步上6阶,最后剩5阶;只有每步上7阶,最后刚好一阶也不剩。 (小甲鱼温馨提示:步子太大真的容易扯着蛋~~~) 题目:请编程求解该阶梯至少有多少阶? 3. 请写下这一节课你学习到的内容:格式不限,回忆并复述是加强记忆的好方式!
5d75d6468c05a33c83854693fd1199bb83cb02ac
joeday05/Problem-Sets
/iterative vs recursive.py
1,402
3.90625
4
def iterMul(a, b): result = 0 while b > 0: result += a b -= 1 return result def iterPower(base, exp): result = 1 while exp > 0: result *= base exp -= 1 return result #print iterPower(10 , 2) def recurMul(a, b): if b == 1: return a else: return a + recurMul(a, b-1) #print recurMul(5, 3) def factI(n): """assumes that n is an int > 0 returns n!""" res = 1 while n > 1: res = res * n n -= 1 return res def factR(n): """assumes that n is an int > 0 returns n!""" if n == 1: return n return n*factR(n-1) #print factR(5) def recurPower(base, exp): if exp == 0: return 1 return base * recurPower(base, exp-1) #print recurPower(4, 2) def recurPowerNew(base, exp): if exp == 0: return 1 if exp % 2 == 1: return base * recurPowerNew(base, exp-1) else: return base * base * recurPowerNew(base, exp-2) #print recurPowerNew(4, 6) def gcd(a, b): c = a while c > 0: if b % c == 0 and a % c == 0: return c c -= 1 #print gcd(2, 12) #Euclidean algorithm to calculate greatest common denomenator def gcdRecur(a, b): if b == 0: return a else: return gcdRecur(b, a % b) print gcdRecur(4, 3)
7397a369153e6d9b76c51a09beaf084d902e9613
Jordonguy/PythonTests
/UsefulPythonCodeLibrary/CountEven.py
345
4.28125
4
count_even = 0 count_odd = 0 # Range to 101 because it doesn't include 101 it will only include upto 100 for number in range(1, 101): if number % 2 == 0: count_even += 1 print(number) else: count_odd += 1 print(number) print(f"We have {count_even} even numbers") print(f"We have {count_odd} odd numbers")
03c83c53be652d41555d16c18e130fbcb12fe60d
Anvi23/Practice_Programs
/SummaryProgram.py
1,545
3.578125
4
filep = open('StudentsData.csv','r') gender = {} college = {} cat = {} for line in filep: data = line.strip().split(',',3) #creating individual list and not saving the list just checking for values. ''' [0] -> Name [1] -> Category [2] -> Gender [3] -> College ''' if data[3] in college: #if element 3 of list is in dictionary,add 1(increasing counter) college[data[3]] = college[data[3]]+1 else: #if it is not, then adding the key(element 3 of list) #and assigning value=1..which will be increased by 1 next time if data[3] comes. college[data[3]] = 1 if data[2] in gender: gender[data[2]] = gender[data[2]] + 1 else: gender[data[2]] = 1 if data[1] in cat: cat[data[1]][0] = cat[data[1]][0] + 1 #print(','.join(data),file=cat[data[1]][1]) cat[data[1]][1].write(','.join(data)+'\n') else: fp = open(data[1] + '.csv', 'w') #data[1]= OBC...need not make different files-AUTOMATED. #and concatenate 'CSV' cat[data[1]] = [1,fp] #assigning a list as a value in dictionary. #fp is passed as an element. WHY? #cat[data[1]][1] = fp...but not using it as fp As--> under IF, we are not initialising fp. #print(','.join(data),file=cat[data[1]][1]) OR cat[data[1]][1].write(','.join(data)+'\n') for i,v in gender.items(): print(i,v) print('-'*20) for i,v in cat.items(): print(i,v[0]) print('-'*20) for i,v in college.items(): print(i,v)
9ffa71ae802ba63c06f0a3de7fe208db25af2ae5
LavanyaJayaprakash7232/python-code---string
/up_low.py
555
4.3125
4
''' Get a string Return number of lowercase and uppercase characters ''' #Function to count the characters def up_low(string): up = 0 low = 0 string1 = string.replace(' ', '') #To remove the whitespaces for i in string1: if i==i.upper(): up = up + 1 elif i==i.lower(): low = low + 1 else: pass return f"Uppercase characters:\t {up} \nLowercase characters: \t {low}" a = input('Enter the string \n') result = up_low(a) print (result)
36aef5cd24f30dbf6d9256384945f417ee67abe8
jmgc/pyston
/test/tests/descriptor_ics.py
621
3.546875
4
# Make sure that we guard in a getattr IC to make sure that # we don't subsequently get an object with a __get__ defined. class D(object): def __repr__(self): return "<D>" class C(object): def __repr__(self): return "<C>" d = D() c = C() def print_d(c): print c.d print_d(c) def get(self, obj, cls): print self, obj, cls return 1 D.__get__ = get print_d(c) # And also the other way around: del D.__get__ print_d(c) class E(object): def __get__(self, obj, cls): print "E.__get__" return 2 C.d = E() # Or if we switch out the object entirely: print_d(c)
417d251240aaf565c206b7c366a6952dd4c1f5fc
bernardombraga/Solucoes-exercicios-cursos-gratuitos
/Curso-em-video-Python3-mundo1/ex025.py
147
3.59375
4
lido = str(input('Qual é seu nome completo? ')) nome = lido.strip().lower() silva = 'silva' in nome print('Seu nome tem Silva? {}'.format(silva))
65ad5336dbad4a9846cb547ae86f894e4d8e31b3
xiidot1303/For-study-module-
/1-amaliy topshiriq/3.py
66
3.53125
4
import numpy as np a = input() a = int(a) print(np.sqrt(3*a*a/4))
464b4e7c23c619666654f55a41198ab1108cc36d
YRApril/LiJia
/21.04.13/others/GerryChain-main/gerrychain/tree.py
12,692
3.6875
4
import networkx as nx from networkx.algorithms import tree from .random import random from collections import deque, namedtuple def predecessors(h, root): return {a: b for a, b in nx.bfs_predecessors(h, root)} def successors(h, root): return {a: b for a, b in nx.bfs_successors(h, root)} def random_spanning_tree(graph): """ Builds a spanning tree chosen by Kruskal's method using random weights. :param graph: Networkx Graph Important Note: The key is specifically labelled "random_weight" instead of the previously used "weight". Turns out that networkx uses the "weight" keyword for other operations, like when computing the laplacian or the adjacency matrix. This meant that the laplacian would change for the graph step to step, something that we do not intend!! """ for edge in graph.edges: graph.edges[edge]["random_weight"] = random.random() spanning_tree = tree.maximum_spanning_tree( graph, algorithm="kruskal", weight="random_weight" ) return spanning_tree def uniform_spanning_tree(graph, choice=random.choice): """ Builds a spanning tree chosen uniformly from the space of all spanning trees of the graph. :param graph: Networkx Graph :param choice: :func:`random.choice` """ root = choice(list(graph.nodes)) tree_nodes = set([root]) next_node = {root: None} for node in graph.nodes: u = node while u not in tree_nodes: next_node[u] = choice(list(nx.neighbors(graph, u))) u = next_node[u] u = node while u not in tree_nodes: tree_nodes.add(u) u = next_node[u] G = nx.Graph() for node in tree_nodes: if next_node[node] is not None: G.add_edge(node, next_node[node]) return G class PopulatedGraph: def __init__(self, graph, populations, ideal_pop, epsilon): self.graph = graph self.subsets = {node: {node} for node in graph} self.population = populations.copy() self.tot_pop = sum(self.population.values()) self.ideal_pop = ideal_pop self.epsilon = epsilon self._degrees = {node: graph.degree(node) for node in graph} def __iter__(self): return iter(self.graph) def degree(self, node): return self._degrees[node] def contract_node(self, node, parent): self.population[parent] += self.population[node] self.subsets[parent] |= self.subsets[node] self._degrees[parent] -= 1 def has_ideal_population(self, node): return ( abs(self.population[node] - self.ideal_pop) < self.epsilon * self.ideal_pop ) Cut = namedtuple("Cut", "edge subset") def find_balanced_edge_cuts_contraction(h, choice=random.choice): # this used to be greater than 2 but failed on small grids:( root = choice([x for x in h if h.degree(x) > 1]) # BFS predecessors for iteratively contracting leaves pred = predecessors(h.graph, root) cuts = [] leaves = deque(x for x in h if h.degree(x) == 1) while len(leaves) > 0: leaf = leaves.popleft() if h.has_ideal_population(leaf): cuts.append(Cut(edge=(leaf, pred[leaf]), subset=h.subsets[leaf].copy())) # Contract the leaf: parent = pred[leaf] h.contract_node(leaf, parent) if h.degree(parent) == 1 and parent != root: leaves.append(parent) return cuts def find_balanced_edge_cuts_memoization(h, choice=random.choice): root = choice([x for x in h if h.degree(x) > 1]) pred = predecessors(h.graph, root) succ = successors(h.graph, root) total_pop = h.tot_pop subtree_pops = {} stack = deque(n for n in succ[root]) while stack: next_node = stack.pop() if next_node not in subtree_pops: if next_node in succ: children = succ[next_node] if all(c in subtree_pops for c in children): subtree_pops[next_node] = sum(subtree_pops[c] for c in children) subtree_pops[next_node] += h.population[next_node] else: stack.append(next_node) for c in children: if c not in subtree_pops: stack.append(c) else: subtree_pops[next_node] = h.population[next_node] cuts = [] for node, tree_pop in subtree_pops.items(): def part_nodes(start): nodes = set() queue = deque([start]) while queue: next_node = queue.pop() if next_node not in nodes: nodes.add(next_node) if next_node in succ: for c in succ[next_node]: if c not in nodes: queue.append(c) return nodes if abs(tree_pop - h.ideal_pop) <= h.ideal_pop * h.epsilon: cuts.append(Cut(edge=(node, pred[node]), subset=part_nodes(node))) elif abs((total_pop - tree_pop) - h.ideal_pop) <= h.ideal_pop * h.epsilon: cuts.append(Cut(edge=(node, pred[node]), subset=set(h.graph.nodes) - part_nodes(node))) return cuts def bipartition_tree( graph, pop_col, pop_target, epsilon, node_repeats=1, spanning_tree=None, spanning_tree_fn=random_spanning_tree, balance_edge_fn=find_balanced_edge_cuts_memoization, choice=random.choice, ): """This function finds a balanced 2 partition of a graph by drawing a spanning tree and finding an edge to cut that leaves at most an epsilon imbalance between the populations of the parts. If a root fails, new roots are tried until node_repeats in which case a new tree is drawn. Builds up a connected subgraph with a connected complement whose population is ``epsilon * pop_target`` away from ``pop_target``. Returns a subset of nodes of ``graph`` (whose induced subgraph is connected). The other part of the partition is the complement of this subset. :param graph: The graph to partition :param pop_col: The node attribute holding the population of each node :param pop_target: The target population for the returned subset of nodes :param epsilon: The allowable deviation from ``pop_target`` (as a percentage of ``pop_target``) for the subgraph's population :param node_repeats: A parameter for the algorithm: how many different choices of root to use before drawing a new spanning tree. :param spanning_tree: The spanning tree for the algorithm to use (used when the algorithm chooses a new root and for testing) :param spanning_tree_fn: The random spanning tree algorithm to use if a spanning tree is not provided :param choice: :func:`random.choice`. Can be substituted for testing. """ populations = {node: graph.nodes[node][pop_col] for node in graph} possible_cuts = [] if spanning_tree is None: spanning_tree = spanning_tree_fn(graph) restarts = 0 while len(possible_cuts) == 0: if restarts == node_repeats: spanning_tree = spanning_tree_fn(graph) restarts = 0 h = PopulatedGraph(spanning_tree, populations, pop_target, epsilon) possible_cuts = balance_edge_fn(h, choice=choice) restarts += 1 return choice(possible_cuts).subset def bipartition_tree_random( graph, pop_col, pop_target, epsilon, node_repeats=1, repeat_until_valid=True, spanning_tree=None, spanning_tree_fn=random_spanning_tree, balance_edge_fn=find_balanced_edge_cuts_memoization, choice=random.choice, ): """This is like :func:`bipartition_tree` except it chooses a random balanced cut, rather than the first cut it finds. This function finds a balanced 2 partition of a graph by drawing a spanning tree and finding an edge to cut that leaves at most an epsilon imbalance between the populations of the parts. If a root fails, new roots are tried until node_repeats in which case a new tree is drawn. Builds up a connected subgraph with a connected complement whose population is ``epsilon * pop_target`` away from ``pop_target``. Returns a subset of nodes of ``graph`` (whose induced subgraph is connected). The other part of the partition is the complement of this subset. :param graph: The graph to partition :param pop_col: The node attribute holding the population of each node :param pop_target: The target population for the returned subset of nodes :param epsilon: The allowable deviation from ``pop_target`` (as a percentage of ``pop_target``) for the subgraph's population :param node_repeats: A parameter for the algorithm: how many different choices of root to use before drawing a new spanning tree. :param repeat_until_valid: Determines whether to keep drawing spanning trees until a tree with a balanced cut is found. If `True`, a set of nodes will always be returned; if `False`, `None` will be returned if a valid spanning tree is not found on the first try. :param spanning_tree: The spanning tree for the algorithm to use (used when the algorithm chooses a new root and for testing) :param spanning_tree_fn: The random spanning tree algorithm to use if a spanning tree is not provided :param balance_edge_fn: The algorithm used to find balanced cut edges :param choice: :func:`random.choice`. Can be substituted for testing. """ populations = {node: graph.nodes[node][pop_col] for node in graph} possible_cuts = [] if spanning_tree is None: spanning_tree = spanning_tree_fn(graph) repeat = True while repeat and len(possible_cuts) == 0: spanning_tree = spanning_tree_fn(graph) h = PopulatedGraph(spanning_tree, populations, pop_target, epsilon) possible_cuts = balance_edge_fn(h, choice=choice) repeat = repeat_until_valid if possible_cuts: return choice(possible_cuts).subset return None def recursive_tree_part( graph, parts, pop_target, pop_col, epsilon, node_repeats=1, method=bipartition_tree ): """Uses :func:`~gerrychain.tree.bipartition_tree` recursively to partition a tree into ``len(parts)`` parts of population ``pop_target`` (within ``epsilon``). Can be used to generate initial seed plans or to implement ReCom-like "merge walk" proposals. :param graph: The graph :param parts: Iterable of part labels (like ``[0,1,2]`` or ``range(4)`` :param pop_target: Target population for each part of the partition :param pop_col: Node attribute key holding population data :param epsilon: How far (as a percentage of ``pop_target``) from ``pop_target`` the parts of the partition can be :param node_repeats: Parameter for :func:`~gerrychain.tree_methods.bipartition_tree` to use. :return: New assignments for the nodes of ``graph``. :rtype: dict """ flips = {} remaining_nodes = set(graph.nodes) # We keep a running tally of deviation from ``epsilon`` at each partition # and use it to tighten the population constraints on a per-partition # basis such that every partition, including the last partition, has a # population within +/-``epsilon`` of the target population. # For instance, if district n's population exceeds the target by 2% # with a +/-2% epsilon, then district n+1's population should be between # 98% of the target population and the target population. debt = 0 for part in parts[:-1]: min_pop = max(pop_target * (1 - epsilon), pop_target * (1 - epsilon) - debt) max_pop = min(pop_target * (1 + epsilon), pop_target * (1 + epsilon) - debt) nodes = method( graph.subgraph(remaining_nodes), pop_col=pop_col, pop_target=(min_pop + max_pop) / 2, epsilon=(max_pop - min_pop) / (2 * pop_target), node_repeats=node_repeats, ) if nodes is None: raise BalanceError() part_pop = 0 for node in nodes: flips[node] = part part_pop += graph.nodes[node][pop_col] debt += part_pop - pop_target remaining_nodes -= nodes # All of the remaining nodes go in the last part for node in remaining_nodes: flips[node] = parts[-1] return flips class BalanceError(Exception): """Raised when a balanced cut cannot be found."""
a68ea520cbdb94f93ffe4f2ec292966096860462
taehwan920/Algorithm
/baekjoon/2857_FBI.py
214
3.625
4
FBI = False FBIs = [] for i in range(1, 6): agent = input() if "FBI" in agent: FBI = True FBIs.append(i) if FBI: for i in FBIs: print(i, end=" ") else: print('HE GOT AWAY!')
c8300d2da7059f2cca63417e200e7cc4bbc06183
RahatIbnRafiq/leetcodeProblems
/Tree/501. Find Mode in Binary Search Tree.py
632
3.5625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): d = None def dfs(self,node): if node: self.d[node.val] = self.d.get(node.val,0)+1 self.dfs(node.left) self.dfs(node.right) def findMode(self, root): if not root:return [] self.d = dict() self.dfs(root) mode = max([self.d[key] for key in self.d.keys()]) return [key for key in self.d.keys() if self.d[key] == mode]
88a0516109dcda0a70df265d79a6de264dd56ca3
NatanLisboa/python
/exercicios-cursoemvideo/Mundo1/ex003.py
306
3.90625
4
# Desafio 003 - Crie um programa que leia dois números e mostre a soma entre eles print('\033[7;34;40mDesafio 003 - Soma entre dois números\033[m') n1 = int(input('1º número: ')) n2 = int(input('2º número: ')) print('{} \033[31m+\033[m {} \033[31m=\033[m \033[4;34m{}\033[m'.format(n1, n2, n1+n2))
7d70e952732f1d990b807f7681b8c301a87e4ac4
harshil1903/leetcode
/Design/1603_design_parking_system.py
1,491
4.15625
4
# 1603. Design Parking System # # Source : https://leetcode.com/problems/design-parking-system/ # # Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each # size. # # Implement the ParkingSystem class: # # ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of # the constructor. # bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: # big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. If there is no space # available, return false, else park the car in that size space and return true. class ParkingSystem: def __init__(self, big: int, medium: int, small: int): self.parking = [0, big, medium, small] def addCar(self, carType: int) -> bool: if self.parking[carType] > 0: self.parking[carType] -= 1 return True else: return False # Your ParkingSystem object will be instantiated and called as such: # obj = ParkingSystem(big, medium, small) # param_1 = obj.addCar(carType) if __name__ == '__main__': s = ParkingSystem(1,1,0) print(s.addCar(1)); print(s.addCar(2)); print(s.addCar(3)); print(s.addCar(1));
33ddf91a2651c35757ddb2cc60ccb4f6317c3f94
saransappa/My-Codeforces-Solutions
/1281A - Suffix three/1281A.py
230
4.15625
4
n=int(input()) for i in range(n): s=input() if s.endswith("po"): print("FILIPINO") elif s.endswith("desu") or s.endswith("masu"): print("JAPANESE") elif s.endswith("mnida"): print("KOREAN")
ba00d6915eb61e95d3a4ffd41f512f38b570ccb1
2292527883/Learn-python-3-to-hard-way
/ex25/ex25.py
1,569
4.34375
4
def break_words(stuff): # 作用:将字符串以空格的判断条件分割 """This fution will break up words for Us .""" words = stuff.split(' ') # split作用:将stuff的字符串以(' ')之间的字符分割此处为空格 return words def sort_words(words): # 降序排序 """sorts the words .""" return sorted(words) # sorted()作用:将字符串进行降序排序 def print_first_word(words): # 删除并打印第一个字符 """prints the first word a after popping it off .""" word = words.pop(0) # pop作用:移除列表中的一个元素(默认为最后一个 :-1)并返回删除的元素 print(word) def print_last_word(words): # 删除并打印最后一个字符 """prints the last word after popping it off""" word = words.pop(-1) print(word) def sort_sentence(sentence): # 一次将sentence进行分割,降序排序 """takes in a full sentence and returns the sortedwords.""" words = break_words(sentence) return sort_words(words) def print_first_and_last(sentence): # 一次将排序后的第一个和最后一个元素删除 """prints the first and last words of the sentence""" words = break_words(sentence) print_first_word(words) print_last_word(words) def print_first_and_last_sroted(sentence): # 一次排序 删除第一个和最后一个元素,函数嵌套 """srots the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words)
474b15ac2e4314e7ee5df2f2835b2ecd2b2367b5
poornasandur/DataScienceStanford
/PopulationWikipedia/Lab_2_A_Live.py
5,715
4.25
4
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> import cs109style cs109style.customize_mpl() cs109style.customize_css() # special IPython command to prepare the notebook for matplotlib %matplotlib inline from collections import defaultdict import pandas as pd import matplotlib.pyplot as plt import requests from pattern import web # <markdowncell> # ## Fetching population data from Wikipedia # # In this example we will fetch data about countries and their population from Wikipedia. # # http://en.wikipedia.org/wiki/List_of_countries_by_past_and_future_population has several tables for individual countries, subcontinents as well as different years. We will combine the data for all countries and all years in a single panda dataframe and visualize the change in population for different countries. # # ###We will go through the following steps: # * fetching html with embedded data # * parsing html to extract the data # * collecting the data in a panda dataframe # * displaying the data # # To give you some starting points for your homework, we will also show the different sub-steps that can be taken to reach the presented solution. # <markdowncell> # ## Fetching the Wikipedia site # <codecell> url = 'http://en.wikipedia.org/wiki/List_of_countries_by_past_and_future_population' website_html = requests.get(url).text #print website_html # <markdowncell> # ## Parsing html data # <codecell> def get_population_html_tables(html): """Parse html and return html tables of wikipedia population data.""" dom = web.Element(html) ### 0. step: look at html source! #### 1. step: get all tables tbls = dom.by_class('sortable wikitable') #### 2. step: get all tables we care about return tbls tables = get_population_html_tables(website_html) print "table length: %d" %len(tables) for t in tables: print t.attributes # <codecell> def table_type(tbl): ### Extract the table type return tbl('th')[0].content # group the tables by type tables_by_type = defaultdict(list) # defaultdicts have a default value that is inserted when a new key is accessed for tbl in tables: tables_by_type[table_type(tbl)].append(tbl) print tables_by_type # <markdowncell> # ## Extracting data and filling it into a dictionary # <codecell> def get_countries_population(tables): """Extract population data for countries from all tables and store it in dictionary.""" result = defaultdict(dict) # 1. step: try to extract data for a single table for table in tables: #print tables[0] tbl = table table_headers = tbl('th') table_headers = [str(x.content) for x in table_headers] first_header = table_headers[0] years = [int(x) for x in table_headers if x.isdigit()] year_indices = [idx for idx,x in enumerate(table_headers) if x.isdigit()] #print first_header #print table_headers #print years #print year_indices rows = tbl('tr')[1:] for row in rows: country_name = row('td')[0]('a')[0].content population_by_year = [int(row('td')[index].content.replace(',','')) for index in year_indices] #print country_name #print population_by_year sub_dict = dict(zip(years,population_by_year)) #print sub_dict #print country_name result[country_name].update(sub_dict) # 2. step: iterate over all tables, extract headings and actual data and combine data into single dict #print len(tables) return result result = get_countries_population(tables_by_type['Country or territory']) #print result # <markdowncell> # ## Creating a dataframe from a dictionary # <codecell> # create dataframe df = pd.DataFrame.from_dict(result, orient='index') # sort based on year df.sort(axis=1,inplace=True) print df # <markdowncell> # ## Some data accessing functions for a panda dataframe # <codecell> subtable = df.iloc[0:2, 0:2] print "subtable" print subtable print "" column = df[1955] print "column" print column print "" row = df.ix[0] #row 0 print "row" print row print "" rows = df.ix[:2] #rows 0,1 print "rows" print rows print "" element = df.ix[0,1955] #element print "element" print element print "" # max along column print "max" print df[1950].max() print "" # axes print "axes" print df.axes print "" row = df.ix[0] print "row info" print row.name print row.index print "" countries = df.index print "countries" print countries print "" print "Austria" print df.ix['Austria'] # <markdowncell> # ## Plotting population of 4 countries # <codecell> plotCountries = ['Austria', 'Germany', 'United States', 'France'] for country in plotCountries: row = df.ix[country] plt.plot(row.index, row, label=row.name ) plt.ylim(ymin=0) # start y axis at 0 plt.xticks(rotation=70) plt.legend(loc='best') plt.xlabel("Year") plt.ylabel("# people (million)") plt.title("Population of countries") # <markdowncell> # ## Plot 5 most populous countries from 2010 and 2060 # <codecell> def plot_populous(df, year): # sort table depending on data value in year column df_by_year = df.sort(year, ascending=False) plt.figure() for i in range(5): row = df_by_year.ix[i] plt.plot(row.index, row, label=row.name ) plt.ylim(ymin=0) plt.xticks(rotation=70) plt.legend(loc='best') plt.xlabel("Year") plt.ylabel("# people (million)") plt.title("Most populous countries in %d" % year) plot_populous(df, 2010) plot_populous(df, 2050) # <codecell>
4a11c643ca1ddccaffd3dc4560bd3bb0b1d885a2
robotech412/ITESCAM-ISC
/Segundo-Semestre/Algebra Lineal/Operaciones con matrices/operaciones_matrices.py
6,656
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as ny import sys def suma (): print ("SUMA DE MATRICES \t") filas = int(input("inserte numero de filas: ")) columnas = int(input("inserte numero de columnas: ")) A = [[0 for x in range(filas)] for y in range(columnas)] print ("Matriz 1") for i in range(filas): for j in range(columnas): A[i][j] = int(raw_input("Introduce los valores (%d,%d): " % (i, j))) filas = int(input("inserte numero de filas:")) columnas = int(input(" inserte numero de columnas: ")) B = [[0 for x in range(filas)] for y in range(columnas)] print("Matriz 2") for i in range(filas): for j in range(columnas): B[i][j] = int(raw_input("Introduce los valores (%d,%d): " % (i, j))) C = [[0 for x in range(filas)] for y in range(columnas)] for i in range(filas): for j in range(columnas): C[i][j] = A[i][j] + B[i][j] def dibujaMatriz(M): for i in range(len(M)): print '[', for j in range(len(M[i])): print '{:>3s}'.format(str(M[i][j])), print ']' print("RESULTADO\t") dibujaMatriz(C) def resta(): print ("RESTA DE MATRICES \t") filas = int(input("inserte numero de filas: ")) columnas = int(input("inserte numero de columnas: ")) A = [[0 for x in range(filas)] for y in range(columnas)] print ("Matriz 1") for i in range(filas): for j in range(columnas): A[i][j] = int(raw_input("Introduce los valores (%d,%d): " % (i, j))) filas = int(input("inserte numero de filas:")) columnas = int(input(" inserte numero de columnas: ")) B = [[0 for x in range(filas)] for y in range(columnas)] print("Matriz 2") for i in range(filas): for j in range(columnas): B[i][j] = int(raw_input("Introduce los valores (%d,%d): " % (i, j))) C = [[0 for x in range(filas)] for y in range(columnas)] for i in range(filas): for j in range(columnas): C[i][j] = A[i][j] - B[i][j] def dibujaMatriz(M): for i in range(len(M)): print '[', for j in range(len(M[i])): print '{:>3s}'.format(str(M[i][j])), print ']' print("RESULTADO\t") dibujaMatriz(C) def multiplicacion(): fila1 = int(input("Inserte el tamaño de la fila A ")) columna1 = int(input("Inserte el tamaño de la columna A: ")) fila2 = int(input("Inserte el tamaño de la fila B: ")) columna2 = int(input("Inserte el tamaño de la columna B: ")) #verificacion de la de la multiplicacion if (columna1 != fila2): print("No es posible hacer la multiplicacion") sys.exit() matrizA = numpy.zeros((fila1, columna1)) matrizB = numpy.zeros((fila2, columna2)) matrizC = numpy.zeros((fila1, columna2)) print("introduce los elementos de la matriz A") for r in range(0, fila1): for c in range(0, columna1): matrizA[r, c] = input("Elemento a["+str(r+1)+str(c+1)+"]") print("Introduce los elementos de la matriz B") for r in range(0, fila2): for c in range(0, columna2): matrizB[r, c] = input("Elemento a["+str(r+1)+str(c+1)+"]") #operaciones de multiplicacion for r in range(0, fila1): for c in range(0, columna2): for k in range(0, fila2): matrizC[r, c] += matrizA[r, k]*matrizB[k, c] print(matrizC) def multiescalar(): SC = int(input("Inserte el numero escalar: ")) fila1 = int(input("Inserte el tamaño de la fila A ")) columna1 = int(input("Inserte el tamaño de la columna A: ")) fila2 = int(input("Inserte el tamaño de la fila B: ")) columna2 = int(input("Inserte el tamaño de la columna B: ")) # verificacion de la de la multiplicacion if (columna1 != fila2): print("No es posible hacer la multiplicacion") sys.exit() matrizA = numpy.zeros((fila1, columna1)) matrizB = numpy.zeros((fila2, columna2)) matrizC = numpy.zeros((fila1, columna2)) print("introduce los elementos de la matriz A") for r in range(0, fila1): for c in range(0, columna1): matrizA[r, c] = input("Elemento a[" + str(r + 1) + str(c + 1) + "]") print("Introduce los elementos de la matriz B") for r in range(0, fila2): for c in range(0, columna2): matrizB[r, c] = input("Elemento a[" + str(r + 1) + str(c + 1) + "]") # operaciones de multiplicacion for r in range(0, fila1): for c in range(0, columna2): for k in range(0, fila2): matrizC[r, c] += ((matrizA[r, k] * SC) * (matrizB[k, c] * SC)) print(matrizC) def determinante(): print "Ingrese los valores:" print "|a00 a01 a02|" print "|a10 a11 a12|" print "|a20 a21 a22|" a00 = float(raw_input('Ingrese el valor a00 ')) a01 = float(raw_input('Ingrese el valor a01 ')) a02 = float(raw_input('Ingrese el valor a02 ')) a10 = float(raw_input('Ingrese el valor a10 ')) a11 = float(raw_input('Ingrese el valor a11 ')) a12 = float(raw_input('Ingrese el valor a12 ')) a20 = float(raw_input('Ingrese el valor a20 ')) a21 = float(raw_input('Ingrese el valor a21 ')) a22 = float(raw_input('Ingrese el valor a22 ')) # !a00 a10 a20! l2a00 l2a10 # !a01 a11 a21! l2a01 l2a11 # !a02 a12 a22! l2a02 l2a12 total=a00*a11*a22 + a10*a21*a02 +a20*a01*a12; total=total+(a02*a11*a20)*-1 + (a12*a21*a00)*-1 + (a22*a01*a10)*-1; if total!=0: print a00," ",a01," ",a02 print a10," ",a11," ",a12 print a20," ",a21," ",a22 print "Determinante 3x3: ",total; else: print "Error el det. da 0"; while (True): print ("1 = suma") print ("2 = resta") print ("3 = multiplicacion") print ("4 = multipliciacion escalar") print ("5 = multiplicacion transpuesta") print ("6 = determinante de una matriz") print ("7 = salir") opcion = int(input("Ingrese opcion\n")) if (opcion == 1): suma() elif (opcion == 2): resta() elif (opcion == 3): multiplicacion() elif (opcion == 4): multiescalar() elif (opcion == 5): () elif (opcion == 6): determinante() elif (opcion == 7): break else: print ("") (input("No has pulsado ninguna opción correcta...\npulsa una tecla para continuar"))
187a193805b80d95d1b77548a4e70f07f947a66e
Siyaoma812/Coursera-Data-Science-Courses
/Coursera_Course 2 Using Python to Access Web Data /Chapter 12 Networks and Sockets/assignment 2 Scraping Numbers from HTML using BeautifulSoup.py
719
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 11 22:46:02 2018 @author: Sylvia """ #Scraping Numbers from HTML using BeautifulSoup In this assignment #you will write a Python program similar to http://www.py4e.com/code3/urllink2.py. #The program will use urllib to read the HTML from the data files below, #and parse the data, extracting numbers and compute the sum of the numbers in the file. import urllib from urllib.request import urlopen from bs4 import BeautifulSoup url = input ('Enter - ') html = urlopen(url, context = ctx).read() soup = BeautifulSoup(html, "html.parser") tags = soup('span') print sum = 0 count = 0 for span in tags: sum +=int(span.string) print (sum)
aa5c112146bdb7ff88907d1c31d7d29b07a6755e
rosettaplus007/Anagrams.github.io
/visualize/src/js/python.py
526
3.546875
4
import urllib.request from collections import defaultdict words = urllib.request.urlopen('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').read().split() anagram = defaultdict(list) # map sorted chars to anagrams for word in words: anagram[tuple(sorted(word))].append( word ) count = len(anagram[0]) for ana in anagram.values(): if(count < len(ana)): count = len(ana) #count = max(len(ana) for ana in anagram.values()) for ana in anagram.values(): if len(ana) >= count: print ([x.decode() for x in ana])
adf34a0a97a911fb9ece21ccbce044cbd442be46
Neo-Teyrall/Mydock
/Langage/Python/Class/addition.py
745
3.765625
4
import sys import traceback class addition(): def __init__(self, new_x, new_y): self.x = new_x self.y = new_y pass def __add__(self,add): if not isinstance(add, addition) : traceback.print_stack() sys.exit("Error: is not addditon class. Addition Impossible ") return addition(self.x + add.x, self.y + add.y ) #def __mul__(self): #def __sub__(self): #def __mul__(self): #def __floodiv__(self): #def __truediv__(self): def __str__(self): return "({}, {})".format(self.x, self.y) if __name__ == "__main__" : a = addition(2,2) b = addition(4,4) print(a) print(b) a += b print(a) a += 1 # Erreur
b009e6a7cc2b0677d189606ea3af1d9bf31b8169
Abdulrahman-Adel/Data-structures-and-Algorithms-Udacity-ND
/Problems vs. Algorithms/Problem 2.py
2,148
3.90625
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 4 16:32:59 2020 @author: Abdelrahman """ def findPivot(arr, low, high): if high < low: return -1 if high == low: return low mid = (low + high) // 2 if mid < high and arr[mid] > arr[mid + 1]: return mid if mid > low and arr[mid] < arr[mid - 1]: return (mid-1) if arr[low] >= arr[mid]: return findPivot(arr, low, mid-1) return findPivot(arr, mid + 1, high) def binarySearch(arr, low, high, key): if high < low: return -1 mid = (low + high) // 2 if key == arr[mid]: return mid if key > arr[mid]: return binarySearch(arr, (mid + 1), high, key) return binarySearch(arr, low, (mid -1), key) def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array Args: input_list(array), number(int): Input array to search and the target Returns: int: Index or -1 """ pivot = findPivot(input_list, 0, len(input_list)-1); if pivot == -1: return binarySearch(input_list, 0, len(input_list)-1, number) if input_list[pivot] == number: return pivot if input_list[0] <= number: return binarySearch(input_list, 0, pivot-1, number) return binarySearch(input_list, pivot + 1, len(input_list)-1, number) def linear_search(input_list, number): for index, element in enumerate(input_list): if element == number: return index return -1 def test_function(test_case): input_list = test_case[0] number = test_case[1] if linear_search(input_list, number) == rotated_array_search(input_list, number): print("Pass") else: print("Fail") test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6]) test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1]) test_function([[6, 7, 8, 1, 2, 3, 4], 8]) test_function([[6, 7, 8, 1, 2, 3, 4], 1]) test_function([[6, 7, 8, 1, 2, 3, 4], 10])
731eb6bbc2c2c1f517a6a9f4e27f0f2e3b1b7b55
bebarrentine/AnytimeWeightedAStar
/a_star/breadth_first_search.py
1,862
3.625
4
from collections import deque from node import Node def breadth_first_search(problem=None): state_space = {} expanded = 0 queue = deque([Node( state=problem.initial_state, path_cost=0, parent=None )]) queue[0].in_frontier = True generated = 1 while queue: node = queue.popleft() node.in_frontier = False actions = problem.actions(node.state) for action in actions: child_state = problem.result(action=action, state=node.state) try: if node.parent.parent.state == child_state: continue except: None step_cost = problem.step_cost( from_state=node.state, action=action, to_state=child_state ) child_node = Node( parent=node, state=child_state, path_cost=node.path_cost + step_cost, action=action ) generated = generated + 1 if not(child_node.state in state_space): if problem.goal_test(child_node.state): solution = [] node = child_node try: while node.action: solution.append(node.action) node = node.parent except: None solution.reverse() return (solution, generated, expanded) else: queue.append(child_node) child_node.in_frontier = True state_space[child_node.state] = child_node expanded = expanded + 1 return (None, expanded, generated)
b2e3fa73a96045b226188e7c7011bd631b016793
adolfonovoa/nyd
/tres.py
436
3.828125
4
# -*- coding: utf8 -*- cant1= input('Digite la cantidad invertida de la primera persona') cant2= input('Digite la cantidad invertida de la segunda persona') cant3= input('Digite la cantidad invertida de la tercera persona') float(cant1) float(cant2) float(cant3) suma=cant1 + cant2 + cant3+ 0.0 porc1=(cant1/suma)*100 porc2=(cant2/suma)*100 porc3=(cant3/suma)*100 print('los porcentajes son :{0}%,{1}%,{2}%'.format(porc1,porc2,porc3))
c060f1b810089ce5de44ae978462260f3c43d488
janiszewskibartlomiej/Python-Postgraduate_studies_on_WSB
/10_2019/Part1_ex_GR2.py
5,409
3.5625
4
# -*- coding: utf-8 -*- #################### # PART 1 exercises # #################### #--- Exercise 1 ----- # a) Utwórz zmienną x i przypisz do niej wartość 3. # b) Utwórz zmienną y i przypisz do niej wartość 4.0. # c) Dodaj obie liczby. Jaki wynik otrzymasz? Jaki jest typ zmiennej wynikowej? x = 3 y = 4.0 z = x+y #otrzymam float 7.0 type(z) #--- Exercise 2 ----- # a) Utwórz zmienną x i przypisz do niej wartość 10.0 # b) Utwórz zmienną y i przypisz do niej wartość 4.0 # c) Odejmij od zmiennej x zmienną y. Jaki wynik otrzymasz? Jaki jest typ zmiennej wynikowej? x = 10.0 y = 4.0 z = x - y #otrzymam float 6.0 type(z) #--- Exercise 3 ----- # a) x = 3.0 # b) Zmień typ zmiennej x na int. x = 3.0 x = int(x) print(x, type(x)) #--- Exercise 4 ----- # a) x = 3 # b) zmień type zmiennej na str # c) Wydrukuj. Co otrzymasz? x = 3 x = str(x) print(x, type(x)) #--- Exercise 5 ----- # a. Utwórz zmienną x i przypisz do niej wartość 3. # b. Utwórz zmienną y i przypisz do niej wartość 3.0. # c. Co wydrukuje x==y? # d. Co wydrukuje x==y==True? Dlaczego? # e. Co wydrukuje x==y==False? Dlaczego? x = 3 y = 3.0 print(x==y) print(x==y==True) print(x==y==False) #--- Exercise 6 ----- # a. Utwórz zmienną x i przypisz do niej wartość 3. # b. Utwórz zmienną y i przypisz do niej wartość 3. # c. Utwórz zmienną z i przypisz do niej wartość wyniku operatora porównania zmiennej x i y. # d. Używając operatora porównania porównaj z oraz True. x = 3 y = 3 z = x==y print(z==True) #--- Exercise 7 ----- # a. Utwórz zmienną x i przypisz do niej tekst ”3” # b. Utwórz zmienną y i przypisz do niej tekst ”4” # c. Co wydrukuje x+y? x = "3" y = "4" print(x+y, type(x+y)) #--- Exercise 8 ----- # a. Utwórz zmienną x i przypisz do niej tekst ”3” # b. Utwórz zmienną y i przypisz do niej tekst ”4” # c. Dodaj x i y tak, by otrzymać wynik 7 i typ int. x = "3" y = "4" x, y = int(x), int(y) z = x + y print(z, type(z)) #--- Exercise 8 ----- # a. utwórz funkcję, która wydrukuje bilet poprzez połączenie imienia poniższych zmiennych. name = "Jan" surname = "Kowalski" def bilet(): x = print(name, surname) return x bilet() def moj(name, surname, sep = " "): bilet = name + sep + surname return bilet bilet(name=name, syrname = surname) #--- Exercise 9 ----- # Utwórz listę o nazwie my_list i dodaj do niej następujące elementy: 1, 3.1, ”a”, False. my_list = [] my_list = [1, 3.1, "a", False] dane = (1, 3.1, "a", False) for x in dane: my_list.append(x) print(my_list) #--- Exercise 10 ----- # Wydrukuj drugi element listy. my_list2 = [1,2,3] print(my_list2[1]) #--- Exercise 11 ----- #Wydrukuj liczbę elementów w liście my list2. len(my_list2) #--- Exercise 12 ----- # Wydrukuj pierwsze 3 elementy listy my_list2 print(my_list2[0:3]) #--- Exercise 13 ----- # Dołącz do list1 liste nr 2 nowa_lista = my_list + my_list2 nowa_lista += my_list2 print(nowa_lista) #--- Exercise 14 ----- # Ile elementów posiada lista? mylist3 = [[1,2], [3,4], [4,5]] len(mylist3) #--- Exercise 15 ----- # Policz sumę wartosci w pierwszej kolumnie input = [ [1,'asdf'], [3, 'dsf'], [5, 'dsf'], [4, 'dsf'], [9, 'dsf'], [33, 'dsf'], [23, 'dsf']] ## method 1 - with numpy import numpy as np input1 = np.array(input) x = input1[:, 0] np.sum(x.astype(int)) sum(x.astype(int)) np.sum(x) ## method 2 - basic method suma = 0 for x in input: suma += x[0] print(suma) ############################ import pandas as pd data_shops = [['Gdynia',100, 'Biedronka'], ['Gdansk',120, 'Biedronka'], ['Sopot',130, 'Lidl'], ['Gdynia',90, 'Lidl'], ['Gdansk',150, 'Kaufland'], ['Sopot', 200, 'Kaufland'], ['Gdansk', 160, 'Lidl'] ] df_shops = pd.DataFrame(data_shops, columns=['City','Sales', 'Shops']) #--- Exercise 16 ----- # Wybierz sklepy Lidl z ramki danych df_shops. # Choose Lidl show from df_shops data frame. lidl = [x for x in data_shops if x[2] == 'Lidl'] print(lidl) df_shops[df_shops['Shops'] == 'Lidl'] #--- Exercise 17 ----- # Sprawdz gdzie sprzedaz byla wieksza niz 150 (df_shops). # Check where sales is higher than 150 (df_shops). sell_150 = [x for x in data_shops if x[1] > 150] df_shops[df_shops['Sales'] > 150] #--- Exercise 18 ----- # Sprawdz w ktorych sklepach w Gdansku i Sopocie sprzedaz przewyzszyla kwote 140. (df_shops) # Check in what shops in Gdansk and Sopot sales is higher than 140. gd_sop = [x for x in data_shops if x[0] in ['Sopot', 'Gdynia'] and x[1]>140] df_shops[(df_shops['City'].isin(['Gdansk','Sopot'])) & (df_shops['Sales'] > 140) ] #--- Exercise 19 ----- # Wybierz wszystkie sklepy oprocz sopockich. # Choose all shops except Sopot. #~~ to jest negacja del_sop = [x for x in data_shops if x[0] != 'Sopot'] df_shops[df_shops['City'] != 'Sopot'] df_shops[~df_shops['City'].isin(['Sopot'])] #--- Exercise 20 ----- # Wybierz wszystkie sklepy Lidl w Gdansku i Sopocie, w ktorych sprzedaz byla wieksza niz 100 oraz mniejsza niz 210 # Choose all Lidl shops in Gdansk and Sopot where sales is higher than 100 and lower than 210. lidl_gd_sop_100 = [x for x in data_shops if x[0] in ['Gdansk','Sopot'] and x[2] == 'Lidl' and 210 > x[1] > 100] df_shops[(df_shops['City'].isin(['Gdansk','Sopot'])) & (df_shops['Shops'] == 'Lidl') & ((df_shops['Sales'] > 100) & (df_shops['Sales'] < 210)) ]
cc93e4274b39484bc9d7cf269b7d024405314eea
Aaron-Raphael/Problems-vs-Algorithms
/4_Problem.py
2,606
4.15625
4
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ traversal_ind = 0 lower_ind = 0 upper_ind = len(input_list) - 1 while traversal_ind <= upper_ind: if input_list[traversal_ind] == 2: input_list[traversal_ind], input_list[upper_ind] = input_list[upper_ind], input_list[traversal_ind] upper_ind -= 1 continue if input_list[traversal_ind] == 0: input_list[traversal_ind], input_list[lower_ind] = input_list[lower_ind], input_list[traversal_ind] lower_ind += 1 traversal_ind += 1 return input_list def test_function(test_case): sorted_array = sort_012(test_case) print(sorted_array) if sorted_array == sorted(test_case): print("Pass") else: print("Fail") test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1]) test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) #egde case: empty list test_function([]) # [] # Pass #egde case 2: a large reversed sorted list test_list=[2]*100+[1]*120+[0]*200 test_function(test_list) ''' [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] ''' # Pass
eb038c9f995a1d1561a6ebfc19a504a393ac4b5f
dankodak/Programmierkurs
/Abgaben/Blatt 6/Aufgabe 2/Team 48628/Thich_David_DavidThich_1761477/Aufgabe_6.2_b.py
718
3.765625
4
import time import numpy as np def time_it(func, m = 10): tstart = time.clock() for i in range(m): func() return (time.clock() - tstart) / m def numpy(A = np.ones((100,100))): C = np.dot(A, A) return C def matrix_multiplication(A = np.ones((100,100))): [I, J] = A.shape C = np.zeros((I, J)) for i in range(I): for j in range(J): C[i, j] = C[i, j] + A[i, j] * A[j, i] return C tnumpy = time_it(numpy) tmatrix_multiplication = time_it(matrix_multiplication) print("Time numpy:",tnumpy) print("Time matrix_multiplication:",tmatrix_multiplication) print("matrix_multiplication is",tnumpy/tmatrix_multiplication,"times faster than numpy!")
6c1c0fa6dc2a2f5a938cc06a87e5084a7138b111
Alex2Pena/data-structures-and-algorithms
/Python/code_challenges/array_reverse/array_reverse.py
185
3.609375
4
# res = arr[::-1] #reversing using list slicing # arr.reverse() #reversing using reverse() # result=list(reversed(arr)) # new_arr.reverse() # res_arr=array.array('i',reversed(new_arr))
02ab7a2647e2e95688519bdf9d89f1b07f0178fe
huhudaya/leetcode-
/剑指offer/面试题05. 替换空格.py
839
3.625
4
''' 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。   示例 1: 输入:s = "We are happy." 输出:"We%20are%20happy."   限制: 0 <= s 的长度 <= 10000 链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof ''' class Solution: def replaceSpace(self, s: str) -> str: s1 = [] # 设列表 for cha in s: # 遍历字符串 if cha == ' ': # 如果是空格,就在列表后面添加%20 s1.append('%20') else: # 如果不是空格,就在列表后面原样添加 s1.append(cha) return ''.join(s1) # 把列表转为str class Solution: def replaceSpace(self, s: str) -> str: return s.replace(' ', '%20')
71ce09395cfda02e35b0ea771874829d05c3e7d6
DivinGu0721/python
/2.7/test.py
449
3.828125
4
# -*- coding: UTF-8 -*- list = ['divin','teddy',01234,'abcde',666] minilist = ['abc',123 ] print list print minilist print "['"+ list[1]+"']" print list[1] print list[0:2] tinydict = {'name': 'john','code':6734, 'dept': 'sales','yes':'oh','no':'haha'} print tinydict.keys() print tinydict.values() print tinydict['yes'] tuple(list) minilist[1]='zbc' print minilist print list a = 21 b = 10 c = 0 c = a + b print "1 - c 的值为:", c print 123
9510f0c8bea151b6b1d666bb85a3ccf0fa01ed4a
nicholask98/Hangman
/main.py
3,694
3.96875
4
import random from os import system, name # import sleep to show output for some time period from time import sleep def clear(): # for windows if name == 'nt': _ = system('cls') # for mac and linux(here, os.name is 'posix') else: _ = system('clear') word_list = ['despite', 'complex', 'project', 'rejected', 'adventure', 'hidden', 'vacuum', 'friends', 'seniors', 'blanket', 'window', 'deadly', 'secret', 'horrible', 'contemporary', 'abrasive', 'orange', 'watermelon', 'curtain', 'dresser', 'cousin', 'cushion', 'family', 'convertible', 'pillow', 'sanctum', 'heaven', 'driving', 'automobile', 'relaxing'] play_again = 'y' while play_again == 'y': current_word = random.choice(word_list) guess_count = 13 clear() print('Welcome to Hangman! You have 13 guesses.\n') correct_guesses = '-' * len(current_word) incorrect_guesses = [] print(correct_guesses.upper()) user_letter = input('Enter a letter, take a full guess at the word, or "0" to quit:\n') while user_letter != '0': clear() while user_letter.isdigit() or not(user_letter.isalnum()): print("invalid entry.") sleep(.5) clear() print('Guesses Left: {}'.format(guess_count)) print(correct_guesses.upper()) print('Incorrect guesses: {}'.format(incorrect_guesses)) user_letter = input('Enter a letter, take a full guess at the word, or "0" to quit:\n') if user_letter == '0': break continue if user_letter == '0': break user_letter = user_letter.lower() if user_letter.lower() == current_word.lower(): print('You Win!') break if len(user_letter.lower()) > 1: guess_count -= 1 if len(user_letter) == 1: guess_count -= 1 if user_letter in current_word: num_occurances = current_word.count(user_letter) current_index = 0 for letter in range(num_occurances): if current_word.find(user_letter) != 0: current_index = current_word.find(user_letter, current_index + 1) correct_guesses = correct_guesses[:current_index] + user_letter + correct_guesses[current_index + 1:] elif user_letter not in current_word: incorrect_guesses.append(user_letter) if len(user_letter) == 0: print('invalid entry') sleep(.5) clear() print('Guesses Left: {}'.format(guess_count)) print(correct_guesses.upper()) print('Incorrect guesses: {}'.format(incorrect_guesses)) user_letter = input('Enter a letter, take a full guess at the word, or "0" to quit:\n') clear() continue if correct_guesses.find('-') == -1: print('You Win!') break elif guess_count == 0: print(correct_guesses.upper()) print('Incorrect guesses: {}'.format(incorrect_guesses)) print('You lose!') break clear() print('Guesses Left: {}'.format(guess_count)) print(correct_guesses.upper()) print('Incorrect guesses: {}'.format(incorrect_guesses)) user_letter = input('Enter a letter, take a full guess at the word, or "0" to quit:\n') print('The word was', current_word) play_again = 'n' if user_letter != '0': play_again = input('enter [y] to play again. Press anything else to quit.\n') print('Thanks for playing!')
7ce279f9b01b2168826b3280dd27bc62d483eaea
bingli8802/leetcode
/0017_Letter_Combinations_of_a_Phone_Number.py
922
3.515625
4
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ ''' 2 3 /|\ a b c /|\ d e f ''' def backTrack(i, tmp): if i == n: output.append(tmp) return # print dic[digits[i]] for letter in dic[digits[i]]: backTrack(i+1, tmp+letter) dic = {'2':['a','b','c'], '3':['d','e','f'], '4':['g','h','i'], '5':['j','k','l'], '6':['m','n','o'], '7':['p','q','r','s'], '8':['t','u','v'], '9':['w','x','y','z']} if not digits: return [] output = [] n = len(digits) backTrack(0,'') return output
ee3fbaa4b872c3d578464b8cce2cdc7b67e024f6
snaga/aind
/Lesson 03 Solving a Sudoku with AI/function.py
5,715
3.828125
4
# -*- coding: utf-8 -*- import sys from utils import * def eliminate_one(values, unit_keys, target): for k in unit_keys: if len(values[k]) == 1: # print("%s = %s" % (k, values[k])) target = target.replace(values[k], "") return target def get_rows_cols(k): if k[0] in 'ABC': r = 'ABC' if k[0] in 'DEF': r = 'DEF' if k[0] in 'GHI': r = 'GHI' if k[1] in '123': c = '123' if k[1] in '456': c = '456' if k[1] in '789': c = '789' return (r,c) def eliminate(values): """Eliminate values from peers of each box with a single value. Go through all the boxes, and whenever there is a box with a single value, eliminate this value from the set of values of all its peers. Args: values: Sudoku in dictionary form. Returns: Resulting Sudoku in dictionary form after eliminating values. """ values2 = values.copy() for k in sorted(values.keys()): row = k[0] col = k[1] # print("%s: %s" % (k, values[k])) if len(values[k]) == 1: continue # print("before: " + values[k]) values2[k] = eliminate_one(values, cross(row, "123456789"), values2[k]) values2[k] = eliminate_one(values, cross("ABCDEFGIH", col), values2[k]) r,c = get_rows_cols(k) # print(cross(r, c)) values2[k] = eliminate_one(values, cross(r, c), values2[k]) # print("after: " + values2[k]) return values2 def trace(s): if False: print (s) def only_choice(values): """Finalize all values that are the only choice for a unit. Go through all the units, and whenever there is a unit with a value that only fits in one box, assign the value to this box. Input: Sudoku in dictionary form. Output: Resulting Sudoku in dictionary form after filling in only choices. """ # TODO: Implement only choice strategy here values2 = values.copy() # display(values) peer_to_values = {} for box in sorted(values.keys()): trace("box: %s" % box) for unit in unitlist: # boxの属するunitを探す if box not in unit: continue trace("unit: %s" % unit) # unit内のpeerの状態を確認する value_to_peers = {} for peer in unit: trace("peer-values: %s => %s" % (peer, values[peer])) # peerがどの値を持ちうるかをdictにする(key:value、value:peer名のリスト) for value in values[peer]: if value not in value_to_peers: value_to_peers[value] = [] value_to_peers[value].append(peer) for value in value_to_peers: trace("value-peers: %s => %s" % (value, value_to_peers[value])) if len(value_to_peers[value]) == 1: peer = value_to_peers[value][0] trace("found: %s => %s" % (peer, value)) values2[peer] = value # display(values2) values = values2.copy() return values def reduce_puzzle(values): stalled = False while not stalled: # Check how many boxes have a determined value solved_values_before = len([box for box in values.keys() if len(values[box]) == 1]) # Your code here: Use the Eliminate Strategy values = eliminate(values) # Your code here: Use the Only Choice Strategy values = only_choice(values) # Check how many boxes have a determined value, to compare solved_values_after = len([box for box in values.keys() if len(values[box]) == 1]) # If no new values were added, stop the loop. stalled = solved_values_before == solved_values_after # Sanity check, return False if there is a box with zero available values: if len([box for box in values.keys() if len(values[box]) == 0]): return False return values reduce_puzzle_counter = 0 search_depth = 0 def search(values): global search_depth search_depth += 1 # print("search_depth: %d" % search_depth) "Using depth-first search and propagation, create a search tree and solve the sudoku." # First, reduce the puzzle using the previous function values = reduce_puzzle(values) if values is False: search_depth -= 1 return False if all(len(values[s]) == 1 for s in boxes): search_depth -= 1 return values # Choose one of the unfilled squares with the fewest possibilities # print("%s" % [(s, len(values[s])) for s in boxes if len(values[s]) > 1]) # n,s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1) s,n = min((s, len(values[s])) for s in boxes if len(values[s]) > 1) # print("n: %s, s: %s" % (n,s)) # Now use recursion to solve each one of the resulting sudokus, and if one returns a value (not False), return that answer! for value in values[s]: attempt_values = values.copy() attempt_values[s] = value attempt = search(attempt_values) if attempt: search_depth -= 1 return attempt # If you're stuck, see the solution.py tab! search_depth -= 1 return False if __name__ == '__main__': grid = "..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3.." # harder Sudoku grid = "4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......" print("start:") values = grid_values(grid) display(values) print("search:") values = search(values) display(values)
170e29d5b02b5c7135e284f58186108193cfaaa0
rehmanm/deep-learning
/assignments/assignment1/question4.py
228
3.921875
4
text = input("enter text:") listText = list(text) dictText = {} for str in listText: currentValue = dictText.get(str, 0) dictText[str] = currentValue + 1 for key, value in dictText.items(): print(key, ',', value)
6e8c2370967bd42d5eaae48d40c3052cf4403eec
Nooder/Cracking-Codes-With-Python
/Chapter 9 - PROGRAMMING A PROGRAM TO TEST YOUR PROGRAM/TranspositionEncrypt.py
1,205
4.21875
4
#! python3 # Chapter 7 Project - Transposition Cipher Encryption def main(): plaintext = "Common sense is not so common." key = 8 cipherText = encryptMessage(key, plaintext) print(cipherText) def encryptMessage(key, message): # Each string in ciphertext represents a column in the grid cipherText = [''] * key # Loop through each column in ciphertext for column in range(key): currentIndex = column # Keep looping until currentIndex goes past the message length while currentIndex < len(message): # Place the character at the currentIndex in message # at the end of the current column in the ciphertext list cipherText[column] += message[currentIndex] # Move currentIndex over currentIndex += key # Convert the ciphertext list in to a string to return it returnText = "".join(cipherText) return returnText # If TranspositionEncypt.py is run (instead of imported as a module) call the main() function: if __name__ == '__main__': main()
fe1c85aa8ee9f886561114598242a0f26c9e26d9
FeHeap/PythonPractice
/PyGamePractice/ObjectEncapsulation.py
1,256
3.53125
4
# -*- coding = utf-8 -*- # @Time: 2021/7/15 下午 05:21 # @Software: PyCharm import pygame import sys pygame.init() size = width , height = (400,600) pygame.display.set_caption("draw image") screen = pygame.display.set_mode(size) #設置圖像的幀數率 FPS = 60 clock = pygame.time.Clock() #定義玩家的類 class Player: def __init__(self): x,y = (width/2,height/2) self.image = pygame.image.load("Player.png") #self.rect = self.image.get_rect(top=200,left=200) #(0,0) self.rect = self.image.get_rect(center = (x,y)) def move(self): #self.rect.y -= 1 #self.rect = self.rect.move(0,-1) self.rect.move_ip(0,-2) #加載背景圖片 background = pygame.image.load("AnimatedStreet.png") #定義玩家對象 player = Player() while True: #繪製圖片 screen.blit(background,(0,0)) screen.blit(player.image,player.rect) player.move() #從事件隊列中取出事件對象,根據類型進行事件處理 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() pygame.display.update() clock.tick(FPS) #按照指定更新速率CLOCK來刷新畫面,沒到時間就讓循環等待
7fb24e6ccf89e75e16a642dd6758cd21dda204ad
akshaynagpal/python_snippets
/code snippets/remove_duplicates.py
531
3.984375
4
#function remove_duplicates takes in a list and removes elements of the list that are the same. def remove_duplicates(input_list): result = [] k = -1 for i in input_list: k += 1 flag = False for j in range(0,k,+1): if(input_list[j] == i): flag = True if(flag==False): result.append(i) else: continue return result """ ALTERNATE SOLUTION USING SETS def remove_duplicates(input_list): return list(set(input_list)) """
bb1b20a1fed7dfb75acae0324e2caf914d323c4a
manjuprasadshettyn/pythonprogramming
/ChineseZodiac.py
612
4.15625
4
# Chinese Zodiac sign is based on 12 year cycle and each year is represented by an animal. year= eval(input("Enter your birth year ")) sign=year%12 print("your Chinese Zodiac Sign is ") if sign==0 : print("Sheep") elif sign == 1 : print("Monkey") elif sign == 2 : print("Roaster") elif sign == 3 : print("Dog") elif sign == 4 : print("Pig") elif sign == 5 : print("Rat") elif sign == 6 : print("Ox") elif sign == 7 : print("Tiger") elif sign == 8 : print("Rabit") elif sign == 9 : print("Dragon") elif sign == 10 : print("Snake") elif sign == 11 : print("Horse") else : print("Invalid Input")
de8d4a940fb3c2098f2e4b6ff689f5a1a69e749f
mushamajay/PythonAssignments
/question8.py
345
4.21875
4
def maximum(numOne, numTwo): if numOne>numTwo: return numOne; else: return numTwo; numOne = float(input("Enter your first number: ")) numTwo = float(input("Enter your second number: ")) print("You entered: {} {} " .format(numOne,numTwo)) print("The larger of the two numbers is: {} " .format(maximum(numOne,numTwo)))
b806dd276b51f3552e9eeb6e100f2e34fda85854
soheil2017/Machine-Learning
/MatPlotlib/barchart.py
2,288
3.875
4
#https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py """ ============================= Grouped bar chart with labels ============================= Bar charts are useful for visualizing counts, or summary statistics with error bars. This example shows a ways to create a grouped bar chart with Matplotlib and also how to annotate bars with labels. """ import matplotlib import matplotlib.pyplot as plt import numpy as np men_means= (0.2, 0.3, 0.31, 0.16, 0.22) women_means = (0.18, 0.27, 0.21, 0.12, 0.19) ind = np.arange(len(men_means)) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(ind - width/2, men_means, width, label='Proposed') rects2 = ax.bar(ind + width/2, women_means, width, label='VI ORB-SLAM') # Add some text for labels, title and custom x-axis tick labels, etc. ax.set_ylabel('Error (m)') ax.set_xlabel('Distance Travelled (m)') #ax.set_xticks(ind) ax.set_xticklabels(('7.0', '14.0', '21.0', '28.0', '35.0', '42')) ax.legend() def autolabel(rects, xpos='center'): """ Attach a text label above each bar in *rects*, displaying its height. *xpos* indicates which side to place the text w.r.t. the center of the bar. It can be one of the following {'center', 'right', 'left'}. """ ha = {'center': 'center', 'right': 'left', 'left': 'right'} offset = {'center': 0, 'right': 1, 'left': -1} for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(offset[xpos]*3, 3), # use 3 points offset textcoords="offset points", # in both directions ha=ha[xpos], va='bottom') autolabel(rects1, "left") autolabel(rects2, "right") #plt.grid(True) fig.tight_layout() plt.show() ############################################################################# # # ------------ # # References # """""""""" # # The use of the following functions, methods and classes is shown # in this example: matplotlib.axes.Axes.bar matplotlib.pyplot.bar matplotlib.axes.Axes.annotate matplotlib.pyplot.annotate
89ba46d2ee7e5440ba54813b65a118487c218f05
chenfengrugao/pythontutorial
/day3/string_slice.py
402
3.984375
4
#!/usr/bin/python3 # slice # 1. a = 'hello world' b = a[0] c = a[10] print(b, c) # h d # 2. b = a[-1] c = a[-2] d = a[-3] print(b, c, d) # d l r # 3. b = a[0:3] c = a[1:3] print(b, c) # hel el # 4. b = a[:2] c = a[1:] d = a[:] print(b) # he print(c) # ello world print(d) # hello world # 5. b = a[::2] c = a[::-1] print(b) # hlowrd print(c) # dlrow olleh
7e582d3dd0f5fe807a4d92bc61f17000e49f725c
jdiaz-dev/practicing-python
/SECTION 0 more about python/python/15 Truthiness.py
1,327
4.28125
4
#Python uses the value None to indicate a nonexistent value. It is similar to other languages’ null: x = None assert x == None, "this is the not the Pythonic way to check for None" assert x is None, "this is the Pythonic way to check for None" """ * all these values is threaded as False by Python - False - None - [] (an empty list) - {} (an empty dict) - "" - set() - 0 - 0.0 """ def some_function_that_returns_a_string(): return s = some_function_that_returns_a_string() #in the conditional will be threated as false first_char = None print('-----first_char', first_char) if s: first_char = s[0] else: first_char = "" print('-----first_char', first_char) first_char = s and s[0] print('-----first_char', first_char) # --------------- using Truthiness # all() function, which takes an iterable and returns True precisely when every element is truthy # any() function, which returns True when at least one element is truthy res = all([True, 1, {3}]) # True, all are truthy print('-----res', res) res = all([True, 1, {}]) # False, {} is falsy print('-----res', res) res = any([True, 1, {}]) # True, True is truthy res = all([]) # True, no falsy elements in the list print('-----res', res) res = any([]) # False, no truthy elements in the list print('-----res', res)
1ed8baf3d400de35afa42694bc798b6442405d84
bluella/hackerrank-solutions-explained
/src/Greedy Algorithms/Luck Balance.py
1,891
4.0625
4
#!/usr/bin/env python3 """ https://www.hackerrank.com/challenges/luck-balance Lena is preparing for an important coding competition that is preceded by a number of sequential preliminary contests. Initially, her luck balance is 0. She believes in "saving luck", and wants to check her theory. Each contest is described by two integers, L[i] and T[i]: L[i] is the amount of luck associated with a contest. If Lena wins the contest, her luck balance will decrease by L[i]; if she loses it, her luck balance will increase by L[i]. T[i] denotes the contest's importance rating. It's equal to 1 if the contest is important, and it's equal to 0 if it's unimportant. If Lena loses no more than k important contests, what is the maximum amount of luck she can have after competing in all the preliminary contests? This value may be negative. """ import math import os import random import re import sys import heapq def luckBalance(max_lost_contests, contests): """ Args: max_lost_contests (int): how many contests could be lost contests (list): 2d array of integers Returns: int: max amount of luck""" most_luck = 0 important_contests = [] # if the contest is unimportant, then we loose it to increase luck balance for contest in contests: if contest[1] == 0: most_luck += contest[0] else: important_contests.append(contest[0]) # if the contest is important we pick the largest ones to loose most_luck += sum(heapq.nlargest(max_lost_contests, important_contests)) most_luck -= sum(heapq.nsmallest(len(important_contests) - max_lost_contests, important_contests)) return most_luck if __name__ == "__main__": ex_max_lost_contests = 2 ex_contests = [[3, 0], [2, 1], [5, 1]] result = luckBalance(ex_max_lost_contests, ex_contests) print(result)
d5da64d898cd3e1b27727e6bc7cf4a4eb37e6900
EdwaRen/Competitve-Programming
/Leetcode/202.happy-number.py
832
3.75
4
class Solution(object): def isHappy(self, n): # Calculate next num based off sum of squares of digits def next(num): happy = 0 while num > 0: digit = num % 10 happy += digit * digit num = int(num/10) return happy # Use the walker/runner method to detect a cycle walk = n run = next(n) if walk == run: return True # Loop until either walk or run hits 1, or a loop is detected # Same algorithm as in detecting a cyclical linkedlist while walk != run: if walk == 1 or run == 1: return True walk = next(walk) run = next(next(run)) return False z = Solution() n = 20 print(z.isHappy(n))
b1d4d0e8f69c05d6f91bf0b264720001750aa7ed
manojakumarpanda/This-is-first
/pattern/pyramid pattern.py
1,148
3.953125
4
#program for the reverse pyrmaid pattern for the alphabets '''for the four row patterns A B C D A B C A B A ''' row=int(input('Enter the number of row you want to print::')) for i in range(row): print(' '*i,end=' ') for j in range(row-i): print(chr(65+j),end=' ') print() #programs for the pyramid in the correct format in the "*" or the uper dimond shape ''' * * * * * * ''' r=int(input('Enter the value for the number of row you want in the pyramid::')) for i in range(r): print(' '*(r-i-1)+('* '*(i+1))) #program for the printing of the dimond shape pattern of the lower shape dimond shape r=int(input('Enter the nomber of the row you want to insert::')) for i in range(r): print(' '*i+'* '*(r-i)) ''' * * * * * * * * * * * * * * * * * * * * ''' #programming for the printing of the dimond pattern in star format n=int(input('Enter the number of row you want to print for the dimond pattern::')) #for the uper tringle for i in range(n): print(' '*(n-i-1)+'* '*(i+1)) #for the lower tringel for i in range(n): print(' '*i+'* '*(n-i))
d5b9d59ab6d0bdde9338bb39ead0e64c9ce77bc0
quanysq/study
/Python/MachineLearning/chapter24/scatter.py
716
3.734375
4
# 散点图显示成对数据集的可视化关系是比较好的 from matplotlib import pyplot as plt friends = [70,65,72,63,71,64,60,64,67] minutes = [175,170,205,120,220,130,105,145,190] labels = ['a','b','c','d','e','f','g','h','i'] plt.scatter(friends, minutes) #每个点加标记 for label, friend_count, minute_count in zip(labels, friends, minutes): plt.annotate(label, xy=(friend_count, minute_count), # 把标记放在对应的点上 xytext=(5, -5), # 但要有轻微偏离 textcoords='offset points') plt.title('Minutes and friends every day') plt.xlabel('friends') plt.ylabel('Minutes spent on the site') plt.show()
4e58b05699e8aabc60edc837ff3075113e3aa50e
GalCohen/GetStartedSnippets
/Python/lambda.py
320
3.84375
4
my_list = range(16) print filter(lambda x: x % 3 == 0, my_list) languages = ["HTML", "JavaScript", "Python", "Ruby"] print filter(lambda x: x == "Python", languages) squares = range(1, 11) squares = [x**2 for x in range(1,11) if (x**2 == x**2)] print squares print filter(lambda x: x > 30 and x < 70, squares)
7d2d4af8df9f967f4bf85ae363eea1d0f6c1d3c9
godwinreigh/web-dev-things
/programming projects/python projects/experiment/testing.py
95
3.671875
4
for n in range(10): print(n % 2) def my_func(n1, n2): return n1 + n2 my_func(1,2,3)
d2d8698c1a761dbde50bd05a2b8c7736e892edae
AmitBaanerjee/Data-Structures-Algo-Practise
/leetcode problems/994.py
1,827
3.5625
4
994. Rotting Oranges In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the value 1 representing a fresh orange; the value 2 representing a rotten orange. Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead. Example 1: Input: [[2,1,1],[1,1,0],[0,1,1]] Output: 4 Example 2: Input: [[2,1,1],[0,1,1],[1,0,1]] Output: -1 Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. Example 3: Input: [[0,2]] Output: 0 Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0. from collections import deque class Solution: def orangesRotting(self, grid: List[List[int]]) -> int: q=deque() for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]==2: q.append((i,j,0)) def neighbours(image,i,j): pairs=[] if i>0: pairs.append([i-1,j]) if i<len(image)-1: pairs.append([i+1,j]) if j>0: pairs.append([i,j-1]) if j<len(image[0])-1: pairs.append([i,j+1]) return pairs depth=0 while q: row,col,depth=q.popleft() for rr,cc in neighbours(grid,row,col): if grid[rr][cc]==1: grid[rr][cc]=2 q.append((rr,cc,depth+1)) for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]==1: return -1 return depth
1ccece800a90aa2bf90d39f04d01849ac42d1525
mubaarik/digitalCommunications
/PS1_audiocom/PS1.py
6,769
3.765625
4
import heapq import operator import sys from collections import defaultdict class HuffmanTree: # Huffman Trees always have a probability. For internal nodes, # symbol will be None, and left and right children will be # defined. For leaf nodes, symbol will *not* be None, but the # children will be. def __init__(self, symbol, probability): self.left_child = None self.right_child = None self.probability = probability self.symbol = symbol # "less than" method, for sorting trees def __lt__(self, other): return self.probability < other.probability def codebook(self, current_bitstring=""): # If we're at a leaf, return our symbol if self.left_child == None: book = {} book[self.symbol] = current_bitstring # Else, walk down the tree. Zeros on the left, ones on the right else: book = self.left_child.codebook(current_bitstring + "0") book1 = self.right_child.codebook(current_bitstring + "1") book.update(book1) # Merge the two dictionaries into one book return book # Input: # symbols, a list of (symbol, probability) tuples # Output: # codebook, which maps symbols to bitstrings def huffman(symbols): # Probabilities need to sum to 1 assert(sum([i for (_, i) in symbols]) >= .999999 and sum([i for (_, i) in symbols]) <= 1.000001) # Degenerate case: only one symbol to encode if len(symbols) == 1: return {symbols[0][0] : "0"} # Convert the list of symbols into a min-heap that sorts # HuffmanTrees instead of (symbol, probability) tuples min_heap = [] for item in symbols: h = HuffmanTree(item[0], item[1]) min_heap.append(h) heapq.heapify(min_heap) while len(min_heap) > 1: # Take the two smallest elements out a = heapq.heappop(min_heap) b = heapq.heappop(min_heap) # Create a new Huffman tree out of the two smallest elements c = HuffmanTree(None, a.probability + b.probability) c.left_child = a c.right_child = b heapq.heappush(min_heap, c) # Return the codebook return min_heap[0].codebook() ''' Calculate the probability of each symbol in data ''' def get_probabilities(data): # Count each element symbol_dict = defaultdict(int) for element in data: symbol_dict[element] += 1 # Turn counts into probabilities symbols = [] for element in symbol_dict: symbols.append((element, symbol_dict[element] / float(len(data)))) assert(sum([i for (_, i) in symbols]) >= .999999 and sum([i for (_, i) in symbols]) <= 1.000001) # probabilities sum to 1 return symbols '''Huffman source-encoding; symbols are calculated directly from the data if not otherwise given''' def huffman_encode(data, symbols=None): if symbols is None: symbols = get_probabilities(data) codebook = huffman(symbols) s = "" for c in data: s += codebook[c] return s '''Huffman decoding''' def huffman_decode(bits, codebook): reverse_codebook = {codebook[c] : c for c in codebook} output = "" j = "" for i in bits: j += str(i) if j in reverse_codebook: output += reverse_codebook[j] j = "" return output if __name__ == "__main__": import PS1_image filename = "PS1_fax_image.png" # 1. Individual bits bits = PS1_image.get_bits_from_bitmap(filename) num_bits = len(bits) print "Encoding 1: Individual bits" print " %d bits" % num_bits # 2. Fixed-length runs runs = PS1_image.get_run_lengths(filename, fixed_length=True) if len(runs) % 2 != 0: runs.append(0) num_bits = len(runs) * 8 print "Encoding 2: Fixed-length runs" print " %d runs" % len(runs) print " %d bits" % num_bits # 3. Huffman-encoded runs s = huffman_encode(runs) print "Encoding 3: Huffman-encoded runs\n %d bits" % len(s) # Get the probability of each run length run_probs = PS1_image.get_run_probabilities(runs) print " Top 10 run lengths [probability]:" for i in range(10): print " %d [%2.2f]" % (run_probs[i][0], run_probs[i][1]) # 4. Huffman-encoded runs, separate colors white_runs = [runs[i] for i in range(len(runs)) if i % 2 == 0] black_runs = [runs[i] for i in range(len(runs)) if i % 2 == 1] white_string = huffman_encode(white_runs) black_string = huffman_encode(black_runs) print "Encoding 4: Huffman-encoded runs by color\n %d bits" % (len(white_string) + len(black_string)) # Get the probabilities of the run lengths white_run_probs = PS1_image.get_run_probabilities(white_runs) print " Top 10 white run lengths [probability]:" for i in range(10): print " %d [%2.2f]" % (white_run_probs[i][0], white_run_probs[i][1]) black_run_probs = PS1_image.get_run_probabilities(black_runs) print " Top 10 black run lengths [probability]:" for i in range(10): print " %d [%2.2f]" % (black_run_probs[i][0], black_run_probs[i][1]) # 5. Huffman-encoded runs, allow pairs paired_runs = [(runs[i], runs[i+1]) for i in range(0, len(runs), 2)] s = huffman_encode(paired_runs) print "Encoding 5: Huffman-encoded run pairs\n %d bits" % len(s) # Get the probabilities run_probs = PS1_image.get_run_probabilities(paired_runs) print " Top 10 run lengths [probability]:" for i in range(10): print " %s [%2.2f]" % (run_probs[i][0], run_probs[i][1]) # 6. Huffman-encoded blocks blocks = PS1_image.get_image_blocks(filename) s = huffman_encode(blocks) print "Encoding 6: Huffman-encoded 4x4 image blocks\n %d bits" % len(s) # Get the probabilities run_probs = PS1_image.get_run_probabilities(blocks) print " Top 10 4x4 blocks [probability]:" for i in range(10): print " %s [%2.2f]" % (hex(run_probs[i][0])[:-1], run_probs[i][1]) # 7. Run-length encoding on a different image runs_v = PS1_image.get_run_lengths("PS1_voyager.png", fixed_length=True) if len(runs) % 2 != 0: runs_v.append(0) # For any run lengths that don't exist, we'll assume a probability # of zero. p = get_probabilities(runs) x = [i for (i, j) in p] for i in range(0, 256): if i not in x: p.append((i, 0.0)) s = huffman_encode(runs_v, symbols=p) print "Final experiment: Huffman-encoded runs on a different image" print " Using probabilities calculated from previous image: %d bits" % len(s) s = huffman_encode(runs_v) print " Using probabilities calculated from source image: %d bits" % len(s)
b98ef0c1c6521511be2a762d914cd99994abe783
bdabrowski/simple-calculator
/operators.py
1,674
4.0625
4
# -*- coding: utf-8 -*- from __future__ import unicode_literals # Add operators here class Operator(object): """ Interface for operators. Operator must be only one char long. """ sign = None def __init__(self): if not self.sign: raise Exception('Operator sign is missing.') if len(self.sign) != 1: raise Exception('Operator sign must be 1 char long.') try: float(self.sign) raise Exception('Operator cannot be a number.') except ValueError: pass def calculate(self, first_number, second_number): pass class Add(Operator): """ Operator responsible for adding """ sign = '+' def calculate(self, first_number, second_number): """ Return sum of two numbers. """ return first_number + second_number class Subtract(Operator): """ Operator responsible for subtracting. """ sign = '-' def calculate(self, first_number, second_number): """ Return distinction of two numbers. """ return first_number - second_number class Multiple(Operator): """ Operator responsible for multiplication. """ sign = '*' def calculate(self, first_number, second_number): """ Return product of two numbers. """ return first_number * second_number class Divide(Operator): """ Operator responsible for dividing. """ sign = '/' def calculate(self, first_number, second_number): """ Return quotient of two numbers. """ return first_number / second_number
21e9cf1d19e7e6d0be9ebc60688a6550908e7779
linuxmahara/generative_art-1
/ball_animations/ball_collisions/02_colliding.py
1,497
3.671875
4
""" This is one script in a series. In 01.. we have the ability to launch a set of balls inside a confined Box Note: This requires that the file ball.py (rename 01ball.py to ball.py) to be in the same folder Author: Ram Narasimhan August 2020 """ from ball import Ball import colors w, h = 600, 600 radius = 10 num_balls = 5 num_active = 0 launch_gap = num_balls * 2 balls = [] for id in range(num_balls): balls.append( Ball( id, 0, int(random(h)), 1 + int(random(3)), 2 + int(random(4)), _radius=radius, ) ) balls.append( Ball( num_balls + id, int(random(h)), 0, 2 + int(random(3)), 1 + int(random(5)), _radius=radius, ) ) def setup(): size(w, h) background(127) smooth() noStroke() frameRate(30) def draw(): global balls, num_active background(127) # when to launch? Waits for a "launch_gap" number of frames before it launches # the next ball if num_active < num_balls * 2: if not frameCount % (launch_gap): balls[num_active].active = True # launch one more ball num_active += 1 # move each ball and show it on the screen for b in balls: if b.active: b.move() b.display() b.collide(balls) saveFrame("images/coll_###.jpg") if frameCount > 600: noLoop()
112f44cb5083c63580ec76da625f1e21abf73a33
antdevelopment1/python104
/guess_the_number_play_again.py
1,190
4.03125
4
import random random_num = 5 #random.randint(1, 10) print("I am thinking of a number between 1 and 10. ") user_input = int(input("Please guess a number? ")) correct_guess = False limit_guess = 3 while correct_guess == False: if user_input == random_num: print("Yay you won!!!") ask_to_play = input("Would you like to play again? Y/N").lower() if ask_to_play == "y": user_input = int(input("Please guess a number? ")) elif ask_to_play == "n": print("Thanks for playing.") correct_guess = True elif user_input != random_num: limit_guess -= 1 print("No you have %d turns left" % limit_guess) if limit_guess > 0: user_input = int(input("Please guess a number? ")) elif limit_guess == 0: print("Sorry you lost the game!!!") ask_to_play = input("Would you like to play again? Y/N").lower() if ask_to_play == "y": limit_guess = 3 user_input = int(input("Please guess a number? ")) elif ask_to_play == "n": print("Thanks for playing.") correct_guess = True
dbb91480afda7a8677176783a4f109732bd01f64
t734070824/tq.python
/tq.python/study/_web/1_basic/if_else.py
396
4.25
4
age=14 if age >= 18: print("your age is : ", age) print("adult") else: print("gag") print("teenager") age=4 age=4 if age >= 18: print("your age is : ", age) print("adult") elif age > 6: print("gag") print("teenager") else: print("123") print("--------------") birth = input("birth: ") birth=int(birth) if birth > 20: print(123) else: print("123123")
8116a960cad6118f63bd882d01d40d55cdffea7d
Shasaravana/programs
/lenofarr.py
153
3.828125
4
#Length of the array def lenofarr(arr): count=0 for _ in arr: count+=1 return count arr=[1,2,3,4,5,6] print(lenofarr(arr))
8d3c3d87ce24f3db07732f0c357078b6b6e84853
tartofour/python-IESN-1BQ2-TIR
/projet.py
21,672
3.671875
4
# -*- coding: utf-8 -*- # TODO: # # - Règles du jeu # - Change keybind import random import datetime class Menu: separation_template = ("------------------------------------------------") def __init__(self, score_file="data.txt", game=None): self._score_file = score_file self._game = game def start_menu(self): launched_menu = 1 while launched_menu: self.display_menu() try : user_input = input("Votre choix : ") assert user_input.lower() in ["1","2","q"] except AssertionError: print("Commande inconnue !") print(self.separation_template) if user_input == "1": self.setup_game() self._game.play() elif user_input == "2": self.display_scores() elif user_input.lower() == "q": print(self.separation_template) print("################## AU REVOIR ! #################") print(self.separation_template) launched_menu = 0 def choose_difficulty(self): while 1: try: print(self.separation_template) difficulty = input("Choisissez un niveau de difficulté (1-2-3) : ") assert difficulty in ["1","2","3"] return int(difficulty) except AssertionError: print("Commande inconnue !") def create_player(self): while 1: try: print(self.separation_template) player_name = input("Entrez votre nom : ") assert len(player_name) >= 5 and len(player_name) <= 12 player = Player(player_name) return player except AssertionError: print("Votre nom doit être composé de 5 à 12 caractères.") def setup_game(self): difficulty = self.choose_difficulty() player = self.create_player() game = Game(player, difficulty) game.create_enclosure_wall() player.position = game.random_legal_position self._game = game def display_menu(self): print(self.separation_template) print("##################### MENU #####################") print(self.separation_template) print("1. Lancer une partie") print("2. Afficher le tableau des scores") print("Q. Quitter le programme") print(self.separation_template) def display_scores(self): players_scores = {} try: with open(self._score_file, "r") as file: print(self.separation_template) print("############## TABLEAU DES SCORES ##############") print(self.separation_template) for line in file : if line != "\n": elements = line.rstrip('\n').split(":") player_name = elements[0] score = int(elements[1]) if player_name not in players_scores: players_scores[player_name] = score elif score > players_scores[player_name]: players_scores[player_name] = score #Triage du dictionnaire (descendant) en fonction du score de chaque joueur sorted_players_scores = dict(sorted(players_scores.items(), key=lambda x: x[1], reverse=True)) # Affiche chaque ligne du classement print("Voici le classement des joueurs : \n") for i, player_score in enumerate(sorted_players_scores, 1): print(i,"-", player_score, ":", sorted_players_scores[player_score]) except FileNotFoundError: print("Aucun fichier de sauvegarde trouvé.") class Game: def __init__(self, player, difficulty=1, game_state=1, items=None, zombies=None, walls=None): self._player = player self._difficulty = difficulty self._items = items or [] self._zombies = zombies or [] self._game_state = game_state def __str__(self): return "Partie de niveau " + str(self._difficulty) + ". Jouée par " + \ self._player.name + "." ### getters & setters @property def player(self): return self._player @property def difficulty(self): return self._difficulty @difficulty.setter def difficulty(self, new_difficulty): self._difficulty = new_difficulty @property def items(self): return self._items @items.setter def items(self, new_items): self._items = new_items @property def zombies(self): return self._zombies @zombies.setter def zombies(self, new_zombies): self._zombies = new_zombies @property def game_state(self): return self._game_state @game_state.setter def game_state(self, new_game_state): self._game_state = new_game_state @property def walls(self): return self._walls @walls.setter def walls(self, new_walls): self._walls = new_walls @property # À enlever def starting_time(self): return _starting_time ##### methods ##### @property def board_size(self): #return 24 // self._difficulty return 24 @property def zombies_position(self): zombies_position = [] hunters_position = [] for zombie in self._zombies: if type(zombie) == Zombie: zombies_position.append(zombie._position) elif type(zombie) == Hunter: hunters_position.append(zombie._position) return {"zombies" : zombies_position, \ "hunters" : hunters_position} @property def items_position(self): teleporters_positions = [] candies_position = [] traps_position = [] walls_position = [] for item in self._items: if type(item) == Teleporter: teleporters_positions.append(item.position) teleporters_positions.append(item.destination) elif type(item) == Candy: candies_position.append(item.position) elif type(item) == Trap: traps_position.append(item.position) elif type(item) == Wall: walls_position.append(item.position) return {"teleporters" : teleporters_positions, \ "candies" : candies_position, \ "traps" : traps_position, \ "walls" : walls_position} @property def free_positions(self): free_positions = [] for line in range(self.board_size): for col in range(self.board_size): free_positions.append((line,col)) for item_type in self.items_position: for item_position in self.items_position[item_type]: if item_position in free_positions: free_positions.remove(item_position) for zombie_type in self.zombies_position: for zombie_position in self.zombies_position[zombie_type]: if zombie_position in free_positions: free_positions.remove(zombie_position) return free_positions @property def random_legal_position(self): return random.choice(self.free_positions) # Dessine le plateau def draw(self): for line in range(self.board_size): for col in range(self.board_size): if (line,col) == self.player.position : print(Player.symbol,end=" ") elif (line,col) in self.zombies_position["hunters"]: print(Hunter.symbol,end=" ") elif (line,col) in self.zombies_position["zombies"]: print(Zombie.symbol,end=" ") elif (line,col) in self.items_position["walls"]: print(Wall.symbol,end=" ") elif (line,col) in self.items_position["candies"]: print(Candy.symbol,end=" ") elif (line,col) in self.items_position["teleporters"]: print(Teleporter.symbol,end=" ") elif (line,col) in self.items_position["traps"]: print(Trap.symbol,end=" ") else : print(".",end=" ") print() print(Menu.separation_template) # Fait apparaitre un item def pop_items(self): if random.randint(1, self._difficulty*3) == 3 : new_teleporter_positions = self.random_legal_position, self.random_legal_position new_teleporter = Teleporter(new_teleporter_positions[0], new_teleporter_positions[1]) self._items.append(new_teleporter) if random.randint(self._difficulty, 3) == 3 : new_trap_position = self.random_legal_position new_trap = Trap(new_trap_position) self._items.append(new_trap) if random.randint(self._difficulty, 3) == 3 : new_candy_position = self.random_legal_position new_candy = Candy(new_candy_position) self._items.append(new_candy) def pop_zombies(self): if random.randint(self._difficulty, 3) == 3 : new_zombie_position = self.random_legal_position new_zombie = Zombie(new_zombie_position) self._zombies.append(new_zombie) if random.randint(self._difficulty*2, 12) == 12 : new_hunter_position = self.random_legal_position new_hunter = Hunter(new_hunter_position) self._zombies.append(new_hunter) def create_enclosure_wall(self): for line in range(self.board_size): self.pop_wall((line, 0)) self.pop_wall((line, self.board_size-1)) for col in range(0,self.board_size): self.pop_wall((0, col)) self.pop_wall((self.board_size-1, col)) def pop_wall(self, position): if position in self.free_positions: new_wall = Wall(position) self._items.append(new_wall) # Regarde s'il y a un ou plusieurs items sur la position du joueur def check_items(self): for item in self._items: if type(item) == Teleporter and ((item.position == self._player.position) or\ (item.destination == self._player.position)): # beurk item.teleport_player(self._player) if item.position == self._player.position : if type(item) == Candy: item.score_increment(self._player) self._items.remove(item) if type(item) == Trap: item.inflict_damage(self._player) self._items.remove(item) # regarde s'il y a un zombie sur la position du joueur def check_zombies(self): for zombie in self._zombies: if zombie._position == self.player.position : zombie.inflict_damage(self._player) self._zombies.remove(zombie) def is_position_walled(self, position): return position in self.items_position["walls"] # Joue un tour complet def play_turn(self): self.display_player_hud() self.draw() # Action du joueur old_position = self._player.position self._player.move(self) if self.is_position_walled(self._player.position): self._player.position = old_position # Déplacement des zombies for enemy in self._zombies: if type(enemy) == Hunter: enemy.move_towards_player(self._player) else: old_enemy_position = enemy.position free_positions = self.free_positions enemy.move() if enemy.position not in free_positions: enemy.position = old_enemy_position # Check des collisions self.check_zombies() self.check_items() # Pop items et zombies self.pop_items() self.pop_zombies() def pause_menu(self): print(Menu.separation_template) print("##################### PAUSE #####################") print(Menu.separation_template) while 1: try: user_input = input("Appuyez sur \"p\" pour continuer : ") assert user_input == "p" print(Menu.separation_template) return 0 except AssertionError: print("Commande inconnue !") print(Menu.separation_template) def display_help(self): print("------------------------------------------------") print("Bienvenue dans le menu aide !\n") print("Vous trouverez ici les commandes permettant d'intéragir avec le jeu. Vous trouverez également une légende des différents objets et zombies.\n") print("ASSIGNATION DES TOUCHES :") for command in Player.keyboard_keys: if Player.keyboard_keys[command] == (-1, 0): print(" -", command, ": Haut") elif Player.keyboard_keys[command] == (1, 0): print(" -", command, ": Bas") elif Player.keyboard_keys[command] == (0, -1): print(" -", command, ": Gauche") elif Player.keyboard_keys[command] == (0, 1): print(" -", command, ": Droite") elif Player.keyboard_keys[command] == "help": print(" -", command, ": Help") elif Player.keyboard_keys[command] == "pause": print(" -", command, ": Pause") print() print("REPRÉSENTATION DES ZOMBIES :") print(" -", Zombie.symbol, ": Zombies") print(" -", Hunter.symbol, ": Chasseurs volants") print() print("REPRÉSENTATION DES OBJETS") print(" -", Teleporter.symbol, ": Téléporteurs") print(" -", Trap.symbol, ": Pièges") print(" -", Candy.symbol, ": Bonbons") print(" -", Wall.symbol, ": Murs") print() print("ASTUCE") print(" - Si vous êtes poursuivit par des chasseurs volants, entrez dans un téléporteur !") self._player.pause_game(self) # Joue une partie complète def play(self): print(Menu.separation_template) print("############# DÉBUT DE LA PARTIE ###############") print(Menu.separation_template) print(self) end = self.end_time(1,0) now = datetime.datetime.today() while now < end : if self._game_state == 0: start_pause_date = datetime.datetime.today() self.pause_menu() end_pause_date = datetime.datetime.today() delta_pause = end_pause_date - start_pause_date end += delta_pause self._player.resume_game(self) else: self.play_turn() now = datetime.datetime.today() print("################ PARTIE TERMINÉE ###############") print(Menu.separation_template) # Enregistrement ou non du score du joueur if self._player.score > 0 : print("Félicitation {}, votre score est de : {}".format(self.player.name,self.player.score)) self.save_score() else: print("Votre score est de {}. Réessayez ;-)".format(self.player.score)) def save_score(self): with open("data.txt", "a") as scores: scores.write(self._player.name + ":" + str(self._player.score) + "\n") def display_player_hud(self): print(Menu.separation_template) print(self._player) print(Menu.separation_template) @staticmethod # retourne le moment où le jeu est censé être fini def end_time(delta_minute, delta_second): delta = datetime.timedelta(minutes=delta_minute, seconds=delta_second) end = datetime.datetime.today() + delta return end class Player: keyboard_keys = {'z':(-1,0),\ 's':(1,0),\ 'q':(0,-1),\ 'd':(0,1),\ 'p':"pause",\ 'h':"help"} symbol = "P" def __init__(self, name, position=(0,0), score=0): self._name = name self._position = position self._score = score def __str__(self): position_line, position_col = self._position return "Position de " + self._name + ": (Ligne : " + str(position_line) + \ ", " + "Colone : " + str(position_col) + ")\n" + "Score : " + \ str(self._score) ### getters & setters @property def name(self): return self._name @name.setter def name(self, new_name): self._name = new_name @property def position(self): return self._position @position.setter def position(self, new_position): self._position = new_position @property def score(self): return self._score @score.setter def score(self, new_score): self._score = new_score #methods def move(self, game) : try: key = input("Déplacez-vous (\"h\" pour afficher l'aide) : ") assert key in Player.keyboard_keys.keys() except AssertionError: print("Commande inconnue !") print(Menu.separation_template) else: # ??? pause_binding = list(Player.keyboard_keys.keys())[list(Player.keyboard_keys.values()).index("pause")] # beurk help_binding = list(Player.keyboard_keys.keys())[list(Player.keyboard_keys.values()).index("help")] if key == pause_binding: self.pause_game(game) elif key == help_binding: self.pause_game(game) # ????? game.display_help() else: move = Player.keyboard_keys[key] self._position = (self._position[0] + move[0], self._position[1] + move[1]) #def change_keybing(self): def pause_game(self, game): game.game_state = 0 def resume_game(self, game): game.game_state = 1 class Item : symbol = "I" def __init__(self, position): self._position = position @property def position(self): return self._position @position.setter def position(self, new_position): self._position = new_position class Teleporter(Item): symbol = "O" def __init__(self, position, destination): super().__init__(position) self._destination = destination @property def destination(self): return self._destination @destination.setter def destination(self, new_destination): self._destination = new_destination print(Menu.separation_template) def teleport_player(self, player): if player.position == self._position: player.position = self._destination elif player.position == self._destination: player.position = self._position class Trap(Item): symbol="X" def __init__(self, position, damage=5): super().__init__(position) self._damage = damage @property def damage(self): return self._damage @damage.setter def damage(self, new_damage): self._damage = new_damage def inflict_damage(self, player): player.score -= self._damage class Candy(Item): symbol="*" def __init__(self, position, value=5): super().__init__(position) self._value = value @property def value(self): return self._value @value.setter def value(self, new_value): self._value = new_value def score_increment(self, player): player.score += self._value class Wall(Item): symbol="#" def __init__(self, position): super().__init__(position) class Zombie: symbol="Z" move_set = {"up" : (-1,0),\ "down" : (0,-1),\ "left" : (1,0),\ "right" : (0,1)} def __init__(self, position, damage=10) : self._position = position self._damage = damage @property def damage(self): return self._damage @property def position(self): return self._position @position.setter def position(self, new_position): self._position = new_position #methods def move(self): zombie_line, zombie_col = self._position zombie_move = Zombie.move_set[random.choice(list(Zombie.move_set.keys()))] self._position = (zombie_line + zombie_move[0], zombie_col + zombie_move[1]) def inflict_damage(self, player): player.score -= self._damage class Hunter(Zombie): symbol="H" def __init__(self, position, damage=15): super().__init__(position, damage) self._damage = damage def move_towards_player(self, player): hunter_line, hunter_col = self._position player_line, player_col = player.position # Mouvement de ligne if hunter_line > player_line: hunter_line -= 1 elif hunter_line < player_line: hunter_line += 1 # Mouvement de colone elif hunter_col > player_col: hunter_col -= 1 elif hunter_col < player_col: hunter_col += 1 self._position = hunter_line, hunter_col if __name__ == "__main__" : m = Menu() m.start_menu()
749d348c13e4178941cd30f69d2f1d1c35886b04
pmosko/JetBrains-Academy
/Password Hacker/stage2.py
928
3.5
4
import argparse import socket from string import ascii_lowercase, digits from itertools import combinations_with_replacement def connect(args): with socket.socket() as sock: sock.connect((args.hostname, args.port)) for length in range(1, 30): for letters in combinations_with_replacement(ascii_lowercase + digits, length): pwd = ''.join(letters) sock.send(pwd.encode()) response = sock.recv(1024).decode("utf-8") if 'Wrong password!' in response: continue if 'Connection success!' in response: print(pwd) return elif 'Too many attempts' in response: return parser = argparse.ArgumentParser() parser.add_argument('hostname') parser.add_argument('port', type=int) connect(parser.parse_args())
768b5e12f909d9712cdba3c9c15813ac56f95a66
MauGarrido/hyperblog
/codigo Python/funciones.py
476
3.921875
4
#def func(): #print ("ola ke ase?") #func() #func() def conversacion (mensaje): print ("Hola") print ("¿Cómo estás?") print (mensaje) opcion = int(input("Elige una opción (1, 2, 3) ")) if opcion == 1 : conversacion ("Elegiste la opción 1") elif opcion == 2: conversacion ("Elegiste la opción 2") elif opcion == 3 : conversacion ("Elegiste la opción 3") else: print ("Lo siento, elige una opción válida")
3f95aadd808720f3beb7519263bcc7400db0adb2
mlinkon/ml101
/VisualaizeDecisionTree/VisualizeIrisFlowerDataSet.py
2,185
3.640625
4
#Iris Flower DataSet [Wikipedia link : https://en.wikipedia.org/wiki/Iris_flower_data_set ] import numpy as np import graphviz from sklearn import tree from sklearn.datasets import load_iris iris = load_iris() print(iris.feature_names) #prints list of features in dataset print(iris.target_names) #prints all distinct flower names in dataset print(iris.data[0]) #prints first record in dataset. Format : [sepal length(cm) sepal Width(cm) petal length(cm) petal width(cm)] print(iris.target[100]) #prints the target value which is label. Output 0:setosa 1:versicolor 2:virginica for i in range(len(iris.target)): print("Example {0} : label {1}, feature {2}".format(i, iris.target[i], iris.data[i])) #Testing Data - For testing remove one example of each type of flower #train_* variable will have majority of data and test_* variable will have only deleted data #Step 1 : Delete data test_index = [0,50,100] train_target = np.delete(iris.target,test_index) train_data = np.delete(iris.data,test_index,axis=0) #Step 2 : Train Data test_target = iris.target[test_index] test_data = iris.data[test_index] #Step 3 : Creating Decision tree clf = tree.DecisionTreeClassifier() clf.fit(train_data,train_target) #train on training data, pass features and labels in fit method print("expected output : {0}".format(test_target)) print ("decision tree output : {0}".format(clf.predict(test_data))) #Visualize the decision tree from sklearn.externals.six import StringIO import pydotplus #using pydotplus in windows10, python 3.6.X dot_data = StringIO() tree.export_graphviz(clf, out_file=dot_data, feature_names=iris.feature_names, class_names=iris.target_names, filled=True, rounded=True, special_characters=True) graph = pydotplus.graph_from_dot_data(dot_data.getvalue()) graph.write_pdf("iris.pdf") #outputs pdf file with decision tree diagram #for verification of output from iris.pdf decision path print(iris.feature_names,iris.target_names) print(test_data[1], test_target[1]) print(test_data[2], test_target[2]) print(test_data[0], test_target[0])
368f7bcfb356ce071570e6242938b173df5d79ca
Aniket121397/Python
/Python/loops and even odd func/count_EVEN_ODD.py
196
3.875
4
A=[23,54,22,98,45,65,37,31,82,64] even=0 odd=0 for x in A: if x%2==0: even +=1 else: odd +=1 print("There are:",even,"even numbers") print("There are:",odd,"odd numbers")
08271853fed13e9073f51705e17ee74003c9f0af
frnhsn/2048
/2048.py
4,000
3.765625
4
# At the moment, this code contain games logic only. This basically just an # excersie for me in building an algortihm and practicing OOP. I'll create GUI # version for further development # For playing the games you could create an object which inherited games() class # e.g # play = games() # play.up() import numpy as np # This games() class contain games logic. It produce an array, called arr, that # can be access by calling games.arr. Some method could be called for altering # the value of games.arr. The games movements (up, down, left, right) are # basically the same so it could be done in two functions (lining_up and merge) # but with additional flips and transpose to the array. class games(): # This function defining number of tiles, set score to zero, create zero arr def __init__ (self): self.tiles = [4, 4] self.score = 0 self.arr = np.array([[0] * self.tiles[0]] * self.tiles[1]) self.prev = self.arr self.generateRandom() self.status = 'not over' print(self.arr) # This function set status to over if there is no zero element in arr def check_status(self): if np.all(self.arr == 0) == False: self.status = 'over' # This function reset the games def reset(self): self.__init__() # This function generates two or for into random zero element of arr def generateRandom(self): zero_id = np.argwhere(self.arr == 0) if zero_id.size != 0: id = zero_id[np.random.randint(len(zero_id))] self.arr[id[0]][id[1]] = np.random.choice([2, 4]) # This function merge two element with same number def merge(self): n_row, n_col = self.arr.shape for col in range(n_col): for row in range(n_row - 1): if self.arr[row + 1][col] == self.arr[row][col] and\ self.arr[row][col] != 0: self.arr[row][col] = self.arr[row][col] * 2 self.arr[row + 1][col] = 0 self.score = self.score + self.arr[row][col] # This function lining up non zero elements of arr to the top def lining_up(self): n_row, n_col = self.arr.shape new = np.array([[0] * n_col] * n_row) for col in range(n_col): idx = 0 for row in range(n_row): if self.arr[row][col] != 0: new[idx][col] = self.arr[row][col] idx = idx + 1 self.arr = new def up(self): self.lining_up() self.merge() self.lining_up() if np.all(self.arr == self.prev) == False: self.generateRandom() self.prev = self.arr print(self.arr) def down(self): self.arr = np.flip(self.arr, 0) self.lining_up() self.merge() self.lining_up() self.arr = np.flip(self.arr, 0) if np.all(self.arr == self.prev) == False: self.generateRandom() self.prev = self.arr print(self.arr) def left(self): self.arr = np.transpose(self.arr) self.lining_up() self.merge() self.lining_up() self.arr = np.transpose(self.arr) if np.all(self.arr == self.prev) == False: self.generateRandom() self.prev = self.arr print(self.arr) def right(self): self.arr = np.transpose(self.arr) self.arr = np.flip(self.arr, 0) self.lining_up() self.merge() self.lining_up() self.arr = np.flip(self.arr, 0) self.arr = np.transpose(self.arr) if np.all(self.arr == self.prev) == False: self.generateRandom() self.prev = self.arr print(self.arr)
b8f99521d38cc11e72da72d45d675b7c49d9abde
C109156212/python
/18.py
1,690
3.5625
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 13 19:09:25 2021 @author: 123 """ a = int(input("測試的資料量")) for i in range (0,a): x = input("輸入血型").split(" ") if x[0]=="O" and x[1]=="O" and x[2]=="O": print("YES") elif x[0]=="O" and x[1]=="A" and (x[2]=="O" or x[2]=="A"): print("YES") elif x[0]=="A" and x[1]=="O" and (x[2]=="O" or x[2]=="A"): print("YES") elif x[0]=="O" and x[1]=="B" and (x[2]=="B" or x[2]=="O"): print("YES") elif x[0]=="B" and x[1]=="O" and (x[2]=="B" or x[2]=="O"): print("YES") elif x[0]=="O" and x[1]=="AB" and (x[2]=="A" or x[2]=="B"): print("YES") elif x[0]=="AB" and x[1]=="O" and (x[2]=="A" or x[2]=="B"): print("YES") elif x[0]=="A" and x[1]=="A" and (x[2]=="A" or x[2]=="O"): print("YES") elif x[0]=="A" and x[1]=="B" and (x[2]=="A" or x[2]=="B" or x[2]=="O" or x[2]=="AB"): print("YES") elif x[0]=="B" and x[1]=="A" and (x[2]=="A" or x[2]=="B" or x[2]=="O" or x[2]=="AB"): print("YES") elif x[0]=="A" and x[1]=="AB" and (x[2]=="A" or x[2]=="B" or x[2]=="AB"): print("YES") elif x[0]=="AB" and x[1]=="A" and (x[2]=="A" or x[2]=="B" or x[2]=="AB"): print("YES") elif x[0]=="B" and x[1]=="B" and (x[2]=="B" or x[2]=="O"): print("YES") elif x[0]=="B" and x[1]=="AB" and (x[2]=="A" or x[2]=="B" or x[2]=="AB"): print("YES") elif x[0]=="AB" and x[1]=="B" and (x[2]=="A" or x[2]=="B" or x[2]=="AB"): print("YES")O elif x[0]=="AB" and x[1]=="AB" and (x[2]=="A" or x[2]=="B" or x[2]=="AB"): print("YES") else: print("IMPOSSIBLE")
898719d642f4caad3b8e8ae42adf1bfcc9b7334a
pk111297/PythonDataStructures
/ds/Stack.py
424
3.75
4
class Stack: def __init__(self): self.lst=[] def push(self,num): self.lst.insert(0,num) def pop(self): if len(self.lst)==0: return "Stack is Empty" z=self.lst[0] del self.lst[0] return z def isEmpty(self): if len(self.lst)==0: return True else: return False def isFull(self): return False
f6d253a1f4f8ab70f72be488d5d8ebe9f1ba5fd4
RuzhaK/pythonProject
/Fundamentals/DictionariesExercise/T10SoftUniExamResults.py
459
3.59375
4
data=input() # submissions={} results={} while data!="exam finished": line=data.split("-") username=line[0] language=line[1] if language!="banned": if username not in results: results[username] = {"subkey": []} results[username] = username if language not in results[username]['subkey']: results[username]['subkey'] = language points=line[3] # else: # todo data = input()
363e341e47561b71b2f66ae86b82b1515841db5c
naye0ng/Algorithm
/SWExpertAcademy/모의SW역량테스트/1952_수영장.py
632
3.609375
4
""" 수영장 https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PpFQaAQMDFAUq&categoryId=AV5PpFQaAQMDFAUq&categoryType=CODE """ def DFS(m, cost) : if m >= 12 : global low_cost low_cost = min(low_cost, cost) else : # 하루 DFS(m+1, cost+cnt[m]*day) # 한달 DFS(m+1, cost+month) # 세달치 DFS(m+3, cost+month3) T = int(input()) for test_case in range(1,1+T) : day, month, month3, low_cost = map(int, input().split()) cnt = list(map(int, input().split())) DFS(0, 0) print('#{} {}'.format(test_case, low_cost))
05db84ab52eef47f63d318a873aef6e0f7a6a8a5
faye-a/Data-Structures-Algorithms-Assignments
/average_runtime.py
264
3.625
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: def calculate_average(array): #total score total = 0 for number in range(len(array)): total += array[number] #calculate average of total average = total / len(array) return average
f1fd9a00a1c3a43c8569a3aa54975a071357a987
Ozcry/PythonCEV
/ex/ex108.py
884
3.890625
4
'''Adapte o código do DESAFIO 107, criando uma função adicional chamada moeda() que consiga mostrar os valores como um valor monetário formatodo.''' from utilidadesCeV import moeda print('\033[1;33m-=\033[m' * 20) n1 = float(input('\033[34mDigite o preço: R$\033[m')) por = int(input('\033[33mQuantos porcentos deseja aumentar ou diminuir?\033[m ')) print(f'\033[35mA metade de {moeda.moeda(n1)} é {moeda.moeda(moeda.metade(n1))}\033[m') print(f'\033[36mO dobro de {moeda.moeda(n1)} é {moeda.moeda(moeda.dobro(n1))}\033[m') if por > 0: print(f'\033[31mAumentando {por}%, temos {moeda.moeda(moeda.aumento(n1, por))}\033[m') elif por < 0: print(f'\033[31mDiminuindo {por * -1}%, temos {moeda.moeda(moeda.aumento(n1, por))}\033[m') else: print(f'\033[31mO preço continua o mesmo {moeda.moeda(n1)}\033[m') print('\033[1;33m-=\033[m' * 20) print('\033[1;32mFIM\033[m')
5e2053f1b601788a1ec99cd1681f7dafcade9401
Lucy-SD-Developer/Encryption-Decryption
/simple_substitution/frequency.py
1,561
4
4
# English letter frequency in order from the highest to lowest frequency _WORDS = [ 'E', 'T', 'A', 'O', 'I', 'N', 'S', 'R', 'H', 'D', 'L', 'U', 'C', 'M', 'F', 'Y', 'W', 'G', 'P', 'B', 'V', 'K', 'X', 'Q', 'J', 'Z'] # English letter frequency corresponding to the predefined array words # data are from English letter frequency table _FREQ = [ 12.02,9.10,8.12,7.68,7.31,6.95,6.28,6.02,5.92,4.32,3.98,2.88,2.71, 2.61,2.30,2.11,2.09,2.03,1.82,1.49,1.11,0.69,0.17,0.11,0.10,0.07 ] # store English letter frequencies def get_frequency(input): input_freq = {} char_count = 0 for char in input: if char > 'Z' or char < 'A': continue input_freq[char] = input_freq.get(char, 0.0) + 1 char_count = char_count + 1 ''' for char in input_freq: input_freq[char] = input_freq[char] / char_count * 100 ''' return input_freq # get key def get_key_by_frequency(input): input_freq = get_frequency(input) key = {} for k, v in input_freq.items(): for i, f in enumerate(_FREQ): left = 100 if i == 0 else _FREQ[i-1] right = _FREQ[i] if left - v <= right: # closer to left word = _WORDS[i-1] else: word = _WORDS[i] while word in key and i - 1 >= 0: i = i - 1 word = _WORDS[i] while word in key and i + 1 < len(_FREQ): i = i + 1 word = _WORDS[i] key[word] = k break return key
f1efb22ccc58b8d43bc95f78ede91b5d025af77c
chinna777/demo.py
/ExceptionsStart.py
599
3.6875
4
import logging logging.basicConfig(filename='myfile.log',level=logging.DEBUG) try: logging.info("entering the required inputs") a,b=[int(x) for x in input('enter the two numbers:' ).split()] f=open("myfile.py","w") c=a//b print(c) f.write('writing %d into myfile'%c) logging.info("writing the output to the file") except ZeroDivisionError: logging.critical("not be divisble by zero ") print('division by zero is not applicable') print('please enter the non zero value') else: print('madda gudu') finally: f.close() print('file is closed')
f44062e0038d4f1a6edd6c6bf2ae5721b9d3d572
codeforcauseorg-archive/DSA-Live-Python-Jun-0621
/lecture-08/stringpool.py
90
3.546875
4
first = "vtvtuyvoyvoytctcgyocifcygcgcvugvgybhbvvyv" second = "vtvtuyvoyvoytctcgyocifcygcgcvugvgybhbvvyv" print(first is second) print(first[2:5] == second[2:5])
e2fc55b51c62dd2dbfa6faaa5c0382b75a60cd2c
piyush9194/data_structures_with_python
/data_structures/trees/lowest_common_ancestor_bt.py
502
3.96875
4
""" Find the LCA of Binary Tree. https://www.youtube.com/watch?v=13m9ZCB8gjw """ def lca(root, n1, n2): if root is None: return None if root.data == n1 or root.data == n2: return root node_left = lca(root.left, n1, n2) node_right = lca(root.right, n1, n2) if node_left is not None and node_right is not None: return root if node_left is None and root.right is None: return None return node_left if node_left is not None else node_right
cbb4737796354e82883c62d67cb46fbf5eb45319
JustinOliver/ATBS
/testie.py
591
3.984375
4
# A dumb program to learn and mess around with command line while True: try: x = int(input('give me an int: ')) except ValueError: print ('Dont be an idiot') continue else: break if x < 4: print ('less than 4') elif x == 4: print ("egual 2 4") else: print ('thats a big number') print("your number is {}" .format(x)) print("Count to {} with me!" .format(x)) for num in range(x + 1): print(num) print("Weee, that was fun!") print("Now lets count backwards!") for num1 in reversed(range(x + 1)): print(num1) print("haha, I can't believe that worked")
108234c47694f40b88818654b0102b1b5a8ae04d
Jiklopo/web-dev
/lab7-python/level2/293.py
147
3.875
4
def compare(a: int, b: int): if a == b: return 0 return a if a > b else b a = int(input()) b = int(input()) print(compare(a, b))
328f126a4c1e42ddcb6af61b1cca3c0ebbf97965
gcpdeepesh/harshis-python-code
/What To Wear.py
549
4.21875
4
rainy = input("How`s the weather outside ? Is it raining (y/n):").lower() cold = input ("Is it cold outside ? (y/n)").lower() if (rainy == 'y' and cold == 'y'): print("Is it important, if yes you`d better wear a raincoat otherwise I wil suggest you to stay at home.") elif (rainy == 'y' and cold == 'n'): print("Don`t forget to carry an umbrella with you.") elif (rainy == 'n' and cold == 'y'): print("Put on your jacket it`s cold out!") elif (rainy == 'n' and cold == 'n'): print("Wear whateever you want, it`s beautiful outside!")
48cec89e2f78d2c4464a27c6e26a983aeec58abb
QitaoXu/Lintcode
/Alog/class2/exercises/totalOccurences.py
1,540
3.703125
4
class Solution: """ @param A: A an integer array sorted in ascending order @param target: An integer @return: An integer """ def totalOccurrence(self, A, target): # write your code here if not A or target == None: return 0 start, end = 0, len(A) - 1 nums = A while (start + 1) < end: mid = ( start + end ) // 2 if nums[mid] < target: start = mid if nums[mid] == target: end = mid if nums[mid] > target: end = mid if nums[start] == target: head = start elif nums[end] == target: head = end else: head = -1 start, end = 0, len(A) - 1 while (start + 1) < end: mid = ( start + end ) // 2 if nums[mid] < target: start = mid if nums[mid] == target: start = mid if nums[mid] > target: end = mid if nums[end] == target: tail = end elif nums[start] == target: tail = start else: tail = -1 if head >= 0 and tail >= 0: return tail - head + 1 else: return 0
5ecc072f66eb13089dedac463551a569da78d6e9
CauanyRodrigues01/Codigos-Python
/Questões do URI/URI_2344.py
194
3.78125
4
nota = int(input()) if nota == 0: print("E") if 1 <= nota <= 35: print("D") if 36 <= nota <= 60: print("C") if 61 <= nota <= 85: print("B") if 86 <= nota <= 100: print("A")