blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
22fefd7fa371833a153e85ab999ed9ede6f54978
chenbiao123/python
/project/project1/authentication.py
598
3.625
4
#!/usr/bin/env python """this model provides function for authentication users""" def login(username, password): try: user_file = open('/etc/users.txt') user_buf = user_file.read() users = [line.split("|") for line in users_buf.split("\n")] if[username,password] in users: return True else: return False except Exception,exc: print "I cant't authentication you " return False def logout(): print '这一行不会用测试用例覆盖到' print '这一行也不会用测试用例覆盖到'
d1fdd9fb1aefa4f2926492baf1a09f38f7133ce4
TERADA-DANTE/algorithm
/python/acmicpc/solved/_11653.py
243
3.546875
4
n = int(input()) def solution(n): answer = [] i = 2 while n != 1: if not n % i: answer.append(i) n /= i else: i += 1 return '\n'.join(map(str, answer)) print(solution(n))
31b62d01b5fdbcfb93e6d5b9b35aef329d49a5fe
swiffo/Text-Mimicry
/Trie.py
5,629
4.21875
4
import random class Trie: """A light-weight trie (or prefix tree).""" def __init__(self): """Initialise Trie().""" # The following lists must have the same lengths at all times. The elements are linked by index across # the lists. E.g., if _letters[2] == 'k', we find in _children[2] the trie with prefixes following the # letter 'k'. _counts[2] will be the number of times 'k' has occurred as part of a prefix. self._children = [] # List of trie's self._letters = [] # List of unique letters self._counts = [] # List of number of times a given letter has occurred as a prefix def add_word(self, word): """Adds word to the prefix tree. Args: word: Word (string) to add to the trie. Returns: None """ if not word: return letter = word[0] if letter in self._letters: index = self._letters.index(letter) else: self._children.append(Trie()) self._letters.append(letter) self._counts.append(0) index = len(self._children) - 1 self._counts[index] += 1 next_node = self._children[index] next_node.add_word(word[1:]) def total_count(self): """Returns the count of words added to the trie. Note that duplicates are counted. Returns: The count of words added to the trie with duplicates counted their multiplicity. """ return sum(self._counts) def random_word(self, word_length, prefix=''): """Returns a random word from the trie. The word returned is chosen with probability proportional to the number of times such a word has been added to the trie. A prefix can optionally be specified to limit the selection space. Args: word_length: Integer specifying the length of the random word to be generated. prefix: A string of length less than or equal to word_length which constrains the random word to be generated to start with the prefix. Returns: A word of length word_length chosen with probability proportional to the occurrence count in the trie. If it is not possible to form such a word (e.g., prefix too constraining or required length too long), None is returned. """ if not word_length: return '' if prefix: if len(prefix) > word_length: return None letter = prefix[0] if letter not in self._letters: return None else: next_node = self._children[self._letters.index(letter)] remaining_word = next_node.random_word(word_length - 1, prefix[1:]) if remaining_word is not None: return letter + remaining_word else: return None else: total_count = self.total_count() if not total_count: return None else: count_stop = random.randint(0, total_count - 1) index = -1 while count_stop >= 0: index += 1 count_stop -= self._counts[index] letter = self._letters[index] next_node = self._children[index] remaining_word = next_node.random_word(word_length - 1) if remaining_word is not None: return letter + remaining_word else: return None def random_text(self, word_length, max_text_length): """Returns randomised text. The text returned is built sequentially by first constructing a random word of length word_length and then inductively extending this by creating new random words of length word_length prefixed by the previous word_length-1 characters. Args: word_length: Length of the words used to inductively build the randomised text. max_text_length: The longest the randomised text is allowed to grow before being cut and returned. Returns: A string of length no greater than max_text_length. The string is a randomised text built based on the word occurrences in the trie. If at some point it is not possible to built the string further (the max length is reached or no word in the trie can extend the last word_length-1 characters), the string is returned as is. """ last_word = self.random_word(word_length) letters = list(last_word)[:-1] max_text_length -= len(letters) while last_word is not None and max_text_length > 0: letters.append(last_word[-1]) max_text_length -= 1 last_word = self.random_word(word_length, prefix=last_word[1:]) return ''.join(letters) def feed_text(self, text, word_length): """Adds words to the trie from the given text. Adds all substrings of length word_length from text to the trie. Args: text: A string from which to extract the words to add to the trie. word_length: The length of the substrings to be extracted from text. Returns: None. """ for start_index in range(len(text) - word_length + 1): self.add_word(text[start_index:start_index+word_length])
bcc735b67c85a8d5b9be1345b55c76ecef345a10
Jiss-Joss-42/PYTHON
/CYC1.3.9-sort-dict-asc.py
116
3.828125
4
prices={'banana':40,'apple':100,'guava':35} print(sorted(prices.items())) print(sorted(prices.items(),reverse=True))
4a226019f683aa634394df386eef1d34188f4915
Abooow/BattleShips
/BattleShips/framework/ai.py
5,926
3.703125
4
''' This module contains the AI class ''' import random import utils import sprites from framework.board import Board from framework.ship import Ship class AI(): ''' Base class for all AI's ''' def __init__(self): self.board = Board() Board.place_ships_randomly(self.board) def get_shoot_coordinate(self): pass def shoot(self, enemy, coordinate) -> None: ''' Shoot at a random coordinate :param enemy (Board): the enemy board to shoot on :returns: NoReturn :rtype: None ''' pass class DumbAI(AI): ''' A very basic AI that shoots at a random cell each time ''' def __init__(self): super().__init__() def shoot(self, enemy): super().shoot(enemy) while True: # get random coordinate x = random.randint(0, 9) y = random.randint(0, 9) coordinate = (x, y) # shoot at that coordinate shot = enemy.shoot_at(coordinate) # if shot was successful, then return, otherwise try again if shot[0]: return class SmartAI(AI): _available_directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] def __init__(self): super().__init__() self._found_ship = False self._first_hit_cord = None self._shoot_direction = None self._latest_hit = None self._available_directions = [] def shoot(self, enemy, coordinate): super().shoot(enemy, coordinate) enemy.shoot_at(coordinate) def get_shoot_coordinate(self, enemy): super().get_shoot_coordinate() # if a ship is found if self._found_ship: return self._get_smart_coordinate(enemy) # think before shooting else: # when a ship is not found, shoot random return self._get_random_coordinate(enemy) def _get_random_coordinate(self, enemy, errorlevel=0) -> tuple: ''' Get a almost random coordinate :param enemy (Board): the enemy board :param errorlevel (int): the number of attempt to shoot at enemy board :returns: a coordinate :rtype: tuple[int,int] ''' while True: # get random coordinate x = random.randint(0, 9) y = random.randint(0, 9) coordinate = (x, y) if (not enemy.list[y][x].hit and len(self._get_empy_cells_around(coordinate, enemy)) <= 3 and errorlevel < 40): self._get_random_coordinate(enemy, errorlevel + 1) break # if shot was successful, then return, otherwise try again if enemy.can_shoot_at(coordinate): cell = enemy.list[coordinate[1]][coordinate[0]] if cell.ship is not None: self._latest_hit = coordinate self._first_hit_cord = coordinate self._on_hit_ship(enemy) return coordinate return coordinate def _get_empy_cells_around(self, coordinate, enemy): available_directions = SmartAI._available_directions[:] # look around the hit cord in all directions for cord in available_directions: # check if cell is hit, then remove cord from available_directions new_cord = (coordinate[0] + cord[0], coordinate[1] + cord[1]) if (new_cord[0] < 0 or new_cord[0] > 9 or new_cord[1] < 0 or new_cord[1] > 9): available_directions.remove(cord) continue if enemy.list[new_cord[1]][new_cord[0]].hit: available_directions.remove(cord) return available_directions def _get_smart_coordinate(self, enemy): if self._shoot_direction is None or (self._shoot_direction not in self._available_directions and self._shoot_direction is not None): if len(self._available_directions) == 0: self._found_ship = False return self._get_random_coordinate(enemy) # get random coordinate from available_directions self._shoot_direction = random.choice(self._available_directions) # shoot at that coordinate new_cord = (self._latest_hit[0] + self._shoot_direction[0], self._latest_hit[1] + self._shoot_direction[1]) # if shot was successful if enemy.can_shoot_at(new_cord): cell = enemy.list[new_cord[1]][new_cord[0]] if cell.ship is not None: if cell.ship.health == 1: # if the ship have sunken find new cell self._found_ship = False else: self._latest_hit = new_cord else: self._available_directions.remove(self._shoot_direction) # reverse shoot direction self._shoot_direction = (self._shoot_direction[0] * -1, self._shoot_direction[1] * -1) self._latest_hit = self._first_hit_cord else: # can't shoot here, have to try again self._available_directions.remove(self._shoot_direction) self._shoot_direction = (self._shoot_direction[0] * -1, self._shoot_direction[1] * -1) self._get_smart_coordinate(enemy) return new_cord def _on_hit_ship(self, enemy): self._found_ship = True self._available_directions = self._get_empy_cells_around(self._first_hit_cord, enemy) class CheatingAI(AI): def __init__(self): super().__init__() def shoot(self, enemy): super().shoot(enemy) class HackerAI(AI): def __init__(self): super().__init__() def shoot(self, enemy): super().shoot(enemy)
ede5fc3847bd066f66fb0f65518e8f076c0f85fa
jemtca/CodingBat
/Python/List-2/shift_left.py
431
4.0625
4
# return an array that is "left shifted" by one, so {6, 2, 5, 3} returns {2, 5, 3, 6} # you may modify and return the given array, or return a new array def shift_left(nums): new_list = [] if len(nums) > 0: for x in range(len(nums) - 1): new_list.append(nums[x+1]) new_list.append(nums[0]) return new_list print(shift_left([6, 2, 5, 3])) print(shift_left([1, 2])) print(shift_left([1]))
6d841c02c394c0d1f210594d398ff013d3056393
pahuja-gor/CodePath-Technical-Interview-Exercises
/Week 2 - Session 1/parse_address.py
927
4.3125
4
## Given an address test_1 = "123 Main St., City Anystate USA 12345" test_2 = "456 Commerce St., Colorado USA 54321" # Print the street number and name on one line # the city and state on the next line # and the zip on the last line """ 123 Main St. Anystate, USA 12345 """ # by the way this is called a "multiline string" """ Separate out the street address from the rest of the address Print the street address Separate out the state Separate out the country Print the state and country with a comma in between Separate out the zipcode Print the zipcode """ def parse_address(address): address_parts = address.split(", ") street_address = address_parts.pop(0) print(street_address) remaining_address = address_parts.pop() address_parts = remaining_address.split(" ") zipcode = address_parts.pop() middle_line = ", ".join(address_parts) print(middle_line) print(zipcode) parse_address(test_1)
5b4bff730a148ff8541ac79b4e17f425a6cde9a7
Dinzine/python_projects
/convert_string_list/average_words.py
1,213
3.921875
4
# Calculating the average number of words per sentence in a paragraph. input = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit nisl quam, eu auctor elit fermentum eu. Fusce faucibus ipsum erat, a semper ante pretium non. Proin blandit at diam eget tincidunt. Nunc efficitur nunc at nisi auctor malesuada. Phasellus a turpis non libero luctus semper. Donec vitae scelerisque tortor. Praesent vel nibh faucibus, aliquam nulla sit amet, aliquam augue. Vivamus vitae justo sodales, luctus erat ut, faucibus elit.Nulla at volutpat orci. Nullam sed odio nulla. Sed gravida accumsan ex, nec posuere lacus sodales id. Nulla vulputate vel risus et bibendum. Mauris ultrices dolor sed nulla finibus, nec consequat arcu mollis. Morbi non tempus nulla, id pharetra libero. Phasellus non turpis non orci pulvinar convallis sit amet nec purus. Nunc egestas interdum sem. Mauris rutrum nunc risus, at posuere lacus euismod ac.""" list_of_lists =[] sentences = input.split('.') list_of_lists = [ sentence.split() for sentence in sentences ] all_words_sum = sum([ len(list) for list in list_of_lists]) word_sentence_average = all_words_sum / len(list_of_lists) print(word_sentence_average)
65d74406a13447bb8b084b5cb039aca2f45c8fd2
adihipo/Python-thingz
/classesAndConstructor/dog.py
200
3.640625
4
class Dog: def __init__(self, isMale, isFat): self.isMale = isMale self.isFat = isFat def display(self): print("Is your dog a male? %s \nAnd is it fat? %s \n"%(self.isMale,self.isFat))
ef3dca2dec55bcbe92fd23bebb79fbac32edbffd
Shahrein/Python-Training-Projects
/Factoral Function.py
262
4.09375
4
def factorial_function(n): if n < 0: return None if n < 2: return 1 product = 1 for i in range(2, n + 1): product *= i return product for n in range(1, 6): # testing print(n, factorial_function(n))
79446fcf6250705fbb739acc79e18d75adb53fa3
Luolingwei/LeetCode
/DepthFirstSearch/Q1088_Confusing Number II.py
578
3.625
4
# 思路: dfs搜索,每次加一位valid number,track它的rotation,比较n和rn是否相等 class Solution: def confusingNumberII(self, N): valid=[0,1,6,8,9] flip={0:0,1:1,6:9,8:8,9:6} self.ans=0 def dfs(n,rn,digit): if n!=rn: self.ans+=1 for i in valid: if n==0 and i==0: continue if n*10+i<=N: dfs(n*10+i,flip[i]*digit+rn,digit*10) dfs(0,0,1) return self.ans a=Solution() print(a.confusingNumberII(20))
a8c136f535405989c1194637dc3aaa3184d99d18
PrangeGabriel/python-exercises
/ex029.py
245
3.71875
4
vel = float(input('Qual sua velocidade em km/h?')) if vel > 80: print('''parabens! voce foi multado por excesso de velocidade! A multa irá custar {} reais'''.format((vel - 80)*7)) else: print('voce não foi multado :(')
6626672d6765009f70b6376ac65201ccb58a7539
Sahil94161/python-
/pro.py
277
3.640625
4
import random cpu=random.randint(1,100) player= int(input("Enetr a number b/w 1-100:-")) while player!=cpu: if player>cpu: print("Too high") else: print(" Too low") player = int(input("Enetr a number b/w 1-100:-")) else: print("Well done")
4572ceb52080514bd18b150bdad201ea78052395
ViktoriaFrantalova/basic-python
/7_ChybyTest/7.2_ZoznamCisel.py
736
3.859375
4
# Zoznam čísel # Napíšte definíciu funkcie cisla, ktorá prijíma reťazec. Reťazec rozdeľte podľa ";" a prvky, ktoré nemožno previesť na číslo, ignorujte. Návratovú hodnotou funkcie bude zoznam čísel (float). # Vaša funkcia bude volaná takto: # retezec = input() # print(cisla(retazec)) # Sample Input: # 8;1;2.2;_;5.3;9.8 # Sample Output: # [8.0, 1.0, 2.2, 5.3, 9.8] from typing import List def cisla(retazec: str) -> List[float]: retazec = retazec.split(';') zoznam = [] for i in range(0,len(retazec)): try: vstup = float(retazec[i]) zoznam.append(vstup) except ValueError: i = i + 1 return zoznam retazec = input() print(cisla(retazec))
2349161e91907b0c8a718a97e9cfbb44f29f3c79
ElykelwinCosta/my_uri_programs
/python/1012 - Área/1012.py
443
3.640625
4
linhaLida = input() lista = linhaLida.split() A = float(lista[0]) B = float(lista[1]) C = float(lista[2]) areaTriangulo = A * C / 2 areaCirculo = 3.14159 * C * C areaTrapezio = (A + B) * C / 2 areaQuadrado = B * B areaRetangulo = A * B print("TRIANGULO: %.3F" %areaTriangulo) print("CIRCULO: %.3F" %areaCirculo) print("TRAPEZIO: %.3F" %areaTrapezio) print("QUADRADO: %.3F" %areaQuadrado) print("RETANGULO: %.3F" %areaRetangulo)
2e5e5ec4667b6ce2113651e68683dace68790b2f
jeffpignataro/Tin-Man
/cipher.py
824
3.59375
4
import sys def decryptTinMan(numbers): return charToNum(numbers) def charToNum(number): return chr(int(number) + 96) # 505091 02411030 02108002 9121515160 5021209021211270 508002 815160 9190 0291819060 508002 # The first one is for the gullible fools that cant see decryptedText = "" for i in sys.argv: if(i != sys.argv[0]): numbersString = i numbersStringArray = numbersString[::-1].split(' ') for numberWord in numbersStringArray: numBuilder = '' for num in numberWord: numBuilder += num if(len(numBuilder) == 2): decryptedText += decryptTinMan(numBuilder) numBuilder = '' decryptedText += ' ' for word in decryptedText.split(' ')[::-1]: print(word, end=' ')
83f4796b0cfe44f79641ab5b9cf0ef40aa30ad5b
Rainlv/LearnCodeRepo
/Pycode/Crawler_L/filetype/csv/csv00_read.py
851
4.03125
4
import csv # 通过迭代器下标获取 def read_csv(): with open(r'Crawler_L\csv\test.csv','r') as r: reader = csv.reader(r) # reader是个迭代器 next(reader) # 跳过第一行(即标题),从第二行开始遍历 for x in reader: date = x[0] number = x[1] name = x[2] print({ 'date':date, 'number':number, 'name':name }) # 通过字典迭代器key获取value def Dicread_csv(): with open(r'Crawler_L\csv\test.csv','r') as r: reader = csv.DictReader(r) # 创建一个迭代器,不包含第一行标题数据,遍历返回的是字典 for x in reader: value = { 'name' : x['name'], 'date' : x['date'] } print(value)
4abc590229c28d449e32981b63902b9a2faea7e4
Felixwbh/leetcode
/哈希/#1 List.py
1,090
3.796875
4
#2021.2.23 #给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。 #你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 #你可以按任意顺序返回答案。 #示例 1: #输入:nums = [2,7,11,15], target = 9 #输出:[0,1] #解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。 from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: n = len(nums) for i in range(n): for j in range(i+1, n): if nums[i] + nums[j] == target: return [i,j] return def twoSum2(self, nums: List[int], target: int) -> List[int]: hashtable = dict() for i, num in enumerate(nums): if target-num in hashtable: return [hashtable[target-num],i] hashtable[num] = i nums = [2,11,7,3,5] target = 9 solution = Solution() print(solution.twoSum2(nums,target))
038402ef81a92190ae443096050ca0cd2ab5738d
YuweiHuang/Basic-Algorithms
/leetcode/tree/144.二叉树的前序遍历.py
732
3.75
4
# # @lc app=leetcode.cn id=144 lang=python3 # # [144] 二叉树的前序遍历 # # @lc code=start # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def __traverse(self, root, data_list): """ docstring """ if root == None: return data_list.append(root.val) self.__traverse(root.left, data_list) self.__traverse(root.right, data_list) def preorderTraversal(self, root: TreeNode) -> List[int]: data_list = [] self.__traverse(root, data_list) return data_list # @lc code=end
54bc3e482330ba82959ffe609050673906844825
lindsaymarkward/CP1404-2016-2
/dict_demo.py
482
3.9375
4
__author__ = 'Lindsay Ward' ages_dict = {"Bill": 21, "Jane": 34, "Jack": 56} # print(ages_dict["Bill"]) # print(ages_dict.get("Bob", -1)) # ages_dict['Bob'] = ages_dict.get("Bob", 0) + 1 # print(ages_dict.get("Bob")) # print(ages_dict) # name = input("Name: ") # age = int(input("Age: ")) # # ages_dict[name] = age # print(ages_dict) for name in ages_dict: print("{} - {}".format(name, ages_dict[name])) for name, age in ages_dict.items(): print("{} - {}".format(name, age))
ee68694df814b01ec5cff60d7999cbd2d09cc252
Arcob/HuaweiAutomatedTesting
/Classes/DictRange.py
1,193
3.59375
4
from Classes import Range import MutateTool class DictRange(Range.Range): # 固定范围参数 只有一个值(一般为字符串) def __init__(self, value_list): self.value_list = value_list # 储存字典的list def mutate_from_value(self, value, mutate_strategy=0): # 如果突变策略在可处理之外就返回空值 if mutate_strategy == MutateTool.MutateType.not_mutate: return value elif mutate_strategy == MutateTool.MutateType.empty_value_mutate: return MutateTool.empty_value_mutate(value) elif mutate_strategy == MutateTool.MutateType.add_one_mutate: return MutateTool.add_one_mutate_dict(value, self.value_list) elif mutate_strategy == MutateTool.MutateType.minus_one_mutate: return MutateTool.minus_one_mutate_dict(value, self.value_list) elif mutate_strategy == MutateTool.MutateType.max_value_mutate: return MutateTool.max_value_mutate_dict(value, self.value_list) elif mutate_strategy == MutateTool.MutateType.min_value_mutate: return MutateTool.min_value_mutate_dict(value, self.value_list) else: return ""
2f26f3d5039e5ff4221121a01036b27b02c5f4ab
jrluecke95/python-project
/hero.py
1,221
3.5625
4
from character import Character class Hero(Character): def __init__(self, items=[], name="", health=0, power=0, armor=0, evasion=0, ability=0, coins=0): super().__init__(name, health, power, armor, evasion, ability) self.items = [["healing potion", 5, 1], ["poison potion", -5, 0], ["bow and arrow", -5, 0]] # self.dict_items = { # "healing potion": { # "health_impact": 5, # "quantity": 1 # }, # "" # } self.coins = coins def get_item(self, item): item_choice = self.items[item] if item_choice == 2: item_choice[2] = 5 else: item_choice[2] += 1 def use_item(self, item): item_choice = self.items[item] item_choice[2] -= 1 return item_choice[1] def print_inventory(self): for item in self.items: print(f"You have {item[2]} {item[0]}'s that provide {item[1]} hit points for your next task") def check_status(self): return(f"{self.name} has {self.health} health, {self.power} power, {self.armor} armor, {self.evasion} evasion, {self.coins} coins, and has {self.ability}.")
5e14d74c22da2988d91d2147b479d3786ba45925
FrankCasanova/Python
/FICHEROS/442.py
208
3.875
4
file_name = input('File name: ') with open(file_name, 'r') as file: count = 0 character = file.read(1) while character != '': count += 1 character = file.read(1) print(count)
f361354f412f998d8c246d2957b0e5a7e9514457
Aidan-Pettit/Code-Writer
/in_out/str-str.py
426
3.546875
4
from re import search, sub def str_str(data): code_list = [] pair = [] unincluded = [] conditions = [] if data[0] == data[1]: code_list.append('output = input') return code_list for _pair in data: if _pair[0][-1] == 1: pass for _pair in data: for char in _pair[0]: if not search(char, _pair[1]): unincluded.append(char)
693118d8d5b966a4ac32c60adfd349afb0d05529
sunshinexf3133/Python_BronzeIII
/hanjia/.svn/pristine/b3/b3f71c6dcb6f1d126370536c55614da81514ddfc.svn-base
796
4.3125
4
#coding:utf-8 #使用列表解析进行筛选 ###下面函数使用列表解析删除字符串中的所有元音 #[c for c in s if c.lower() not in 'aeiou'],这是一个筛选型列表解析, #它以每次一个字符的方式扫描s,将每个字符转换为小写,再检查它是不是元音。 #如果是元音,则不将其加入最终的列表,否则将其加入最终列表 # #该列表解析的结果是一个字符串列表,因此我们使用join将所有字符串拼接成一个, #再返回这个字符串。 #eatvowels.py def eat_vowels(s) : """Removes the vowels from s.""" return ''.join([c for c in s if c.lower() not in 'aeiou']) if __name__ == "__main__" : s = raw_input("Please input a string :") print('After eat_vowels:{}'.format(eat_vowels(s)))
9e60bd69d7058b6d69400048f82c59eb7d01c2d2
haseenarahmath/Retina
/demos/basics/bold.py
1,178
3.671875
4
""" A demo of the Layer2D.bold()/Layer3D.bold() function. """ import matplotlib.pyplot as plt import retina.core.axes import numpy as np import time plt.ion() fig = plt.figure(figsize=(20, 20)) ax = plt.subplot('111', projection='Fovea2D') plt.xlabel('x') plt.ylabel('y') plt.title('Boldface Plot Demo') sinc = ax.add_layer('sinc') x = np.linspace(-6, 6) y = 20 * (np.sin(x) / x) sinc.add_data(x, y) sinc.set_style('r-') quadsin = ax.add_layer('quadsin') y = (x ** 2) * np.sin(x) quadsin.add_data(x, y) quadsin.set_style('b--') ax.build_layers() plt.show() plt.pause(2) # Bold the sinc layer. sinc.bold() print("Making 'sinc' layer bold.") plt.pause(2) # Bold the sinc layer a second time. # As you can see, boldening effects # stack incrementally. sinc.bold() print("Increasing boldness of 'sinc' layer.") plt.pause(2) # Unbold the sinc layer. sinc.unbold() print("Decreasing boldness of 'sinc' layer.") plt.pause(2) # Unbold a second time. sinc.unbold() print("Returning 'sinc' layer to default linewidth.") plt.pause(2) # Subsequent unbolds have no effect # since layer has reached default linewidth. sinc.unbold() print("This unbold operation has no effect.")
8df494e1a058339ae664cf2569f947e2b6ecb507
gistable/gistable
/all-gists/7618531/snippet.py
196
3.75
4
from collections import Iterable def flatten(iterable): for item in iterable: if isinstance(item, Iterable): yield from flatten(item) else: yield item
d0616bdfd18d0a1a91e7a51da474723e4790476d
1string2boolthem/CST-205
/mod6lab14.py
2,299
4.1875
4
#Sevren Gail #Christopher Rendall #Team 3 - Lab 14 import re #For regular expressions, to replace an undetermined number of spaces in eggs.txt. #wordCount counts the number of total words in wordDict and returns the result. def wordCount(wordDict): count = 0 for key in wordDict: count += wordDict[key] return count #mostCommonWord finds the word that occurs the most in dictionary wordDict. def mostCommonWord(wordDict): word = "" count = 0 for key in wordDict: if wordDict[key] > count: word = key count = wordDict[key] return word #printHeadlines() prints the headlines in The Otter Realm. def printHeadlines(): file = open(pickAFile(), "rt") data = file.read() file.close() blocks = data.split("rel=\"bookmark\">") printNow("*** Otter Realm Breaking News! ***") for i in range(1, len(blocks)): block = str(blocks[i].split("</a")[0]) block = block.strip() block = block.replace("&nbsp;", ' ') #Replace html space character. block = block.replace("&#8230;", "...") #Replace the encoded ellipsis with an ellipsis block = block.replace('', '\'') #Replace this character with an apostrophe. block = block.replace('', '') #Replace this with nothing. block = block.replace(chr(128), '') #Replace this weird space character with nothing. printNow(block) #Print the headline. #greenEggs reads the eggs.txt file input by the user, creates a dictionary with each unique word as a key #and the key's value as the number of times that word occurs in the text. It also prints various #information as per specifications. def greenEggs(): file = open(pickAFile(), "rt") data = file.read() file.close() data = data.replace('\n', ' ') data = data.replace('-', ' ') data = re.sub(' +', ' ', data) wordList = data.split(' ') wordDict = {} for word in wordList: if wordDict.has_key(word.lower()): wordDict[word.lower()] += 1 else: wordDict[word.lower()] = 1 printNow("Word counts per word:") for key in wordDict: printNow(key + ": " + str(wordDict[key])) printNow("Total number of words in this story: " + str(wordCount(wordDict))) printNow("Total number of unique words in this story: " + str(len(wordDict))) printNow("Most Common Word: " + mostCommonWord(wordDict)) greenEggs() #printHeadlines()
9935c72b0e17a89e1c59fcce87ac39f448e84b8e
hazrmard/Agents
/src/agents/helpers/spaces.py
11,889
4.1875
4
""" Defines functions that convert space variables to and from tuples of floats. Defines functions to analyze spaces like size of tuple, size of space, continuous or discrete etc. """ from collections import OrderedDict from itertools import product, zip_longest from typing import Callable, Iterable, List, Tuple, Union import numpy as np from gym.core import Space from gym.spaces import Tuple as TupleSpace from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete def enumerate_discrete_space(space: Space, prod: bool = True) -> List[Tuple[int]]: """ Generates a list of space coordinate tuples corresponding the the discrete space. i.e a (2,2) `MultiDiscrete` space becomes [(0,0), (0,1), (1,0), (1,1)]. Args: * space: A discrete space instance from `gym.spaces`. * prod: Whether to return a product or individual enumerations of variables. For e.g for Multibinary(2) with product: (0,0), (0,1), (1,0), (1,1) and without product: [(0,1), (0,1)]. Returns: * Either iterator of tuples of coordinates for each point in the space. For invalid arguments, or for Tuple or Dict spaces with Box spaces that are continuous, returned tuples contain 'None' in place. Or a list of tuples enumerating each variable in a state individually. """ # TODO: Add resolution parameter to enumerate continuous spaces. linspaces = [(None,)] if isinstance(space, MultiBinary): linspaces = [(0, 1)] * space.n elif isinstance(space, Discrete): linspaces = [tuple(np.linspace(0, space.n-1, space.n, dtype=space.dtype))] elif isinstance(space, MultiDiscrete): linspaces = [tuple(np.linspace(0, n-1, n, dtype=space.dtype)) for \ n in space.nvec] elif isinstance(space, Box): if np.issubdtype(space.dtype, np.integer): linspaces = [tuple(np.linspace(l, h, h-l+1, dtype=space.dtype)) for \ l, h in zip(space.low.ravel(), space.high.ravel())] else: linspaces = [(None,)] * np.prod(space.shape) elif isinstance(space, TupleSpace): linspaces = [] for subspace in space.spaces: linspaces.extend(enumerate_discrete_space(subspace, False)) elif isinstance(space, Dict): linspaces = [] for _, subspace in space.spaces.items(): linspaces.extend(enumerate_discrete_space(subspace, False)) return product(*linspaces) if prod else linspaces def size_space(space: Space) -> List[Tuple[int]]: """ Calculates the size of a space. For continuous spaces, size is simply the range of values (# of states is infinite, however). I.e a (2,2) MultiDiscrete space returns 4. A Box(low=[0,0], high=[3, 2], dtype=float) returns 6. Args: * space: A discrete space instance from `gym.spaces`. Returns: * The number of possible states. Infinity if space is `gym.spaces.Box` and dtype is not integer. """ n = 1 if isinstance(space, MultiBinary): n = 2 ** space.n elif isinstance(space, Discrete): n = space.n elif isinstance(space, MultiDiscrete): n = np.prod(space.nvec) elif isinstance(space, Box): if np.issubdtype(space.dtype, np.integer): n = np.prod(space.high - space.low + 1) # +1 since high is inclusive else: n = np.prod(space.high - space.low) elif isinstance(space, TupleSpace): for subspace in space.spaces: n *= size_space(subspace) elif isinstance(space, Dict): for _, subspace in space.spaces.items(): n *= size_space(subspace) return n def len_space_tuple(space: Space) -> int: """ Calculates the length of the flattened tuple generated from a sample from space. For e.g. TupleSpace((MultiDiscrete([3,4]), MultiBinary(2))) -> 4 Args: * space: A discrete space instance from `gym.spaces`. Returns: * The length of the tuple when a space sample is flattened. """ n = 0 if isinstance(space, MultiBinary): n = space.n elif isinstance(space, Discrete): n = 1 elif isinstance(space, MultiDiscrete): n = len(space.nvec) elif isinstance(space, Box): n = np.prod(space.low.shape) elif isinstance(space, TupleSpace): for subspace in space.spaces: n += len_space_tuple(subspace) elif isinstance(space, Dict): for _, subspace in space.spaces.items(): n += len_space_tuple(subspace) return n def bounds(space: Space) -> Tuple: """ Computes the inclusive bounds for each variable in a tuple representing the space. So a TupleSpace(MultiDiscrete(2), MultiBinary([3, 5])) will have bounds of ((0,1), (0,1), (0,1), (0,2), (0, 4)). Infinite limits are returned as None in bounds. Args: * space (Space): Space instance describing the sample. Returns: * A flat tuple of inclusive (low, high) bounds for each variable in state. """ if isinstance(space, Discrete): return ((0, space.n-1),) elif isinstance(space, MultiDiscrete): return tuple(zip(np.zeros_like(space.nvec), space.nvec-1)) elif isinstance(space, MultiBinary): return tuple([(0, 1)] * space.n) elif isinstance(space, Box): bds = zip(space.low.ravel(), space.high.ravel()) bds = [(None if l==-np.inf else l, None if h==np.inf else h) for \ l, h in bds] return tuple(bds) elif isinstance(space, TupleSpace): spaces = space.spaces elif isinstance(space, Dict): spaces = [subspace for _, subspace in space.spaces.items()] flattened = [] for subspace in spaces: flattened.extend(bounds(subspace)) return tuple(flattened) def is_bounded(space: Space) -> Tuple[bool]: """ For each variable in a tuple representing the space, returns a boolean indicating if its a bounded variable. So a TupleSpace(MultiDiscrete(2), Box([-1, -2], [1, inf])) will return a tuple (True, True, True, False). Args: * space (Space): Space instance describing the sample. Returns: * A flat tuple of booleans indicating if the corresponding variable is finite. """ if isinstance(space, Discrete): return (True,) elif isinstance(space, MultiDiscrete): return tuple([True] * len(space.nvec)) elif isinstance(space, MultiBinary): return tuple([True] * space.n) elif isinstance(space, Box): low_inf = space.low == -np.inf high_inf = space.high == np.inf return tuple((low_inf | high_inf).ravel()) elif isinstance(space, TupleSpace): spaces = space.spaces elif isinstance(space, Dict): spaces = [subspace for _, subspace in space.spaces.items()] flattened = [] for subspace in spaces: flattened.extend(is_bounded(subspace)) return tuple(flattened) def is_continuous(space: Space) -> Tuple[bool]: """ Checks whether each variable in space is continuous of discrete. Only True for Box space with float dtype. Args: * space: The `gym.core.Space` instance. Returns: * A tuple of length equal to variables in space which is True when the corresponding variable is continuous. """ continuous = [] if isinstance(space, Discrete): return (False,) elif isinstance(space, MultiDiscrete): return tuple([False] * len(space.nvec)) elif isinstance(space, MultiBinary): return tuple([False] * space.n) elif isinstance(space, Box): if np.issubdtype(space.dtype, np.integer): res = False else: res = True return tuple([res] * np.prod(space.shape)) elif isinstance(space, Dict): spaces = spaces = [subspace for _, subspace in space.spaces.items()] elif isinstance(space, TupleSpace): spaces = space.spaces for s in spaces: continuous.extend(is_continuous(s)) return tuple(continuous) def to_tuple(space: Space, sample: Union[Tuple, np.ndarray, int, OrderedDict])\ -> Tuple: """ Converts a sample from one of `gym.spaces` instances into a flat tuple of values. I.e. a Dict sample {'a':1, 'b':2} becomes (1, 2). Args: * space (Space): Space instance describing the sample. * sample: The sample (`space.sample()` result type) taken from the space to be flattened. Returns: * A flat tuple of state variables. """ if isinstance(space, Discrete): return tuple((sample,)) elif isinstance(space, (MultiBinary, MultiDiscrete)): return tuple(sample) elif isinstance(space, Box): return tuple(sample.ravel()) elif isinstance(space, TupleSpace): spaces = zip(space.spaces, sample) elif isinstance(space, Dict): spaces = zip([subspace for _, subspace in space.spaces.items()],\ [subsample for _, subsample in sample.items()]) flattened = [] for subspace, subsample in spaces: flattened.extend(to_tuple(subspace, subsample)) return tuple(flattened) def to_space(space: Space, sample: Tuple) -> Union[tuple, np.ndarray, int,\ OrderedDict]: """ Reconstructs a `gym.spaces` sample from a flat tuple. Reverse of `to_tuple`. I.e. (1, 2) becomes a Dict sample {'a':1, 'b':2}. Args: * space (Space): Space instance describing the sample. * sample: The flat tuple to be reconstructed into a sample (`space.sample()` result type). Returns: * Any one of int, tuple, np.array, OrderedDict depending on space. """ if isinstance(space, Discrete): return sample[0] elif isinstance(space, (MultiBinary, MultiDiscrete)): return np.asarray(sample, dtype=space.dtype) elif isinstance(space, Box): return np.asarray(sample).reshape(space.shape).astype(space.dtype) elif isinstance(space, TupleSpace): aggregate = [] i = 0 for subspace in space.spaces: if isinstance(subspace, Discrete): aggregate.append(to_space(subspace, sample[i:i+1])) i += 1 elif isinstance(subspace, MultiBinary): aggregate.append(to_space(subspace, sample[i:i+subspace.n])) i += subspace.n elif isinstance(subspace, MultiDiscrete): aggregate.append(to_space(subspace, sample[i:i+len(subspace.nvec)])) i += len(subspace.nvec) elif isinstance(subspace, Box): aggregate.append(to_space(subspace, sample[i:i+np.prod(subspace.shape)])) i += np.prod(subspace.shape) elif isinstance(subspace, TupleSpace): sub_len = len_space_tuple(subspace) aggregate.append(to_space(subspace, sample[i:i+sub_len])) return tuple(aggregate) elif isinstance(space, Dict): aggregate = OrderedDict() i = 0 for name, subspace in space.spaces.items(): if isinstance(subspace, Discrete): aggregate[name] = to_space(subspace, sample[i:i+1]) i += 1 elif isinstance(subspace, MultiBinary): aggregate[name] = to_space(subspace, sample[i:i+subspace.n]) i += subspace.n elif isinstance(subspace, MultiDiscrete): aggregate[name] = to_space(subspace, sample[i:i+len(subspace.nvec)]) i += len(subspace.nvec) elif isinstance(subspace, Box): aggregate[name] = to_space(subspace, sample[i:i+np.prod(subspace.shape)]) i += np.prod(subspace.shape) elif isinstance(subspace, TupleSpace): sub_len = len_space_tuple(subspace) aggregate[name] = to_space(subspace, sample[i:i+sub_len]) return aggregate
8e55b2916f1c23233e710fd2b146d2c62b8ac746
aimdarx/data-structures-and-algorithms
/solutions/_Patterns for Coding Questions/_Other/Parenthesis/longest_balanced_parenthesis.py
4,072
3.703125
4
""" Longest Valid Parentheses: Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. https://leetcode.com/problems/longest-valid-parentheses/ https://paulonteri.notion.site/Parenthesis-b2a79fe0baaf47459a53183b2f99115c """ class Solution: def longestValidParentheses(self, s: str): if not s: return 0 opening_brackets = 0 longest_so_far = [0]*(len(s)+1) for idx, char in enumerate(s): # opening brackets if char == '(': opening_brackets += 1 # closing brackets else: if opening_brackets <= 0: continue opening_brackets -= 1 length = 2 # create streak # # "()" if s[idx-1] == "(" and idx > 1: # add what is outside the brackets. Eg: (())() - at the last idx length += longest_so_far[idx-2] # #"))" elif s[idx-1] == ")": # continue streak length += longest_so_far[idx-1] # add what is outside the brackets. Eg: ()(()) - at the last idx if idx-length >= 0: length += longest_so_far[idx-length] longest_so_far[idx] = length return max(longest_so_far) """ "((())())" ['(', '(', '(', ')', ')', '(', ')', ')'] [ 0, 1, 2, 3, 4, 5, 6, 7] idx,res,c_l,stack 0 0 0 [0] 1 0 0 [0,0] 2 0 0 [0,0,0] 3 2 2 [0,0] 4 4 4 [0] 5 4 0 [4,0] 6 6 6 [0] 7 8 8 [] """ class Solution__: def longestValidParentheses(self, s: str): """ Whenever we see a new open parenthesis, we push the current longest streak to the prev_streak_stack. and reset the current length Whenever we see a close parenthesis, If there is no matching open parenthesis for a close parenthesis, reset the current count. else: we pop the top value, and add the value (which was the previous longest streak up to that point) to the current one (because they are now contiguous) and add 2 to count for the matching open and close parenthesis. Use this example to understand `"(()())"` """ res = 0 prev_streak_stack, curr_length = [], 0 for char in s: # # saves streak that might be continued or broken by the next closing brackets if char == '(': prev_streak_stack.append(curr_length) # save prev streak curr_length = 0 # reset streak # # create/increase or reset streak elif char == ')': if prev_streak_stack: curr_length = curr_length + prev_streak_stack.pop() + 2 res = max(res, curr_length) else: curr_length = 0 return res """ """ class Solution_: def longestValidParentheses(self, s: str): """ use stack to store left most invalid positions (followed by opening brackets) note that an unclosed opening brackets is also invalid """ result = 0 # stack contains left most invalid positions stack = [-1] for idx, bracket in enumerate(s): if bracket == "(": stack.append(idx) else: stack.pop() # the top of the stack should now contain the left most invalid index if stack: result = max(result, idx-stack[-1]) # if not, the element removed was not an opening bracket but the left most invalid index # which means that this closing bracket is invalid and should be added to the top of the stack else: stack.append(idx) return result
7c7b991c5d76f3a915ae5fc1d6f1c2e40235a4f2
bMedarski/SoftUni
/Python/Fundamentals/Dictionaries and Functional Programming/02. Count Real Numbers.py
278
3.625
4
list_input = list(map(float, input().split(" "))) items_count = {} for item in list_input: if item in items_count: items_count[item] += 1 else: items_count[item] = 1 for key in sorted(items_count.keys()): print(f"{key} -> {items_count[key]} times")
ab3c8f81a0158c0ddc5e48e66a7a06add225a905
epson121/principles_of_computing
/cookie_clicker.py
7,838
3.515625
4
""" Cookie Clicker Simulator """ import simpleplot # Used to increase the timeout, if necessary import codeskulptor import math codeskulptor.set_timeout(20) import poc_clicker_provided as provided # Constants SIM_TIME = 10000000000.0 class ClickerState: """ Simple class to keep track of the game state. """ def __init__(self): self._tot_number = 0.0 self._cur_number = 0.0 self._cur_time = 0.0 self._cur_cps = 1.0 self._history = [(0.0, None, 0.0, 0.0)] def __str__(self): """ Return human readable state """ state = "\n" state += "TOTAL: " + str(self._tot_number) + "\n" state += "CURRENT: " + str(self._cur_number) + "\n" state += "TIME: " + str(self._cur_time) + "\n" state += "CPS: " + str(self._cur_cps) + "\n" return state def get_cookies(self): """ Return current number of cookies (not total number of cookies) Should return a float """ return self._cur_number def get_cps(self): """ Get current CPS Should return a float """ return self._cur_cps def get_time(self): """ Get current time Should return a float """ return self._cur_time def get_history(self): """ Return history list History list should be a list of tuples of the form: (time, item, cost of item, total cookies) For example: (0.0, None, 0.0, 0.0) """ return self._history def time_until(self, cookies): """ Return time until you have the given number of cookies (could be 0 if you already have enough cookies) Should return a float with no fractional part """ if self._cur_number > cookies: return 0.0 else: difference = cookies - self._cur_number time = difference / self._cur_cps return math.ceil(time) def wait(self, time): """ Wait for given amount of time and update state Should do nothing if time <= 0 """ if time <= 0: return else: self._cur_time += time self._cur_number += (self._cur_cps * time) self._tot_number += (self._cur_cps * time) def buy_item(self, item_name, cost, additional_cps): """ Buy an item and update state Should do nothing if you cannot afford the item """ if self._cur_number < cost: pass else: self._cur_cps += additional_cps self._cur_number -= cost history_item = (self._cur_time, item_name, cost, self._tot_number) self._history.append(history_item) def simulate_clicker(build_info, duration, strategy): """ Function to run a Cookie Clicker game for the given duration with the given strategy. Returns a ClickerState object corresponding to game. """ new_build_info = build_info.clone() clicker = ClickerState() while clicker.get_time() <= duration: cookies = clicker.get_cookies() cps = clicker.get_cps() time = clicker.get_time() _cur_time = clicker.get_time() item = strategy(cookies, cps, duration - time, new_build_info) if (item == None): clicker.wait(duration-_cur_time) break cost = new_build_info.get_cost(item) time_until = clicker.time_until(cost) if time_until + _cur_time > duration: clicker.wait(duration-_cur_time) break else: clicker.wait(time_until) clicker.buy_item(item, cost, new_build_info.get_cps(item)) new_build_info.update_item(item) return clicker def strategy_cursor(cookies, cps, time_left, build_info): """ Always pick Cursor! Note that this simplistic strategy does not properly check whether it can actually buy a Cursor in the time left. Your strategy functions must do this and return None rather than an item you can't buy in the time left. """ return "Cursor" def strategy_none(cookies, cps, time_left, build_info): """ Always return None This is a pointless strategy that you can use to help debug your simulate_clicker function. """ return None def strategy_cheap(cookies, cps, time_left, build_info): """ Docstring """ items = build_info.build_items() item_to_buy = None mini = SIM_TIME for item in items: cost = build_info.get_cost(item) if cost < mini: mini = cost item_to_buy = item cost2 = build_info.get_cost(item_to_buy) money = cookies + time_left * cps if cost2 > money: return None else: return item_to_buy def strategy_expensive(cookies, cps, time_left, build_info): """ Docstrings """ items = build_info.build_items() item_to_buy = None maxi = -1 money = cookies + cps * time_left for item in items: cost = build_info.get_cost(item) if cost <= money and cost > maxi: item_to_buy = item maxi = cost if item_to_buy == None: return None return item_to_buy def strategy_best(cookies, cps, time_left, build_info): """ Docstring """ items = build_info.build_items() money2 = cookies + cps * time_left * 0.07 ratio = 1 res = {} for item in items: cost = build_info.get_cost(item) cps = build_info.get_cps(item) ratio = cost/cps if cost <= money2: res[item] = ratio if res == []: return None else: return get_best_cps_2(res, build_info) def get_best_cps_2(items, build_info): """ Docstring """ ratio = 0.0 best_ratio_item = None for key in items.keys(): _ratio = items[key] if _ratio > ratio: if best_ratio_item != None: cost_bri = build_info.get_cost(best_ratio_item) cost_k = build_info.get_cost(key) if cost_k > cost_bri * 180: continue else: ratio = _ratio best_ratio_item = key else: ratio = _ratio best_ratio_item = key return best_ratio_item def run_strategy(strategy_name, time, strategy): """ Run a simulation with one strategy """ state = simulate_clicker(provided.BuildInfo(), time, strategy) print strategy_name, ":", state # Plot total cookies over time # Uncomment out the lines below to see a plot of total cookies vs. time # Be sure to allow popups, if you do want to see it history = state.get_history() history = [(item[0], item[3]) for item in history] #simpleplot.plot_lines(strategy_name, 1000, 400, 'Time', 'Total Cookies', [history], True) def run(): """ Run the simulator. """ #run_strategy("Cursor", SIM_TIME, strategy_cursor) run_strategy("Best", SIM_TIME, strategy_best) run() #import user34_GhjnBEJSmI_10 as test_suite #test_suite.run_simulate_clicker_tests(simulate_clicker,strategy_none,strategy_cursor) #test_suite.run_clicker_state_tests(ClickerState) #import user34_1yyodNweJj_0 as init_test #init_test.run_test(ClickerState) #import user34_gwOBYcB0vg_5 as wait_test #wait_test.run_test(ClickerState) #import user34_JegqHUeyeq_1 as time_until_test #time_until_test.run_test(ClickerState) #import user34_CX25TCXsrD_4 as buy_test #buy_test.run_test(ClickerState) #import user34_rjdKnsYfB9_2 as testsuite #testsuite.run_tests(ClickerState, simulate_clicker,strategy_cursor, strategy_cheap, strategy_expensive, strategy_best)
93661ba2f6bba475f195e409125987868f5097ea
SooDevv/Algorithm_Training
/CS Dojo/if_else.py
280
4.21875
4
name = input("What's your name : ") height_m = int(input("Write your height : ")) weight_kg = int(input("Write your weight : ")) bmi = weight_kg / (height_m ** 2) if bmi < 25: print("%s, you are not overweight" % name) else: print("WARNING %s, you are overweight" % name)
4863817cfc0fa0acfd127acb965fbefbcc84c2b1
deebika1/guvi
/codeketa/basis/give_two_number_N_and_K_if_K_is_persent_in_the_N_list_print_yes.py
355
3.640625
4
# program which is used to print yes if K is persent in the list def function1(N,K): l=list(map(int,input("").strip().split()))[:N] for i in range(0,N): count=0 if(K==l[i]): count=count+1 return count # get the value of N and K form the user N,K=list(map(int,input("").split())) res=function1(N,K) if(res==1): print("yes") else: print("no")
0d165e47659f509fad71cfdcd726c287ad555d33
yjthay/Python
/Python for Data Analysis/PythonDryRun.py
1,202
3.75
4
letters = "a/b/c" delimiter = "/" jlist = letters.split("/") #print jlist #print len(jlist) del jlist[len(jlist)-1] #print jlist jlist.append([4]) #print jlist orig = jlist[:] jlist.sort() #print orig #print jlist #mbox-short.txt emailfile = raw_input("Whats the file name? \n") fhand = open(emailfile) count =0 for line in fhand: words = line.split() #print "Debug: " + str(words) #print len(words) if len(words) != 0 and words[0] == "From": print words[1] count = count +1 continue #if words[0] != "From" : continue #print words[1] print "There were " + str(count) + " lines in the files with 'From' as the first word" fhand.close romeo = open("romeo.txt") romeolines = [] for line in romeo: #print line romeolines = romeolines + line.split() romeolines.sort() print romeolines userinput = "" list_of_numbers = [] while userinput != "DONE": userinput = raw_input("What is the number in your mind? :") if userinput !="DONE": userinput = int(userinput) list_of_numbers.append(userinput) print list_of_numbers print max(list_of_numbers) print min(list_of_numbers) raw_input("Press enter to exit")
a1adb38ba23296bbe303e997b2a0aeb16b394090
Luckyaxah/leetcode-python
/二叉树_判断完全二叉树.py
875
3.734375
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def isCBT(head): if not head: return from queue import Queue q = Queue() isMeet = False q.put(head) while not q.empty(): cur = q.get() l = cur.left r = cur.right if (isMeet and (l !=None or r != None ))\ or \ (l==None and r !=None): return False if l: q.put(l) if r: q.put(r) if (not l) or ( not r): isMeet = True return True if __name__ == "__main__": head = TreeNode(1) head.left = TreeNode(2) head.right = TreeNode(3) head.left.left = TreeNode(4) head.left.right = TreeNode(5) head.right.left = TreeNode(6) head.right.right = TreeNode(7) print(isCBT(head))
4f8f62b7bfd5d381756f4a99ba5cdaba9e145a01
heyitshenrylin/ArduinoCostCalculator
/modules/csvIO.py
3,945
3.84375
4
# Authors: Eric Claerhout, Henry Lin # Student IDs: 1532360, 1580649 # CMPUT 274 Fall 2018 # # Final Project: Price Finder ########### # Imports # ########### from sys import exit from csv import reader, DictReader, DictWriter ############# # Functions # ############# def getSupportedSites(): """ Get Supported Sites Function Reads the information from supportedSites.csv and generates a list of dictionaries where each dictionary contains various information regarding a website including its base URL, currency type, and price-identifying HTML elements Returns - supportedSites - A list of dictionaries """ supportedSites = [] try: with open('supportedSites.csv', newline='', mode='r') as csvFile: csvReader = DictReader(csvFile) for row in csvReader: supportedSites.append(dict(row)) return supportedSites # Exceptions except FileNotFoundError: print("supportedSites.csv could not be found.") print("Quitting...") exit() except Exception as e: print("getSupportedSites encountered the following error:") print(e) print("Quitting...") exit() def getPartsList(): """ Get Parts List Function Reads the information from partsList.csv and generates a list of lists. An inner-most list is referred to as a "part type" as it contains either a single part or multiple parts that are considered equivalent. The outer-most list is therefore considered to be a list of various part types. Returns - partsList- A list of lists """ partsList = [] try: with open('partsList.csv', newline='', mode='r') as csvFile: csvReader = reader(csvFile) for row in csvReader: # Filter is used to remove any the empty strings partsList.append(list(filter(None, row))) return partsList # Exceptions except FileNotFoundError: print("partsList.csv could not be found.") print("Quitting...") exit() except Exception as e: print("getPartsList encountered the following error:") print(e) print("Quitting...") exit() def writeOutput(results, fieldnames): """ Write Output Function Outputs the various part prices from the given results to output.csv, where 'results' is a list of lists of dictionaries. Each dictionary represents the data (prices) for an individual site, the inner-most list is a collection of these dictionaries for a given part-type, and the outer-most list is a collection of these part-type lists. Places blank lines between the various part-types. Args: - results: A list of lists of dictionaries - fieldnames: A list of strings indicating the output fieldnames (column titles) and their order. Values should match what can be found in the dictionaries. """ try: with open('output.csv', newline='', mode='w') as csvFile: csvWriter = DictWriter(csvFile, fieldnames=fieldnames) blankSpace = dict.fromkeys(fieldnames, '') # Write the fieldnames into the CSV csvWriter.writeheader() # Write the part prices for partTypePrices in results: for partPrice in partTypePrices: csvWriter.writerow(partPrice) # Add a blank space between part types csvWriter.writerow(blankSpace) # Exceptions except FileNotFoundError: print("output.csv could not be found.") print("Quitting...") exit() except Exception as e: print("writeOutput encountered the following error:") print(e) print("Quitting...") exit() ######## # Main # ######## if __name__ == "__main__": print(getSupportedSites()) print(getPartsList())
055de7907d3ff7bbed2bf78395965126af5ce606
alexmatros/codingbat-solutions
/python/string-2/cat_dog.py
243
3.765625
4
def cat_dog(str): cat = 0 dog = 0 for i in range(len(str) - 2): if str[i:i+3] == "dog": dog += 1 elif str[i:i+3] == "cat": cat += 1 else: continue if dog == cat: return True else: return False
d04bf6cf8400adbde17ea8a5330b3aad71bfac06
Sonalsutar/assignments
/reversearray.py
140
3.734375
4
#Program to reverse the array a=[11,22,33,44,55] L=(len(a)) for i in range (int(L/2)): n=a[i] a[i]=a[L-i-1] a[L-i-1]=n print(a)
857ad05329cfd9323d4d6954e6f03b928b06899f
bfontaine/Katas
/KataPotter/KataPotter.py
2,042
3.765625
4
#! /usr/bin/python3.2 # Note : # I don't think that this program is *really* working for # books > 8, but I don't have more tests to test it # class TooManyBooksException(Exception): def __init__(self,*args): super(*args) # returns the price with as big discount as # possible. Format: list of books, e.g. : # [2,4,7,0,1] = 2x the first book, # + 4x the second one, # + 7x the third one, # + 1x the fifth one. def calculate_price(*books): if (len(books) > 5): raise TooManyBooksException # see Notes file COEFS = [8, 7.2, 6.4, 4, 4.4] # keep only non-0 elements books = [b for b in books if b] # 0 books if (len(books) == 0): return get_original_price(0) # some books with the same title if (len(books) == 1): return get_original_price(books[0]) # N books for each different title if (min(books) == max(books)): return apply_discount(books[0], len(books)) books2 = books[:] books2.sort() books2.reverse() if ((sum(books) > 7) and (max(books) == 2)): COEFS[-1] = 4 price = sum([a*b for a,b in zip(books2, COEFS)]) if (sum(books) > 8): # hack price -= 0.4 * ((int(sum(books)/25))+1) return price # returns the discount for n different books, in % # (i.e. 0 <= discount <= 0.25) def get_discount(n): # 1 -> 0 | 2 -> 0.05 # 3 -> 0.10 | 4 -> 0.20 # 5 -> 0.25 return (n-1)/20.0 if (n<4) else n/20.0 # Apply discount for `n` books of `n_diff` different titles # e.g. : n=3, n_diff=4 -> 12 books -> 9.6 euros def apply_discount(n, n_diff=None): if (n_diff == None): # if only one of each n_diff = n tmp = n%5 n -= tmp total = get_original_price(tmp*n_diff) * (1 - get_discount(n_diff)) while (n > 0): total += get_original_price(n*n_diff) * (1 - get_discount(n_diff)) n -= 5 return total # returns the price for n books, without discount def get_original_price(n): return 8 * n
e9549c96c867696c13ceb49ede8d36fb7edbf4c4
Fahad1192/programming-with-shazzal
/Class-2/palindrome.py
479
3.5
4
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ s = ''.join(char for char in s if char.isalnum()) s = s.lower() start = 0 end = len(s) - 1 start = 0 end = len(s) - 1 while start < end: if s[start] != s[end]: return False start, end = start + 1, end - 1 return True
77e7f95efb1d5ab19077266f6596f5b97466afa0
esethuraman/SearchEngine
/utils/StopWordsFormatter.py
572
3.875
4
''' given stopwords file has every word in a new line which might have newline characters and other noise. So, this utility cleans up all and write all the stopwords in a single line separated by spaces ''' from utils import properties def regenerate_stop_words(): output_file = open(properties.formatted_stop_words_file, 'w') with open(properties.given_stop_words_file, 'r') as file: all_lines = file.readlines() for line in all_lines: output_file.write(line.strip() + " ") output_file.close() regenerate_stop_words()
aab0e62aad35b3c03d6e29e9dbd066f7b7ea89d9
AlexNalev/DS
/BST.py
2,631
4.125
4
class Node: def __init__(self, data): self.data = data self.left = self.right = None class BinarySearchTree: def __init__(self): self.root = None self.ask_elements() @classmethod def insert(cls, root, data): """ This method is a class method to create a tree that is not gonna have more elements once it's built. If we want to allow the insertion of new elements, we take out the class references and make this function a function of the instances of the Binary Search Tree class. In the main it will be called as: bt.insert(bt.root, data) """ if root is None: return Node(data) else: if data < root.data: node = cls.insert(root.left, data) root.left = node elif data > root.data: node = cls.insert(root.right, data) root.right = node else: pass return root def ask_elements(self): number_elements = int(input("Number of elements in the tree (root included): ")) for i in range(number_elements): data = int(input(f"Element {i + 1}: ")) self.root = self.insert(self.root, data) def preorder(self, node): if node is None: return else: print(node.data, end=" ") self.preorder(node.left) self.preorder(node.right) def inorder(self, node): if node is None: return else: self.inorder(node.left) print(node.data, end=" ") self.inorder(node.right) def postorder(self, node): if node is None: return else: self.postorder(node.left) self.postorder(node.right) print(node.data, end=" ") def level_order(self, root): queue = [] queue.append(root) while len(queue) != 0: node = queue.pop(0) print(node.data, end=" ") if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) bt = BinarySearchTree() print("--------------------Preorder traversal-----------------") bt.preorder(bt.root) print("\n--------------------Inorder traversal-----------------") bt.inorder(bt.root) print("\n--------------------Postorder traversal-----------------") bt.postorder(bt.root) print("\n--------------------Level traversal-----------------") bt.level_order(bt.root)
885a0cb8d39778eddd28c20d1e7193a77cf14d6b
marcos-evangelista/Projeto-validando-nota-no-python
/validando.py
1,803
4.125
4
#Esse codigo foi atualizado, pois o if foi trocado por while. #Caso a nota seja maior que 10, irá informar que a nota foi digitada errada! #Fará que o usuário, fique em um loop, até que digite a nota correta!!! nome= str(input('Digite seu nome:')) a = int (input('\n {nome} digite a nota do primeiro bimestre: '.format(nome=nome))) #Entrada da nota while a > 10: #Verificando se a nota é maior que 10. a=int (input('A nota do primeiro bimestre está errada! {nome}Digite novamente:'.format(nome=nome)))#Caso a nota >10 informo o erro b = int (input ('\n {nome} digite a nota do segundo bimestre: '.format(nome=nome)))#Entrada da nota while b > 10: #Verificando se a nota é maior que 10 b=int (input('{nome} a nota do segundo bimestre está errada! Digite novamente:'.format(nome=nome)))#Se for informar erro c = int(input('\n{nome} digite a nota do terceiro bimestre: '.format(nome=nome))) #Entrada da nota while c > 10: #Verificando se a nota é maior que 10 c=int (input('{nome} nota do terceiro bimestre está errada! Digite novamente:'.format(nome=nome)))#Se for informar erro d = int(input('\nAgora {nome} digite a nota do quarto bimestre: '.format(nome=nome)))#Entrada da nota while d > 10: d=int (input('A nota do quarto bimestre está errada! {nome} Digite novamente:'.format(nome=nome)))#Se for informar erro media = (a+b+c+d)/4 print('A média é: {}'.format(media)) #Irá imprimir na tela a média if media >=7<10: print ('Parabéns! {nome} Você foi aprovado(a)! média {media}'.format(nome=nome,media=media)) elif media <6: print ('Infelizmente você foi reprovado(a)!{nome} a sua média foi média {media}'.format(nome=nome,media=media)) else: print('{nome} você está de recuperação e terá que fazer a prova novamente!'.format(nome=nome))
cf8af6e2ac070b3298da5676b0ffeac62552dd49
MihaiAnton/University
/Semester 4/Artificial Intelligence/Lab1/Sudoku/DFS/SudokuSolver.py
1,684
3.890625
4
from SudokuLogic.Table import Table class SudokuSolver: """ Solves a valid sudoku grid using DFS(backtracking) :param - the sudoku table """ def solveSudoku(self, table): treeStack = [table] #the DFS stack while len(treeStack) > 0: #still a sudoku table to try crtTable = treeStack.pop(0) #get the stack's top line,col = crtTable.getNextLineCol() #get the next position to add #line,col = crtTable.getBestAddSquare() print(str(line) + " " + str(col)) if line >= table.getN() or col >= table.getN(): #if the sudoku is complete return crtTable #return the solution for val in range(1, crtTable.getN()+1): #for each possible value [1,n] if crtTable.validAdd(line,col,val): #add the value and continue adding #print("Added " + str(val) + " on " + str(line) + " " + str(col)) nextTable = Table(crtTable.getN(),crtTable.getTable()[:]) #duplicate the table nextTable.add(line,col,val) #add the element treeStack.insert(0,nextTable) #add the new table to the DFS stack if treeStack[0].isFull(): #if the table lately created is full(complete) return treeStack[0] #return the solution return False #could not find a solution
27da6e733371c8f82b8268d2a0d514b0a44b72a2
shfjri/learn_from_home
/mechanical_energy.py
3,142
3.953125
4
author = 'shfjri' def asks_help_again(): # function to asks user, need more help or exit play = input('\nNeed more help? [y/n] ') # asks user, need more help or exit if play.isalpha() == True: # if user input a letter play = play.lower() # convert letter to lowercase if play == 'y': # if user need more help print() main() # run the game again elif play == 'n': # if user want to exit print('\nThank you for asking me.') print('Have a nice day') else: # if user's input not in the option print('\nPlease choose one from the option.') asks_help_again() # asks user again, need more help or exit else: # if user input a number or symbol print('\nYou have to choose a letter in option, not number or symbols') asks_help_again() # asks user again, need more help or exit return None def kinetic(): try: print('\nKinetic Energy Calculator') m = float(input('Input the mass in kg: ')) # asks user to input value of mass in kg v = float(input('Input the velocity in m/s: ')) # asks user to input value of velocity in m/s K = (1/2) * m * (v**2) # calculate the value of kinetic energy print('Kinetic energy of a {} kg mass with {} m/s velocity is {} J'.format(m,v,K)) # print the result except: print('\nYou have to input a number\n') kinetic() return None def potential(): try: print('\nPotential Energy Calulator') m = float(input('Input the mass: ')) # asks user to input value of mass in kg g = float(input('Input the gravity acceleration: ')) # asks user to input value of graviticy acceleration h = float(input('Input the altitude in meter: ')) # asks user to input value of altitude in m V = m * g * h # calculate the value of potential energy print('Potential energy of a {} kg object at {} m altitude is {} J'.format(m, h, V)) # print the result except: print('\nYou have to input a number\n') potential() return None def choice(): user_choice = input('''What do you want to calculate? a. Potential Energy b. Kinetic Energy\n''') # asks user, what they need a help to, calculate kinetic or potential energy if user_choice.isalpha() == True: # check user's input, alphabet or others if user_choice.lower() == 'a': # if user need a help to calculate potential energy potential() elif user_choice.lower() == 'b': # if user need help to calculate kinetic energy kinetic() else: print('You have to choose one of the option') # if user's input is not in the option choice() # asks user again else: print('Your input is not alphabet') # if user's input not alphabet choice() # asks user again return None def main(): print('Welcome to mechanical energy calculator') print('It was made by {}'.format(author)) choice() # call the choice function asks_help_again() # call help function return None main()
b8873226de4e7ffe1e3500c0ceb9aa35a3454897
zhangquanliang/python
/学习/day1/强密码判断.py
784
4
4
# -*- coding: utf-8 -*- def demo(L): k = len(L) if k >= 10: if L.isalnum() and not L.isdigit() and not L.isalpha()and not L.isspace(): return print("是强密码") else: L = L.replace("!","") L = L.replace("_","") L = L.replace("#","") L = L.replace("@","") m = len(L) if k != m and L.isalnum()and not L.isdigit() and not L.isalpha(): return print("是强密码") elif k != m and L.isalpha() and not L.lower() in L and not L.upper() in L: return print("是强密码") else: return print("不是强密码") else: return print("不是强密码") L = input("请输入一组密码:") demo(L)
c736afedd997c47409388caee2f1a33e313be117
abhisheksahnii/python_you_and_me
/simple_calculator.py
769
4.28125
4
#!/usr/bin/env python3 ''' Program make a simple calculator that can add, sub, mul and div using functions ''' def add(x, y): return x + y def sub(x, y): return x - y def mul(x, y): return x * y def div(x, y): return x / y print("Select Operation.") print("1. ADD") print("2. SUBTRACT") print("3. MULTIPLY") print("4. DIVIDE") choice = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == 1: print(num1,"+",num2,"=",add(num1, num2)) elif choice == 2: print(num1,"-",num2,"=",sub(num1, num2)) elif choice == 3: print(num1,"*",num2,"=",mul(num1, num2)) elif choice == 4: print(num1,"/",num2,"=",div(num1, num2)) else: print("Invalid Input.")
f508f2adb8b67c02bd314fd95c57df8a16fa7a77
BavoGoosens/TMI
/Position.py
475
4.1875
4
from math import sqrt class Position(object): """A class used to represent Position""" def __init__(self , x, y): self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y def distance(self, other): return ((self.getX() - other.getX())**2 + (self.getY() - other.getY())**2)**0.5 def to_string( self ): return "(" + str(self.getX()) + ", " + str(self.getY()) + ")"
3a50f6e196c1206bf3c913a207099e1121dc8571
doctor-to-code/number
/r.py
350
3.75
4
a = input('請輸入數字下限') b = input('請輸入數字上限') a = int(a) b = int(b) import random r = random. randint(a, b) i = 0 while True: i = i + 1 x = input('請輸入數字') x = int(x) if x == r: print('you win') break elif x > r: print('比答案大') elif x < r: print('比答案小') print('已經猜第', i,'次')
5c98ee140ab31db46bef905417ebeefbdc230573
EasternBlaze/ppawar.github.io
/Spring2019/CSE101-S19/programs/Lecture5-Examples/find_max.py
314
4.1875
4
# This function finds and returns the maximum value in a list. def find_max(nums): maximum = nums[0] for i in range(1, len(nums)): if nums[i] > maximum: maximum = nums[i] return maximum ages = [20, 16, 22, 30, 17, 24] max_age = find_max(ages) print('Maximum age: ' + str(max_age))
8bba3e5b01696ffe21f7a072962a666ece3dfefe
cnrmurphy/python-lessons
/notes/session_3/linked_list_solution.py
1,086
4.15625
4
class Node(): def __init__(self, data): self.data = data self.next = None def get_data(self): return self.data # returns 1 class Linked_List(): def __init__(self): self.head = None def append(self, data): if not self.head: self.head = Node(data) return current_node = self.head while current_node.next is not None: current_node = current_node.next current_node.next = Node(data) def traverse(self): if not self.head: return current_node = self.head while current_node is not None: print(f'{current_node.data}') current_node = current_node.next # Visit every node in the list, and print the node's data/value def reverse(self): prev = None current_node = self.head while current_node is not None: nextnode = current_node.next current_node.next = prev prev = current_node current_node = nextnode self.head = prev linked_list = Linked_List() linked_list.append(1) linked_list.append(2) linked_list.append(3) linked_list.traverse()
8216d661d2cc71c36769b6f1041a2142af1a2220
YAJINGE/StudyPython
/chapter_2/library.py
973
3.6875
4
book_list = ['坏蛋是怎样炼成的', '上门女婿', 'D调的华丽', 'java', '数据结构与算法'] for num in range(0, 50): jud = input('借书or还书:') # 借书 if jud == '借书': print(book_list) str_lend = input('请输入要借的书名:') if str_lend in book_list: print('图书馆有1本'+str_lend) str_judge = input('是否要借出:是/否') if str_judge == '是': # 图书清单中删除已借出的图书 book_list.remove(str_lend) print(str_lend, '已成功借出') print(book_list) else: print('本次借书已结束') else: print(str_lend, '已被借出') print(book_list) # 还书 else: str_return = input('请输入要还的书名:') book_list.append(str_return) print(str_return, '已成功还入') print(book_list)
522dce7d5f624aaa241fe4b51fb6709b338d4ab3
Vasu-Eranki/Project_Euler
/Challenge65.py
773
3.828125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import os def convergence(n): y = [1, 2] k = 2 count =1 x=[2,3] for i in range(2, n): if(count%3==0): y.append(2*k) k+=1 count= 1 else: y.append(1) count+=1 for i in range(1,n-1): temp = y[i]*x[i]+x[i-1] x.append(temp) z=str(max(x)) print() total=0 for j in z: total = total+int(j) if(n==1): total =2 elif(n==2): total = 3 else: pass return total if __name__=='__main__': n = int(input()) sum1 = convergence(n) fptr = open(os.environ['OUTPUT_PATH'],'w') fptr.write(str(sum1)+'\n') fptr.close()
26059cd97175a43a6c583545daaa5f4e9aacc2d9
junwoo77lee/Python_Algorithm
/fibonacci_sum_squares.py
2,541
3.953125
4
# Uses python3 import sys import random import time # Problem description # Input: n is an integer; 0 ≤ n ≤ 10**14 # Output: The last digit of F0^2 + F1^2 + ... + Fn^2 def fibonacci_sum_squares_naive(n): if n <= 1: return n previous = 0 current = 1 sum = 1 for _ in range(n - 1): previous, current = current, previous + current sum += current * current return sum % 10 def fibonacci_sum_squares_fast(n): periodic_squared_last_digits = get_fibonacci_squared_last_digits() pisano_period = len(periodic_squared_last_digits) modulo = n % pisano_period return sum(periodic_squared_last_digits[:modulo+1]) % 10 def get_fibonacci_squared_last_digits(n=29): # period is 60 periodic_squared_list = [] periodic_list = [] for i in range(n+1): if i <= 1: periodic_list.append(i) periodic_squared_list.append(i**2) else: last_digit = (periodic_list[i-2] + periodic_list[i-1]) % 10 periodic_list.append(last_digit) periodic_squared_list.append((last_digit**2) % 10) return periodic_squared_list if __name__ == '__main__': n = int(input()) print(fibonacci_sum_squares_fast(n)) ################################################################################################ # Stress test1: check if correct answers on the fast algorithm in a comparison to the naive one. ################################################################################################ # start, end = 0, 10000 # while True: # n = random.randint(start, end) # print(n) # naive = fibonacci_sum_squares_naive(n) # fast = fibonacci_sum_squares_fast(n) # if naive != fast: # print(f"Wrong answer. Naive vs. Fast = {naive} vs. {fast}") # break # else: # print(f"OK") ################################################################################################ # Stress test2: speed test ################################################################################################ # start, end = 0, 10**14 # while True: # n = random.randint(start, end) # print(n) # t0 = time.time() # fast = fibonacci_sum_squares_fast(n) # t1 = time.time() # tdiff = t1 - t0 # if tdiff < 5: # print(f"It takes {tdiff} seconds.") # else: # print("It takes more than 5 seconds.")
fa8b179cebc011a00a9fda1cbc9beb8a4bd3e3ce
letterbeezps/leetcode-algorithm
/leetcode/STR/1408.stringMatching/1408python3.py
319
3.5625
4
class Solution: def stringMatching(self, words: List[str]) -> List[str]: ans = [] for word in words: for s in words: if s == word: continue if word in s: ans.append(word) break return ans
dae1d1c8b93af26f277b407fa13e4dbd98e0df83
gschen/sctu-ds-2020
/1906101073-李闻达/3.31/test.py
1,512
3.859375
4
class Stack(object): def __init__(self,limit = 10): self.stack = [] self.limit = limit def is_empty(self): return len(self.stack) == 0 def push(self,data): if len(self.stack) >= self.limit: print('栈溢出') else: self.stack.append(data) def pop(self): if self.stack: return self.stack.pop() else: print('空栈不能被弹出') def top(self): if self.stack: return self.stack[-1] def size(self): return len(self.stack) class Node(object): def __init__(self,data): self.data=data self.next=None class Stack(object): def __init__(self): self.node=Node(None) self.head=self.node self.size=0 def is_empty(self): return self.size==0 def get_size(self): return self.size def push(self,data): node=Node(data) node.next=self.head.next self.head.next=node self.size+=1 def pop(self): if not self.is_empty(): current_node=self.head.next if self.get_size()==1: self.head.next=None else: self.head.next=self.head.next.next self.size-=1 return current_node.data else: print('栈为空') def top(self): if not not self.is_empty(): return self.head.next.data else: print('栈为空')
c4c48ddd2b0f2c5cc2686a85d58811582e7f6005
SullyJHF/python-dev
/uni/numbers.py
169
4
4
a = int(input('Enter your first number: ')) b = int(input('Enter your second number: ')) print(a + b) print(a - b) print(a * b) print(a / b) print(a % b) print(a // b)
274136af16f83d42c9249cbe767711d7d49f4185
thedarkknight513v2/daohoangnam-codes
/C4E18 Sessions/Session_8/f-math-problem/freakingmath.py
1,499
3.84375
4
from random import * def generate_quiz(): # Hint: Return [x, y, op, result] x_variable = randint(1, 10) y_variable = randint(1, 10) operation_list = ["+" , "-" , "*", "/"] operation_choice = choice(operation_list) error_list = [-1, 1, 0] error_choice = choice(error_list) if operation_choice == "+": give_result = x_variable + y_variable + error_choice correct_result = x_variable + y_variable elif operation_choice == "-": give_result = x_variable - y_variable + error_choice correct_result = x_variable - y_variable elif operation_choice == "*": give_result = x_variable * y_variable + error_choice correct_result = x_variable * y_variable elif operation_choice == "/": give_result = x_variable / y_variable + error_choice correct_result = x_variable / y_variable return [x_variable, y_variable, operation_choice, give_result] def check_answer(x_variable, y_variable, operation_choice, give_result, player_response): correct_or_not = True if x_variable + y_variable == give_result: if player_response == "Y": correct_or_not = True elif player_response == "N": correct_or_not = False elif x_variable + y_variable != give_result: if player_response == "Y": correct_or_not = False elif player_response == "N": correct_or_not = True return correct_or_not
a20e95d2298516cba1cf0cf0401d85f6fe9b7ea1
anildoferreira/CursoPython-PyCharm
/exercicios/aula20.py
879
3.828125
4
'''def linha(): print('-------------') linha() print('Curso em vídeo') linha() def título(msg): print('-------------') print(msg) print('-------------') título('Testando Função!') título('Outra teste') def soma(a, b): print(f'A = {a} e B = {b}') s = a + b print(f'A soma de A + B = {s}') # Programa Principal soma(4, 5) soma(2, 9) soma(3, 8) def contador(* num): tam = len(num) print(f'Recebi os valores de num {num} e o seu tamanho é de {tam}') contador(2, 3, 5, 0, 4) contador(4, 5, 4, 9) contador(3, 5, 7) def dobra(lista): pos = 0 while pos < len(lista): lista[pos] *= 2 pos += 1 valores = [2, 5, 6, 4] dobra(valores) print(valores)''' def soma(* valores): s = 0 for num in valores: s += num print(f'Somando os valores {num}, a soma é {s}') soma(2, 5, 5) soma(2, 4)
2414859705c106dd053bb162f5e42089864611e7
danocando/Axelrod
/axelrod/player.py
2,154
3.59375
4
import inspect import random C, D = 'C', 'D' flip_dict = {C: D, D: C} def update_histories(player1, player2, move1, move2): """Updates histories and cooperation / defections counts following play.""" # Update histories player1.history.append(move1) player2.history.append(move2) # Update player counts of cooperation and defection if move1 == C: player1.cooperations += 1 elif move1 == D: player1.defections += 1 if move2 == C: player2.cooperations += 1 elif move2 == D: player2.defections += 1 class Player(object): """A class for a player in the tournament. This is an abstract base class, not intended to be used directly. """ name = "Player" def __init__(self): """Initiates an empty history and 0 score for a player.""" self.history = [] self.stochastic = "random" in inspect.getsource(self.__class__) self.tournament_length = -1 if self.name == "Player": self.stochastic = False self.cooperations = 0 self.defections = 0 def __repr__(self): """The string method for the strategy.""" return self.name def _add_noise(self, noise, s1, s2): r = random.random() if r < noise: s1 = flip_dict[s1] r = random.random() if r < noise: s2 = flip_dict[s2] return s1, s2 def strategy(self, opponent): """This is a placeholder strategy.""" return None def play(self, opponent, noise=0): """This pits two players against each other.""" s1, s2 = self.strategy(opponent), opponent.strategy(self) if noise: s1, s2 = self._add_noise(noise, s1, s2) update_histories(self, opponent, s1, s2) def reset(self): """Resets history. When creating strategies that create new attributes then this method should be re-written (in the inherited class) and should not only reset history but also rest all other attributes. """ self.history = [] self.cooperations = 0 self.defections = 0
f251558f1c5df765081f8d5f477a5b17c6b30ffb
pravallikachowdary/pravallika
/pg21.py
443
4.34375
4
# Python 3 Program to # find nth term of # Arithmetic progression def Nth_of_AP(a, d, N) : # using formula to find the # Nth term t(n) = a(1) + (n-1)*d return (a + (N - 1) * d) # Driver code a = 2 # starting number d = 1 # Common difference N = 5 # N th term to be find # Display the output print( "The ", N ,"th term of the series is : ", Nth_of_AP(a, d, N)) # This code is contributed # by Nikita Tiwari.# your code goes here
9e5fccbc4007cd46abf4471e6b07b82846f41ddc
szabgab/slides
/python/examples/multitasking/counter_with_locking.py
595
3.59375
4
import multitasking import time import threading multitasking.set_max_threads(10) counter = 0 locker = threading.Lock() @multitasking.task def count(n): global counter for _ in range(n): locker.acquire() counter += 1 locker.release() if __name__ == "__main__": start = time.time() k = 10 n = 1000000 for _ in range(k): count(n) multitasking.wait_for_tasks() end = time.time() expected = k * n print(f'done actual: {counter} expected: {expected}. Missing: {expected-counter}') print(f'Elapsed time {end-start}')
b7a8d6a4aa9c972a7cb653996c38e07b5ea4aa9b
RayGutt/python
/chapter_09_Classes/ex_9.3.py
697
3.71875
4
class User: def __init__(self, first_name, last_name, username, email): self.first_name = first_name self.last_name = last_name self.username = username self.email = email def describe_user(self): print(f"Username: {self.username}") print(f"Email: {self.email}") print(f"Full name: {self.first_name} {self.last_name}") def greet_user(self): print(f"Hello, {self.first_name} !") user_0 = User('matthieu', 'boucard', 'mboucard', '[email protected]') user_1 = User('norbert', 'zobi', 'nzobi', 'norbert@hotmail') user_2 = User('Zoé', 'zimoula', 'zz', '[email protected]') user_0.describe_user() user_0.greet_user() user_1.describe_user() user_1.greet_user() user_2.describe_user() user_2.greet_user()
319d4110bb8af0d3bd3ccc7f88908367e4c982fe
Herna7liela/New
/list7.py
162
3.640625
4
# What is an expression using the range function that yields a list of 10 # consecutive integers starting at 0? for i in range(0,10,1): print (i) # DONE
8e9b898f03f3a2183664aeeaa1e1bf11e7672f70
Geodit/Homework
/task4_les3.py
1,302
4.4375
4
# 4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить # возведение числа x в степень y. Задание необходимо реализовать # в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа # в степень. # Подсказка: попробуйте решить задачу двумя способами. Первый — возведение в степень с помощью оператора **. # Второй — более сложная реализация без оператора **, предусматривающая использование цикла. def exponentation(number: float, exponent: int): '''this function does something''' print (1 / number ** exponent) result = 1 / number for i in range(1, exponent): result /= number print(result) number = float(input('Enter a positive float number: ')) exponent = int(input('Enter a negative exponent: ')) exponentation(number, exponent*(-1)) # комментарий
cde55aa19b77d10a74fab1856bcb521d8a39263b
ilieandrei98/labs
/python/solutii/stefan_caraiman/fill.py
1,834
4.03125
4
""" Implement paint fill function for a given matrix """ from __future__ import print_function def matrix_print(rows, columns, image): """ Prints a matrix :param rows: rows of the matrix :param columns: cols of the matrix :param image: the image/matrix :return: a printed image/matrix """ for i in xrange(0, rows): for j in xrange(0, columns): print(image[i][j], end="") print() def umple(imagine, punct): """ Fills the image with * characters :param imagine: the image/matrix :param punct: the position from where to start filling :return: the filled image """ positionx, positiony = punct[0], punct[1] if imagine[positionx][positiony] == '*': return imagine[positionx][positiony] = '*' if positiony < (len(imagine[0]) - 1): umple(imagine, (positionx, positiony + 1)) if positiony >= 1: umple(imagine, (positionx, positiony - 1)) if positionx < (len(imagine) - 1): umple(imagine, (positionx + 1, positiony)) if positionx >= 1: umple(imagine, (positionx - 1, positiony)) return imagine def main(): """ The main function :return: a printed filled image """ imaginea = [ ["-", "-", "-", "-", "-", "*", "-", "-", "-", "-", "-", "-"], ["-", "-", "-", "-", "-", "*", "-", "-", "-", "-", "-", "-"], ["-", "-", "-", "-", "-", "*", "-", "-", "-", "-", "-", "-"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "*", "-"], ["-", "-", "-", "-", "-", "*", "-", "*", "-", "-", "*", "-"], ["-", "-", "-", "-", "-", "*", "-", "*", "-", "-", "*", "-"], ] umple(imaginea, (1, 3)) umple(imaginea, (5, 11)) matrix_print(len(imaginea), len(imaginea[0]), imaginea) if __name__ == "__main__": main()
36b4a4747a53174c8854c5308445a025632e6840
Jyotirm0y/kattis
/autori.py
95
3.75
4
line = input().split('-') result = "" for part in line: result += part[0] print(result)
b6efe20ff22a0062cb4aebf580660916d5df7e6e
4ions/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
456
3.984375
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) if number < 0: _number = number * -1 tmp = (_number % 10) * -1 else: _number = number tmp = _number % 10 if tmp > 5: print("Last digit of {} is {} and is greater than 5".format(number, tmp)) elif tmp == 0: print("Last digit of {} is {} and is 0".format(number, tmp)) else: print("Last digit of {} is {} and \ is less than 6 and not 0".format(number, tmp))
78419d1cdd5f7cb0a7ee0435f9f157c197ff2d70
leguims/Project-Euler
/Problem0025.py
1,102
4.1875
4
Enonce = """ 1000-digit Fibonacci number Problem 25 The Fibonacci sequence is defined by the recurrence relation: Fn = Fn-1 + Fn-2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ import EulerTools def main(): print(40*"=") print(Enonce) print(40*"-") Solution = 0 size = 1000 #3 highest = int('9'*size) for index, fibo_value in enumerate(EulerTools.Fibonacci(highest_value=highest),1): #print(f"Fibo({index})={fibo_value}") if len(str(fibo_value)) >= size: Solution = index + 1 # F1=1 ; F2=1 instead of F1=1 ; F2=2 break print(f"The {Solution}th Fibonacci value is {len(str(fibo_value))} digits") print(40*"-") print("Solution = {}".format(Solution)) print(40*"=") if __name__ == "__main__": # execute only if run as a script main()
c8e676131ea65596bf41b860e2b094555465d28c
srini4547/cumulus
/cumulus/cumulus_ds/terminal_size.py
2,442
3.5
4
""" Functions for calculating the teminal size """ import os import shlex import struct import platform import subprocess def get_terminal_size(): """ Get the current terminal size """ current_os = platform.system() tuple_xy = None if current_os == 'Windows': tuple_xy = _get_terminal_size_windows() if tuple_xy is None: tuple_xy = _get_terminal_size_tput() # needed for window's python in cygwin's xterm! if current_os in ['Linux', 'Darwin'] or current_os.startswith('CYGWIN'): tuple_xy = _get_terminal_size_linux() if tuple_xy is None: print "default" tuple_xy = (80, 25) # default value return tuple_xy def _get_terminal_size_windows(): """ Get the terminal size on Windows """ try: from ctypes import windll, create_string_buffer # stdin handle is -10 # stdout handle is -11 # stderr handle is -12 handle = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi) if res: (_, _, _, _, _, left, top, right, bottom, _, _) = struct.unpack("hhhhHhhhhhh", csbi.raw) sizex = right - left + 1 sizey = bottom - top + 1 return sizex, sizey except: pass def _get_terminal_size_tput(): """ Fallback function for Windows """ try: cols = int(subprocess.check_call(shlex.split('tput cols'))) rows = int(subprocess.check_call(shlex.split('tput lines'))) return (cols, rows) except: pass def _get_terminal_size_linux(): """ Get the terminal size in Linux / Darwin """ def ioctl_GWINSZ(fdd): """ Undocumented """ try: import fcntl import termios crd = struct.unpack( 'hh', fcntl.ioctl(fdd, termios.TIOCGWINSZ, '1234')) return crd except: pass crd = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not crd: try: fdd = os.open(os.ctermid(), os.O_RDONLY) crd = ioctl_GWINSZ(fdd) os.close(fdd) except: pass if not crd: try: crd = (os.environ['LINES'], os.environ['COLUMNS']) except: return None return int(crd[1]), int(crd[0])
86111f06b3cde48dfbb3c54f111dd4126045351f
rtx34/Calentando-el-brazo
/Calentando el brazo pendiente.py
8,492
3.671875
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 3 10:09:41 2021 @author: jorge """ import numpy as np import re from math import prod from math import sqrt from collections import Counter #=================================1================================ class Solution: def solve(self, palabras): s = "".join(palabras[0].upper() + palabras[1:].lower() for palabras in palabras) return s[0].lower() + s[1:] ob = Solution() palabras = ["Hello", "World", "Python", "Programming"] print(ob.solve(palabras)) #==================================2================================ def conversion(palabra): conversion = re.sub('([a-z][A-Z]+)(.)', r'\1_\2', palabra) return re.sub('([a-z0-9])([A-Z])', r'\1_\2' , conversion).lower() print(conversion('Hola Mundo')) #==================================3================================ def kebab(s): return '-'.join( re.sub(r"(\s|_|-)+"," ", re.sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", lambda mo: ' ' + mo.group(0).lower(), s)).split()) print(kebab('Hola Mundo')) #==================================4=============================== test_str = 'Hola Mundo' print("The original string is : " + test_str) res = test_str.replace("_", " ").title().replace(" ", "") print("Cambiado : " + str(res)) #==================================5=============================== def conversion(palabra): conversion = re.sub('([a-z][A-Z]+)(.)', r'\1_\2', palabra) return re.sub('([a-z0-9])([A-Z])', r'\1_\2' , conversion).upper() print(conversion('Hola Mundo')) #==================================6=============================== s1 = ' abc ' print(f'String =\'{s1}\'') print(f'After Removing Leading Whitespaces String =\'{s1.lstrip()}\'') #==================================7=============================== print(f'After Removing Trailing Whitespaces String =\'{s1.rstrip()}\'') #==================================8=============================== print(f'After Trimming Whitespaces String =\'{s1.strip()}\'') #==================================9=============================== list1 = [5, 6, 9] list2 = [1, 2, 3] vector1 = np.array(list1) vector2 = np.array(list2) reversed_arr = vector1[::-1] addition = vector1 + vector2 print("Vector Addition : " + str(addition)) #==================================10============================== subtraction = vector1 - vector2 print("Vector Subtraction : " + str(subtraction)) #==================================11=============================== print(addition * 2) #==================================12=============================== print(vector1 * 2) #==================================13============================= print(reversed_arr) #==================================14============================== #==================================15============================== #==================================16============================== def calcularPersistenciaAditiva(numero, cont): if numero < 10: return 'Respuesta: %s' % cont cont += 1 lista = [] numero = str(numero) for i in numero: lista.append(int(i)) numeronuevo = sum(lista) print(cont, numero, numeronuevo) if numeronuevo < 10: return 'Respuesta: %s' % cont else: return calcularPersistenciaAditiva(numeronuevo, cont) print (calcularPersistenciaAditiva(5978, 0)) #==================================17============================== n = 969 def primer_persistente(n): digitos = [int(i) for i in str(n)] # Lista con los digitos separados persistencia = [prod(digitos)] # Lista con el producto de todos los digitos if len(digitos) != len(persistencia): print(persistencia[0]) primer_persistente(persistencia[0]) primer_persistente(n) #==================================18============================== class Ecuaciones2Grado(): def calcular(self, A, B, C): if ((B**2)-4*A*C) < 0: print("La solución de la ecuación es con números complejos") else: x1 = (-B+sqrt(B**2-(4*A*C)))/(2*A) x2 = (-B-sqrt(B**2-(4*A*C)))/(2*A) print("""\ Las soluciones de la ecuación son: x1 = {} x2 = {} """.format(x1, x2)) ec1 = Ecuaciones2Grado() ec1.calcular(1,-5,6) ec2 = Ecuaciones2Grado() ec2.calcular(2,-7,3) #==================================19============================== datos = [1,3,2,4,7,3,2,2,1,4] result = [] for item in datos: if item not in result: result.append(item) print(result) #==================================20============================== result = [] for item in datos: if item not in result: result.append(item) print(result) #==================================21============================== # Python3 program for the above approach # function to check if two strings are # anagram or not def check(s1, s2): # implementing counter function if(Counter(s1) == Counter(s2)): print("Son anagrams.") else: print("No son anagrams.") # driver code s1 = "FORM" s2 = "FROM" check(s1, s2) #==================================22============================== def getMissingNo(A): n = len(A) total = (n + 1)*(n + 2)/2 sum_of_A = sum(A) return total - sum_of_A A = [1, 2, 4, 5, 6] miss = getMissingNo(A) print(miss) #==================================23============================== def find_len(list1): length = len(list1) list1.sort() print("Largest element is:", list1[length-1]) print("Smallest element is:", list1[0]) print("Second Largest element is:", list1[length-2]) print("Second Smallest element is:", list1[1]) # Driver Code list1=[12, 45, 2, 41, 31, 10, 8, 6, 4] Largest = find_len(list1) #==================================24============================== def reverseWordSentence(Sentence): words = Sentence.split(" ") newWords = [word[::-1] for word in words] newSentence = " ".join(newWords) return newSentence Sentence = "GeeksforGeeks is good to learn" print(reverseWordSentence(Sentence)) #==================================25============================== my_str = 'aIbohPhoBiA' # make it suitable for caseless comparison my_str = my_str.casefold() # reverse the string rev_str = reversed(my_str) # check if the string is equal to its reverse if list(my_str) == list(rev_str): print("The string is a palindrome.") else: print("The string is not a palindrome.") #==================================26============================== print("012345".isdecimal()) #==================================27============================== vowels = ['a', 'e', 'i', 'o', 'u'] #input a string and transform it to lower case str = ("hola mundo") #define counter variable for both vowels and consonants v_ctr = 0 c_ctr = 0 #iterate through the characters of the input string for x in str: #if character is in the vowel list, #update the vowel counter otherwise update consonant counter if x in vowels: v_ctr += 1 else: c_ctr += 1 #output the values of the counters print("Vowels: ", v_ctr) print("Consonants: ", c_ctr) #==================================28============================== a = "546" result = 0 for digit in a: result *= 10 for d in '0123456789': result += digit > d print(result) #==================================29============================== def my_mean(sample): return sum(sample) / len(sample) print(my_mean([4, 8, 6, 5, 3, 2, 8, 9, 2, 5])) def my_median(sample): n = len(sample) index = n // 2 if n % 2: return sorted(sample)[index] return sum(sorted(sample)[index - 1:index + 1]) / 2 print(my_median([3, 5, 1, 4, 2])) def my_mode(sample): c = Counter(sample) return [k for k, v in c.items() if v == c.most_common(1)[0][1]] print(my_mode([4, 1, 2, 2, 3, 5])) #==================================30============================== A = {3, 1, 2}; B = {2, 2, 1, 5}; # union print("Union :", A | B) # intersection print("Intersection :", A & B) # difference print("Difference :", A - B)
9bf8507a6f2e1e6b0974c89e30a56f3dc4e38bb9
HBharathi/Python-Programming
/Pattern.py
137
3.84375
4
#to print F pattern type numbers =[5,2,5,2,2] for x in numbers: out = "" for con in range(x): out += "x" print(out)
a7e1176afb804719b2f7b1b7782dbb2a4c261e37
dkljajo/Python-for-everybody---Coursera
/1. Programming 4 E/Assignment 5.2/Assignment_5_2.py
948
3.90625
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 11 17:51:48 2019 @author: dk 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below. """ largest = None smallest = None while True: num = input("Enter a number: ") if num == "done" : break try: inum=int(num) except: print('Invalid input') continue if smallest is None: smallest=inum elif inum<smallest: smallest=inum if largest is None: largest=inum elif inum>largest: largest=inum print("Maximum is", largest) print("Minimum is", smallest)
7ed2e3dce6c283bd6bfa51fbf2554e0f0704ff22
balder33/codingame
/venv/skynet_revolution_episode01.py
3,659
3.65625
4
from typing import ( List, Optional, Set, Tuple, ) def get_input_data() -> Tuple[List[List[int]], Set[int]]: """Возвращает существующие ссылки между узлами сети и номера узлов, являющихся выходными шлюзами. Нумерация узлов начинается с нуля, перемещаться между узлами можно в обоих направлениях. """ _, links_n, exits_n = [int(i) for i in input().split()] links, exits = [], set() for _ in range(links_n): links.append([int(j) for j in input().split()]) for _ in range(exits_n): exits.add(int(input())) return links, exits def get_graph_repr(edges: List[List[int]]) -> dict: """Возвращает представление графа в виде словаря. Ключами словаря являются вершины графа, значениями - достижимые вершины. """ def add_edge(i, j, gr): if i in gr: gr[i].add(j) else: gr[i] = {j} graph = {} for edge in edges: add_edge(*edge, graph) add_edge(*edge[::-1], graph) return graph def get_edge_to_marked_vertex(graph, marked_vertexes) -> Optional[Tuple[int, int]]: """Возвращает ребро до размеченной вершины графа, если такое существует.""" existing_marked_vertexes = marked_vertexes & graph.keys() if not existing_marked_vertexes: return None v1 = existing_marked_vertexes.pop() v2 = next(iter(graph[v1])) return v1, v2 def get_edge_to_delete(vertex: int, graph: dict, marked_vertexes: Set[int]) -> Optional[Tuple[int, int]]: """Возвращает ребро графа. Если из вершины vertex существует ребро до одной из вершин marked_vertexes, то оно будет возвращено. Если такого ребра нет, будет возвращено любое ребро в одну из вершин marked_vertexes. Если и таких ребер нет, то будет возвращено любое ребро из вершины vertex. Если ребер из вершины vertex не существует, будет возвращено None. """ neighbors = graph.get(vertex) if not neighbors: return marked_neighbors = neighbors & marked_vertexes if marked_neighbors: return vertex, marked_neighbors.pop() else: edge_to_marked_vertex = get_edge_to_marked_vertex(graph, marked_vertexes) if edge_to_marked_vertex: return edge_to_marked_vertex else: return vertex, next(iter(neighbors)) def delete_edge_from_graph(edge: Tuple[int, int], graph: dict) -> None: """Удаляет ребро графа.""" i, j = edge graph[i].remove(j) graph[j].remove(i) def destroy_link(node: int, network_repr: dict, exit_nodes: Set[int]) -> Tuple[int, int]: """Уничтожает связи между узлами сети.""" link_to_destroy = get_edge_to_delete(node, network_repr, exit_nodes) if not link_to_destroy: raise Exception('No links related with node %s' % node) delete_edge_from_graph(link_to_destroy, network_repr) return link_to_destroy if __name__ == '__main__': links, exits = get_input_data() network = get_graph_repr(links) while True: node = int(input()) print(*destroy_link(node, network, exits))
06a24d1c35a833bbdc1e048c8f0956da1029f89b
franktea/acm
/uva.onlinejudge.org/uva 10878 - Decode the tape/10878.py
469
3.609375
4
from sys import stdin def solve(line): for c in line: if c == '_': return ascii = [] for c in line: if (c == '|') or (c == '.'): continue if c == ' ': ascii.append('0') else: ascii.append('1') number = int(''.join(ascii), 2) print(chr(number), end='') for line in stdin.readlines(): line = line.strip() if not line: exit(0) solve(line)
815407c9127f970c80a70d5f5bd1c431fbecc150
Sasha2508/Python-Codes
/Others/bytelanc_coin_exchange.py
1,702
3.890625
4
''' problem statement: In Byteland they have a very strange monetary system. Each Bytelandian gold coin has an integer number written on it. A coin n can be exchanged in a bank into three coins: n/2, n/3 and n/4. But these numbers are all rounded down (the banks have to make a profit). You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. You have one gold coin. What is the maximum amount of American dollars you can get for it? Input The input will contain several test cases (not more than 10). Each testcase is a single line with a number n, 0 <= n <= 1 000 000 000. It is the number written on your coin. Output For each test case output a single line, containing the maximum amount of American dollars you can make. Explanation You can change 12 into 6, 4 and 3, and then change these into $6+$4+$3 = $13. If you try changing the coin 2 into 3 smaller coins, you will get 1, 0 and 0, and later you can get no more than $1 out of them. It is better just to change the 2 coin directly into $2. ''' # Write your code here def split(n): a,b,c = n//2, n//3, n//4 return a,b,c def process(n): a,b,c = split(n) value = a+b+c if value >= n: new_value = 0 value_list = [a,b,c] for i in range(len(value_list)): x,y,z = split(value_list[i]) if x+y+z >= value_list[i]: new_value += x+y+z if new_value > value: value = process(new_value) else: return value else: return n if __name__ == '__main__': t = int(input()) while t: n = int(input()) print(process(n)) t -= 1
fe682d5d0e549f7e3f1a90ff8f3ca3a54becd9ec
zmx0142857/dminor
/rational.py
13,650
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """basic rational calculation""" # 用 hashtable 保存整数因子, 加速有理数乘除? __author__ = 'Clarence Zhuo' from poly import Poly class Rat(object): """ Doctest: >>> r1 = Rat(1,2) >>> r2 = Rat(2,4) >>> r3 = Rat(0,1) >>> r4 = Rat(0,3) >>> r5 = Rat(-3) >>> r6 = Rat('1/2') >>> r7 = Rat('3/') >>> r8 = Rat('0') >>> r9 = Rat('5.5') >>> r10 = Rat(5.5) >>> r1 == r2 True >>> r1 < r3 False >>> r3 != r4 False >>> r7 == 3 True >>> r9 == 5.5 True >>> r10 == [] False >>> r10 < () Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'Rat' and 'tuple' >>> Rat(1,2) + Rat(-1,3) 1/6 >>> Rat(1,2) - Rat(-1, 3) 5/6 >>> Rat(100,90) * Rat(-3,25) -2/15 >>> Rat(100,90) / Rat(-3,25) -250/27 >>> from math import pi >>> approx(pi) 355/113 >>> Rat(1) * Poly(Rat(1), Rat(0)) """ def __init__(self, arg1=0, arg2=1): """ Rat(int a=0, positive-int b=1) -> a/b Rat(Rat a, non-zero-value b=1) -> a/b Rat(float a, non-zero-value b=1) -> a/b Rat(str) """ if isinstance(arg1, int): self._num = arg1 # arg2 must be positive int: try: self._den = _check(arg2, key='den') except TypeError: print('TypeError:', type(arg1), arg1, type(arg2), arg2) self._num = Rat(type(arg2)(arg1)) self._den = arg2 elif isinstance(arg1, Rat): # arg2 must be Rat, int or float and arg2 != 0: _check(arg2, key='Rat') tmp = arg1 / arg2 if arg2 != 1 else arg1 self._num = tmp._num self._den = tmp._den elif isinstance(arg1, float): # arg2 must be Rat, int or float and arg2 != 0: _check(arg2, key='float') tmp = arg1 / arg2 if isinstance(tmp, Rat): self._num = tmp._num self._den = tmp._den else: # isinstance(tmp, float): self._num = tmp self._den = 1 while self._num != int(self._num): self._num *= 10 self._den *= 10 self._num = int(self._num) self._self_reduce() elif isinstance(arg1, str): # you may TRY STR.PARTITION in this part # arg2 must be 1: self._den = _check(arg2, key='str') index = arg1.find('/') try: # found '/': if index != -1: self._num = int(arg1[:index]) # '/' is not the last character in the str: if index + 1 != len(arg1): self._den = int(arg1[index+1:]) elif '.' in arg1: tmp = Rat(float(arg1)) self._num, self._den = tmp._num, tmp._den else: self._num = int(arg1) except ValueError as err: raise ValueError("Counldn't convert '%s' to Rat." % arg1) elif isinstance(arg1, Poly): self._num = arg1 self._den = Poly(arg2) elif isinstance(arg1, type(arg2)) or isinstance(arg2, type(arg1)): self._num = arg1 self._den = arg2 else: #print('Notimplemented:', type(arg1), arg1, type(arg2), arg2) raise NotImplementedError("Couldn't convert %s to Rat." % type(arg1)) # getters and setters-------------------------------------- @property def num(self): return self._num @property def den(self): return self._den @num.setter def num(self, value): self._num = _check(value, key='num') @den.setter def den(self, value): self._den = _check(value, key='den') # specials------------------------------------------------- # print() def __str__(self): def par(obj): # parenthesis try: if obj.precedence() < self.precedence(): return "(%s)" % obj else: return "%s" % obj except AttributeError: return "%s" % obj if self._den == 1: return '%s' % self._num else: return par(self._num) + '/' + par(self._den) # repr() __repr__ = __str__ # float() def __float__(self): return self._num / self._den def to_float(self, length=15): num = self._num exp = quantity_level(float(self)) while num < self._den: num *= 10 return '0.%se%s' % (num * (10**length) // self._den, exp) # int() def __int__(self): # round up to 0 if self._num >= 0: return self._num // self._den else: return -( -self._num // self._den ) # len(): deprecated #def __len__(self): # return len(str(self)) # abs() def __abs__(self): return Rat(self._num, self._den) if (self._num >= 0) else Rat(-self._num, self._den) # operator == def __eq__(self, other): try: other = Rat(other) except Exception: return False lhs = self.reduce() rhs = other.reduce() return lhs._num == rhs._num and lhs._den == rhs._den # operator != def __ne__(self, other): return not self == other # operator < def __lt__(self, other): if not isinstance(other, Rat): try: other = Rat(other) except Exception: return NotImplemented return self._num * other._den < self._den * other._num # operator > def __gt__(self, other): if not isinstance(other, Rat): try: other = Rat(other) except Exception: return NotImplemented return other < self # operator <= def __le__(self, other): if not isinstance(other, Rat): try: other = Rat(other) except Exception: return NotImplemented return not other < self # operator >= def __ge__(self, other): return not self < other # unary operator + def __pos__(self): return self # unary operator - def __neg__(self): return Rat(-self._num, self._den) # operator + def __add__(self, other): return _do_operation(self, other, '+') def __radd__(self, other): return _do_operation(other, self, '+') # operator - def __sub__(self, other): return _do_operation(self, other, '-') def __rsub__(self, other): return _do_operation(other, self, '-') # operator * def __mul__(self, other): return _do_operation(self, other, '*') def __rmul__(self, other): return _do_operation(other, self, '*') # operator / def __truediv__(self, other): return _do_operation(self, other, '/') def __rtruediv__(self, other): return _do_operation(other, self, '/') # operator ** def __pow__(self, other): return Rat(self._num ** other, self._den ** other) # other methods-------------------------------------------- def copy(self): return Rat(self._num, self._den) def _self_reduce(self): d = _gcd(self._num, self._den) if d == 0: raise ValueError('Bug: d == 0 whlie reducing.') self._num //= d self._den //= d return None def reduce(self): r = self.copy() r._self_reduce() return r def str2d(self, pnt=True): """a delux view of the faction :)""" if self._den == 1: ret = '%s' % self._num else: width = max( len(str(self._num)), len(str(self._den)) ) + 2 ret = str(self._num).center(width) + '\n'\ + ''.ljust(width, '-') + '\n'\ + str(self._den).center(width) if pnt: print(ret) return None else: return ret @staticmethod def precedence(): return 10 # class ends--------------------------------------------------- def _check(value, *, key): """helper function for __init__()""" if key == 'num': if not isinstance(value, int): raise TypeError('Numerator must be int, %s given.' %\ type(value)) elif key == 'den': msg = 'Denominator must be positive int, %s given' % value if not isinstance(value, int) or value <= 0: raise TypeError(msg) elif value <= 0: raise ValueError(msg) elif key == 'Rat' or key == 'float': if not isinstance(value, (int, float, Rat)): raise TypeError('The second argument must be ' 'int, float or Rat when the first ' 'argument is %s.' % key) elif value == 0: raise ZeroDivisionError('The second argument must ' 'be non-zero.') elif key == 'str': if value != 1: raise ValueError('The second argument must be 1 ' 'when the first argument is str, ' '%s given.' % value) return value def _gcd(a, b): try: a, b = abs(a), abs(b) except TypeError: pass while b != 0: a, b = b, a % b # same as: c = a % b; a = b; b = c return a def gcd(*args): """ gcd(*args) -> (int, list) Takes a few numbers, returns their greatest common denominator d, along with k0, k1, k2...kn, for which k0*args[0] + k1*args[1] + k2*args[2] +...+ kn*args[n] = d. """ q = [] r0, r1 = args[0], args[1] if r1 == 0: print(r0, '= 1 *', r0, '+ 1 * 0') return None while r1 != 0: q.append(-(r0 // r1)) r0, r1 = r1, r0 % r1 q.pop() if q == []: print(r0, '= 1 * 0 + 1 *', r0) return None c0, c1 = 1, q.pop() while q != []: c0 = c0 + q.pop() * c1 c0, c1 = c1, c0 if r0 < 0: r0, c0, c1 = -r0, -c0, -c1 print(r0, '=', c0, '*', args[0], '+', c1, '*', args[1]) def _do_operation(lhs, rhs, method): """helper function for method __add__, __radd__, __sub__ and so on""" try: if not isinstance(lhs, Rat): lhs = Rat(lhs) if not isinstance(rhs, Rat): rhs = Rat(rhs) except Exception: return NotImplemented if method == '+' or method == '-': d = _gcd(lhs._den, rhs._den) if method == '+': func = lambda x,y: x+y else: func = lambda x,y: x-y ret = Rat(func(rhs._den // d * lhs._num, lhs._den // d * rhs._num),\ lhs._den // d * rhs._den) ret._self_reduce() return ret elif method == '*': r1 = Rat(lhs._num, rhs._den) r1._self_reduce() r2 = Rat(rhs._num, lhs._den) r2._self_reduce() ret = Rat(r1._num * r2._num, r1._den * r2._den) ret._self_reduce() return ret elif method == '/': if rhs._num < 0: return _do_operation(lhs, Rat(-rhs._den, -rhs._num), '*') else: return _do_operation(lhs, Rat(rhs._den, rhs._num), '*') else: return NotImplemented def _continued_frac(L): if len(L) == 1: return Rat(L[0]) else: return Rat(L[0] + 1 / _continued_frac(L[1:])) def approx(value, tolerance = 1e-6): """ approx(value, tolerance = 1e-6) -> Rat returns a Rat with smaller _num and _den, abs(ret - value) < tolerance guarenteed. https://cn.mathworks.com/help/matlab/ref/rat.html """ target = value den_list = [] while True: # a substitute for do-while loop den_list.append(int(target)) ret = _continued_frac(den_list) if abs(ret - value) < tolerance: return ret target = 1 /( target - den_list[-1] ) def choose(n, k): """ choose(n, k) -> int Returns C_n^k, or n(n-1)...(n+1-k)/k! """ err = 'Expecting a non-negative interger for k!' if not isinstance(k, int): raise TypeError(err) elif k < 0: raise ValueError(err) ret = 1 if isinstance(n, int): if (k <= n): k = min(k, n-k) for i in range(1, k+1): # it's ok. int division won't truncate. ret = ret * (n - i + 1) // i else: for i in range(1, k+1): ret = ret * (n - i + 1) / i return ret def Bernoulli(n): """ Bernoulli(n) -> generator Algorithm Akiyama–Tanigawa algorithm for second Bernoulli numbers B_n^+ yields Bernoulli number: 1, 1/2, 1/6, 0, -1/30... """ err = 'Expecting a non-negative integer!' if not isinstance(n, int): raise TypeError(err) elif n < 0: raise ValueError(err) L = [] for i in range(n+1): L.append(Rat(1, i+1)) for j in range(i, 0, -1): L[j-1] = j * (L[j-1] - L[j]) yield L[0] def quantity_level(n): import math if n == 0: return 0 return math.floor(math.log10(abs(n))) + 1 class RatFunc(Rat): def __call__(self, value): return self._num(value) / self._den(value) if __name__ == '__main__': import doctest doctest.testmod()
6eb86605ddcd87353650957bc8fa4c8349b517df
tsukasan3/Impractical_Python_Projects
/Chapter2/dictionary_cleanup_practice.py
482
3.828125
4
"""リストにある一文字の単語はaかeでなければ削除する""" word_list = ['stick', 'odd', 'b', 'g', 'a', 'e'] word_cleanup_list = [] permissible = ('a', 'e') # 一文字の単語はaかeでなければ削除する for word in word_list: if len(word) > 1: word_cleanup_list.append(word) elif len(word) == 1 and word in permissible: word_cleanup_list.append(word) else: continue print(word_list, '\n') print(word_cleanup_list)
66d068bc1cb4a840ff65774d20a9b8bf81c94bd1
tansuluu/DataAnalysis
/insertion2.py
457
3.78125
4
def sortingI(arr): for i in range(1,len(arr)): key=arr[i] j=i-1 while key<arr[j] and j>= 0: arr[j+1]=arr[j] j=j-1 arr[j+1]=key return arr print(sortingI([9,6,2,3,6])) def insr(arr): for i in range(1,len(arr)): key=arr[i] j=i-1 while j>=0 and arr[j]>key: arr[j+1]=arr[j] j=j-1 arr[j+1]=key; return arr; print(insr([5,2,4,1]))
51cfdd34bd47546b852a220fa829c51324cf256d
whisust/jellynote-backend
/api/validators.py
993
3.59375
4
from re import Pattern from typing import Optional def non_empty(field: str): def _test_non_empty(value: str): if value is None or len(value) == 0: raise ValueError(field + " should not be empty") else: return value return _test_non_empty def non_all_empty(fields: list): def _test_non_empty(values: str): non_empty_values = [v for v in values if v is not None] if len(non_empty_values) == 0: raise ValueError("Require at least one of " + ', '.join(fields)) else: return non_empty_values return _test_non_empty def match_regex(field: str, regex: Pattern, example: Optional[str] = None): def _test_regex(value: str): if regex.match(value) is None: msg = field + " is incorrect" if example is not None: msg += ". Example: " + example raise ValueError(msg) else: return value return _test_regex
55192b763594e1a84bb4bd9b8913ce1d16382a6b
Redpike/codewars
/Python/d026/d026.py
1,027
3.640625
4
class Plugboard(object): pairs = [] def __init__(self, wires=None): """ wires: This is the mapping of pairs of characters """ if wires is None: wires = "" if len(set(wires)) != len(wires): raise Exception("Should not have accepted a second definition for a wire end") if len(wires) / 2 > 10: raise Exception("Should not have accepted too many wires defined") self.pairs = [[wires[index], wires[index + 1]] for index in range(0, len(wires), 2)] pass def process(self, c): """ c: The single character to process """ for pair in self.pairs: if c in pair: return pair[0] if pair.index(c) == 1 else pair[1] return c def test(): plugboard = Plugboard("AB") assert "B" == plugboard.process("A") assert "A" == plugboard.process("B") assert "C" == plugboard.process("C") def main(): test() if __name__ == '__main__': main()
407f6cf7af7bfe4c153a1de40cd81cb066c93977
sabinzero/various-py
/binari to decimal/main.py
141
3.734375
4
a = input("enter a binary number (e.g. 0b00110011): ") print "decimal: %d" % a print "hexadecimal: %x" % a print "hexadecimal: %X" % a
36e5d3b0e401891ca62730cdb82ff7408884809e
simranjmodi/cracking-the-coding-interview-in-python
/chapter-04/exercise-4.5.1.py
622
4
4
""" 4.5 Validate BST Implement a function to check if a binary tree is a binary search tree Solution 1: In Order Traversal (Assuming no duplicate elements) """ last_printed = None class TreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def check_BST(n): global last_printed if n == None: return True if not check_BST(n.left): return False if last_printed is not None and n.data <= last_printed: return False last_printed = n.data if not check_BST(n.right): return False return True
b734b6d198302abd85d9b6059c5b3f52f2f265c4
liuqiangcl/liuqiang
/github/src/ex33.py
583
4.125
4
#-*- coding:utf-8-*- ''' Created on 2014-3-6 @author: Hunk ''' # i = 0 # numbers=[] # #б # while i<6: # print "At the top i is %d " % i # numbers.append(i) # i+=1 # print "Numbers now:",numbers # print "At the bottom i is %d" % i # #бѭ # print "The numbers:" # for num in numbers: # print num # # def create_list(num): i=0 numbers=[] while i<num: #print "At the top i is %d " % i numbers.append(i) i+=1 print "Numbers now:",numbers for i in range(0,10): create_list(i)
134b6c2511e16c53d5886c55d50f624c3695b594
JeffreyAsuncion/CSPT15_DataStructuresAndAlgorithms3
/SprintChallenge/uncover_spy.py
2,153
3.953125
4
""" In a city-state of n people, there is a rumor going around that one of the n people is a spy for the neighboring city-state. The spy, if it exists: Does not trust anyone else. Is trusted by everyone else (he's good at his job). Works alone; there are no other spies in the city-state. You are given a list of pairs, trust. Each trust[i] = [a, b] represents the fact that person a trusts person b. If the spy exists and can be found, return their identifier. Otherwise, return -1. Example 1: Input: n = 2, trust = [[1, 2]] Output: 2 Explanation: Person 1 trusts Person 2, but Person 2 does not trust Person 1, so Person 2 is the spy. Example 2: Input: n = 3, trust = [[1, 3], [2, 3]] Output: 3 Explanation: Person 1 trusts Person 3, and Person 2 trusts Person 3, but Person 3 does not trust either Person 1 or Person 2. Thus, Person 3 is the spy. Example 3: Input: n = 3, trust = [[1, 3], [2, 3], [3, 1]] Output: -1 Explanation: Person 1 trusts Person 3, Person 2 trusts Person 3, and Person 3 trusts Person 1. Since everyone trusts at least one other person, there is no spy. Example 4: Input: n = 3, trust = [[1, 2], [2, 3]] Output: -1 Explanation: Person 1 trusts Person 2, and Person 2 trusts Person 3. However, in this situation, we don't have any one person who is trusted by everyone else. So we can't determine who the spy is in this case. Example 5: """ """ like GraphFindJudge.py """ def uncover_spy(n, trust): # base case if len(trust) < n-1: return -1 # indegree ---> num of directed edges into a vertex == N-1 # outdegree ---> num of directed edges from a vertex == 0 # N+1 so not to go out of bounds, accounts for 0 # create an indegree list indegree = [0] * (n+1) # create an outdegree list outdegree = [0] * (n+1) # iterate over the trust and extract a and b for a, b in trust: outdegree[a] += 1 indegree[b] += 1 # iterate check indegree and outdegree for i in range(1, n+1): if indegree[i] == n-1 and outdegree[i] == 0: return i # otherwise return -1 False return -1
dd8efc35b3e959c3ee5bc93834fb6e06e068b44b
anurag5398/DSA-Problems
/Heaps/KthSmallestElementMatrix.py
1,243
3.625
4
""" Given a sorted matrix of integers A of size N x M and an integer B. Each of the rows and columns of matrix A are sorted in ascending order, find the Bth smallest element in the matrix. NOTE: Return The Bth smallest element in the sorted order, not the Bth distinct element. """ #Incomplete import heapq class Maxheap: def __init__(self): self.heap = list() def build(self, array): self.heap = array heapq.heapify(self.heap) def insert(self, val): heapq.heappush(self.heap, val) def remove(self): return heapq.heappop(self.heap) def replace(self, val): return heapq.heapreplace(self.heap, val) class Solution: def solve(self, A, B): heap = Maxheap() for i, val in enumerate(A[0]): heap.insert((val, (0,i)) ) for i in range(B): print(heap.heap) v, i = heap.remove() if i[0] < len(A)-1: val = A[i[0]+1][i[1]] heap.insert((val, (i[0]+1, i[1]))) return v t = Solution() A = [ [5, 9, 11], [9, 11, 13], [10, 12, 15], [13, 14, 16], [16, 20, 21] ] B = 12 print(t.solve(A, B))
172dfe71b07dd48f8817859387c7d761b1e94421
imn00133/PythonSeminar19
/Users/Jade/convert_fahrenheit_celsius/convert_fahrenheit_celsius.py
196
3.75
4
# 입력 fahrenheit = float(input("변환할 화씨온도(℉)를 입력하십시오: ")) celsius = (fahrenheit - 32) * 5/9 # 출력 print("%.2f℉는 %.2f℃입니다." % (fahrenheit, celsius))
1bc93d957e2ea77cd97a52624cf255e85312b606
hljjj/python_note
/3.2.1.string.py
1,392
4.375
4
# 新建一个字符串 words = "hello,world" # 长字符串 context = """ Never give up, Never lose hope. Always have faith, It allows you to cope. Trying times will pass, As they always do. Just have patience, Your dreams will come true. So put on a smile, You'll live through your pain. Know it will pass, And strength you will gain """ print(context) # 索引访问元素 hello = words[:5] # 字符串拼接 new_words_1 = "hello"+",python" new_words_2 = "hello,{},{}".format('python','nice to meet you') new_words_3 = "hello,{1},{0}".format('python','nice to meet you') new_words_4 = ".".join(["ab","cd","ef"]) # fromat的简写 name = input("请输入名字:") welcome = f"hello,{name}" print(welcome) # 字符串的修改 upper = words.upper() lower = upper.lower() # 返回单词开头大写的英文字符 words.title() # str.replace(old,new) words.replace("world","python") # strip 清除首尾空格 trip_string = ' string ' print(trip_string.strip()) # lstrip 清除左边空格 left strip # rstrip同理,right strip print(trip_string.lstrip()) # 对字符串进行拆分 split_1 = new_words_3.split(',') split_2 = new_words_3.split() # 判断字符是否字母、数字、大写、小写,都是返回bool值 "hello".isalpha() "2020".isdigit() words.isupper() words.islower() # find 会返回第一次出现匹配字符串的位置索引 words.find("w")
6261a0f25df405ad1dc4bae93dc8a6eb8e424791
bizkanta/exam-python-2016-06-27
/test_third.py
755
3.71875
4
import unittest from third import count_letter_in_string class TestCountLetters(unittest.TestCase): def test_empty_string(self): self.assertEqual(count_letter_in_string('', 'a'), (0)) def test_string_letter_in_it(self): self.assertEqual(count_letter_in_string('apple', 'p'), (2)) def test_string_letter_not_in_it(self): self.assertEqual(count_letter_in_string('apple', 'k'), (0)) def test_string_with_nums(self): self.assertEqual(count_letter_in_string('123', '3'), (1)) def test_int(self): self.assertEqual(count_letter_in_string(123, 'a'), (0)) def test_int_in_int(self): self.assertEqual(count_letter_in_string(123, 1), (0)) if __name__ == '__main__': unittest.main()
f3ce1b3def324707552acaf9f998489d4f299de8
BrashFlea/CS3030PythonTest
/jonathanMirabile_exam2_p2.py
1,534
4.4375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 Jonathan <[email protected]> # # Distributed under terms of the MIT license. import sys """ Python exam Problem 2 Secure password checker """ def IsValidPassword(password): #Password length check if(len(password) < 8): print("Password too short") return False #Using some reverse logic here. Checking to see if the password is: #islower() all lowercase (missing uppercase) #isupper() all uppercase (missing lowercase) #isalpha() all alphabetic characters (missing number) #This will validate the password as we want to not trip the if block. if(password.islower() or password.isupper() or password.isalpha()): print("That password didn't have the required properties") return False else: print("Password satisfies conditions") return True # Main function def main(password): IsValidPassword(password) return if __name__ == "__main__": # Call Main status = True while(status == True): firstPass = input("Enter your password: ") secondPass = input("Re-enter your password: ") while(firstPass != secondPass): print("Passwords didn't match") firstPass = input("Enter your password: ") secondPass = input("Re-enter your password: ") main(firstPass) quit = input("Would you like to quit? Y/N: ") if(quit == "Y" or quit == "y"): status = False exit(0)
1d4ae3151e22c5e7c1e97ab5f163a49d1d56b526
Roger423/python-tips
/create_random_mac/random_mac_2.py
814
3.859375
4
#! python3 import random, sys def Gen_random_mac(): mac_al = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] mac_al_2 = ['0', '2', '4', '6', '8', 'A', 'C', 'E'] mac_ls = [] for i in range(6): if i == 0: mac_se = random.choice(mac_al) + random.choice(mac_al_2) else: mac_se = random.choice(mac_al) + random.choice(mac_al) mac_ls.append(mac_se) mac = ':'.join(mac_ls) return mac if len(sys.argv) != 2: print("Arguments Err!") print("Usage: python3 random_mac_2.py mac_number") else: mac_num = int(sys.argv[1]) mac_file = open('random_mac_list.txt', 'w') try: for i in range(mac_num): mac_file.write(Gen_random_mac()) mac_file.write('\n') except: pass mac_file.close()
954172b3e7a6226dded0faa0ac8f483ee22de652
gayu2723/python
/evennotinv;id.py
158
4.03125
4
def evennotin(): n=int(input()) if(n%2==0): print("even") elif(n<=0): print("invalid") else: print("odd") evennotin()
12829cf8870af69b22379baa5dab09c8295f2856
itsmrajesh/python-programming-questions
/Day1/reverseNumber.py
166
4
4
num = int(input("Enter a numeber : ")) numCopy=num rev=0 while num>0: rem = num%10 rev = (rev*10)+rem num //= 10 print(f"The rev of {numCopy} is {rev}")
fbaa8dceb1b65112f98f12a10f8698d330463777
abhinavjainR/textbasecaptcha
/textbasedcaptcha.py
696
3.96875
4
# Capcha module is used to convert our text to image from captcha.image import ImageCaptcha # PIL module is used to show our captcha image from PIL import Image # Captcha variable is used to take input text Captcha=input("Enter captcha : ") # Form variable is used to take name of image Form=input("Enter name of Image : ") # image variable is used to give dimentions to image and creating object of captcha.image image = ImageCaptcha(width = 280, height = 90) # Here write function is used to assemble our text into image image.write(Captcha, Form ) # im is a object of PIL module used to open image im=Image.open(Form) # we use show image to view captcha im.show()
9423706d5515927d9bc6dd210d444625a6e4f00a
mmtmn/lightsout
/translator5x5.py
1,381
3.6875
4
# made by Thiago M Nóbrega # to run this project: python main.py def translate(pick): """ receives numerical state of space, outputs finalpick as a coordenate """ #pick = int(input("pick a number: ")) x1 = 0 y0 = 0 if pick == 1: finalpick = 0,0 elif pick == 2: finalpick = 0,1 elif pick == 3: finalpick = 0,2 elif pick == 4: finalpick = 0,3 elif pick == 5: finalpick = 0,4 elif pick == 6: finalpick = 1,0 elif pick == 7: finalpick = 1,1 elif pick == 8: finalpick = 1,2 elif pick == 9: finalpick = 1,3 elif pick == 10: finalpick = 1,4 elif pick == 11: finalpick = 2,0 elif pick == 12: finalpick = 2,1 elif pick == 13: finalpick = 2,2 elif pick == 14: finalpick = 2,3 elif pick == 15: finalpick = 2,4 elif pick == 16: finalpick = 3,0 elif pick == 17: finalpick = 3,1 elif pick == 18: finalpick = 3,2 elif pick == 19: finalpick = 3,3 elif pick == 20: finalpick = 3,4 elif pick == 21: finalpick = 4,0 elif pick == 22: finalpick = 4,1 elif pick == 23: finalpick = 4,2 elif pick == 24: finalpick = 4,3 elif pick == 25: finalpick = 4,4 return finalpick
7b68c185011994faaf39432161753f006c2a43d4
Rob0128/Battleships
/battleships.py
10,871
3.84375
4
import random def is_sunk(ship): #finds length of the input ship and compares the int value to the number of hits on the ship ship_len = ship[3] count = 0 boat = ship[4] for hit in boat: count += 1 if ship_len == count: return True else: return False def ship_type(ship): #returns ship type depending on length(int) of input ship type_ship = "" if ship[3] == 1: type_ship = "submarine" elif ship[3] == 2: type_ship = "destroyer" elif ship[3] == 3: type_ship = "cruiser" elif ship[3] == 4: type_ship = "battleship" return type_ship def is_open_sea(row, column, fleet): #creates a list of squares that are part of a ship in fleet or next to a ship in fleet spot = (row, column) no_go = [] for ship in fleet: bottoml = ship[0] - 1 bottomr = ship[1] - 1 bottom = (bottoml, bottomr) horizontal = ship[2] if horizontal == True: #iterates through current ships in fleet and adds all squares that are adjacent to some ship to list 'no_go' for j in range(0, (ship[3] + 2)): new_botr = bottomr + j for i in range(0, 3): new_botl = bottoml + i new_tup = (new_botl, new_botr) no_go.append(new_tup) else: for j in range(0, 3): new_botr = bottomr + j for i in range((ship[3] + 2)): new_botl = bottoml + i new_tup = (new_botl, new_botr) no_go.append(new_tup) if spot in no_go: return False else: return True def ok_to_place_ship_at(row, column, horizontal, length, fleet): #checks if row, column is an occupied square or is next to an occupied square ship = [] if horizontal == True: for i in range(0, length): new_spot = (row, column + i) if new_spot[0] > 9 or new_spot[1] > 9: return False else: ship.append((row, column + i)) else: for i in range(0, length): new_spot = (row + i, column) if new_spot[0] > 9 or new_spot[1] > 9: return False else: ship.append((row + i, column)) count = 0 for part in ship: x = part[0] y = part[1] ok = is_open_sea(x, y, fleet) if ok == True: count += 1 else: count = count if count == length: return True else: return False def place_ship_at(row, column, horizontal, length, fleet): #returns a new fleet with a new ship added after it is checked by the 'ok_to_place_ship_at' function if ok_to_place_ship_at(row, column, horizontal, length, fleet): new_fleet = fleet ship = [] if horizontal == True: for i in range(0, length): ship.append((row, column + i)) else: for i in range(0, length): ship.append((row + i, column)) x = row y = column l = len(ship) hits = set() ship_formatted = (x, y, horizontal, l, hits) new_fleet.append(ship_formatted) return new_fleet else: return fleet def randomly_place_all_ships(): #iterates through all 4 ship types and places the required amount of each using the 'ok_to_place_ship_at' funcation list = [] for x in range(0, 10): for y in range(0, 10): list.append((x, y)) fleet = [] for battleship in range(0, 1): done = False while done == False: z = random.choice(list) k = z[0] s = z[1] r = random.randint(0, 1) hor = True if r == 0: hor = False else: hor = True test_new = ok_to_place_ship_at(k, s, hor, 4, fleet) new_fleet = fleet if test_new == True: new_fleet = place_ship_at(k, s, hor, 4, fleet) fleet = new_fleet done = True for cruiser in range(0, 2): done = False while done == False: z = random.choice(list) k = z[0] s = z[1] r = random.randint(0, 1) hor = True if r == 0: hor = False else: hor = True test_new = ok_to_place_ship_at(k, s, hor, 3, fleet) if test_new == True: fleet = place_ship_at(k, s, hor, 3, fleet) done = True for destroyer in range(0, 3): done = False while done == False: z = random.choice(list) k = z[0] s = z[1] r = random.randint(0, 1) hor = True if r == 0: hor = False else: hor = True test_new = ok_to_place_ship_at(k, s, hor, 2, fleet) if test_new == True: fleet = place_ship_at(k, s, hor, 2, fleet) done = True for sub in range(0, 4): done = False while done == False: z = random.choice(list) k = z[0] s = z[1] r = random.randint(0, 1) hor = True if r == 0: hor = False else: hor = True test_new = ok_to_place_ship_at(k, s, hor, 1, fleet) if test_new == True: fleet = place_ship_at(k, s, hor, 1, fleet) done = True return fleet def check_if_hits(row, column, fleet): #first checks if this shot is already registered as a hit for ship in fleet: for hit in ship[4]: if ((row, column)) == hit: return False #then finds all ship occupied squares and returns them in a list else: fleet_tups = [] for ship in fleet: ship_across = ship[1] ship_down = ship[0] ship_start = (ship_down, ship_across) ship_hor = ship[2] ship_len = ship[3] if ship_hor == True: for ship_part in range(0, ship_len): new_across = ship_across + ship_part full_ship = (ship_down, new_across) fleet_tups.append(full_ship) else: for ship_part in range(0, ship_len): new_down = ship_down + ship_part full_ship = (new_down, ship_across) fleet_tups.append(full_ship) #searches the 'fleet_tups' list of shi occupied squeares to see if the shot is a hit tup = (row, column) if tup in fleet_tups: return True else: return False def hit(row, column, fleet): #adds a hit to the hit ship and returns that updated ship to the fleet and removes the old version of the ship fleet1 = fleet hit_ship = () for ship in fleet: if ship[2] == True: for i in range(0, ship[3]): h = (ship[0], ship[1] + i) if ((row, column)) == h: hit_ship = ship fleet1.remove(ship) else: for j in range(0, ship[3]): h = (ship[0] + j, ship[1]) if ((row, column)) == h: hit_ship = ship fleet1.remove(ship) hit_ship[4].add((row, column)) fleet1.append(hit_ship) return(fleet1, hit_ship) def are_unsunk_ships_left(fleet): #iterates through every shi in fleet an returns true if hits is equal to total squares occupied by a full fleet hit_tot = 0 for ship in fleet: for hit in ship[4]: hit_tot += 1 if hit_tot == 20: return False else: return True board = [] #creates the board that will be printed via 'print_board' function when 'main' runs board.append(' ' ' ' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9') board.append(' ' ' ' + '-' * 10) for x in range(0, 10): board.append(([str(x)] + ['|'] + ['.'] * 10)) def print_board(board): for row in board: print (" ".join(row)) def main(): #initiates the game and prints the board visualisation current_fleet = randomly_place_all_ships() ship_hit = () print(current_fleet) print_board(board) game_over = False shots = 0 while not game_over: loc_str = input("Enter row and colum to shoot (separted by space): ").split() #below tests if the input was correct (exactly two numbers bet as input) checked = False check_len = False check_num = False while checked == False: if len(loc_str) == 2: check_len = True else: check_len = False if check_len == True: check_first = loc_str[0].isnumeric() check_second = loc_str[1].isnumeric() if check_first == True and check_second == True and int(loc_str[0]) >= 0 and int( loc_str[0]) < 10 and int(loc_str[1]) >= 0 and int(loc_str[1]) < 10: check_num = True if check_len == True and check_num == True: checked = True else: print("Incorrect input, please input 2 numbers seperated by a space") loc_str = input("Enter row and colum to shoot (separted by space): ").split() current_row = int(loc_str[0]) current_column = int(loc_str[1]) shots += 1 if check_if_hits(current_row, current_column, current_fleet): print("You have a hit!") (current_fleet, ship_hit) = hit(current_row, current_column, current_fleet) board[current_row + 2][current_column+2] = 'H' if is_sunk(ship_hit): print("You sank a " + ship_type(ship_hit) + "!") for x in ship_hit[4]: board[x[0]+2][x[1]+2] = 'S' else: print("You missed!") board[current_row + 2][current_column + 2] = 'x' if not are_unsunk_ships_left(current_fleet): game_over = True print_board(board) print("Game over! You required", shots, "shots.") if __name__ == '__main__': main()
f4646daf05c18f3e67f8700cf90e0deee748eeb2
Jason-Yonghan-Park/PythonML_Practical
/modelsave/tensorflow_model01/tensorflow_model_read01.py
2,345
3.515625
4
# CNN을 이용한 Fashion MNIST 분류 - 98% # tensorflow와 tf.keras 임포트 import tensorflow as tf from tensorflow import keras # 추가로 필요한 라이브러리 임포트 import numpy as np import matplotlib.pyplot as plt # 학습 완료 후 저장된 모델 읽어옴 model = keras.models.load_model('D:\PythonML_Practical\modelsave/tensorflow_model01/fashionmnist_cnn01.h5') # 패션 MNIST는 keras.datasets 패키지에서 읽어 적재할 수 있다. # load_data() 함수를 호출하면 네 개의 넘파이(NumPy) 배열이 반환된다. # train_X와 train_y 배열은 모델 학습에 사용되는 training set # test_X와 test_y 배열은 모델 테스트에 사용되는 test set fasion_mnist = keras.datasets.fashion_mnist (train_X, train_y), (test_X, test_y) = fasion_mnist.load_data() # 학습 데이터 60,000개, 테스트 데이터 10,000개, 클래스는 0 ~ 9까지 10개 print(train_X.shape, test_X.shape) print(set(train_y)) """ # 첫 번째 이미지를 흑백으로 화면에 출력하면서 그 옆에 색상 바를 # 같이 출력해 보면 이미지의 각 픽셀은 0 ~ 255까지의 값을 가지는 # 28 x 28 = 768 픽셀의 이미지 데이터인 것을 확인 할 수 있다. plt.imshow(train_X[0], cmap="gray") plt.colorbar() plt.show() """ # 신경망 모델에 주입하기 전에 픽셀 값의 범위를 0~1 사이로 조정해 정규화 한다. # training set와 test set 둘 다 255로 나누어 정규화(normalize) 한다. train_X = train_X / 255.0 test_X = test_X / 255.0 # Fashion MNIST 데이터는 흑백 이미지로 색상에 대한 1개 채널을 갖기 # 때문에 reshape() 함수를 사용해 데이터의 가장 뒤 쪽에 채널에 대한 차원 # 정보를 추가 한단. 데이터 수는 달라지지 않지만 차원이 다음과 같이 바뀐다. # (60000, 28, 28) -> (60000, 28, 28, 1) print("reshape 이전 : ", train_X.shape, test_X.shape, train_X[0].shape) train_X = train_X.reshape(-1, 28, 28, 1) test_X = test_X.reshape(-1, 28, 28, 1) print("reshape 이후 : ", train_X.shape, test_X.shape, train_X[0].shape) # 읽어온 모델 성능 평가 test_loss, test_acc = model.evaluate(test_X, test_y) print('eval acc: {}'.format(test_acc)) # 테스트 데이터 사용하여 예측 pred = model.predict(test_X) print(np.argmax(pred[7])) print([round(p, 4) for p in pred[7]])
ba9f6a372d459c6a35bd76efa9c30cb356d60498
danyuanwang/karatsuba_mult
/array_inversions/main.py
1,887
4
4
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def extract_file(): handle = open('data_array_coursera_algo_week2.txt') print(handle) list = [] for line in handle: list.append(float(line)) return list def split_list(list): half = len(list)//2 return list[:half], list[half:] def count_split_inv(list_first, list_second, n): sorted_list = [] inv = 0 i = 0 j = 0 print(list_first, list_second) print(n) for k in range(n): if i >= len(list_first): sorted_list.insert(k, list_second[j]) j += 1 elif j >= len(list_second): sorted_list.insert(k, list_first[i]) i += 1 else: if list_first[i] < list_second[j]: sorted_list.insert(k, list_first[i]) i += 1 elif list_first[i] > list_second[j]: sorted_list.insert(k, list_second[j]) j += 1 inv += len(list_first) - i return inv, sorted_list def count(list): # Use a breakpoint in the code line below to debug your script. n = len(list) if n == 1: print('base') return 0, list else: list_first, list_second = split_list(list) x, sorted_first = count(list_first) y, sorted_second = count(list_second) z, sorted_list = count_split_inv(sorted_first, sorted_second, n) print(sorted_list) print('answer') print(x + y + z) return x + y + z, sorted_list file = extract_file() count(file) # Press Ctrl+F8 to toggle the breakpoint. # Press the green button in the gutter to run the script. # See PyCharm help at https://www.jetbrains.com/help/pycharm/
50982d3ce29e4344b20c1c06f8ae676924105780
BeyondEvil/AoC2017
/2015/day_01/solution.py
430
3.53125
4
def read_input(): with open('input.txt', 'r') as f: return f.read().strip() def run_it(seq): floor = 0 position = False for index, each in enumerate(seq): floor += 1 if each == '(' else -1 if floor == -1 and not position: position = index + 1 print('Part 1: ', floor) print('Part 2: ', position) if __name__ == '__main__': run_it(read_input()) # 232, 1783