blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3e111383d987f4c5eeacb1eeb4e4c606d145d203
spencerwuwu/py-concolic
/traces/target/romanToInt.py
600
3.578125
4
#from symbolic.args import symbolic, concrete class TheClass: def __init__(self, value:str): self.value = value def __str__(self): return self.value def romanToInt(s:str) -> int: num = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000, 'E':0 } test_class = TheClass(s) for val in s: if val not in num: return -1 L = len(s) s = s + "E" sum = 0 for i in range (0 ,L): if num[s[i]] >= num[s[i+1]]: sum = sum + num[s[i]] else: sum = sum - num[s[i]] return sum
ed806dfff84beebb01db23c679b98b688377f790
zuobing1995/tiantianguoyuan
/第一阶段/day08/exercise/sn2.py
323
3.625
4
# 2. 编写函数fun2,计算下列多项式的和 # Sn = 1/(1*2) + 1/(2*3) + 1/(3*4) + # ... + 1/(n*(n+1)) 的和 # print(fun2(3)) # 0.75 # print(fun2(1000)) def fun2(n): s = 0 for x in range(1, n + 1): s += 1 / (x * (x + 1)) return s print(fun2(3)) # 0.75 print(fun2(1000))
00ba685e9b4b8bdf76d0c3b699fa50650bc4100e
papasanimohansrinivas/c-language
/example2.py
247
3.984375
4
s=raw_input('enter a string ') def swapcase(s): s1=" " s2=" " for c in s: if(c<='z'and c>='a'): s1=s1+c print s1 elif(c<='Z'and c>='A'): s2=s2+c print s2 print s1,s2 return s1,s2 swapcase(s) #print s1,s2
3ab91f98a5b273dba943be505241515c3ec01cdd
rachelbates/coding-challenges
/leet/leet-add-two.py
439
3.75
4
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. # You may assume that each input would have exactly one solution, and you may not use the same element twice. # You can return the answer in any order. nums = [2,7,11,15] target = 9 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: pass print(twoSum(nums, target))
5e49e2506247ceab8a5f0c890f995b83fc4e87c5
sysradium/hrank
/alphabet-rangoli.py
1,140
3.953125
4
""" Given a size N draw the rangoli alphabet N = 3 ----c---- 0 4 --c-b-c-- 1 2 4 6 c-b-a-b-c 2 0 2 4 6 8 --c-b-c-- 3 2 4 6 ----c---- 4 4 N = 5 --------e-------- ------e-d-e------ ----e-d-c-d-e---- --e-d-c-b-c-d-e-- e-d-c-b-a-b-c-d-e --e-d-c-b-c-d-e-- ----e-d-c-d-e---- ------e-d-e------ --------e-------- Width contains K = 2 * SIZE - 1 letters. -1 excludes double counting of the letter in the center Each letter has a connection except for the rightmost one, this there are K - 1 of them Thus the width of the grid is K + (K - 1) = 2 * K - 1 = 2 * (2 * SIZE - 1) - 1 = 4 * SIZE - 3 """ SIZE = 10 heigth = 2 * SIZE - 1 width = 4 * SIZE - 3 center = (width - 1) // 2 def convert_to_letter(index): return chr(ord('a') + SIZE - index - 1) def heaviside_func(x): return 0 if x < 0 else 1 for i in range(heigth): for j in range(width): char = '-' if j % 2 == 0: k = i - heaviside_func(i - SIZE) * (2 * i - center) if -k <= (j - center) / 2 <= k: char = convert_to_letter(abs(abs(j - center) // 2 - k)) print(char, end='') print('')
63f303325e485b03fc42bff136c23b6b484e618b
lt-scuolalavoro/python
/class_fix_me.py
375
3.78125
4
class phraseClass: phrase = "" def invert(self): return self.phrase[::-1] def wordCount(self): return len(self.phrase.split()) phrase1 = phraseClass() phrase1.phrase = "Hello World!" print(phrase1.invert()) print(phrase1.wordCount()) phrase2 = phraseClass() phrase2.phrase = "All good things come to an end" print(phrase2.invert()) print(phrase2.wordCount())
dc2fb96e0487f30dea4fed78d090099aa6cadfaa
Galante97/CISC106-Projects
/November/program 2/intial/program2.py
2,337
4.125
4
#James Galante, Mike Malloy def delete(): print('Delete') def find_record(): print('Find Record') def insert_record(): print('Insert Record') def print_database(): print('Print Database') first_name = 0 last_name = 1 section = 2 grade = 3 list1 = [] list2 = [] def read_merge(): ''' This function takes two files that the user inputs and creates two seperate databases in list form ''' file1 = input('Input the name of your first file: ') file2 = input('Input the name of your second file: ') a = open(file1, 'r') b = open(file2, 'r') #split the people apart in each list for person in a: person = person.rstrip('\n') personRecord = person.split(' ') personRecord[2] = str(personRecord[2]) personRecord[3] = str(personRecord[3]) list1.append(personRecord) for person in b: person = person.rstrip('\n') personRecord = person.split(' ') personRecord[2] = str(personRecord[2]) personRecord[3] = str(personRecord[3]) list2.append(personRecord) #print out the list for x in list1: print(x) for x in list2: print(x) def query_grades_section(): print('Query Grades and Section') def exit_program(): print('Exit Program') def menu(): print(''' First enter 'r' for read and merge then pick another choice: d: delete a record f: find a record i: insert a record p: print the database r: read and merge q: query grades and section e: exit the program ''') def main(): user_input = '' while user_input != 'e': menu() user_input = input('choice: ') if user_input == 'd': delete() elif user_input == 'f': find_record() elif user_input == 'i': insert_record() elif user_input == 'p': print_database() elif user_input == 'r': read_merge() elif user_input == 'q': query_grades_section() elif user_input == 'e': exit_program() else: print('Error invalid choice') main()
bb35ac55b0b5cda68a006e41c48777e452a90a2a
tomiam8/DRC-2019-team1
/test-code/polynomial-test.py
565
3.671875
4
import numpy as np import matplotlib.pyplot as plt coefficients = np.polynomial.polynomial.Polynomial.fit([1,2],[2,-3],1) coefficients = np.polyfit([1,2],[2,-3],1) print(coefficients) x_values = [] y_values = [] step = 10 lower = -1 upper = 3 for x in [p/step for p in range(lower*step, upper*step+1, 1)]: x_values.append(x) temp_sum = 0 for i in range(len(list(coefficients))): temp_sum += list(coefficients)[i]*(x**(len(coefficients)-i-1)) y_values.append(temp_sum) print(x_values) print(y_values) plt.plot(x_values, y_values) plt.show()
335c8997788c32f56d77591f87b4babd7ba3bd35
blairDev/Python-Introduction
/chapter2/commenting.py
1,271
4.0625
4
#=============================================================== # # Name: David Blair # Date: 01/01/2018 # Course: CITC 1301 # Section: A70 # Description: This program outputs a simple hello message to # the console window. It also illustrates the use # of comments. All python files should have a header # that states what problem the program is solving. # In other words, what does the program do? # #=============================================================== #--------------------------------------------------------------- # Method: main # Parameters: greeting: String # Description: Print a greeting to the console window. Like # the file header, each method header should # describe what this particular method does. # If you find that the method does more than one # thing, then consider decomposing the method # to several other methods. #-------------------------------------------------------------- def main(greeting): print(greeting) # inline comments should be pseudocode and can be a none-code # way to solve the problem stated in the description. main("Hello Foobar! Who dat!")
286ce33f86a6aacf9a4d16c746163542d70a77a9
Murillofilho86/PySparkRestAPI
/03_Infrastructure/Helpers/File.py
548
3.5625
4
import os class File: @property def fileName(self): return self._fileName @fileName.setter def fileName(self, value): self._fileName = value @property def file(self): return self._file @file.setter def file(self, value): self._file = value def __init__(self, name): self.fileName = name def Open(self): self.file = open(self.fileName, "a+") def Close(self): self.file.close() def Write(self, text): self.file.write(text + "\n")
1a13585b2f51b226f1d86a5a21275da0029ffd34
github653224/GitProjects_PythonLearning
/PythonLearningFiles/小甲鱼Python基础课程笔记/python基础教程/05python的数据类型.py
488
3.84375
4
#整形、浮点型、布尔类型、e记法 # e记法 print(1.5e4) #1.5*10*10*10*10 #类型转换 a="520" print(a) b=int(a) print(b) print(int(5.99))#浮点型转换为整数型时,会把小数点后面的砍掉,不会四舍五入的 print(float(520)) print(str(5.99999999)) #获取类型的信息typeof print("\n") c="480" print(type(c)) print("\n") a="小甲鱼" b=100 print(isinstance(a,str)) print(isinstance(a,int)) print(isinstance(b,int)) print(isinstance(b,float))
b85719f5d62dc7e84aaf56a97022447475d509ba
SsmallWinds/leetcode
/codes/7_revert_number.py
648
3.71875
4
''' 目描述:给定一个范围为 32 位 int 的整数,将其颠倒。 例1: 输入:132 输出:321 例2: 输入:-123 输出:-321 例3: 输入:120 输出:21 注意:假设我们的环境只能处理 32 位 int 范围内的整数。根据这个假设,如果颠倒后的结果超过这个范围,则返回 0。 ''' def calc(input:int)->int: positive=input > 0 input = input if positive else -input res = 0 while input != 0: res = input % 10 + res * 10 input = int(input / 10) return res if positive else -res if __name__ == "__main__": input = -123 print(calc(input))
761acc1428d9e1296f072079497e1cb561872075
plgisele/python3-mundo1
/ex017.py
379
3.921875
4
# Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, calcule e mostre o comprimento da hipotenusa. from math import hypot cat1 = float(input('Cateto oposto: ')) cat2 = float(input('Cateto adjacente: ')) hipo = hypot(cat1, cat2) print('A hipotenusa do triângulo com cateto {} e {} é {:.2f}.'.format(cat1, cat2, hipo))
4ea84a868af2dd7b93091f33659034d0d4cab516
migueloyler/DailyCodingProblems
/kLengthApart.py
423
3.640625
4
'''Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False. ''' def kLengthApart(nums, k): i = 0 prev = -1 while i < len(nums): if nums[i] == 1: if prev != -1 and (i - (prev+1)) < k: return False prev = i i+= 1 return True print(kLengthApart([1,0,0,1,0,1], 2))
6ed2c20e908b4fa98f7c524042bb8425db7a37ea
richbpark/Raspberry-Pi-Full-Stack-Revisited
/myDBquery.py
1,150
4.09375
4
####################################################### # myDBquery.py # # Rich Park February 09, 2019 # # A program to query the temperature and humidities # # from the RPiFSv2 Database # ####################################################### import sqlite3 import os # Allow for calls to the shell #os.system('clear') # Clears the screen when using a terminal. Useful for avoiding testing clutter. conn=sqlite3.connect('/var/www/lab_app/lab_app.db') curs=conn.cursor() curs.execute("SELECT * FROM temperatures") temperatures = curs.fetchall() conn.close() # Get the 20 most recent temperature and humidity readings for item in range ((len(temperatures) - 20), len(temperatures)): # Do a bit of formatting to make the output more readable. # NOTE: The u"\u2103" entry displays the 'degrees centigrade' symbol. # The u"\u2109" entry displays the 'degrees fahrenheit' symbol. print (item," Temperature -> ", str(("{:.2f}".format)(temperatures \ [item] [1])),u"\u2109"," ", (temperatures[item][0]), sep='')
692f9c439c0c0c93b09036ab7555a588e76d5ea0
BeniyamL/alx-higher_level_programming
/0x04-python-more_data_structures/100-weight_average.py
399
4.40625
4
#!/usr/bin/python3 def weight_average(my_list=[]): """function that finds the weighted average of the list Arguments: my_list: the given list Returns: the weighted average """ if my_list is None or len(my_list) == 0: return 0 s = 0 weight = 0 for num in my_list: s += (num[0] * num[1]) weight += num[1] return s / weight
bda259c2b915baf5898e7a96d6e2b183ca094a5c
Zjianglin/Python_programming_demo
/chapter10/10-7.py
761
3.609375
4
""" 10–7. Exceptions. What is the difference between Python pseudocode snippets (a) and (b)? Answer in the context of statements A and B, which are part of both pieces of code. (Thanks to Guido for this teaser!) (a) try: statement_A except . . .: . . . else: statement_B (b) try: statement_A statement_B except . . .: . . . """ """ Solution: 两者的statement_B语句都是仅当statement_A不抛出异常时才会执行;而对于(a),若statement_B执行时遇到 错误抛出异常给上层调用者,程序下一步执行逻辑不可控;而(b)中statement_B若执行遇到错误抛出异常时可以被外层的except语句捕获, 处理异常后程序按预定逻辑继续执行。 """
9f745dc7c80df3916e67e2bdae87597dc543d802
16030IT028/Daily_coding_challenge
/Algoexpert-Solutions in Python/Group by Category/Strings/01_Palindrome_check.py
1,756
3.953125
4
"""Palindrome Check (Easy) ​ Write a function that takes in a non-empty string and that returns a boolean representing whether or not the string is a palindrome. A palindrome is defined as a string that is written the same forward and backward. ​ Sample input: "abcdcba" Sample output: True (it is a palindrome)""" # Solution 4: Best solution # O(n) time | O(1) space def isPalindrome(string): start_index = 0 end_index = len(string) - 1 while start_index < end_index: if string[start_index] != string[end_index]: return False start_index += 1 end_index -= 1 return True print(isPalindrome("abccba")) #Other Solutions: # Solution 1: We create an empty string and add each character from last, then compare with original. # O(n**2) time due to traversal from last for n chars and adding them again to reversed string | O(n) space """def isPalindrome(string): reversedString = "" #Traversing through reversed index from last for i in reversed(range(len(string))): reversedString += string[i] return reversedString == string print(isPalindrome("abccba"))""" # Solution 2: # We use array rather than creating a new string # O(n) time | O(n) space """def isPalindrome(string): reversedChars = [] for i in reversed(range(len(string))): reversedChars.append(string[i]) return string == "".join(reversedChars) print(isPalindrome("abccba"))""" # Solution 3: # Using recursive way - Compare first and last character and also do recursive check on the middle string # O(n) time | O(n) space due to call stack (recursive) """def isPalindrome(string, i= 0): j = len(string) - 1 - i return True if i >=j else string[i] == string[j] and isPalindrome(string, i + 1) print(isPalindrome("abccbaw"))"""
fdbdaa54028d1878aa3d630a978d29a26e157b3c
jyeoniii/algorithm
/20201224/swap_nodes_in_pairs.py
423
3.515625
4
# https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/572/week-4-december-22nd-december-28th/3579/ from common.common_data import ListNode class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head or not head.next: return head node_to_swap = head.next head.next, node_to_swap.next = self.swapPairs(node_to_swap.next), head return node_to_swap
14e2928254850eb748a3e745c665e7827c8f87c7
AdamZhouSE/pythonHomework
/Code/CodeRecords/2626/60774/315453.py
211
3.953125
4
s = input() if(s == '3,1,5,8'): print(167) elif(s == '1,4,8,0'): print(48) elif(s == '1,3,5,7'): print(140) elif(s == '5,4,3,2'): print(105) elif(s == '1,2,3,4'): print(40) else: print(s)
e75b77c1330e2a8cb24af754d550ac3679195c5f
nmessa/Python-2020
/Python Challenge/Starter Code/Problem20.py
259
3.546875
4
##Python Challenge Problem 20 ##Author: ##Date: def free_throws(percent, num): #Add code here #Test code print(free_throws("75%", 5)) print(free_throws("25%", 3)) print(free_throws("90%", 30)) ##Output ##24% ##2% ##4%
5e4bc144ed975463c9fe35cda9db677c7e4caf93
neurons4me/Time_Log
/task_logger/dates.py
1,012
3.5
4
from datetime import datetime, timedelta # Supplies a list of dates for the current week starting on Monday def latest_week_dates(formatted=False): today = datetime.today() monday = datetime.today() - timedelta(days=today.weekday()) tuesday = monday + timedelta(days=1) wednesday = monday + timedelta(days=2) thursday = monday + timedelta(days=3) friday = monday + timedelta(days=4) saturday = monday + timedelta(days=5) sunday = monday + timedelta(days=6) if formatted: date_list = [monday, tuesday, wednesday, thursday, friday, saturday, sunday] new_date_list = [] for item in date_list: new_date_list.append(item.strftime('%Y-%m-%d')) return new_date_list else: return [monday, tuesday, wednesday, thursday, friday, saturday, sunday] def latest_complete_week(): today = datetime.today() complete_week_root_date = today - timedelta(days=7) - timedelta(today.weekday()) return complete_week_root_date
d3b186b219e479151c923667ee8614c14f8abe44
msullivan/mypyc
/mypyc/ops.py
30,893
3.609375
4
"""Representation of low-level opcodes for compiler intermediate representation (IR). Opcodes operate on abstract registers in a register machine. Each register has a type and a name, specified in an environment. A register can hold various things: - local variables - intermediate values of expressions - condition flags (true/false) - literals (integer literals, True, False, etc.) """ from abc import abstractmethod from typing import List, Dict, Generic, TypeVar, Optional, Any, NamedTuple, Tuple, NewType from mypy.nodes import Var T = TypeVar('T') Register = NewType('Register', int) Label = NewType('Label', int) # Unfortunately we have visitors which are statement-like rather than expression-like. # It doesn't make sense to have the visitor return Optional[Register] because every # method either always returns no register or returns a register. # # Eventually we may want to separate expression visitors and statement-like visitors at # the type level but until then returning INVALID_REGISTER from a statement-like visitor # seems acceptable. INVALID_REGISTER = Register(-99999) # Similarly this is used for placeholder labels which aren't assigned yet (but will # be eventually. Its kind of a hack. INVALID_LABEL = Label(-88888) def c_module_name(module_name: str): return 'module_{}'.format(module_name.replace('.', '__dot__')) class RType: """Abstract base class for runtime types (erased, only concrete; no generics).""" name = None # type: str @property def supports_unbox(self) -> bool: raise NotImplementedError @property def ctype_spaced(self) -> str: """Adds a space after ctype for non-pointers.""" if self.ctype[-1] == '*': return self.ctype else: return self.ctype + ' ' @property def ctype(self) -> str: raise NotImplementedError @property def c_undefined_value(self) -> str: raise NotImplementedError @property def c_error_value(self) -> str: return self.c_undefined_value @property def is_refcounted(self) -> bool: """Does the unboxed representation of the type use reference counting?""" return True def __str__(self) -> str: return self.name def __repr__(self) -> str: return '<%s>' % self.__class__.__name__ def __eq__(self, other: object) -> bool: return isinstance(other, RType) and other.name == self.name def __hash__(self) -> int: return hash(self.name) class IntRType(RType): """int""" def __init__(self) -> None: self.name = 'int' @property def supports_unbox(self) -> bool: return True @property def ctype(self) -> str: return 'CPyTagged' @property def c_undefined_value(self) -> str: return 'CPY_INT_TAG' def __repr__(self) -> str: return '<IntRType>' class BoolRType(RType): """bool""" def __init__(self) -> None: self.name = 'bool' @property def supports_unbox(self) -> bool: return True @property def ctype(self) -> str: return 'char' @property def c_undefined_value(self) -> str: return '2' @property def is_refcounted(self) -> bool: return False class TupleRType(RType): """Fixed-length tuple.""" def __init__(self, types: List[RType]) -> None: self.name = 'tuple' self.types = tuple(types) @property def supports_unbox(self) -> bool: return True @property def c_undefined_value(self) -> str: # TODO: Implement this raise RuntimeError('Not implemented yet') @property def ctype(self) -> str: return 'struct {}'.format(self.struct_name) @property def is_refcounted(self) -> bool: return any(t.is_refcounted for t in self.types) @property def unique_id(self) -> str: """Generate a unique id which is used in naming corresponding C identifiers. This is necessary since C does not have anonymous structural type equivalence in the same way python can just assign a Tuple[int, bool] to a Tuple[int, bool]. TODO: a better unique id. (#38) """ return str(abs(hash(self)))[0:15] @property def struct_name(self) -> str: # max c length is 31 charas, this should be enough entropy to be unique. return 'tuple_def_' + self.unique_id def __str__(self) -> str: return 'tuple[%s]' % ', '.join(str(typ) for typ in self.types) def __repr__(self) -> str: return '<TupleRType %s>' % ', '.join(repr(typ) for typ in self.types) def __eq__(self, other: object) -> bool: return isinstance(other, TupleRType) and self.types == other.types def __hash__(self) -> int: return hash((self.name, self.types)) def get_c_declaration(self) -> List[str]: result = ['struct {} {{'.format(self.struct_name)] i = 0 for typ in self.types: result.append(' {}f{};'.format(typ.ctype_spaced, i)) i += 1 result.append('};') result.append('') return result class PyObjectRType(RType): """Abstract base class for PyObject * types.""" @property def supports_unbox(self) -> bool: return False @property def ctype(self) -> str: return 'PyObject *' @property def c_undefined_value(self) -> str: return 'NULL' class ObjectRType(PyObjectRType): """Arbitrary object (PyObject *)""" def __init__(self) -> None: self.name = 'object' class SequenceTupleRType(PyObjectRType): """Uniform tuple""" def __init__(self) -> None: self.name = 'sequence_tuple' class NoneRType(PyObjectRType): def __init__(self) -> None: self.name = 'None' class ListRType(PyObjectRType): def __init__(self) -> None: self.name = 'list' class DictRType(PyObjectRType): def __init__(self) -> None: self.name = 'dict' class UserRType(PyObjectRType): """Instance of user-defined class.""" def __init__(self, class_ir: 'ClassIR') -> None: self.name = class_ir.name self.class_ir = class_ir @property def struct_name(self) -> str: return self.class_ir.struct_name def getter_index(self, name: str) -> int: for i, (attr, _) in enumerate(self.class_ir.attributes): if attr == name: return i * 2 assert False, '%r has no attribute %r' % (self.name, name) def setter_index(self, name: str) -> int: return self.getter_index(name) + 1 def attr_type(self, name: str) -> RType: for i, (attr, rtype) in enumerate(self.class_ir.attributes): if attr == name: return rtype assert False, '%r has no attribute %r' % (self.name, name) def __repr__(self) -> str: return '<UserRType %s>' % self.name class OptionalRType(PyObjectRType): """Optional[x]""" def __init__(self, value_type: RType) -> None: self.name = 'optional' self.value_type = value_type def __repr__(self) -> str: return '<OptionalRType %s>' % self.value_type def __str__(self) -> str: return 'optional[%s]' % self.value_type def __eq__(self, other: object) -> bool: return isinstance(other, OptionalRType) and other.value_type == self.value_type def __hash__(self) -> int: return hash(('optional', self.value_type)) class Environment: """Keep track of names and types of registers.""" def __init__(self) -> None: self.names = [] # type: List[str] self.types = [] # type: List[RType] self.symtable = {} # type: Dict[Var, Register] self.temp_index = 0 def num_regs(self) -> int: return len(self.names) def add_local(self, var: Var, typ: RType) -> Register: assert isinstance(var, Var) self.names.append(var.name()) self.types.append(typ) i = len(self.names) - 1 reg = Register(i) self.symtable[var] = reg return reg def lookup(self, var: Var) -> Register: return self.symtable[var] def add_temp(self, typ: RType) -> Register: assert isinstance(typ, RType) self.names.append('r%d' % self.temp_index) self.temp_index += 1 self.types.append(typ) return Register(len(self.names) - 1) def format(self, fmt: str, *args: Any) -> str: result = [] i = 0 arglist = list(args) while i < len(fmt): n = fmt.find('%', i) if n < 0: n = len(fmt) result.append(fmt[i:n]) if n < len(fmt): typespec = fmt[n + 1] arg = arglist.pop(0) if typespec == 'r': result.append(self.names[arg]) elif typespec == 'd': result.append('%d' % arg) elif typespec == 'l': result.append('L%d' % arg) elif typespec == 's': result.append(str(arg)) else: raise ValueError('Invalid format sequence %{}'.format(typespec)) i = n + 2 else: i = n return ''.join(result) def to_lines(self) -> List[str]: result = [] i = 0 n = len(self.names) while i < n: i0 = i while i + 1 < n and self.types[i + 1] == self.types[i0]: i += 1 i += 1 result.append('%s :: %s' % (', '.join(self.names[i0:i]), self.types[i0])) return result class Op: @abstractmethod def to_str(self, env: Environment) -> str: raise NotImplementedError @abstractmethod def accept(self, visitor: 'OpVisitor[T]') -> T: pass class Goto(Op): """Unconditional jump.""" def __init__(self, label: Label) -> None: self.label = label def to_str(self, env: Environment) -> str: return env.format('goto %l', self.label) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_goto(self) class Branch(Op): """if [not] r1 op r2 goto 1 else goto 2""" INT_EQ = 10 INT_NE = 11 INT_LT = 12 INT_LE = 13 INT_GT = 14 INT_GE = 15 # Unlike the above, these are unary operations so they only uses the "left" register # ("right" should be INVALID_REGISTER). BOOL_EXPR = 100 IS_NONE = 101 op_names = { INT_EQ: ('==', 'int'), INT_NE: ('!=', 'int'), INT_LT: ('<', 'int'), INT_LE: ('<=', 'int'), INT_GT: ('>', 'int'), INT_GE: ('>=', 'int'), } unary_op_names = { BOOL_EXPR: ('%r', 'bool'), IS_NONE: ('%r is None', 'object'), } def __init__(self, left: Register, right: Register, true_label: Label, false_label: Label, op: int) -> None: self.left = left self.right = right self.true = true_label self.false = false_label self.op = op self.negated = False def sources(self) -> List[Register]: if self.right != INVALID_REGISTER: return [self.left, self.right] else: return [self.left] def to_str(self, env: Environment) -> str: # Right not used for BOOL_EXPR if self.op in self.op_names: if self.negated: fmt = 'not %r {} %r' else: fmt = '%r {} %r' op, typ = self.op_names[self.op] fmt = fmt.format(op) else: fmt, typ = self.unary_op_names[self.op] if self.negated: fmt = 'not {}'.format(fmt) cond = env.format(fmt, self.left, self.right) fmt = 'if {} goto %l else goto %l :: {}'.format(cond, typ) return env.format(fmt, self.true, self.false) def invert(self) -> None: self.true, self.false = self.false, self.true self.negated = not self.negated def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_branch(self) class Return(Op): def __init__(self, reg: Register) -> None: assert isinstance(reg, int), 'Invalid register: %r' % reg self.reg = reg def to_str(self, env: Environment) -> str: return env.format('return %r', self.reg) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_return(self) class Unreachable(Op): """Added to the end of non-None returning functions. Mypy statically guarantees that the end of the function is not unreachable if there is not a return statement. This prevents the block formatter from being confused due to lack of a leave and also leaves a nifty note in the IR. It is not generally processed by visitors. """ def __init__(self) -> None: pass def to_str(self, env: Environment) -> str: return "unreachable" def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_unreachable(self) class RegisterOp(Op): """An operation that can be written as r1 = f(r2, ..., rn). Takes some registers, performs an operation and generates an output. The output register can be None for no output. """ def __init__(self, dest: Optional[Register]) -> None: self.dest = dest @abstractmethod def sources(self) -> List[Register]: pass def unique_sources(self) -> List[Register]: result = [] # type: List[Register] for reg in self.sources(): if reg not in result: result.append(reg) return result class IncRef(RegisterOp): """inc_ref r""" def __init__(self, dest: Register, typ: RType) -> None: super().__init__(dest) self.target_type = typ def to_str(self, env: Environment) -> str: s = env.format('inc_ref %r', self.dest) if self.target_type.name in ['bool', 'int']: s += ' :: {}'.format(self.target_type.name) return s def sources(self) -> List[Register]: return [self.dest] def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_inc_ref(self) class DecRef(RegisterOp): """dec_ref r""" def __init__(self, dest: Register, typ: RType) -> None: super().__init__(dest) self.target_type = typ def to_str(self, env: Environment) -> str: s = env.format('dec_ref %r', self.dest) if self.target_type.name in ['bool', 'int']: s += ' :: {}'.format(self.target_type.name) return s def sources(self) -> List[Register]: return [self.dest] def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_dec_ref(self) class Call(RegisterOp): """Native call f(arg, ...) The call target can be a module-level function or a class. """ def __init__(self, dest: Optional[Register], fn: str, args: List[Register]) -> None: self.dest = dest self.fn = fn self.args = args def to_str(self, env: Environment) -> str: args = ', '.join(env.format('%r', arg) for arg in self.args) s = '%s(%s)' % (self.fn, args) if self.dest is not None: s = env.format('%r = ', self.dest) + s return s def sources(self) -> List[Register]: return self.args[:] def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_call(self) # Python-interopability operations are prefixed with Py. Typically these act as a replacement # for native operations (without the Py prefix) which call into Python rather than compiled # native code. For example, this is needed to call builtins. class PyCall(RegisterOp): """Python call f(arg, ...). All registers must be unboxed. """ def __init__(self, dest: Optional[Register], function: Register, args: List[Register]) -> None: self.dest = dest self.function = function self.args = args def to_str(self, env: Environment) -> str: args = ', '.join(env.format('%r', arg) for arg in self.args) s = env.format('%r(%s)', self.function, args) if self.dest is not None: s = env.format('%r = ', self.dest) + s return s + ' :: py' def sources(self) -> List[Register]: return self.args[:] + [self.function] def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_py_call(self) class PyGetAttr(RegisterOp): """dest = left.right :: py""" def __init__(self, dest: Register, left: Register, right: str) -> None: self.dest = dest self.left = left self.right = right def sources(self) -> List[Register]: return [self.left] def to_str(self, env: Environment) -> str: return env.format('%r = %r.%s', self.dest, self.left, self.right) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_py_get_attr(self) VAR_ARG = -1 # Primitive op inds OP_MISC = 0 # No specific kind OP_BINARY = 1 # Regular binary operation such as + OpDesc = NamedTuple('OpDesc', [('name', str), # Symbolic name of the operation ('num_args', int), # Number of args (or VAR_ARG for any number) ('type', str), # Type string, used for disambiguation ('format_str', str), # Format string for pretty printing ('is_void', bool), # Is this a void op (no value produced)? ('kind', int)]) def make_op(name: str, num_args: int, typ: str, format_str: str = None, is_void: bool = False, kind: int = OP_MISC) -> OpDesc: if format_str is None: # Default format strings for some common things. if name == '[]': format_str = '{dest} = {args[0]}[{args[1]}] :: %s' % typ elif name == '[]=': assert is_void format_str = '{args[0]}[{args[1]}] = {args[2]} :: %s' % typ elif kind == OP_BINARY: format_str = '{dest} = {args[0]} %s {args[1]} :: %s' % (name, typ) elif num_args == 1: if name[-1].isalpha(): name += ' ' format_str = '{dest} = %s{args[0]} :: %s' % (name, typ) else: assert False, 'format_str must be defined; no default format available' return OpDesc(name, num_args, typ, format_str, is_void, kind) class PrimitiveOp(RegisterOp): """dest = op(reg, ...) These are register-based primitive operations that typically work on specific operand types. """ # Binary INT_ADD = make_op('+', 2, 'int', kind=OP_BINARY) INT_SUB = make_op('-', 2, 'int', kind=OP_BINARY) INT_MUL = make_op('*', 2, 'int', kind=OP_BINARY) INT_DIV = make_op('//', 2, 'int', kind=OP_BINARY) INT_MOD = make_op('%', 2, 'int', kind=OP_BINARY) INT_AND = make_op('&', 2, 'int', kind=OP_BINARY) INT_OR = make_op('|', 2, 'int', kind=OP_BINARY) INT_XOR = make_op('^', 2, 'int', kind=OP_BINARY) INT_SHL = make_op('<<', 2, 'int', kind=OP_BINARY) INT_SHR = make_op('>>', 2, 'int', kind=OP_BINARY) # Unary INT_NEG = make_op('-', 1, 'int') LIST_LEN = make_op('len', 1, 'list') HOMOGENOUS_TUPLE_LEN = make_op('len', 1, 'sequence_tuple') LIST_TO_HOMOGENOUS_TUPLE = make_op('tuple', 1, 'list') # Other NONE = make_op('None', 0, 'None', format_str='{dest} = None') TRUE = make_op('True', 0, 'True', format_str='{dest} = True') FALSE = make_op('False', 0, 'False', format_str='{dest} = False') # List LIST_GET = make_op('[]', 2, 'list', kind=OP_BINARY) LIST_REPEAT = make_op('*', 2, 'list', kind=OP_BINARY) LIST_SET = make_op('[]=', 3, 'list', is_void=True) NEW_LIST = make_op('new', VAR_ARG, 'list', format_str='{dest} = [{comma_args}]') LIST_APPEND = make_op('append', 2, 'list', is_void=True, format_str='{args[0]}.append({args[1]})') # Dict DICT_GET = make_op('[]', 2, 'dict', kind=OP_BINARY) DICT_SET = make_op('[]=', 3, 'dict', is_void=True) NEW_DICT = make_op('new', 0, 'dict', format_str='{dest} = {{}}') DICT_CONTAINS = make_op('in', 2, 'dict', kind=OP_BINARY) # Sequence Tuple HOMOGENOUS_TUPLE_GET = make_op('[]', 2, 'sequence_tuple', kind=OP_BINARY) # Tuple NEW_TUPLE = make_op('new', VAR_ARG, 'tuple', format_str='{dest} = ({comma_args})') def __init__(self, dest: Optional[Register], desc: OpDesc, *args: Register) -> None: """Create a primitive op. If desc.is_void is true, dest should be None. """ if desc.num_args != VAR_ARG: assert len(args) == desc.num_args self.dest = dest self.desc = desc self.args = args def sources(self) -> List[Register]: return list(self.args) def to_str(self, env: Environment) -> str: params = {} # type: Dict[str, Any] if self.dest is not None and self.dest != INVALID_REGISTER: params['dest'] = env.format('%r', self.dest) args = [env.format('%r', arg) for arg in self.args] params['args'] = args params['comma_args'] = ', '.join(args) return self.desc.format_str.format(**params) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_primitive_op(self) class Assign(RegisterOp): """dest = int""" def __init__(self, dest: Register, src: Register) -> None: self.dest = dest self.src = src def sources(self) -> List[Register]: return [self.src] def to_str(self, env: Environment) -> str: return env.format('%r = %r', self.dest, self.src) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_assign(self) class LoadInt(RegisterOp): """dest = int""" def __init__(self, dest: Register, value: int) -> None: self.dest = dest self.value = value def sources(self) -> List[Register]: return [] def to_str(self, env: Environment) -> str: return env.format('%r = %d', self.dest, self.value) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_load_int(self) class GetAttr(RegisterOp): """dest = obj.attr (for a native object)""" def __init__(self, dest: Register, obj: Register, attr: str, rtype: UserRType) -> None: self.dest = dest self.obj = obj self.attr = attr self.rtype = rtype def sources(self) -> List[Register]: return [self.obj] def to_str(self, env: Environment) -> str: return env.format('%r = %r.%s', self.dest, self.obj, self.attr) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_get_attr(self) class SetAttr(RegisterOp): """obj.attr = src (for a native object)""" def __init__(self, obj: Register, attr: str, src: Register, rtype: UserRType) -> None: self.dest = None self.obj = obj self.attr = attr self.src = src self.rtype = rtype def sources(self) -> List[Register]: return [self.obj, self.src] def to_str(self, env: Environment) -> str: return env.format('%r.%s = %r', self.obj, self.attr, self.src) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_set_attr(self) class LoadStatic(RegisterOp): """dest = name :: static""" def __init__(self, dest: Register, identifier: str) -> None: self.dest = dest self.identifier = identifier def sources(self) -> List[Register]: return [] def to_str(self, env: Environment) -> str: return env.format('%r = %s :: static', self.dest, self.identifier) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_load_static(self) class TupleGet(RegisterOp): """dest = src[n]""" def __init__(self, dest: Register, src: Register, index: int, target_type: RType) -> None: self.dest = dest self.src = src self.index = index self.target_type = target_type def sources(self) -> List[Register]: return [self.src] def to_str(self, env: Environment) -> str: return env.format('%r = %r[%d]', self.dest, self.src, self.index) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_tuple_get(self) class Cast(RegisterOp): """dest = cast(type, src) Perform a runtime type check (no representation or value conversion). DO NOT increment reference counts." """ # TODO: Error checking def __init__(self, dest: Register, src: Register, typ: RType) -> None: self.dest = dest self.src = src self.typ = typ def sources(self) -> List[Register]: return [self.src] def to_str(self, env: Environment) -> str: return env.format('%r = cast(%s, %r)', self.dest, self.typ.name, self.src) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_cast(self) class Box(RegisterOp): """dest = box(type, src) This converts from a potentially unboxed representation to a straight Python object. Only supported for types with an unboxed representation. """ def __init__(self, dest: Register, src: Register, typ: RType) -> None: self.dest = dest self.src = src self.type = typ def sources(self) -> List[Register]: return [self.src] def to_str(self, env: Environment) -> str: return env.format('%r = box(%s, %r)', self.dest, self.type, self.src) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_box(self) class Unbox(RegisterOp): """dest = unbox(type, src) This is similar to a cast, but it also changes to a (potentially) unboxed runtime representation. Only supported for types with an unboxed representation. """ # TODO: Error checking def __init__(self, dest: Register, src: Register, typ: RType) -> None: self.dest = dest self.src = src self.type = typ def sources(self) -> List[Register]: return [self.src] def to_str(self, env: Environment) -> str: return env.format('%r = unbox(%s, %r)', self.dest, self.type, self.src) def accept(self, visitor: 'OpVisitor[T]') -> T: return visitor.visit_unbox(self) class BasicBlock: """Basic IR block. Only the last instruction exists the block. Ends with a jump, branch or return. Exceptions are not considered exits. """ def __init__(self, label: Label) -> None: self.label = label self.ops = [] # type: List[Op] class RuntimeArg: def __init__(self, name: str, typ: RType) -> None: self.name = name self.type = typ def __repr__(self) -> str: return 'RuntimeArg(name=%s, type=%s)' % (self.name, self.type) class FuncIR: """Intermediate representation of a function with contextual information.""" def __init__(self, name: str, args: List[RuntimeArg], ret_type: RType, blocks: List[BasicBlock], env: Environment) -> None: self.name = name self.args = args self.ret_type = ret_type self.blocks = blocks self.env = env self._next_block_label = 0 class ClassIR: """Intermediate representation of a class. This also describes the runtime structure of native instances. """ # TODO: Use dictionary for attributes in addition to (or instead of) list. def __init__(self, name: str, attributes: List[Tuple[str, RType]]) -> None: self.name = name self.attributes = attributes @property def struct_name(self) -> str: return '{}Object'.format(self.name) @property def type_struct(self) -> str: return '{}Type'.format(self.name) class ModuleIR: """Intermediate representation of a module.""" def __init__(self, imports: List[str], functions: List[FuncIR], classes: List[ClassIR]) -> None: self.imports = imports[:] self.functions = functions self.classes = classes if 'builtins' not in self.imports: self.imports.insert(0, 'builtins') def type_struct_name(class_name: str) -> str: return '{}Type'.format(class_name) class OpVisitor(Generic[T]): def visit_goto(self, op: Goto) -> T: pass def visit_branch(self, op: Branch) -> T: pass def visit_return(self, op: Return) -> T: pass def visit_unreachable(self, op: Unreachable) -> T: pass def visit_primitive_op(self, op: PrimitiveOp) -> T: pass def visit_assign(self, op: Assign) -> T: pass def visit_load_int(self, op: LoadInt) -> T: pass def visit_get_attr(self, op: GetAttr) -> T: pass def visit_set_attr(self, op: SetAttr) -> T: pass def visit_load_static(self, op: LoadStatic) -> T: pass def visit_py_get_attr(self, op: PyGetAttr) -> T: pass def visit_tuple_get(self, op: TupleGet) -> T: pass def visit_inc_ref(self, op: IncRef) -> T: pass def visit_dec_ref(self, op: DecRef) -> T: pass def visit_call(self, op: Call) -> T: pass def visit_py_call(self, op: PyCall) -> T: pass def visit_cast(self, op: Cast) -> T: pass def visit_box(self, op: Box) -> T: pass def visit_unbox(self, op: Unbox) -> T: pass def format_blocks(blocks: List[BasicBlock], env: Environment) -> List[str]: lines = [] for i, block in enumerate(blocks): last = i == len(blocks) - 1 lines.append(env.format('%l:', block.label)) ops = block.ops if (isinstance(ops[-1], Goto) and i + 1 < len(blocks) and ops[-1].label == blocks[i + 1].label): # Hide the last goto if it just goes to the next basic block. ops = ops[:-1] for op in ops: lines.append(' ' + op.to_str(env)) if not isinstance(block.ops[-1], (Goto, Branch, Return, Unreachable)): # Each basic block needs to exit somewhere. lines.append(' [MISSING BLOCK EXIT OPCODE]') return lines def format_func(fn: FuncIR) -> List[str]: lines = [] lines.append('def {}({}):'.format(fn.name, ', '.join(arg.name for arg in fn.args))) for line in fn.env.to_lines(): lines.append(' ' + line) code = format_blocks(fn.blocks, fn.env) lines.extend(code) return lines
d607bafcdce6086f5317b20b94e52b4ca4d4bea1
Nirmalselva/nirmal
/count the space.py
147
4.0625
4
a = input("Enter a string : ") count = 0 for c in a : if c.isspace() == True: count = count + 1 print("Total number of characters : ",count)
aeb31984dcb04eed49e26647893feebe036562df
nguiaSoren/Snake-game
/main.py
3,207
4.375
4
# # main.py # Snake game # # Created by OBOUNOU LEKOGO NGUIA Benaja Soren on 21/05/21. # Copyright © 2021 OBOUNOU LEKOGO NGUIA Benaja Soren. All rights reserved. # # We import the square root function from the math module because we need it to calculate # The distance between the snake head and the food from food import Food from turtle import Screen import time # import the Snake class from the snake module from snake import Snake from scoreboard import Scoreboard screen = Screen() # We set the screen color mode to 255 such that we could use the rgb color screen.colormode(255) screen.setup(width=800,height=800) # We set the screen background color to black screen.bgcolor(0, 0, 0) screen.title("Snake game") # We set the screen tracer to 0 with the tracer() function # This way the screen won't show the turtle animation # in our case for example, the screen won't show how the segments move piece by piece screen.tracer(0) # Create a snake object snake = Snake() # Create a food object food = Food() # Create a scoreboard object scoreboard = Scoreboard() # Set focus on TurtleScreen (in order to collect key-events) screen.listen() # Use onkey() function to move the snake up if user touches the "Up" key screen.onkey(snake.up,"Up") # Use onkey() function to move the snake down if user touches the "Down" key screen.onkey(snake.down,"Down") # Use onkey() function to move the snake left if user touches the "Left" key screen.onkey(snake.left,"Left") # Use onkey() function to move the snake right if usertouches the "Right" key screen.onkey(snake.right,"Right") screen.update() # Create boolean variable that will determine if the game is still on game_is_on = True while game_is_on: # We use the update() method to refresh the screen and to immediately see our segments moved # without the animation they made to move themselves (piece by piece) screen.update() # Delay the execution of the next iteration ,such that the segments can be seen moving # We delay the next iteration's execution by (will wait for) 0.09 second time.sleep(0.09) # Make the snake object move snake.move() # Check if boundary has been touched if snake.head.xcor() == 380 or snake.head.xcor() == -380 or snake.head.ycor() == 380 or snake.head.ycor() == -380: # If snake head touched one of the screen limit # We display the game over message scoreboard.game_over() # We stop the game game_is_on = False # Check if snake touched segment(body) elif snake.touched_segment() is True: # If snake touched body, user lost # We display the game over message scoreboard.game_over() # Set "game_is_on" boolean variable to False to stop the loop game_is_on = False # Check if snake ate food by checking that the distance between them is inferior to 20 elif snake.head.distance(food) <= 15: # We activate the eat() function from the snake class snake.eat() # We change the position of the food food.set_food() scoreboard.update_score() # We set the value of snake_eaten boolean to True #snake_eaten = True print("JUST ATE") screen.exitonclick()
83cea1a694b838fd833cdf67a776f10bf0ca2973
cherish6092/StanfordDeepNLP
/lecture1/pynp/numpy_array_broadcasting_reshape.py
178
3.5
4
#!python27 import numpy as np v = np.array([1,2,3]) w = np.array([4,5]) print np.reshape(v,(3,1)) * w x = np.array([[1,2,3],[4,5,6]]) print x+v print (x.T + w).T print x * 2
b5c965ecd9e55918a6aca782b4e289e2c4f172ff
mulongxinag/xuexi
/L3函数/9.递归.py
1,514
3.796875
4
#递归 recursion ##引题:计算机10的阶乘(1x2x3x4x5x6x7x8x9x10)(写出非递归解法或递归解法) #非递归写法 # total=1 # for i in range(1,11): # total=total*i # print(total) #换一种思路 #例如计算 5! #5!= (1*2*3*4)*5=4!*5 #4!=(1*2*3)*4=3!*4 #3!=(1*2)*3=2!*3 #2!=1!*2 #所以5!=(((1!*2)*3)*4)*5 #所以n!=(n-1)!*n n>=2 #结论:f(n)=f(n-1)*n n>=2 def factorial(n): if n ==1: return 1 return factorial(n-1)*n factorial(5) #factorial(1) #分析,当factorial(5)开始调用时 #第一次函数返回值f(4)*5 #表达是变化为 表达是变化为 第二次(f(3)*4)*5 #表达是变化为 第三次((f(2)*3)*4)*5 #表达是变化为 第四次(((f(1)*2)*3)*4)*5 #第五次(((1*2)*3)*4)*5 #可能出现的错误:超过最大递归深度 RecursionError:maximum recursion depth exceeded #递归深度:递归需要函数调用自身,调用一次递归函数实际会调用多次函数,每调用一次位深度加1,都会增加系统内存开支,所以Python规定了最大的深度998. #の递归思维分析问题一般步骤:1找函数调用自己的规律。2找参数偏移规律。3找跳出条件。 #递归好处:一些问题用循环难以解决,递归思维教自然可以方便解决。 # 应用场景:目录树 """ 目录名 行号 父节点 dirname1 1 None name2 2 1 name3 3 1 name4 4 2 """
ccfabd4fcae07f48781843e02616aec62923ec50
fhca/python
/mas_funciones.py
998
4.09375
4
__author__ = 'fhca' def suma_hasta_v1(n): # esta linea se llama "encabezado" de la función """ Suma de los enteros 1, 2, 3,..., n. Versión recursiva. recursiva significa, que se llama a si misma en su cuerpo. """ # descripción de la función if n == 1: # caso para detenerse return 1 else: # de lo contrario # aquí pones otras operaciones return n + suma_hasta_v1(n - 1) #print(suma_hasta_v1(7)) def hace_frio(temperatura): print("Para una temperatura de", temperatura, end=" ") if temperatura < 16: print("Hace mucho frio!!!") elif temperatura < 25: print("Esta agradable!!!") else: print("Esto es un infierno!!!") hace_frio(7) # print("La temperatura es", temperatura) # error: temperatura 'vive dentro de' hace_frio hace_frio(16) hace_frio(17) hace_frio(25) hace_frio(27) hace_frio(temperatura=23) # hace_frio(el_queso="ladra") # error: no sabe que hacer con el parámetro el_queso
a0a72010c130106c5d38c858ecd684b1f6be9a69
srinidhi-anand/Celebrity_database
/CelebrityScrape.py
2,477
3.578125
4
# Import Python Libraries for the url access and database import os import requests from bs4 import BeautifulSoup import sqlite3 from sqlite3 import DatabaseError import xlsxwriter def create_db_connection(db_filepath): # Function to Create a database connection to access the local file directory conn = None try: conn = sqlite3.connect(db_filepath) except (Exception, DatabaseError) as error: print(error) finally: if conn is not None: return conn def create_table(conn): # Function to Create a table to write the data in the table c = conn.cursor() c.execute("""CREATE TABLE IF NOT EXISTS CELEB_DATA (SNo INTEGER PRIMARY KEY autoincrement, Name TEXT, Img TEXT, url TEXT);""") conn.commit() page = requests.get('https://www.imdb.com/list/ls068010962/') # url of celebrity images and their information soup = BeautifulSoup(page.text, 'html.parser') # Variable declarations List_data = [] row = 0 col = 0 # Links to be decomposed to avoid data tidiness links = soup.find(class_='text-muted text-small') links.decompose() artist_name_list = soup.find(class_='lister-list') artist_images = artist_name_list.find_all('img') artist_content = artist_name_list.find_all('p') # Initiating the Excel sheet to write the information workbook = xlsxwriter.Workbook('Celebrity Database.xlsx') worksheet = workbook.add_worksheet() # Adding the column names in the Excel File worksheet.write(row, col, 'Names') worksheet.write(row, col + 1, 'Images Links') worksheet.write(row, col + 2, 'Personality traits') # Data is looped to get as list as well import it in Excel for images, desc in zip(artist_images, artist_content): List_data.append({'Names': images.get('alt'), 'Images': images.get('src'), 'Links': desc.contents[0]}) worksheet.write(row, col, images.get('alt')) worksheet.write(row, col + 1, images.get('src')) worksheet.write(row, col + 2, desc.contents[0]) workbook.close() # close the worksheet as data is written db_filepath = os.path.dirname('Celebrity Database.xlsx') # Created Excel File is connected with the SQL database conn = create_db_connection(db_filepath) # Function call to open connection and create table create_table(conn) for data in List_data: c = conn.cursor() # Insert Data into the table once the table is created c.execute("""INSERT INTO CELEB_DATA (Name, Img, url) VALUES (?,?,?);""",(data['Names'], data['Images'],data['Links'])) conn.commit()
0abd382ece73a9732f988cf13ec756d65005cf00
981377660LMT/algorithm-study
/6_tree/前缀树trie/1554. 只有一个不同字符的字符串.py
1,392
3.875
4
# !给定一个字符串列表 dict ,其中所有字符串的长度都`相同`。 # 当存在两个字符串在相同索引处只有一个字符不同时,返回 True ,否则返回 False 。 # dict 中的字符数小于或等于 10^5 。 # 你可以以 O(n*m) 的复杂度解决问题吗?其中 n 是列表 dict 的长度,m 是字符串的长度。 # 将单词插入前缀树之前判断是否可以满足只有一个字符不同的条件 from typing import List from Trie import Trie, TrieNode class Solution: def differByOne(self, dict: List[str]) -> bool: def search(word: str) -> bool: def dfs(cur: "TrieNode", index: int, changed: bool) -> bool: if index == len(word): return changed res = False for child in cur.children: if child == word[index]: res |= dfs(cur.children[child], index + 1, changed) elif not changed: res |= dfs(cur.children[child], index + 1, True) return res return dfs(trie.root, 0, False) trie = Trie() for word in dict: if search(word): return True trie.insert(word) return False assert Solution().differByOne(["abcd", "acbd", "aacd"])
749d01fceb94be1504cfc393e09da60e895c3c73
youssefmamdouh/coursera_algorithms_course
/course1_toolbox/week3/dot_product.py
356
3.6875
4
#Uses python3 def max_dot_product(a, b): a = sorted(a, reverse=True) b = sorted(b, reverse=True) return sum([x*y for (x,y) in zip(a, b)]) if __name__ == '__main__': n = int(input()) a = [int(ai) for ai in input().split()] b = [int(bi) for bi in input().split()] assert len(a) == len(b) == n print(max_dot_product(a, b))
d5fabba9e4dcc7286dc35b44abecaef29c027aaf
huioo/byte_of_python
/main/base.py
4,852
4.5625
5
# 这里的文本,主要用作程序读者的注释 # 注释也可以使用 ''' 注释 ''' 或 """ 注释 """ """ 注释 """ ''' 注释 ''' # 例如:print是一个函数 print("help(len) 的结果信息:") # help方法,获取帮助信息 help('len') # print()函数参数:end表示结尾的字符,sep表示多个参数的中间连接字符 print('a', end='') print('b', end=', ') print('c', 'd', 'e', sep=' + ') print('*'*20) # 复制运算符(=)将常量5赋给变量i。称之为(陈述)语句,因为它陈述了需要完成的一些事情。 i = 5 print(i) # 文字常量,值不能改变的为常量 print('文字常量:', '5', '1.23', '\n字符串:', 'This is a string', "It's a string") # 字符串是 字符 的序列。字符串本质上是一堆单词。 # 指定字符串 # 1)单引号: 'Quote me on this' # 2)双引号: "What's your name?" # 3)三引号:使用三引号——(""" 或 ''')指定多行字符串,可以在三引号中自由地使用单引号和双引号: '''This is a multi-line string. This is the first line. This is the second line. "What's your name?," I asked. He said "Bond, James Bond." ''' # 字符串是不可改变的 """ 字符串含有 “'”,可以使用 “"”,例如:"What's your name?",而不能使用 'What's your name?' 也可以使用 “\” 转义符号来实现,将单引号指定为 “\'”,例如 'What\'s your name?' """ # 指定两行字符串 # 1)使用换行符 \n print('This is the first line\nThis is the second line') # 2)使用三引号 print('''This is the first line This is the second line''') # 使用“\”,放在行尾表示字符串在下一行继续,单不添加换行符; print('This is the first line \ This is the second line') print(20*'*') # 原始字符串 # 如果你需要指定一些没有特殊处理(转义)的字符串,那么你需要指定一个“原始”字符串,指定方法是在字符串前面加上“r”或“R”。 r"Newlines are indicated by \n" print(20*'*') # 数字,分为整数和浮点数 print('整数:', 2, sep='\t') print('浮点数:', 3.23, 52.3E-4, 'floating point numbers,简称floats', sep='\t') # 变量 # 变量的值可以变化,变量只是存储信息的计算机内存中的一部分。和文字常量不同的是,你需要一些方法来访问这些变量,因此你需要为它们命名。 # 变量可以直接通过赋值来使用,不需要任何声明活着数据类型定义。 i = i + 1 print(i) # 标识符命名 # 变量是标识符的例子。标识符 是用来标识 某事物的名的名称。在命名标识符的时候必须遵循一些规则: """ 标识符的第一个字符必须是字母(大写 ASCII 或小写 ASCII 或 Unicode 字符)或者下划线 (_)。 标识符的其余部分可以由字母、下划线 (_) 或者数字 (0-9) 组成。 标识符的名称区分大小写。例如, myname 和 myName 是 不 相同的。注意前者中的小写 n 和后者中的大写 N 。 有效标识符名称的例子有 i、name_2_3。 无效 标识符名称的例子有 2things、this is spaced out、my-name 以及 >a1b2_c3。 """ # 数据类型 # 变量可以保存不同类型(数据类型)的值。基本类型是数字和字符串。 # 对象 # python中一切皆对象,从某种意义上来讲,Python的面相对象是非常纯粹的,因为一切皆对象,包括数字、字符串和函数。 # 逻辑行,物理行 """ 物理行是当你在写程序的时候,你眼睛可以看见的行。 逻辑行是Python看到的一个程序语句。Python默认每一个物理行对应一个逻辑行。 一个逻辑行的一个例子就是一个语句,如 print('hello world!') 默认情况下,Python推荐一行一个语句,这会使代码更具有可读性 如果你希望在单个物理行中编写更多的逻辑行,则必须使用分号 (;) 显式地指定此逻辑行/此语句的结尾。 例如:i = 5; print(i); """ # 缩进 """ 空格在Python中非常重要。实际上,行首的空格非常重要。这就是所谓的缩进。 逻辑行开头的前导空格(空格和制表符)用于确定逻辑行的缩进级别,然后用于确定语句的分组。 这意味着同一组的语句 必须 有相同的缩进。每一个这样的语句集被称为 语句块 。 需要牢记的一件事情是,错误的缩进会导致报错。例如: i = 5 # 错误如下!注意,在行的开头处有一个空格 print('Value is', i) print('I repeat, the value is', i) 当你运行该程序时,你会得到下面的错误: File "whitespace.py", line 3 print('Value is', i) ^ IndentationError: unexpected indent 如何缩进 使用四个空格进行缩进。这是Python的官方建议。 Python将始终使用缩进进行分块,永远不会使用花括号。 """
dea4f8dd32723d3cab3de803468d18810edbd2da
seismatica/guttag
/6.00.1x/OCW/2/ps2b.py
2,166
4.0625
4
def is_diophantine(x, a, b, c): """ Input: a non-negative integer Output: boolean on whether the integer is a diophantine """ diophantine_flag = False for k in range(x//c + 1): for j in range((x - k*c)//b + 1): remaining = x - k*c - j*b if remaining % a == 0: return True else: diophantine_flag = False return diophantine_flag def diophantine_combination(x, a, b, c): """ Input: a non-negative integer (x), and package sizes (a, b, c) Output: list containing combination of a, b, and c packages that add up wholly to the input integer """ combinations = [] for k in range(x//c + 1): for j in range((x - k*c)//b + 1): remaining = x - k*c - j*b if remaining % a == 0: i = remaining//6 combinations.append([i, j, k]) return combinations while True: diophantine_count = 0 # Input package size packages = input("Enter package size from large to small ('q' to quit): ") if packages.lower() == 'q': break a, b, c = (int(x) for x in packages.split(',')) if a > b or b > c: print("You did not enter package sizes in the right order (smallest to largest)") continue # Input nugget count max_nuggets = input("Enter max numbers of McNuggets you want to buy ('q' to quit): ") if max_nuggets.lower() == 'q': break max_nuggets = int(max_nuggets) # Count diophantine numbers between range, exit loop when there are 6 diophantine numbers in a row or when all # nugget sizes are counted for num in range(0, max_nuggets + 1): if is_diophantine(num, a, b, c): diophantine_count += 1 else: diophantine_count = 0 # Optional since all the diophantine numbers will be subtracted at the end, # but this provides a quick way to end loop if diophantine_count == a: break print("Largest number of McNuggets (between 0 and", str(max_nuggets) + ") that cannot be bought in exact quantity:", num - diophantine_count)
012bce34f65c197a6604d809d4854f9176e1b223
stanman71/Python_Basics
/Machine Learning/Regression/Polynomiale Regression.py
1,916
3.75
4
""" Erweiterung der linearen Regression: y = a + bx + cx^2 """ ## ###################### ## Teil 0: Daten einlesen ## ###################### import pandas as pd df = pd.read_csv("./Python_Training/Machine Learning/Regression/CSV/fields.csv") ## ##################################### ## Modell 1: Normale, lineare Regression ## ##################################### X = df[["width", "length"]].values Y = df[["profit"]].values ######################## from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, Y, random_state = 42, test_size = 0.25) ######################## from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train, y_train) # Bestimmtheitsmaß R2 print(model.score(X_test, y_test)) ## ############################################################## ## Modell 2: Daten transformieren (polynomiale Regression Grad 2) ## ############################################################## from sklearn.preprocessing import PolynomialFeatures pf = PolynomialFeatures(degree = 2, include_bias = False) pf.fit(X_train) X_train_transformed = pf.transform(X_train) [:, [0, 2]] # nur bestimmte Spalten berücksichtigen X_test_transformed = pf.transform(X_test) [:, [0, 2]] # hier: Spalte 0 und 2 ## ############################################################################# ## Modell 3: Lineare Regression mit Daten aus polynomiale Regression durchführen ## ############################################################################# from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train_transformed, y_train) # Bestimmtheitsmaß R2 print(model.score(X_test_transformed, y_test)) """ Ausgabe der Spaltenmodifikation (Gibt Potenzzahl für jeden Eintrag an) """ print(pf.powers_)
093b6ffa0e3852a3720623d6b7154f03bdd08732
jisshub/python-django-training
/regex/Matching_with_start_and_plus.py
658
4.53125
5
import re pattern = re.compile('bat(wo)*man') match = pattern.search('batman') print(match.group()) # The * (called the star or asterisk) means “match zero or more”—the group # that precedes the star can occur any number of times in the text. It can be # completely absent or repeated over and over again. # Example-2 import re pattern = re.compile('bat(wo)*man') match = pattern.search('batwowowowowoman') print(match.group()) # here group wo occurs many times. import re pattern = re.compile('(hi)*\sguys') match = pattern.search(' guys') print(match.group()) # here pattern matches the given string even though it dont acontans the 'hi'.
e49e44d64bacbdb171d09cd36903fa1e60a403c5
bhagyashrishitole/coding-challenges
/LeetCode31DaysChallenge/Week2/straight_line.py
1,786
4.09375
4
""" Problem Statement: Check If It Is a Straight Line You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Example 2: Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Output: false Constraints: 2 <= coordinates.length <= 1000 coordinates[i].length == 2 -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 coordinates contains no duplicate point. Hide Hint #1 If there're only 2 points, return true. Hide Hint #2 Check if all other points lie on the line defined by the first 2 points. Hide Hint #3 Use cross product to check collinearity. """ class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: """Solution-1""" if len(coordinates) == 2: return True dx = coordinates[0][0] - coordinates[1][0] dy = coordinates[0][1] - coordinates[1][1] for i in range(0, len(coordinates)): if dx * (coordinates[1][1] - coordinates[i][1]) != dy * (coordinates[1][0] - coordinates[i][0]): return False return True """Solution-2""" # def checkStraightLine(self, coordinates: List[List[int]]) -> bool: # (x0, y0), (x1, y1) = coordinates[: 2] # for x, y in coordinates: # if (x1 - x0) * (y - y1) != (x - x1) * (y1 - y0): # return False # return True """Solution-3""" # def checkStraightLine(self, coordinates: List[List[int]]) -> bool: # (x0, y0), (x1, y1) = coordinates[: 2] # return all((x1 - x0) * (y - y1) == (x - x1) * (y1 - y0) for x, y in coordinates)
1fb38baea8d26a27ebc64c0f8b415738b7b0f2ed
mukeshbhoria/PythonClassData
/PythonClassData/Python_IMP/Link Codes/FileHandling/ExceptionDim.py
797
3.65625
4
def dimCheck(): try: print("st1") print("st1") #return 10 # '''(except only execute when try block have some error code)''' except TypeError : #( must be child of next excepts) print("st1") print("st1") return 21 except Exception : #( must be parent of previous excepts) print("st1") print("st1") return 22 # '''(else only execute when try block executed successfully)''' else: print("st1") print("st1") return 30 # '''(anyway finally we definately execute even try execute successfully or not)''' finally: print("st1") print("st1") return 40 return 50 ''' check return scenario with concepts by commenting the return statement '''
69ee99dbc01c7b52a02b3756c4c24613e081d9c6
junbinding/algorithm-notes
/str.string-to-integer-atoi.py
1,787
3.515625
4
class Solution: """ 8. 字符串转换整数 (atoi) https://leetcode-cn.com/problems/string-to-integer-atoi 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下: 如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。 假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。 该字符串在有效的整数部分之后也可能会存在多余的字符,那么这些字符可以被忽略,它们对函数不应该造成影响。 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换,即无法进行有效转换。 在任何情况下,若函数不能进行有效的转换时,请返回 0 。 """ def myAtoi(self, s: str) -> int: res = '' s = s.lstrip() sym = 1 num = '0123456789' for i in range(len(s)): if i == 0 and s[i] == '+': continue elif i == 0 and s[i] == '-': sym = -1 elif s[i] in num: res += s[i] else: break if res == '': return 0 res = int(res) * sym if 2147483647 >= res >= - 2147483648: return res if res >= 0: return 2147483647 else: return -2147483648 so = Solution() print(so.myAtoi('words and 987'))
61f5dec30eb20338d189e8568bb1aa764ea4cb77
dbgsprw/python-competitive-programming
/solutions/min_max_division.py
904
3.546875
4
def binary_search(start, end, array, value): mid = (start + end) // 2 if start == end: if mid >= len(array) or value == array[mid]: return start else: return start - 1 if value <= array[mid]: return binary_search(start, mid, array, value) else: return binary_search(mid + 1, end, array, value) def solution(K, M, A): prefix_sum = [A[0]] for a in A[1:]: prefix_sum.append(prefix_sum[-1] + a) min_ = max(A) start = 0 end = len(A) for i in range(K - 1): previous = prefix_sum[start - 1] if start > 0 else 0 min_ = max((prefix_sum[-1] - previous) // (K - i), min_) idx = binary_search(start, end, prefix_sum, previous + min_) start = idx + 1 previous = prefix_sum[start - 1] if start > 0 else 0 min_ = max((prefix_sum[-1] - previous), min_) return min_
51ac158f55c15c1b158c543b1f8cfad527051570
DolglasMesquita/teste1
/desafio.py
1,227
3.515625
4
import csv with open("tabela.csv", 'w', newline='') as arquivo: escrever = csv.writer(arquivo) escrever.writerow(["id", "nome", "salario"]) escrever.writerow(["1", "fulano", "1000.00"]) escrever.writerow(["2", "beltrano", "2000.00"]) escrever.writerow(["3", "andre", "1500.00"]) escrever.writerow(["4", "renato", "10.50"]) arquivo.close() while True: print("Escolha uma opção:") print("1 - listar | 2 - incluir | 3 - excluir") opcao = int(input("Opção: ")) if(opcao == 1): with open("tabela.csv") as arquivo: lista = csv.reader(arquivo) for linha in lista: print(linha) print("\n") if(opcao == 2): id = input("Id: ") nome = input("Nome: ") salario = input("Salário: ") with open("tabela.csv", 'a', newline='') as arquivo: incluir = csv.writer(arquivo) incluir.writerow([id, nome, salario]) print("\n") arquivo.close() if(opcao == 3): with open("tabela.csv", 'w', newline='') as arquivo: escrever = csv.writer(arquivo) escrever.writerow(["id", "nome", "salario"]) arquivo.close()
ff6fbd4f9cb152462121b57ed3bf6e3ffce386f6
wangzexin/ProblemEuler
/10001st prime.py
283
3.625
4
# Initialization primes = [2, 3] k = 4 # Calc the first 10001 prime numbers while len(primes) < 10001: f = True for prime in primes: if k % prime == 0: f = False break if f: primes.append(k) k += 1 # Output print(primes[-1])
aae3d7a73fdec85a6780c2a345a94f47097f13d0
srikanthpragada/python_18_jan_2021
/demo/assignments/06-FEB/even_first_odd_next.py
139
3.75
4
def odd_even(n): return 0 if n % 2 == 0 else 1 nums = [10, 29, 20, 40, 55, 33, 50] for n in sorted(nums, key=odd_even): print(n)
7340d0e3a03c4cb5e30921a5b2d4a2ed236c07ad
nazariinyzhnyk/sorting-algs
/sorters/insertion_sort.py
442
3.796875
4
from utils import register_sorter @register_sorter def insertion_sort(lst): for i in range(1, len(lst)): key = lst[i] j = i - 1 while j >= 0 and lst[j] > key: lst[j + 1] = lst[j] j -= 1 lst[j + 1] = key return lst if __name__ == '__main__': from utils import check_if_sorted srt = insertion_sort([7, 8, 5, 2, 2, 3, 1]) print(srt) print(check_if_sorted(srt))
08719a54c0227963b51f17d519b3bed4e17304bf
contactshadab/data-structure-algo-python
/data_structure/binary_tree/siblings_in_binary_tree.py
1,415
4.09375
4
from binary_search_tree_implementation import BinaryTree class MyBinaryTree(BinaryTree): def are_siblings(self, first, second): if self.root is None: raise Exception('Empty tree') if None in [first, second]: raise Exception('Illegal arguments') return self.__are_siblings(self.root, sorted([first, second])) def __are_siblings(self, root, values): if root is None: return False if root.left_child is not None and root.right_child is not None and sorted([root.left_child.value, root.right_child.value]) == values: return True return self.__are_siblings(root.left_child, values) or self.__are_siblings(root.right_child, values) if __name__ == "__main__": binary_tree = MyBinaryTree() # Populate binary tree binary_tree.insert(10) binary_tree.insert(30) binary_tree.insert(20) binary_tree.insert(60) binary_tree.insert(50) binary_tree.insert(5) binary_tree.insert(4) binary_tree.insert(6) # Find print(binary_tree.are_siblings(5, 30)) # True print(binary_tree.are_siblings(30, 5)) # True print(binary_tree.are_siblings(50, 60)) # False print(binary_tree.are_siblings(20, 20)) # False print(binary_tree.are_siblings(20, 60)) # True print(binary_tree.are_siblings(6, 20)) # False print(binary_tree.are_siblings(6, 4)) # True
aa63696b8ab13f9028fba208e632e921699d0f7e
andrewmeng810/python_algorithm
/fibonacci.py
340
4.125
4
def fibonacci(n): """ return a list of fibonacci sequence """ fib_list = [0,1] if n == 0: return [] elif n == 1: return [0] else: x = 2 a, b = fib_list[0],fib_list[1] while x < n: a, b = b , a + b fib_list.append(b) x += 1 return fib_list
3fc750619f4c500e1f354d060302cd12481c2038
semydava/python-hw
/is_palindrome.py
84
3.65625
4
def is_palindrome(string): string = str(string) return string[::-1]== string
7d894b25c1abe93fc6bd6bf1070a58beb914ad35
yhtsai0916/Python200803
/Day1-5.py
396
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 3 14:26:51 2020 @author: USER """ x=input("請輸入成績:") x=int(x) if x>=0: print("你的等級是:") if x>100: print("!輸入錯誤!") elif x>=90: print("A") elif x>=80: print("B") elif x>=70: print("C") elif x>=60: print("D") else: print("F")
415f249b906aab416914916e212c53be2c0f60fa
alukinykh/python
/lesson5/3.py
803
3.875
4
# 3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. # Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. # Выполнить подсчет средней величины дохода сотрудников. with open('task_3.txt') as f_obj: employees = f_obj.readlines() average = 0 for line in employees: person = line.split() average += float(person[1]) if float(person[1]) < 20000: print(person[0]) print(f'Средний доход сотрудников: {average / len(employees):.2f}')
20aed6b2c3088c4eeabbb620795ba3f45b426e60
Subaru3000/my_python
/dict_cinema_price.py
1,113
3.625
4
"Фильм «Паразиты», " "сеансы: 12 часов – 250 руб, 16 – 350 руб, 20 – 450 руб." "Фильм «1917»," "сеансы: 10 часов – 250 руб, 13 – 350 руб, 16 – 350 руб." "Фильм «Соник в кино», " "сеансы: 10 часов – 350 руб, 14 – 450 руб, 18 – 450 руб. " cinema = dict() cinema = {'Паразиты': {'сегодня': {12: 250, 16: 350, 20: 450}, 'завтра': {12: 250*0.95, 16: 350*0.95, 20: 450*0.95}}, '1917': {'сегодня': {10: 250, 13: 350, 16: 350}, 'завтра': {10: 250*0.95, 13: 350*0.95, 16: 350*0.95}}, 'Соник в кино': {'сегодня': {10: 350, 14: 450, 18: 450}, 'завтра': {10: 350*0.95, 14: 450*0.95, 18: 450*0.95}}} a = input("Введите название фильма: ") b = input("выбрать дату (сегодня, завтра): ") c = input("выбрать время: ") d = input("указать количество билетов: ") if int(d) >= 20: x = 0.8 else: x = 1 print("Стоимость билета", cinema[a][b][int(c)]*x)
19dd2d1fce5d506ee4adb422ed78d5be51e3afaa
jsdiuf/leetcode
/src/Reverse String.py
642
4.28125
4
""" @version: python3.5 @author: jsdiuf @contact: [email protected] @time: 2018-9-4 17:28 Write a function that takes a string as input and returns the string reversed. Example 1: Input: "hello" Output: "olleh" Example 2: Input: "A man, a plan, a canal: Panama" Output: "amanaP :lanac a ,nalp a ,nam A" """ class Solution: def reverseString(self, s): """ :type s: str :rtype: str """ i, j = 0, len(s) - 1 arr=list(s) while i <= j: arr[i], arr[j] = arr[j], arr[i] i += 1 j -= 1 return "".join(arr) s = Solution() print(s.reverseString("a"))
9822c6b25c80e8cdc24aaca1bd23b485978c448b
bb04265/PythonStudy
/BaekjoonSolving/for/8393.py
83
3.796875
4
num = int(input()) total = 0 for i in range(1, num+1): total += i print(total)
1de642152b89acfe2fbfd498a63985076856089e
viniTWL/Python-Projects
/funçoes/ex103.py
316
3.53125
4
def ficha(j, g): if not j: j = '<desconhecido>' if not g: g = 0 print(f'O jogador {j} fez {g} gols no total.') #Programa j = str(input('Qual o nome do seu jogador?')).strip() g = str(input(f'Quantos gols {j} fez?')).strip() if g.isnumeric(): g = int(g) else: g = 0 (ficha(j, g))
e6a83f2621681872cd86a0ab713fbb17c27ed1b0
Theskill19/sweetpotato
/les1.6.py
1,049
4.4375
4
#6. Спортсмен занимается ежедневными пробежками. # В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. # Программа должна принимать значения параметров a и b и выводить одно натуральное число — номер дня. a = float(input("Введите результаты пробежки первого дня в км ")) b = float(input("Введите общий желаемый результат в км ")) c = 1 d = a while a < b: a = a + 0.1 * a c += 1 d = d + a print(f"Вы достигните результата на %.d" % c)
eeb2a1f2e049286d1b8124dc4d5690cf40408b6a
hiratekatayama/math_puzzle
/leet/Reverse_String.py
339
3.8125
4
class Solution: def reverse_String(self, s): left, right = 0, len(s)-1 while left < right: s[left], s[right] = s[right], s[left] left = left + 1 right = right - 1 return s if __name__ == '__main__': test = Solution() lst_reverse = ["h","e", "l", "l" ,"o"] print(test.reverse_String(lst_reverse))
0db13b1dbf0003a08f5b167544492f7aae48ab9b
helaahma/python
/conditions_task.py
807
4.1875
4
#Define 2 variables and one operator var1= input("Please enter 1st integer: \n") var2= input("Please enter 2nd integer: \n") oper=input("Please enter an operator (+,-,*,/): \n") #Conditions if (var1.isdigit()==True and var2.isdigit() == True) and oper== "+": print ("the result of %s %s %s=" %(var1,oper,var2), int(var1)+int(var2)) elif (var1.isdigit()==True and var2.isdigit() == True) and oper=="*": print ("the result of %s %s %s= "%(var1,oper,var2), int(var1)*int(var2)) elif (var1.isdigit()==True and var2.isdigit() == True) and oper=="-": print ("the result of %s %s %s=" %(var1,oper,var2), int(var1)-int(var2)) elif (var1.isdigit()==True and var2.isdigit() == True) and oper=="/": print ("the result of %s %s %s=" %(var1,oper,var2), int(var1)/int(var2)) else: print ("Operation is invalid \n")
df998b88731d7bd6021b2782d7ba0923cd1e74d5
yashgupta777/AllDataScienceProjects
/keepitup/pythonBasics/checkIfStringIsAValidKeyword.py
3,324
4.5
4
# Python code to demonstrate working of iskeyword() # In programming, a keyword is a "reserved word" by the language which convey a special meaning to the interpreter. # It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. # Keywords in Python: Python language also reserves some of keywords that convey special meaning. # Knowledge of these is necessary part of learning this language. Below is list of keywords registered by python. # importing "keyword" for keyword operations # Python in its language defines an inbuilt module "keyword" which handles certain operations related to keywords. # A function "iskeyword()" checks if a string is keyword or not. Returns true if a string is keyword, else returns false. import keyword # initializing strings for testing s = "for" s1 = "geeksforgeeks" s2 = "elif" s3 = "elseif" s4 = "malika" s5 = "assert" s6 = "shambhavi" s7 = "True" s8 = "False" s9 = "Yash" s10 = "akash" s11 = "break" s12 = "ashty" s13 = "lambda" s14 = "suman" s15 = "try" s16 = "vaishnavi" # checking which are keywords if keyword.iskeyword(s): print (s + " is a python keyword") else: print (s + " is not a python keyword") if keyword.iskeyword(s1): print (s1 + " is a python keyword") else: print (s1 + " is not a python keyword") if keyword.iskeyword(s2): print (s2 + " is a python keyword") else: print (s2 + " is not a python keyword") if keyword.iskeyword(s3): print (s3 + " is a python keyword") else: print (s3 + " is not a python keyword") if keyword.iskeyword(s4): print (s4 + " is a python keyword") else: print (s4 + " is not a python keyword") if keyword.iskeyword(s5): print (s5 + " is a python keyword") else: print (s5 + " is not a python keyword") if keyword.iskeyword(s6): print (s6 + " is a python keyword") else: print (s6 + " is not a python keyword") if keyword.iskeyword(s7): print (s7 + " is a python keyword") else: print (s7 + " is not a python keyword") if keyword.iskeyword(s8): print (s8 + " is a python keyword") else: print (s8 + " is not a python keyword") if keyword.iskeyword(s9): print (s9 + " is a python keyword") else: print (s9 + " is not a python keyword") if keyword.iskeyword(s10): print (s10 + " is a python keyword") else: print (s10 + " is not a python keyword") if keyword.iskeyword(s11): print (s11 + " is a python keyword") else: print (s11 + " is not a python keyword") if keyword.iskeyword(s12): print (s12 + " is a python keyword") else: print (s12 + " is not a python keyword") if keyword.iskeyword(s13): print (s13 + " is a python keyword") else: print (s13 + " is not a python keyword") if keyword.iskeyword(s14): print (s14 + " is a python keyword") else: print (s14 + " is not a python keyword") if keyword.iskeyword(s15): print (s15 + " is a python keyword") else: print (s15 + " is not a python keyword") if keyword.iskeyword(s16): print (s16 + " is a python keyword") else: print (s16 + " is not a python keyword") # printing all keywords at once using "kwlist()" print ("The list of keywords is : ") print (keyword.kwlist)
c0e261fc546da6261b884c46f0ccc4d709dac54a
953250587/leetcode-python
/TotalHammingDistance_MID_477.py
1,616
4.125
4
""" The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Now your job is to find the total Hamming distance between all pairs of the given numbers. Example: Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just showing the four bits relevant in this case). So the answer will be: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. Note: Elements of the given array are in the range of 0 to 10^9 Length of the array will not exceed 10^4. """ class Solution(object): def totalHammingDistance(self, nums): """ :type nums: List[int] :rtype: int 969ms """ l=len(nums) result=0 for i in range(32): count=0 for j in nums: b=j>>i if bin(b)[-1]=='1': count+=1 result+=(l-count)*count return result # 302ms return sum(b.count('0') * b.count('1') for b in zip(*map('{:032b}'.format, nums))) def totalHammingDistance_1(self, nums): """ :type nums: List[int] :rtype: int 212ms """ n = len(nums) ans = 0 for i in range(16): cnt = 0 for num in nums: cnt += (num >> i) & 0x10001 cnt0, cnt1 = cnt & 0xFFFF, cnt >> 16 ans += cnt0 * (n - cnt0) + cnt1 * (n - cnt1) return ans print(Solution().totalHammingDistance([])) print(4,3,20^19,20|19,4&3)
37f3095f02e9c7b2539785f2c559a3eb7c612480
eroicaleo/LearningPython
/interview/leet/457_Circular_Array_Loop.py
1,179
3.578125
4
#!/usr/bin/env python3 class Solution: def circularArrayLoop(self, nums): l = len(nums) for i in range(l): print(f'i = {i}') head = slow = fast = i while True: slow = (slow+nums[slow])%l fast1 = (fast+nums[fast])%l fast2 = (fast1+nums[fast1])%l if fast == fast1 or fast1 == fast2: print(f'break 1 fast = nums[{fast}] = {nums[fast]}') break if (nums[head]*nums[fast] <= 0) or (nums[head]*nums[fast1] <= 0): print(f'break 2, fast = nums[{fast}] = {nums[fast]}') break fast = fast2 print(f'slow = nums[{slow}] = {nums[slow]}, fast = nums[{fast}] = {nums[fast]}') if slow == fast: return True while head != fast: nums[head], head = 0, (head+nums[head])%l print(f'nums = {nums}') return False sol = Solution() nums = [-2, 1, -1, -2,-2] nums = [2, -1, 1, 2,2] nums = [-1, 2] nums = [-1,-2,-3,-4,-5] print(sol.circularArrayLoop(nums))
24bfddf06f7e90a9cb4f6617bb540cf20a76ea78
EldadZZipori/WoG-Devops_course_project
/GuessGame.py
914
3.84375
4
import Utils from random import randint # this module contains the function needed to run the Guess Game # generates a number between 1 and the games difficulty def generate_number(difficulty: int) -> int: return randint(1,difficulty) # asks the user for a guess between 1 to difficulty, returns the users guess def guess_from_user(difficulty: int) -> int: return Utils.validate_user_input(1, difficulty, "guess") # checks weather the generated number is the same as the users guess # calls guess_from_user to get the users input def compare_results(difficulty: int, secret_number: int) -> bool: return guess_from_user(difficulty) == secret_number # starts the game by using the above functions # returns: # True - if user won # False - if user lost def play(difficulty: int) -> bool: secret_number = generate_number(difficulty) return compare_results(difficulty, secret_number)
ba5d8361fd1873acda1456f546ea2dd8583cf354
SmallConcern/python_leetcode
/25_reverse_nodes_in_k_group/reverse_nodes_in_k_group.py
909
3.953125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def append(self, val): self.next = ListNode(val) def reverse_linked_list_in_k_group(head): pass class TestReverseNodesInKGroup(object): def string_to_linked_list(self, input): head = ListNode(None) next = head.next for c in input: if not head.val: head.val = c ne else: next.append(c) next = next.next return next def linked_list_to_string(self, head): output = '' while head: output += str(head.val) head = head.next return output def test_reverse_nodes(self): head = self.string_to_linked_list("12345") assert self.linked_list_to_string(head) == "12345"
f577efa63fa683f8a08703307a1e1090ee4a41bf
JeromeLefebvre/ProjectEuler
/Python/Problem197.py
737
3.921875
4
#!/usr/local/bin/python3.3 ''' http://projecteuler.net/problem=197() Investigating the behaviour of a recursively defined sequence Problem 197 Given is the function f(x) = ⌊230.403243784-x2⌋ × 10-9 ( ⌊ ⌋ is the floor-function), the sequence un is defined by u0 = -1 and un+1 = f(un). Find un + un+1 for n = 1012. Give your answer with 9 digits after the decimal point. ''' ''' Notes on problem 197(): ''' from projectEuler import primes from decimal import * def problem197(): getcontext().prec = 20 u = Decimal(-1) def f(x): return int(2**(Decimal(30.403243784)-x**2)) * Decimal(10**(-9)) while abs(u - f(f(u)))>10**(-12): u = f(u) return float(str(u + f(u))[0:11]) if __name__ == "__main__": print(problem197())
b7160f91633bc75bc9cdca7d5aebb8d894163cad
svnaumov1985/Python_alg_2
/less3_task1.py
377
3.53125
4
# В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9. dict = {i:0 for i in range(2,10)} for i in range(2, 100): for a in range(2, 10): dict[a] += 1 if i % a == 0 else 0 for a in dict: print(a, " - ", dict[a])
6b036d8879f329ee40aeace04a15863212f13763
vvaldes/ejemplo1
/baseDatosMysql.py
7,326
3.53125
4
#base datos #http://docs.peewee-orm.com/en/latest/peewee/installation.html #pip install peewee # o bien git clone https://github.com/coleifer/peewee.git # cd peewee # python setup.py install #python runtests.py #sudo pip3 install PyMySQL import pymysql import pymysql.cursors con = pymysql.connect('192.168.0.7', 'victor','vvgvvg', 'zurbaies') with con: cur = con.cursor() cur.execute("SELECT * FROM Alumnos") rows = cur.fetchall() for row in rows: print("{0} {1} {2}".format(row[0], row[1], row[2])) cur.execute("SELECT * FROM Alumnos") rows = cur.fetchall() for row in rows: #print(row["Nombre"], row["DniAlumno"], row("Domicilio")) print("{0}".format(row[0])) con.close() ## Connecting to the database ## importing 'mysql.connector' as mysql for convenient #pip3 install mysql.connector import mysql.connector as mysql ## connecting to the database using 'connect()' method ## it takes 3 required parameters 'host', 'user', 'passwd' db = mysql.connect( host = "192.168.0.7", user = "victor", passwd = "vvgvvg" ) ## creating an instance of 'cursor' class which is used to execute the 'SQL' statements in 'Python' cursor = db.cursor() ## creating a databse called 'datacamp' ## 'execute()' method is used to compile a 'SQL' statement ## below statement is used to create tha 'datacamp' database try: cursor.execute("CREATE DATABASE datacamp") except mysql.Error as err: print("Dabase ya creada", err) except : print("Error desconocido") ## executing the statement using 'execute()' method cursor.execute("SHOW DATABASES") ## 'fetchall()' method fetches all the rows from the last executed statement databases = cursor.fetchall() ## it returns a list of all databases present ## printing the list of databases print(databases) ## showing one by one database for database in databases: print(database) db.close() import mysql.connector as mysql db = mysql.connect( host = "192.168.0.7", user = "victor", passwd = "vvgvvg", database = "datacamp" ) cursor = db.cursor() ## creating a table called 'users' in the 'datacamp' database #cursor.execute("CREATE TABLE users (name VARCHAR(255), user_name VARCHAR(255))") ## creating the 'users' table again with the 'PRIMARY KEY' #cursor.execute("DROP TABLE users") try: cursor.execute("CREATE TABLE users (id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), user_name VARCHAR(255))") except mysql.Error as err: print("tabla ya creada", err) ## 'DESC table_name' is used to get all columns information cursor.execute("DESC users") ## it will print all the columns as 'tuples' in a list print(cursor.fetchall()) cursor = db.cursor() ## defining the Query query = "INSERT INTO users (name, user_name) VALUES (%s, %s)" ## storing values in a variable values = [ ("Peter", "peter"), ("Amy", "amy"), ("Michael", "michael"), ("Hennah", "hennah") ] ## executing the query with values cursor.executemany(query, values) ## to make final output we have to run the 'commit()' method of the database object db.commit() print(cursor.rowcount, "records inserted") ## defining the Query query = "SELECT * FROM users" ## getting records from the table cursor.execute(query) ## fetching all records from the 'cursor' object records = cursor.fetchall() ## Showing the data for record in records: print(record) ## defining the Query query = "DELETE FROM users WHERE id = 5" ## executing the query cursor.execute(query) ## final step to tell the database that we have changed the table data db.commit() ## defining the Query query = "UPDATE users SET name = 'Kareem' WHERE id = 1" ## executing the query cursor.execute(query) ## final step to tell the database that we have changed the table data db.commit() db.close() from decimal import Decimal from datetime import datetime, date, timedelta import mysql.connector # Connect with the MySQL Server #cnx = mysql.connector.connect('192.168.0.7', 'victor','vvgvvg', 'zurbaies') cnx = mysql.connector.connect(user='victor', password='vvgvvg', database='employees',host='192.168.0.7',port='3306') #con = pymysql.connect('192.168.0.7', 'victor','vvgvvg', 'zurbaies') # Get two buffered cursors curA = cnx.cursor(buffered=True) curB = cnx.cursor(buffered=True) #try: curA.execute("CREATE TABLE IF NOT EXISTS employees (emp_no INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255),hire_date DATE)") curA.execute("CREATE TABLE IF NOT EXISTS salaries (emp_no INT(11) , salary INT, from_date DATE, to_date DATE)") query = "INSERT INTO employees (name,hire_date) VALUES ('victor',DATE('1000-01-01'))" curA.execute(query) cnx.commit() query = "SELECT emp_no FROM employees as a WHERE a.name='victor' AND a.hire_date=DATE('1000-01-01')" curB.execute(query) #rows = curB.fetchall() #row=rows[0] #print("rows:", rows, "row", row, "row0", rows[0]) query = "INSERT INTO salaries (salary,from_date,to_date) VALUES (1000,DATE('1000-01-01'),DATE('9999-01-01'))" curA.execute(query,row[0]) query = "INSERT INTO salaries (emp_no,salary,from_date,to_date) VALUES (%i,1000,DATE('1000-01-01'),DATE('9999-01-01'))" #curA.execute(query,row[0]) cnx.commit() #except mysql.Error as err: # print("tabla ya creada", err) # Query to get employees who joined in a period defined by two dates query = ( "SELECT s.emp_no, salary, from_date, to_date FROM employees AS e " "LEFT JOIN salaries AS s USING (emp_no) " "WHERE to_date = DATE('9999-01-01')" "AND e.hire_date BETWEEN DATE(%s) AND DATE(%s)") # UPDATE and INSERT statements for the old and new salary update_old_salary = ( "UPDATE salaries SET to_date = %s " "WHERE emp_no = %s AND from_date = %s") insert_new_salary = ( "INSERT INTO salaries (emp_no, from_date, to_date, salary) " "VALUES (%s, %s, %s, %s)") # Select the employees getting a raise curA.execute(query, (date(2000, 1, 1), date(2000, 12, 31))) # Iterate through the result of curA for (emp_no, salary, from_date, to_date) in curA: # Update the old and insert the new salary new_salary = int(round(salary * Decimal('1.15'))) curB.execute(update_old_salary, (tomorrow, emp_no, from_date)) curB.execute(insert_new_salary, (emp_no, tomorrow, date(9999, 1, 1,), new_salary)) # Commit the changes cnx.commit() cnx.close() #import peewee as pw from peewee import * myDB = MySQLDatabase("datacamp", host="192.168.0.7", port=3306, user="victor", passwd="vvgvvg") class MySQLModel(Model): """A base model that will use our MySQL database""" class Meta: database = myDB class Users(MySQLModel): id = IntegerField(unique=True) name = CharField() user_name = CharField() class Meta: database = myDB def create_table(): with myDB: myDB.create_tables([Users]) # when you're ready to start querying, remember to connect myDB.connect() #myDB.create_tables() try: with myDB.atomic(): user = Users.create(name="Victor",user_name="usuario") print("Registro insertado") except IntegrityError: #flash('That username is already taken') print("Registro existente") #list records for user in user.select(): print(user.name," ",user.user_name) for user in user.select().where(user.name == "Victor"): print(user.name) myDB.close()
778a7d64d7426203ada920095c5c26122ae5fc7f
bpraggastis/Mac_Battleship
/battleship.py
21,765
4
4
###################################################### # # Battleship Game # started 8/3/14 # working version completed 8/13/14 # # ###################################################### import math import random import sys ######## Constants ############################## Ship = {'A' : ["Aircraft Carrier", 5], 'B' : ["Battleship", 4], 'D' : ["Destroyer", 3], 'S' : ["Submarine", 3], 'P' : ["Patrol Boat", 2]} HIT= " X " MISS = " O " HIDDEN = " --- " ######## Class Definitions ############################## class Player: """ Each player is given a name and potentially will have scores and battle points. Each player will be given a board and 5 ships to place on the board. """ def __init__(self, name = "Anonymous"): """ Initialize player with name, score, and battle points. """ self._name = name self._score = 0 self._battle_points = 0 def __str__(self): """ Returns the name of the player. """ return self._name class Board: """ Class representation of playing board. Each player will have their own board. """ def __init__(self, player = Player(), size = 10): self._player = str(player) self._size = size self._grid = set([(row,col) for row in range(self._size) for col in range(self._size)]) self._status = [[HIDDEN for col in range(self._size)] for row in range(self._size)] self._unused = set(self._grid) self._used = set() self._hidden = set(self._grid) def __str__(self): """ Generates a string representation for the board returns a string """ print self._player + "'s board:" board = " " for col in range(self._size): board += " " + str(col) + " " board += "\n +" + "-----" * 10 + "+\n" for row in range(self._size): board += str(row) + " |" for col in range(self._size): board += self._status[row][col] board += "|\n" board += " +" + "-----" * 10 + "+\n\n" return board def get_grid(self): """ Returns a set of tuples referencing the squares on the board. """ return self._grid def get_size(self): """ Returns the length of the board (all boards are square) """ return self._size def get_player(self): """ Returns the string representation of the owner of the board. """ return self._player def update_used(self, new = ()): """ Adds new to set of used squares """ self._used.update(set(new)) def update_unused(self, new = ()): """ Adds new to set of unused squares """ self._unused.update(set(new)) # print self._unused def remove_used(self, new = ()): """ Removes new from set of used squares """ self._used.difference_update(set(new)) def remove_unused(self, new = ()): """ Removes new from set of unused squares """ self._unused.difference_update(set(new)) def get_unused(self): """ Returns unused squares """ return self._unused def get_used(self): """ Returns used squares """ return self._used def update_status(self, pos = None, new_status = HIDDEN): """ Updates the entry in self._status at grid position pos to reflect the hits received during the game. """ if pos != None: self._status[pos[0]][pos[1]] = new_status return None def get_status(self, pos = None): """ Returns the visible status of the position on the board. """ return self._status[pos[0]][pos[1]] def check_available(self, pos_set): return set(pos_set) <= set(self._unused) class Naval_Vessel: """ Naval_Vessel class will give methods common to all ships in the game. Owner, length, type of vessel, status (hidden, hit, sunk) and current location will adjusted using these methods. Each ship is tied to a specific board. """ def __init__(self, board = Board(), code = "A", berth = None, orientation = 0): """ Initialize the Naval Vessel Class to have berth location, horizontal orientation, and status hidden """ self._board = board self._player = board.get_player() self._code = code self._name = Ship[code][0] self._length = Ship[code][1] self._location = berth # position of the ship's helm as a tuple self._orientation = orientation # 0 is horizontal, 1 is vertical self._hits = set() self._sunk = False def __str__(self): """ Returns string indicating player, their ship, its location, and its status in symbols """ return self._player + "'s " + self._name + ", Location = " + str(self.get_location()) def get_helm(self): """ Returns helm location as an ordered pair """ return self._location def get_location(self): """ Returns a list of tuples on board occupied by the ship. If the ship is still at the berth it returns None. """ if self._location == None: return None hpos = self._location # this is just the position of the helm ori = self._orientation return [(hpos[0] + ori*idx , hpos[1] + ((ori + 1)%2 )*idx) for idx in range(self._length)] def get_code(self): """ Returns code for printing when ship is sunk. """ return " " + self._code + " " def change_orientation(self): """ flips the ship's orientation """ self._orientation = (self._orientation + 1 ) % 2 return def set_orientation(self,orientation): """ Allows user to set the actual orientation. """ if orientation in [0,1]: self._orientation = orientation return def get_length(self): """ Returns the length of the ship """ return self._length def move(self, pos, ori = None): """ Changes the ship's location so that its helm is at pos. The full location is then determined by its length and orientation. The helm is always positioned at the top or far left of the vessel If the new position is unavailable, the ship will not be moved. Return True if a move was successful """ if ori == None: ori = self.get_orientation() if self._location != None: self._board.remove_used(self.get_location()) # this lifts the ship off the board self._board.update_unused(self.get_location()) # and makes those squares available again # now check if the new position is available. If so, reset the helm to this position new_pos = [(pos[0] + ori*idx , pos[1] + ((ori + 1)%2 )*idx) for idx in range(self._length)] if self._board.check_available(set(new_pos)): self._location = pos self._orientation = ori self._board.update_used(set(new_pos)) self._board.remove_unused(set(new_pos)) return True else: print "Requested location not available, try another spot or shift the orientation." if self.get_location() != None: self._board.update_used(self.get_location()) # this puts the ship back where it was self._board.remove_unused(self.get_location()) return False def check_damages(self, pos): """ Determines if the ship is on a certain square on the board. Returns boolean. """ return pos in set(self.get_location()) def update_status(self, pos): """ Given a grid position tuple, the position will be added to the hits and the total number of hits will be returned """ if pos in set(self.get_location()): self._hits.add(pos) if len(self._hits) == self._length: for hit in list(self._hits): self._board.update_status(hit, self.get_code()) print "You sank my " + self._name + "!" self._sunk = True else: self._board.update_status(pos, HIT) return len(self._hits) class Fleet: """ Each player is given 5 ships (Naval Vessels) to play with. At the beginning of the game the ships are located in a berth. During the set up stage each player will move their ships to a place on their board. This class will keep track of the position of the fleet and the health (the number of hits) of each vessel. When all vessels are sunk the player concedes the game. """ def __init__(self, board = Board(), manual = True, berth = None): """ The type of Fleet will depend on whether the player is manually controlling the boats or the computer is controlling the boats. I the latter case the Fleet will be initialized on the board in random locations. If manual = True then additional functions must be called to place the ships. """ self._board = board self._player = str(board.get_player()) self._manual = manual self._health = 17 if manual == True: self._fleet = {} for vessel in Ship.iterkeys(): self._fleet[vessel] = Naval_Vessel(board, vessel) # print self._fleet else: self._fleet = {} for vessel in Ship.iterkeys(): berth, orientation = create_ship(self._board, vessel) self._fleet[vessel] = Naval_Vessel(self._board, vessel, berth, orientation) self._berth = berth def __str__(self): """ Returns a list of Vessels """ fleet = str(self._board.get_player()) + "'s Fleet:\n" for vessel in self._fleet.itervalues(): fleet += " " + str(ship) + "\n" return str(fleet) def get_health(self): """ How many spots in the Fleet are still hidden? """ return self._health def check_for_damages(self, pos_set): """ Checks if a pos is on one of the ships in the fleet. If it is it updates the status of the ships and the board. """ for pos in pos_set: hit = False for ship in self._fleet.itervalues(): if pos in ship.get_location(): print str(pos) + " is a HIT" hit = True ship.update_status(pos) self._health -= 1 if self._health == 0: print self._player + "'s fleet is Destroyed. Game Over." print self._board sys.exit(0) if hit == False: print str(pos) + " is a MISS" self._board.update_status(pos,MISS) print self._board return def get_fleet_list(self): """ Returns a list of all positions held by fleet along with the corresponding codes List has the form [ [pos,code] ...] """ fleet = set() for ship in self._fleet.itervalues(): for pos in ship.get_location(): fleet.update([pos, ship.get_code()]) return fleet def get_fleet(self): """ Returns the self._fleet dictionary to reference individual ships in the fleet. """ return self._fleet def get_player(self): """ Returns the player for this fleet """ return self._board.get_player() class Strategy: """ Class representation of automated strategy for search and strike of ships on Battleship Game board. """ def __init__(self, board = Board(), fleet = Fleet()): """ Initialize the strategy with a blank board. Only even numbered squares will be struck at random. """ self._board = board self._fleet = fleet self._grid = [ (x,y) for x in range(0,10) for y in range(0,10)] self._checkers = [pos for pos in self._grid if (pos[1] + pos[0]) % 2 == 0 ] self._hit_list = [] self._move_idx = 0 self._hit_idx = 1 self._moves = {3:(1,0), 2:(-1,0), 0:(0,1), 1:(0,-1)} def add_vectors(self, pos1, pos2): """ Used to add components of vectors when moving around board. """ return (pos1[0] + pos2[0], pos1[1] + pos2[1]) def scalar(self, pos, scalar): """ Multiplies the entries in a vector by a scalar. """ return (pos[0] * scalar, pos[1] * scalar) def update_hit_list(self): """ Checks if any of the hits in the hit_list correspond to sunk ships. If so they will be removed from the list. """ temp_list = list(self._hit_list) for hit in temp_list: if self._board.get_status(hit) != HIT: self._hit_list.remove(hit) def random_strike(self): """ Randomly strikes a position from the checkerboard grid. """ self._move_idx = 0 self._hit_idx = 1 pos = random.choice(self._checkers) self._checkers.remove(pos) self._fleet.check_for_damages([pos]) status = self._board.get_status(pos) if status == HIT: self._hit_list.append(pos) elif status != MISS: self.update_hit_list() def strike(self): """ If a ship has been hit the strategy is to continue to hit until the ship is sunk. A ship is sunk when its identity is revealed in the board status. """ if self._hit_list == []: return # the following loop will repeat until the next target is found. available = False while available == False: # find the next available target by moving around a known hit next_hit = self.add_vectors(self._hit_list[0], self.scalar(self._moves[self._move_idx], self._hit_idx)) if next_hit[0] in range(0,10) and next_hit[1] in range(0,10): # this says the target is on the board if self._board.get_status(next_hit) == HIDDEN: # this says the target's status is still unknown available = True else: self._hit_idx = 1 self._move_idx = (self._move_idx + 1) % 4 # this looks for a target in a different direction else: self._hit_idx = 1 self._move_idx = (self._move_idx + 1) % 4 # this looks for a target in a different direction if next_hit in self._checkers: self._checkers.remove(next_hit) self._fleet.check_for_damages([next_hit]) status = self._board.get_status(next_hit) if status == HIT: self._hit_list.append(next_hit) self._hit_idx += 1 # Keep going in this direction elif status == MISS: self._move_idx = (self._move_idx + 1) % 4 # Change directions self._hit_idx = 1 else: self.update_hit_list() self._hit_idx = 1 def take_turn(self): """ Check to see if there are any hit ships in the list. If so, then hit around the first element in the list by using strike algorithm. If not, randomly choose a target from the checker board pattern. """ # print self._hit_list if self._hit_list == []: self.random_strike() else: self.strike() self.update_hit_list() ######## Helper Functions ############################## def create_ship(board = Board(), code = "A"): """ Generates a set containing all possible places a ship of type code could go on the given board and then randomly chooses one of these to be the position of the ship. It updates the used and unused squares on the board and returns the helm position of the ship and orientation of the ship """ avail = [] ship_length = Ship[code][1] for row in range(0, board.get_size()): for col in range(0,board.get_size() + 1 - ship_length): poss = [] for idx in range(0, ship_length): poss.append((row,col + idx)) if set(poss) <= board.get_unused(): avail.append(poss) for col in range(0, board.get_size()): for row in range(0,board.get_size() + 1 - ship_length): poss = [] for idy in range(0,ship_length): poss.append((row + idy,col)) if set(poss) <= board.get_unused(): avail.append(poss) ship_span = random.choice(avail) board.remove_unused(ship_span) board.update_used(ship_span) # print ship_span ship_orientation = ship_span[1][0] - ship_span[0][0] ship_helm = ship_span[0] return ship_helm, ship_orientation def draw_occupied_board(fleet = Fleet()): """ Shows the location of all ships in the fleet as a graphical display. """ show_board = Board(fleet.get_player()) for ship in fleet.get_fleet().itervalues(): if ship.get_location() != None: for pos in ship.get_location(): show_board.update_status(pos,ship.get_code()) print show_board return show_board def player_set_up(board = Board(), fleet = Fleet()): """ Asks player to move ships onto the board """ player = board.get_player() print print print print "#########################################################################" print "# " print "# Welcome to Battleship: Your Player vs. The Computer " print "#" print "#########################################################################" print print print " Hello " + str(player) + ". It is time for you to place your ships on the board." print " You have 5 ships: \n 'A' = an Aircraft carrier (5 spaces), \n 'B' = a Battleship (4 spaces), " print " 'D' = a Destroyer (3 spaces), \n 'S' = Submarine (3 spaces), and \n 'P' = a Patrol Boat (2 spaces)" print print "Look at your board below. You have 10 rows labeled 0 - 9 and 10 columns labeled 0 - 9." print "You will place your ships by entering the following information separated only by spaces. Example: A 1 2 0." print " At the prompt, enter the ship you wish to place. You may reenter any ship multiple times. When all ships" print " have been placed and you are happy with your arrangement, type 'x to exit setup and begin the game." print board set_up = True placed_ships = 0 while set_up == True: print " <shipcode: A, B, D, S, P> <row: 0-9> <column:0-9> <orientation:0=horizontal,1=vertical> " print " remember to separate each letter or number using only spaces. Press enter when done. Press 'q' to quit and 'x' to exit setup." your_resp = raw_input() if your_resp == 'q': sys.exit(0) return if your_resp == 'x' and placed_ships < 5: print "You do not have all of your ships placed. Please reenter your response." elif your_resp == 'x': print "Set up complete" set_up = False elif your_resp == "": print "You must enter some response." else: response = your_resp.split() if len(response) < 4: print "Re-enter your response as a 4 symbol code." else: code = response[0] pos = (int(response[1]), int(response[2])) ori = int(response[3]) print code, pos, ori if code not in Ship.iterkeys(): print "Letter symbol must be A B D S or P. Re-enter response." elif len(response) < 4: print " Re-enter your response as a 4 symbol code, each symbol separated by a space like: B 0 4 1." elif pos not in board.get_grid(): print "Row and Column values must be in 0-9. Re-enter response." elif ori not in [0,1]: print "Orientation is 0 for horizontal and 1 for vertical. Re-enter response." else: success = fleet.get_fleet()[code].move(pos, ori) draw_occupied_board(fleet) placed_ships = 0 for ship in fleet.get_fleet().itervalues(): if ship.get_location() != None: placed_ships += 1 if placed_ships == 5: print "You have placed all of your ships. You may move a ship or enter x when you are ready to continue." return def player_test_set_up(board = Board(), fleet = Fleet(), test = None): """ This receives a placement for the ships and puts the players ships there test is a list of the form ['A 1 0 1', 'B 3 4 0', ect.... for all 5 ships] """ if len(test) != 5: print "insufficient data" return for your_resp in test: response = your_resp.split() if len(response) < 4: print "Re-enter your response as a 4 symbol code." return else: code = response[0] pos = (int(response[1]), int(response[2])) ori = int(response[3]) print code, pos, ori if code not in Ship.iterkeys(): print "Letter symbol must be A B D S or P. Re-enter response." return elif pos not in board.get_grid(): print "Row and Column values must be in 0-9. Re-enter response." return elif ori not in [0,1]: print "Orientation is 0 for horizontal and 1 for vertical. Re-enter response." return else: fleet.get_fleet()[code].move(pos, ori) placed_ships = 0 for ship in fleet.get_fleet().itervalues(): if ship.get_location() != None: placed_ships += 1 if placed_ships == 5: print "You have placed all of your ships. " draw_occupied_board(fleet) ######## Play the Game ############################## ####### Step 1 - pass out the pieces to each player ## print "What is your name? >> ", your_name = raw_input() print print "Hello " + your_name + ". Welcome to Battleship" my_player = Player(your_name) my_board = Board(my_player) my_fleet = Fleet(my_board) ######## Step 2 - place players ship on the board print ################## For Testing ########################################## # uncomment the next two lines and comment out player_set_up to auto run the player set up #test1 = ['A 4 3 1', 'B 0 0 1', 'D 9 2 0', 'S 2 9 1', 'P 0 8 0'] #player_test_set_up(my_board, my_fleet, test1) ###################################################################### player_set_up(my_board, my_fleet) print enemy = Player("The Enemy") enemy_board = Board(enemy) enemy_fleet = Fleet(enemy_board, False) ######### If you want to cheat, uncomment the following line and the enemy board will ######### be displayed with its ships placed. # draw_occupied_board(enemy_fleet) ####### Step 3 - give the computer an algorithm to follow to find the player's ships enemy_strategy = Strategy(my_board, my_fleet) ####### Step 4 - begin taking turns - game will terminate when a fleet is destroyed turn = 0 while my_fleet.get_health > 0 and enemy_fleet.get_health > 0: if turn % 2 == 0: print enemy_board next_hit = () while next_hit == (): print str(my_player) + ", please enter a row (0-9) and column (0-9) separated only by a space." print ">> ", your_response = raw_input() entry = your_response.split() if len(entry) != 2: print "Please enter exactly two numbers" else: entry = (int(entry[0]), int(entry[1])) if entry[0] not in range(0,10) or entry[1] not in range(0,10): print "Please enter two numbers between 0 and 9." elif enemy_board.get_status(entry) != HIDDEN: print "Please choose a point not already chosen." else: next_hit = entry enemy_fleet.check_for_damages([next_hit]) turn += 1 else: enemy_strategy.take_turn() turn += 1
6701472df3653b2b954c63a962a67ac1c99e9e12
shilpavijay/Algorithms-Problems-Techniques
/Python/dictFromList.py
305
3.6875
4
l = [1,2,3,3,5,1,2,3,4] d = {} for each in set(l): d.update({each:l.count(each)}) # OR # {d.update({each:l.count(each)}) for each in set(l)} print(d) OR from collections import Counter c=Counter(l) print(c) #DICT FROM TWO LISTS a=['a','b','c'] b=[1,2,3] lstDict = dict(zip(a,b)) print(lstDict)
4ff16ef8b0ccfe65512eabfdaf6f6e8180e8b587
PNeekeetah/Leetcode_Problems
/Same_Tree.py
1,681
3.953125
4
""" First time submission succesful. It beats 62% in terms of runtime and 0% in terms of memory. Admittedly, I was supposed to do this using an iterative version of inorder, postorder or preorder. I did it with a BFS. It took me about 1 hour to ditch trying to compare and write the iterative tree traversal. It took me about 10 minutes to write this approach. I think the way i've designed it is really good. In my other approach, I was trying was to iterate through the 2 trees at the same time. I am essentially doing the same thing here, only that it's a lot cleaner. """ # 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 def same_node(p: "TreeNode", q: "TreeNode") -> bool: if p is None and q is None: return True elif p is not None and q is None: return False elif p is None and q is not None: return False elif p is not None and q is not None: return p.val == q.val def bfs(node): queue = list() index = 0 queue.append(node) queue_length = 1 while index < queue_length: current = queue[index] if current is not None: queue.append(current.left) queue.append(current.right) queue_length = len(queue) index += 1 yield current class Solution: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: tree1 = bfs(p) tree2 = bfs(q) for node1, node2 in zip(tree1, tree2): if not same_node(node1, node2): return False return True
c2124b0dc7f0495e4eded0e261fc496d0edddb70
Siahnide/All_Projects
/Back-End Projects/Python/Python_OOP/hospital/hospital.py
595
3.609375
4
class hospital (object): def __init__(self,name,capacity,*patients): self.patients = list(patients) self.name = name self.capacity = capacity - len(self.patients) def info(self): print self.name names = "" for x in range(0,len(self.patients)): names += str(self.patients[x].ids) names += " " names += self.patients[x].name names += " " names += str(self.patients[x].bed) names += ", " print names print self.capacity
4ad0ec821a198bec6db30932374cd48592001009
hoang-ng/LeetCode
/Greedy/135.py
1,308
3.84375
4
# 135. Candy # There are N children standing in a line. Each child is assigned a rating value. # You are giving candies to these children subjected to the following requirements: # - Each child must have at least one candy. # - Children with a higher rating get more candies than their neighbors. # What is the minimum candies you must give? # Example 1: # Input: [1,0,2] # Output: 5 # Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. # Example 2: # Input: [1,2,2] # Output: 4 # Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. # The third child gets 1 candy because it satisfies the above two conditions. class Solution(object): def candy(self, ratings): candies = [1] * len(ratings) for i in range(1, len(ratings)): if ratings[i] > ratings[i - 1]: candies[i] = candies[i - 1] + 1 res = candies[len(ratings) - 1] for i in range(len(ratings) - 2, -1, -1): if ratings[i] > ratings[i + 1]: candies[i] = max(candies[i], candies[i + 1] + 1) res += candies[i] return res sol = Solution() sol.candy([12, 4, 3, 11, 34, 34, 1, 67])
196b097cdad5b1fb306fdb05832d7bbee1573516
JackMGrundy/coding-challenges
/common-problems-leetcode/hard/basic-calculator-III.py
2,377
3.859375
4
""" Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . The expression string contains only non-negative integers, +, -, *, / operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647]. Some examples: "1 + 1" = 2 " 6-4 / 2 " = 4 "2*(5+5*2)/3+(6/2+8)" = 21 "(2+6* 3+5- (3*14/7+2)*5)+3"=-12 """ # 48ms. 93 percentile. class Solution: def calculate(self, s: str) -> int: s += "$" def helper(s, stack, i): num, operation = 0, '+' while i < len(s): character = s[i] if character.isdigit(): num = num*10 + int(character) i += 1 elif character == ' ': i += 1 elif character == "(": num, i = helper(s, [], i+1) else: if operation == '+': stack.append(num) elif operation == '-': stack.append(-num) elif operation == '/': stack.append(int(stack.pop() / num) ) elif operation == '*': stack.append(stack.pop() * num) i += 1 num = 0 if character == ')': return (sum(stack), i) operation = character return sum(stack) return helper(s, [], 0) """ Notes: Careful handling of if cases + use of recursion to deal with parentheses. """
bf6033be9647c3599b3ff07160f5c4d2f704da06
rompe/adventofcode2020
/src/day16.py
3,430
3.625
4
#!/usr/bin/env python import collections import itertools import math import sys cache = dict(timestamp=0) def parse_input(input_file): """Parse input file and return rules, my ticket, nearby tickets.""" lines = open(input_file).read().split('\n\n') rules = {} for line in lines[0].splitlines(): key, values = line.split(':') items = values.replace(' or ', ' ').split() rules[key] = items my_ticket = lines[1].splitlines()[1] tickets = lines[2].splitlines()[1:] return rules, my_ticket, tickets def check_ranges(ranges, value): """Check if value is in any of the ranges.""" for fromto in ranges: start, end = fromto.split('-') if int(value) in range(int(start), int(end) + 1): return True # else: # print('%s is not between %s and %s' % (value, start, end)) return False def solution1(input_file): """Solve today's riddle.""" # lines = open(input_file).read().split('\n\n') # lines = open(input_file).read().splitlines() rules, my_ticket, tickets = parse_input(input_file) invalid_numbers = [] invalid_tickets = set() for ticket in tickets: values = ticket.split(',') for value in values: for rule in rules: if check_ranges(rules[rule], value): break else: invalid_tickets.add(ticket) invalid_numbers.append(int(value)) return sum(invalid_numbers) def check_column(rule, column): """Check if all values in column are covered by rule.""" for value in column: if not check_ranges(rule, value): return False return True def solution2(input_file): """Solve today's riddle.""" # This is basically part 1... rules, my_ticket, tickets = parse_input(input_file) invalid_numbers = [] invalid_tickets = set() for ticket in tickets: values = ticket.split(',') for value in values: for rule in rules: if check_ranges(rules[rule], value): break else: invalid_tickets.add(ticket) invalid_numbers.append(int(value)) for invalid_ticket in invalid_tickets: tickets.remove(invalid_ticket) # Part 2 follows... column_names = collections.defaultdict(list) columns = [[int(row.split(',')[column]) for row in tickets] for column in range(len(my_ticket.split(',')))] for index, column in enumerate(columns): for rule in rules: if check_column(rules[rule], column): print('%s ist %s' % (rule, index)) column_names[rule].append(index) # break else: print("%s %s passt nicht" % (index, column)) print(column_names) for dummy in range(len(columns) * len(columns)): for name in column_names.copy(): if len(column_names[name]) == 1: for name2 in column_names: if name != name2 and column_names[name][0] in column_names[name2]: column_names[name2].remove(column_names[name][0]) print(column_names) return math.prod(int(my_ticket.split(',')[column_names[name][0]]) for name in column_names if name.startswith('departure')) if __name__ == "__main__": print(solution1(sys.argv[1])) print(solution2(sys.argv[1]))
6c2e47052f4302fb4fd741608ed8bfb653491858
ZbigniewPowierza/pythonalx
/Kolekcje/zadanie_9.py
2,464
3.78125
4
""" OFERUJEMY NASTĘPUJĄCE PRODUKTY marchew: 2,35, ziemniaki: 2,20, cebula: 1,8, ogórki: 4,0 co chcesz kupić? marchew ile chcesz kupic [marchew]? 3 Za [marchew] płcisz 7,05 pPLN DODAJEMY obsluge magazynu po zakupie ilosc towaru sie zmniejsza jezeli ktos chce kupic wiecej niz w magazynie to mowie ze nie moze """ def wyprintuj(dict, jednostka): for k, v in dict.items(): return print(f" - {k}: {v} ") slownik = { 'marchew': 2.35, 'ziemniaki': 2.20, 'cebula': 1.80, 'ogórki': 4.00, # 'bataty': {'cena': 8.0, 'magazyn': 40} # 'bataty': [8, 40] } magazyn = { 'marchew': 100, 'ziemniaki': 200, 'cebula': 50, 'ogórki': 50, } print("Witaj w naszym PyZieleniaku") print("OFERUJEMY NASTĘPUJĄCE PRODUKTY: ".title()) # for i in slownik: # print(f" - {i}: {slownik[i]}") wyprintuj(slownik, "PLN") # print(slownik.keys()) while True: tryb = input("Wybierz tryb: [z-zakupowy], [m-magazynowy] [k-kończymy]") if tryb.lower() == 'k': break elif tryb.lower() == 'z': while True: wyprintuj (slownik, "PLN") co_kupuje = input("Jaki towar chces kupić [wpisz k by zakończyć]").lower() if co_kupuje.lower() == 'k': break if co_kupuje in slownik: ile = input(f"Ile chcesz kupić [{co_kupuje}]") ile = float(ile) if ile <= magazyn[co_kupuje]: naleznosc = ile * slownik[co_kupuje] magazyn[co_kupuje] = magazyn[co_kupuje] - ile # magazyn[co_kupuje] -= float (ile) print(f"Za [{co_kupuje}] płacisz: {naleznosc:.2f} PLN") else: print("Nie mam tyle kg tego towaru") else: print("Nie mam takiego produktu!") elif tryb.lower() == 'm': while True: print("W magazynie: ") # for product, ilosc in magazyn.items(): # print(f" - {product}: {ilosc} kg") wyprintuj(magazyn, "kg") #print(f"Lista towarów, których stan jest niższy od wyjściowego [{}") produkt_do_dodania = input("Co chcesz dodać?") ile_do_dodania = int(input("Ile chcesz dodać?")) if not produkt_do_dodania in slownik: cena_nowego_produku = float(input("Jaka będzie cena?")) slownik[produkt_do_dodania] = cena_nowego_produku
eed03c633e966eba5ecaed3708c6b975e28631fc
emmanuelbarturen/aprendiendo-python
/main.py
5,904
3.90625
4
import sys import copy print('Aprendiendo Python3') clients = 'ronny,renzo,paul' print(id(clients)) # puntero de memoria print('Valor de variable: ' + clients) print('*' * 25 + ' FUNCIONES ' + '*' * 25) def separator(title='', character='*'): """Esto es un texto de ayuda de como utilizar esta funcion. puede ser llamada con help(nombrefuncion)""" print('\n') # salto de línea para la consola print('*' * 25 + title + '*' * 25) pass # help(separator) # FUNCIONES ########################################################################################################### def create_client(client_name): # Convención 2 espacios entre funciones global clients # para traer una variable a entorno local _add_comma() clients += client_name def update_client(client_name, update_client_name): global clients if client_name in clients: clients = clients.replace(client_name, update_client_name + ',') else: print('Cliente no existe') def delete_client(client_name): global clients if client_name in clients: clients = clients.replace(client_name, '') else: print('Cliente no existe') def _get_client_name(): client_name = None # variable seteada como vacía while not client_name: client_name = input('Cual es el nombre del cliente?\n') if client_name == 'exit': break if client_name == 'exit': sys.exit() return client_name def _add_comma(): global clients clients += ',' # concatenar en letras ó sumar en numéricos def list_clients(): print('Todos los clientes ==> ' + clients) def _print_welcome(): # funciones que empiezan por subguión son privadas, las demás son públicas print('Welcome to python') print('#' * 50) list_clients() print('Seleccione una opción') print('[C]reate client') print('[U]pdate client') print('[D]elete client') print('[S]earch client') print('#' * 50) print('\n\r') def search_client(client_name): global clients clients_list = clients.split(',') for client in clients_list: if client == client_name: return True else: continue def first_application(): _print_welcome() command = input() # obtiene el valor ingresado por consola command = command.upper() if command == 'C': client_name = _get_client_name() # Muestra texto y guarda valor ingresado por consola create_client(client_name) list_clients() elif command == 'U': client_name = _get_client_name() updated_client_name = input('Por qué nombre desea cambiar?') update_client(client_name, updated_client_name) list_clients() elif command == 'D': client_name = _get_client_name() delete_client(client_name) list_clients() elif command == 'S': client_name = _get_client_name() found = search_client(client_name) if found: print('Cliente encontrado!') else: print('Cliente {} no ha sido encontrado'.format(client_name)) list_clients() else: print('Comando desconocido') separator('CONDICIONALES') ########################################################################################### x = 2 # asignación de variables y = 3 if x < y: # comparación simple print('x es menor que y') else: print('x no es menor que y') separator('JUGANDO CON STRINGS (CADENAS)') ########################################################################### country = 'Perú' print('Mostrando una posición específica de la palabra: ' + country) print(country[3]) # Muestra el caracter ú de la palabra Perú print(country.upper()) # convertir en mayusculas print(country.find('e')) # devuelve posición inicial del caracter o palabra ingresada print(country.startswith('p')) # valida si el valor de la variable inicia con la letra p, aquí es true print(country.startswith('x')) print(dir(country)) # Muestra todas las funciones que pueden ser aplicadas. # Las que tienen subguión permiten modificar como python se ejecuta # las que no tienen subguión se pueden aplicar normalmente separator('SLICES') # Rebanadas ###################################################################################### word = 'ferrocarril' print(word[1:4]) # toma desde la posición 0 hasta el 4, en este caso "err" print(word[1:8]) # toma desde la posición 1 hasta el 8, en este caso "errcar" print(word[::-1]) # toma desde la posición 0 hasta el final en pasos de 1 en reversa print(word[:8:3]) # toma desde la posición 0 hasta el 8, en pasos de 3 en 3 print(word[::2]) # toma desde la posición 0 hasta el final, en pasos de 2 en 2 separator('ITERACIONES') ############################################################################################# print('iteración con for de 5 elementos') for i in range(5): # range genera una secuencia de números print(i) print('iteración con while en reversa de 10 elementos') n = 10 while n > 0: print(n) n -= 1 separator('LISTAS') ################################################################################################## countries = ['Mexico', 'Perú', 'Argentina'] print(countries) ages = [12, 18, 24, 34, 50] countries[0] = 'Ecuador' # Reasignación de un valor print(countries) global_countries = countries # se genera un alias, cualquier modificación en contries se refleja en global_countries countries[0] = 'Chile' print(global_countries) global_countries_copy = copy.copy(countries) # hace una copia exacta de la lista en otro punto de memoria countries[0] = 'Colombia' print(global_countries_copy) separator('APLICACIÓN PRINCIPAL') #################################################################################### if __name__ == '__main__': first_application() pass
9cb120b8d8376536a7a37502588eea468c0b98d4
castellanprime/ProgrammingChallenges
/minesweeper_challenge/minesweeper.py
3,460
3.90625
4
#!/usr/bin/env python """ ACM Minesweeper PC/UVa IDs: 110102/10189 """ def minesweeper(path_to_file): """ Play the minesweeper game Args: path_to_file:file path Returns: Nothing Raises: IOError: if it cannot open file """ gameboard = [] assert(type(path_to_file) is str), "I need a string!" assert(path_to_file), "I need a non-empty string!" try: with open(path_to_file) as f: line = f.readline().rstrip() while int(line[0]) is not 0: field = [] field.append(list(str((int(line[2]) + 2) * "0" ))) for i in range(int(line[0])): st = ("0", f.readline().rstrip(), "0") # join takes exactly one argument field.append(list(''.join(st))) field.append(list(str((int(line[2]) + 2) * "0" ))) gameboard.append(field) line = f.readline().rstrip() if line == '': break except IOError as e: print ("I/O Error({0}) when opening {1}: {2}! I quit!").format(e.errno, path_to_file, e.strerror) raise e # print gameboard for index, item in enumerate(gameboard): for i, it in enumerate(item): print(item[i]) # print output outputboard = collate_results(gameboard) for index, item in enumerate(outputboard): print ('{0} {1}{2}'.format('Field','#',index)) for i in item: print(''.join(str(v) for v in i)) def collate_results(gameboard): """ Board algorithm Applies rules for the board Args: gameboard: the input board Return: outputboard: the output fields """ outputboard = [] for field in gameboard: # to copy the entire field, use field[:] shape = len(field), len(field[0]) # the field that would contain the output output_field = [[0, ]*(shape[1]) for i in range(shape[0])] for row in range(1, shape[0]-1): for col in range(1, shape[1]-1): if field[row][col] == "*": output_field[row][col]="*" if output_field[row-1][col-1] is not "*": output_field[row-1][col-1] += 1 if output_field[row-1][col] is not "*": output_field[row-1][col] += 1 if output_field[row-1][col+1] is not "*": output_field[row-1][col+1] += 1 if output_field[row][col-1] is not "*": output_field[row][col-1] += 1 if output_field[row][col+1] is not "*": output_field[row][col+1] += 1 if output_field[row+1][col-1] is not "*": output_field[row+1][col-1] += 1 if output_field[row+1][col] is not "*": output_field[row+1][col] += 1 if output_field[row+1][col+1] is not "*": output_field[row+1][col+1] += 1 # Clean-up output_field = output_field[1:-1] for index in range(len(output_field)): output_field[index] = output_field[index][1:-1] outputboard.append(output_field) return outputboard minesweeper("test")
c5f411fb61cb8e8c329af0c2f62d15b2be4bee69
UzaifAhmed/python-
/textutility.py
259
3.765625
4
def charCount(paragraph): """this func accepts a texting and returns an integr count of num of char in it""" char_count = len(paragraph) return char_count def word_count(paragraph): word_count = len(paragraph.split(" ")) return word_count
7c739be259cf7af3d84ea73aa577539d80a4553a
rampedro/Cracking-the-coding-interview-leetcode
/paint-fill.py
966
4.0625
4
def paint(A,i,j,color=3,p=None): if i<0 or i>len(A) or j<0 or j>len(A[0]): print("***") return A else: A[i][j] = 3 if A[i-1][j] == p: paint(A,i-1,j,color=3,p=p) if i+1 < len(A) and A[i+1][j] == p: paint(A,i+1,j,color=3,p=p) if A[i][j-1] == p: paint(A,i,j-1,color=3,p=p) if j+1 < len(A[0]) and A[i][j+1] == p: paint(A,i,j+1,color=3,p=p) return A A = [[1,1,1,1,1,1],[1,1,2,2,1,1],[1,1,2,2,1,1],[2,2,2,2,2,2]] s = "" # A is the matric # next integer is the row position of the selected point # next integer is the column posiiton of the selected point #color : is the color we want at the end #p : indicates the current color/value of the selected point A = paint(A,1,2,color=3,p=2) for i in range(len(A)): for j in range(len(A[i])): s += str(A[i][j]) if j != len(A[i])-1: s += "," print(s) s=""
3661a819a5a69541700fc59a55a38e06e7266876
CaduSantana/Data-Visualization-study
/Estudo matplotlib/Population growth/Brazil_population_growth.py
610
3.5
4
# Growth of Brazil's Population # Source: DataSus import matplotlib.pyplot as plt data = open("populacao_brasileira.csv").readlines() x = [] # Population qtd array y = [] # Year number array for i in range(len(data)): if i != 0: linha = data[i].split(";") x.append(int(linha[0])) y.append(int(linha[1])) # print(x) # debugging plt.bar(x, y, color="#e4e4e4") plt.plot(x, y, color = "k", linestyle = "--") plt.title("Growt of Brazil's Population from 1980 to 2016") plt.xlabel("Year") plt.ylabel("Population x 100,000,000") plt.savefig("bra_population.pdf", dpi = 1200) plt.show()
3f09425de5769280530daafb32c77edf6a2f5f67
priscilamarques/pythonmundo1
/desafio6.py
267
4.03125
4
##Desafio 6 #Crie um algoritmo que leia um número que mostre seu dobro, trilo e raiz quadradra. n = int(input('Digite um número: ')) d = n * 2 t = n * 3 e = n ** (1/2) print('O número é {}. O dobro é {}, o triplo é {} e a raiz quadrada é {}.'.format(n,d,t,e))
40c7b4940ae9bca1260ff0ad47239e40b47ea0ba
VenkateshBisoyi/DSP-Lab-2
/perfect number.py
353
3.828125
4
#This is the program for Perfect number print ('''Venkatesh Bisoy 121910313056''') a = int(input("Enter the number: ")) # the factors of the number are found s= 0 for i in range(1,a): if (a % i==0): s = s + i # the Logic for perfect number if(a==s): print(a,'is a perfect number') else: print(a,'is not a perfect number')
857f68baac8ad732a615d8b05aa074d81950f564
zhangchizju2012/LeetCode
/300.py
1,086
3.703125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat May 6 12:11:24 2017 @author: zhangchi """ #============================================================================== # example: # nums: [1, 3, 6, 7, 9, 4, 10, 5, 6] # result: [6, 5, 4, 3, 2, 3, 1, 2, 1] # result的每i项代表nums从第i个开始往后,含有nums[i]这个元素的Longest Increasing Subsequence # 我的思路是从后往前推 #============================================================================== class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 length = len(nums) result = [1] * length for i in xrange(length-2,-1,-1): temp = - float('inf') for j in xrange(i+1,length): if nums[i] < nums[j]: temp = max(temp, result[j]) if temp > 0: result[i] = temp + 1 return max(result) s = Solution() print s.lengthOfLIS([1,3,6,7,9,4,10,5,6])
8230906264f21b36b0256cdb09938d1837e42de9
xiyiwang/leetcode-challenge-solutions
/2021-02/2021-02-16-letterCasePermutation.py
1,440
3.65625
4
# LeetCode Challenge: Letter Case Permutation (02/16/2021) # Given a string S, we can transform every letter individually # to be lowercase or uppercase to create another string. # # Constraints: # * S will be a string with length between 1 and 12. # * S will consist only of letters or digits. # Solution 1 - 52 ms def letterCasePermutation(S): ans = [] for c in S: if c.isalpha(): if not ans: ans.append(c.lower()) ans.append(c.upper()) else: for i in range(len(ans)): ans.append(ans[i]+c.upper()) ans[i] += c.lower() else: if not ans: ans.append(c) else: for i in range(len(ans)): ans[i] += c return ans # Solution 2 - dfs - 56ms def letterCasePermutation2(S): def dfs(i, built): if i == len(S): ans.append(built) return if S[i].isalpha(): dfs(i+1, built + S[i].lower()) dfs(i+1, built + S[i].upper()) ans = [] dfs(0, "") return ans # Solution 3 - product() - 44 ms def letterCasePermutation3(S): from itertools import product return map(''.join, product(*[set([i.lower(), i.upper()]) for i in S])) S = "a1b2" # ["a1b2","a1B2","A1b2","A1B2"] # S = "3z4" # ["3z4","3Z4"] # S = "12345" # ["12345"] # S = "0" # ["0"] print(letterCasePermutation3(S))
75158accae5dc815e1012f4c40286452b2268d46
abhijeetbhagat/dsa-python
/DSA/binary_search.py
576
3.859375
4
def binary_search_recursive(a : list, key : int, l : int, h : int): if l > h: return -1 m = (l + h) // 2 if a[m] == key: return m if a[m] > key: h = m - 1 else: l = m + 1 return binary_search_recursive(a, key, l, h) def binary_search(a, key): return binary_search_recursive(a, key, 0, len(a) - 1) assert(binary_search([1,2,3,4,5], -1) == -1) assert(binary_search([1,2,3,4,5], 1) == 0) assert(binary_search([1,2,3,4,5], 3) == 2) assert(binary_search([1,2,3,4,5], 4) == 3) assert(binary_search([1,2,3,4,5], 5) == 4)
993ddad7b3b9b282bfab82229801df2afe263bb6
TenzinJam/pythonPractice
/freeCodeCamp1/variables.py
598
4.34375
4
character_name = "John" character_age = "35" print("There once was a man named "+ character_name + ", ") print("he was " + character_age + " years old.") print("he really liked the name "+ character_name + ", ") print("but didnt like being "+ character_name + ".") print("Fullstack\nAcademy") print(character_name.lower()) print(character_name.upper()) print(character_name.isupper()) print(character_name.upper().isupper()) print(len(character_name)) print(character_name[0]) print(character_name[len(character_name)-1]) print(character_name.index("o")) print(character_name.replace("Jo", "Pe"))
7b2373b96d9a34f8c0009e19ef8e836a5cd1611a
Jashwanth-k/Data-Structures-and-Algorithms
/4.Linked Lists/Reverse the LL by using Tail T.C O[n] .py
1,148
3.71875
4
class Node: def __init__(self, data): self.data = data self.next = None def printLL(head): while head is not None: print(str(head.data) + '->', end='') head = head.next print('None') return def takeInput(): inputList = [int(ele) for ele in input().split()] head = None tail = None for currData in inputList: if currData == -1: break newNode = Node(currData) if head == None: head = newNode tail = newNode else: tail.next = newNode tail = newNode return head head = takeInput() printLL(head) def reverse_LL(head): if head is None or head.next is None: return head,head #smallhead,smalltail returns head and tail of LL smallhead,smalltail = reverse_LL(head.next) smalltail.next = head head.next = None return smallhead,head #We should return smallhead and head in line nbr 41. Because here head is smallhead and # Tail is head which we will add ourself last of the LL head,tail = reverse_LL(head) printLL(head)
a020246b2ca273f73bcffe86e0b196ad6ad6a5e2
flpsantos3/FProg-Project
/writeFiles.py
4,560
3.59375
4
# 2019-2020 Fundamentos de Programação # Grupo 20 # 55142 Filipe Santos # 28115 Lara Nunes import times import readFiles def writeHeaderD(fileName): """Uses the header info from a file of drones to write a new file, updating time and date (if needed) Requires: fileName is str, the name of a .txt file listing available drones Ensures: a .txt file with the updated header, containing time, date, company name and where the scope is "Drones:" """ info = readFiles.readHeader(fileName) t = info[0] title = "drones" timeNext = times.newTime(t) #if the file is the first of the day (8h00) the date changes d = info[1] if timeNext == "8h00": dateNext = times.new_date(d) else: dateNext = d #splitting date string into 3 strings that can be written in the file name ddmmyy = dateNext.split("-") day = ddmmyy[0] month = ddmmyy[1] year = ddmmyy[2] #assembling the new file name newName = "drones" + timeNext + "_" + year + "y" + month + "m" + day + ".txt" fileOut = open(newName, 'w') company = info[2] #writing the header with the update info header = "Time:\n" + timeNext + "\n" + "Day:\n" + dateNext + "\n" + "Company:\n" + company + "\n" + "Drones:\n" fileOut.write(header) #file is not closed so this function can be called later return fileOut def writeHeaderP(fileName): """Uses the header info from fileName to write the header for a new file, updating time and date (if needed) Requires: fileName is str, the name of a .txt file containing parcel info, with time, day and company info Ensures: a .txt file with the updated header info, containing time, date, company name and where the scope is "Timeline:" """ info = readFiles.readHeader(fileName) #info is a list with the format[time, date, company, scope] time = info[0] title = "timetable" date = info[1] company = info[2] #splits date to be able to write the name of the new file in the correct format ddmmyy = date.split("-") day = ddmmyy[0] month = ddmmyy[1] year = ddmmyy[2] #formats fileName to fit with the intended format newName = title + time + "_" + year + "y" + month + "m" + day + ".txt" fileOut = open(newName, 'w') #writing the header with the update info header = "Time:\n" + time + "\n" + "Day:\n" + date + "\n" + "Company:\n" + \ company + "\n" + "Timeline:\n" fileOut.write(header) #file is not closed so this function can be called later return fileOut def writeBodyD(info, fileName): """Receives a list of updated drone info and writes it on a new .txt file, where the header contents are fetched from fileName and updated Requires: info is a list of lists, each representing a drone, with the updated info after pairing with a parcel; fileName is the original drones .txt file Ensures: a .txt file with the updated header info and the updated info for all drones """ fileOut = writeHeaderD(fileName) #writing each element of a list to the output file; #changing lines after the last element of the list for j in range(0, len(info)): for i in range(0, len(info[j])): if i == len(info[j]) - 1: info[j][i] = info[j][i] + "\n" fileOut.write(info[j][i]) else: info[j][i] = info[j][i] + ", " fileOut.write(info[j][i]) fileOut.close() def writeBodyP(info, fileName): """Receives a list of drone pairings and writes it on a new .txt file, where the header contents are fetched from fileName and updated Requires: info is a list of lists with date, time, client name and drone name, representing a pairing, or cancelled deliveries; fileName is the original parcels .txt file Ensures: a .txt file with the header info from fileName and the info for all the pairings, even the cancelled """ fileOut = writeHeaderP(fileName) #writing each element of a list to the output file; #changing lines after the last element of that list for j in range(0, len(info)): for i in range(0, len(info[j])): if i == len(info[j]) - 1: info[j][i] = info[j][i] + "\n" fileOut.write(info[j][i]) else: info[j][i] = info[j][i] + ", " fileOut.write(info[j][i]) fileOut.close()
b5490db37d86c866f2ed0102dee69bf890e225c8
itaouil/Daily-Coding-Problem
/6_is_happy.py
1,224
4.125
4
""" Write an algorithm to determine if a number n is "happy". Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Return True if n is a happy number, and False if not. """ import unittest def digit_sum(n: int) -> int: # Digit sum sum_ = 0 # Compute sum as # sum of digit squares while (n): # Get digit digit = n % 10 # Update number n //= 10 # Update sum sum_ += (digit * digit) return sum_ def is_happy(n: int) -> bool: # Unordered set seen = set() while (True): # Compute sum of squares n = digit_sum(n) # Check loop if n in seen: return False # Update set seen.add(n) # Check if number is happy if n == 1: return True class TestHappiness(unittest.TestCase): def test_working(self): self.assertEqual(True, is_happy(19)) if __name__ == "__main__": unittest.main()
1bff13e307b98ee7e39b59101cca172fd48f3ad3
sguberman/pyku
/query.py
1,379
3.578125
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 25 15:29:20 2017 @author: Seth Guberman - [email protected] """ from collections import defaultdict from parse import mhyph_dict_from_file, mpos_dict_from_file def words_by_syllable(): """ Build an index of all words with n syllables. """ print('Building n-syllable lookup table...') words = defaultdict(list) for word, syllables in mhyph_dict_from_file().items(): words[syllables].append(word) print('Done!') return words def words_by_part_of_speech(): """ Build an index of all words with a given part of speech. """ print('Building parts of speech lookup table...') words = defaultdict(list) for word, pos in mpos_dict_from_file().items(): for symbol in pos: words[symbol].append(word) print('Done!') return words def query_intersection(n, pos, syllable_dict=None, pos_dict=None): """ Return the intersection (set) of all words with n syllables and given part of speech. """ if syllable_dict is None: syllable_dict = words_by_syllable() if pos_dict is None: pos_dict = words_by_part_of_speech() return set(syllable_dict[n]).intersection(set(pos_dict[pos])) if __name__ == '__main__': words_with_n_syllables = words_by_syllable() words_with_part_of_speech = words_by_part_of_speech()
5ac50982dd50b142c7c8b07c20482073b9733115
MATATAxD/untitled1
/8.14/递归函数.py
1,199
3.9375
4
# 递归函数的思想:把规模大的问题拆分成规模小的问题,然后把规模小的问题再拆分成规模更小的问题...一层层的拆分拆分到一定的程度 # 变成很小的问题,最后问题就解决了 import sys # count=0 # def f(count): # count+=1 # print(count) # # if count==10: # return count # # # f(count) # f(count) # return n + f(n-1) # # 1-100的和 #f(100) return 100+ f(99) # def f(n): #f(99) retuun 99 + f(98) # return n+f(n-1) #f(98) return 98 + f(97) # if n==1: #... # return #f(2) return 2+1 # f(100) #f(1) return 1 # # def f(n): #1-100的和 # if n==1: # return 1 # return n+f(n-1) # print(f(100)) # def f(n): # if n==1: # return 1 # return n*f(n-1) # print(f(5)) # def f(n): #斐波那契数列 # if n==1 or n==2: # return 1 # return f(n-1)+f(n-2) # print(f(7)) def f(n): if n==7: return 1 return (f(n+1)+1)*2 print(f(1))
0c604dc4576c389c6e1423e30dd8afd7a22440e2
green-fox-academy/bauerjudit
/week-3/tuesday/list.py
927
3.734375
4
class Elem(object): _slots_ = ["value", "next"] def _repr_(self): return "({}, {})".format(self.value, self.next) def new_elem(value): elem = Elem() elem.value = value elem.next = None return elem def append(head, value): end = head while end.next is not None: end = end.next end.next = new_elem(value) return head def insert(head, index, value): if index == 0: new = new_elem(value) new.next = head return new def insert(head, index, value): prev = head i = 0 while i < index-1: prev = prev.next new = new_elem(value) new.next = prev.next prev.next = new return prev def remove(head,index): if index==0: head=head.next return head prev=head i=0 while i<index-1: prev=prev.next i+=1 prev.next=prev.next.next return head
096de9431086031fefe85924814b2d0f8aafb865
Headmx/z59
/mytimer.py
517
3.859375
4
import datetime import time class Mydatetime: def __init__(self,s, h = None, m = None, ): self.h = h self.m = m self.s = s def timer(self): if 1<= self.m <60: self.s = self.s + self.m*60 elif 1<= self.h : self.s = self.s + self.h * 3600 for i in range(self.s): time.sleep(1) self.s -=1 print('осталось, сек :', self.s) print ('the end') cc = Mydatetime(23,0,0) print (cc.timer())
eb4104f22cc658efc7273e05ac451ee3959c7ed6
Giammi77/f3kcompetizioneDeploy
/packages/f3kp/lib/f3krules.py
12,625
3.515625
4
class task_base_one_validation: def __init__(self): self.maximum_flights=0 self.maximum_flight_time=0 def validate_flight(self,time,flyed=None): if time <= self.maximum_flight_time: return time else : return self.maximum_flight_time class A(task_base_one_validation): ''' 5.7.11.1. Task A (Last flight) Each competitor has an unlimited number of flights, but only the last flight is taken into account to determine the final result. The maximum flight time is limited to 300 seconds. Any subsequent launch of the model glider annuls the previous time. Working time: 7 minutes or 10 minutes ''' def __init__(self): super().__init__() self.maximum_flights=1 self.maximum_flight_time=300 class A2(task_base_one_validation): def __init__(self): super().__init__() self.maximum_flights=1 self.maximum_flight_time=300 class B(task_base_one_validation): ''' 5.7.11.2. Task B (Next to last and last flight) Each competitor has an unlimited number of flights, but only the next to last and the last flight will be scored. Maximum time per flight is 240 seconds for 10 minutes working time. If the number of competitors is large, the maximum flight time may be reduced to 180 seconds and 7 minutes working time. Example: 1st flight 65 s 2nd flight 45 s 3rd flight 55 s 4th flight 85 s Total score: 55 s + 85 s = 140 s ''' def __init__(self): super().__init__() self.maximum_flights=2 self.maximum_flight_time=240 class B2(task_base_one_validation): def __init__(self): super().__init__() self.maximum_flights=2 self.maximum_flight_time=180 class C(task_base_one_validation): ''' 5.7.11.3. Task C (All up, last down) All competitors of a group must launch their model gliders simultaneously, within 3 seconds of the acoustic signal. The maximum measured flight time is 180 seconds. The official timekeeper takes the individual flight time of the competitor according to 5.7.6 and 5.7.7 from the release of the model glider and not from the start of the acoustic signal. Launching a model glider before or more than 3 seconds after the start of the acoustic signal will result in a zero score for the flight. The number of launches (3 to 5) must be announced by the organiser before the contest begins. The preparation time between attempts is limited to 60 seconds after the end of the landing window. During this time the competitor may not perform test flights. The competitor is not allowed any help during the flight testing time, working time or landing window. The flight times of all attempts of each competitor will be added together and will be normalised to calculate the final score for this task. No working time is necessary. Example for 3 flights: Competitor A: 45 s + 50 s + 35 s = 130 s = 812.50 points Competitor B: 50 s + 50 s + 60 s = 160 s = 1000.00 points Competitor C: 30 s + 80 s + 40 s = 150 s = 937.50 points ''' def __init__(self): super().__init__() self.maximum_flights=3 self.maximum_flight_time=180 class C2(task_base_one_validation): def __init__(self): super().__init__() self.maximum_flights=4 self.maximum_flight_time=180 class C3(task_base_one_validation): def __init__(self): super().__init__() self.maximum_flights=5 self.maximum_flight_time=180 class D(task_base_one_validation): ''' 5.7.11.4. Task D (Two flights) Each competitor has two (2) flights. These two flights will be added together. The maximum accounted single flight time is 300 seconds. Working time is 10 minutes. ''' def __init__(self): super().__init__() self.maximum_flights=2 self.maximum_flight_time=300 class E(): ''' 5.7.11.5. Task E (Poker - variable target time) Each competitor has an unlimited number of flights to achieve or exceed up to three (3) target times. Before the first launch of a new target, each competitor announces a target time to the official timekeeper. He can then perform an unlimited number of launches to reach or exceed, this time. If the target is reached or exceeded, then the target time is credited and the competitor can announce the next target time, which may be lower, equal or higher, before he releases the model Class F3K Hand Launch Gliders SC4_Vol_F3_Soaring_20 Effective 1st January 2020 Page 37 glider during the launch. If the target time is not reached, the announced target flight time cannot be changed. The competitor may try to reach the announced target flight time until the end of the working time. For the competitors last flight he may announce “end of working time”. For this specific call, the competitor has ONLY one attempt. The target time must be announced clearly in the official contest language or alternatively shown to the timekeeper in written numbers (e g 2:38) by the competitor’s helper immediately after the launch. If the competitor calls “end of working time” the competitor’s helper writes the letter “W”. The target(s) (1 - 3) with achieved target times are scored. The achieved target times are added together. This task may be included in the competition program only if the organiser provides a sufficient number of official timekeepers, so that each competitor in the round is accompanied by one official timekeeper. The working time may be 10 or 15 minutes. Example: Announced time Flight time Scored time 45 s 1st flight 46 s 45 s 50 s 1st flight 48 s 0 s 2nd flight 52 s 50 s 47 s 1st flight 49 s 47 s Total score is 142 s ''' def __init__(self): self.maximum_flights=3 self.maximum_flight_time=599 def validate_flight(self,time=None,flyed=None): flyed=float(flyed) if flyed: if time+flyed<=self.maximum_flight_time: return time else: if self.maximum_flight_time-flyed == 0: return 0 else: return self.maximum_flight_time-flyed else: if time <= self.maximum_flight_time: return time else : return self.maximum_flight_time class E2(E): def __init__(self): super().__init__() self.maximum_flights=3 self.maximum_flight_time=899 class F(task_base_one_validation): def __init__(self): super().__init__() self.maximum_flights=3 self.maximum_flight_time=180 ''' 5.7.11.6. Task F (3 out of 6) During the working time, the competitor may launch his model glider a maximum of 6 times. The maximum accounted single flight time is 180 s. The sum of the three longest flights up to the maximum of 180 s for each flight is taken for the final score. Working time is 10 minutes. ''' class G(task_base_one_validation): def __init__(self): super().__init__() self.maximum_flights=5 self.maximum_flight_time=120 ''' 5.7.11.7. Task G (Five longest flights) Each competitor has an unlimited number of flights. Only the best five flights will be added together. The maximum accounted single flight time is 120 seconds. Working time is 10 minutes. ''' class H(task_base_one_validation): # TO DO CORRECT VALIDATION !!! def __init__(self): super().__init__() self.maximum_flights=4 self.maximum_flight_time=999 ''' 5.7.11.8. Task H (One, two, three and four minute target flight times, any order) During the working time, each competitor has an unlimited number of flights. He has to achieve four flights each of different target flight times duration. The target flight times are 60, 120, 180 and 240 seconds in any order. Thus the competitor’s four longest flights flown in the working time are assigned to the four target flight times, so that his longest flight is assigned to the 240 seconds target flight time, his 2nd longest flight to the 180 seconds target flight time, his 3rd longest flight to the 120 seconds target flight time and his 4th longest flight to the 60 seconds target flight time. Only the flight time up to the target flight time is taken into account for scoring. Working time is 10 minutes. Example: Flight time Scored time 1st flight 63 s 60 s 2nd flight 239 s 239 s 3rd flight 182 s 180 s 4th flight 90 s 90 s Total score of this task would be 60 s + 239 s + 180 s + 90 s = 569 s ''' class I(task_base_one_validation): # TO DO CORRECT VALIDATION !!! def __init__(self): super().__init__() self.maximum_flights=3 self.maximum_flight_time=200 ''' 5.7.11.9 Task I (Three longest flights) During the working time, each competitor has an unlimited number of flights. Class F3K Hand Launch Gliders SC4_Vol_F3_Soaring_20 Effective 1st January 2020 Page 38 Only the best three flights will be added together. The maximum accounted single flight is 200 seconds. Working time is 10 minutes. ''' class J(task_base_one_validation): def __init__(self): super().__init__() self.maximum_flights=3 self.maximum_flight_time=180 ''' 5.7.11.10 Task J (Three last flights) During the working time, each competitor has an unlimited number of flights, but only the three last flights will be scored. Maximum time per flight is 180 seconds for 10 minutes working time. Example: 1st flight 150 s 2nd flight 45 s 3rd flight 180 s 4th flight 150 s Total score: 45 s + 180 s + 150 s = 375 s ''' class K(task_base_one_validation): # TO DO CORRECT VALIDATION !!! def __init__(self): super().__init__() self.maximum_flights=5 self.maximum_flight_time=999 ''' 5.7.11.11 Task K (Increasing time by 30 seconds, “Big Ladder”) Each competitor must launch his/her model glider exactly five (5) times to achieve five (5) target times as follows: 1:00 (60 seconds), 1:30 (90 seconds), 2:00 (120 seconds), 2:30 (150 seconds), 3:00 (180 seconds). The targets must be flown in the increasing order as specified. The actual times of each flight up to (not exceeding) the target time will be added up and used as the final score for the task. The competitors do not have to reach or exceed the target times to count each flight time. Working time: 10 minutes. ''' class L(task_base_one_validation): def __init__(self): super().__init__() self.maximum_flights=1 self.maximum_flight_time=599 ''' 5.7.11.12 Task L (One flight) During the working time, the competitor may launch his model glider one single time. The maximum flight time is limited to 599 seconds (9 minutes 59 seconds). Working time: 10 minutes. ''' class M(task_base_one_validation): # TO DO CORRECT VALIDATION !!! def __init__(self): super().__init__() self.maximum_flights=3 self.maximum_flight_time=999 ''' 5.7.11.13 Fly-off Task M (Increasing time by 2 minutes “Huge Ladder”) Each competitor must launch his/her model glider exactly three (3) times to achieve three (3) target times as follows: 3:00 (180 seconds), 5:00 (300 seconds), 7:00 (420 seconds). The targets must be flown in the increasing order as specified. The actual times of each flight up to (not exceeding) the target time will be added up and used as the final score for the task. The competitors do not have to reach or exceed the target times to count each flight time. Working time: 15 minutes. '''
a7d1043fedfc101f7b7e00275c277935d601e56f
timvan/reddit-daily-programming-challenges
/route_planner.py
1,812
3.65625
4
# Google Maps Route Planner # Project 4 Python # 01-11-2015 import urllib import webbrowser place = () def place_request(): global route route = [] cont = True count = 0 print "Enter route" print "Press enter on black entry to route" while cont == True: if count ==0: place = raw_input("Starting Location: ") else: place = raw_input("Destination %d: " % count) if place == "": cont = False else: route.append(place.lower().title()) count += 1 cont = True check_route() def check_route(): global route via_locs = "" if len(route) == 0: print "No destination entered." place_request() if len(route) == 1: print_request = str(route[0]) elif len(route) == 2: print_request = str(route[0]) + " to " + str(route[1]) + "." elif len(route) == 3: print_request = str(route[0]) + " to " + str(route[2]) + " via " + str(route[1]) \ + "." elif len(route) == 4: print_request = str(route[0]) + " to " + str(route[3]) + " via " + str(route[1]) \ + " and " + str(route[2]) + "." else: for r in range(len(route) - 4): via_locs += ", " + str(route[r + 2]) print_request = str(route[0]) + " to " + str(route[len(route)-1]) + " via " + \ str(route[1]) + via_locs + " and " + str(route[(len(route)-2)]) + "." print "Generate route from " + print_request check = raw_input("Is this correct? (y/n): ") if caps(check) == Y: print "Redirecting to Google Maps" run_maps() else: place_request() def run_maps(): global route url = "https://www.google.co.uk/maps/dir/" for p in range(len(route)): url += route[p] + "/" print url # webbrowser.open_new(url) def start_planner(): print "-" * 40 print "Welcome to Route Planner using Google Maps" print "-" * 40 place_request() start_planner()
71d2c279fef11aad5b0bd5ddce70be5a8523665f
onlysingle007/labs
/Lab_5/4.py
238
4.0625
4
x = input("Enter a string.") count=0 for i in range(0,int(len(x)/2)): if(x[i]==x[len(x)-i-1]): count=count+1 if(count==int(len(x)/2)): print("String is a palindrome.") else: print("String is not a palindrome.")
2c52f8e1653a11cc93d37a144656cd7f5d8804f0
bus1029/HackerRank
/Interview Preparation Kit/Array/MinimumSwaps2.py
2,013
3.515625
4
#!/bin/python3 import math import os import random import re import sys # Complete the minimumSwaps function below. def minimumSwaps(arr): # Input Format:: # The first line contains an integer n, the size of arr. # The second line contains n space-separated integers arr[i]. # Constraints # 1 <= n <= pow(10, 5) # 1 <= arr[i] <= n swap = 0 # length = len(arr) # 주의! .index를 쓰는 과정에서 Timeout이 발생 # for i in range(length//2): # index = arr.index(i+1) # if i != index: # swap += 1 # arr[i], arr[index] = arr[index], arr[i] # # index = arr.index(length-i) # if length-1-i != index: # swap += 1 # arr[length-1-i], arr[index] = arr[index], arr[length-1-i] # .index를 쓰지 않고, 직접 array에 접근해서 해결 # 각 숫자들이 원래 있어야 할 위치로 옮겨짐 # 여기서 포인트는 바꿔진 위치에서 다시 한번 실행한다는 점 i = 0 while i < len(arr): # 해당 값이 해당 값-1의 Index에 위치해 있을 때 if arr[i] == arr[arr[i]-1]: i += 1 continue # 위치해있지 않다면 elif arr[i] != arr[arr[i]-1]: swap += 1 # temp = arr[i] # arr[i] = arr[arr[i]-1] # arr[temp-1] = temp # 위 식과 같은 식 # 여기서 arr[arr[i]-1]과 arr[i]의 순서가 바뀌면 안되는데 # 순서가 바뀌면 arr[i]에 다른 숫자가 먼저 들어가고 # 그 뒤에 arr[arr[i]-1]에 적용되기 때문에 의도치 않게 숫자가 바뀌게 된다. arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1] return swap if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) arr = list(map(int, input().rstrip().split())) res = minimumSwaps(arr) fptr.write(str(res) + '\n') fptr.close()
da0c6825ea583680e399ca0affa5f55ea5dc9bf9
arjundha/COMP1510-Hackathon
/covid19_stats.py
1,769
3.59375
4
""" Handles retrieval of covid-19 statistics """ import requests import json import doctest def get(api_link: str) -> dict: """ Get response from api :param api_link: a valid api request link :preconditon: api_link must be a string :postcondition: return the response as a json dictionary :return: the response as a json dictionary >>> get('https://api.covid19api.com/summary')['Countries'][44]["Country"] 'Chile' """ # Get response from the api response = requests.get(api_link) # Check status of response try: response.raise_for_status() except requests.exceptions.HTTPError as e: print(e) else: # Return json dictionary return json.loads(response.text) def global_stats(): """ Get dictionary from global statistics api :postcondition: get the response from the api for global statistics :return: the response as a json dictionary """ return get('https://api.covid19api.com/summary') def get_country_stats(country: str) -> int or slice or str: """ Search api dictionary for country :param country: a country :precondition: country must be a string :postcondition: will search through the dictionary of countries from api for the country :return: the country as a string >>> get_country_stats('canada')['Country'] 'Canada' >>> get_country_stats('United States of America')['Country'] 'United States of America' """ # Search list for specified country key return next(item for item in get('https://api.covid19api.com/summary')['Countries'] if item["Country"].lower() == country.strip().lower()) def main(): doctest.testmod() if __name__ == '__main__': main()
85aee223bbe358b44453fef2ca7b1e08ecdbc9fe
pranjay01/leetcode_python
/RecoverBinarySearchTree.py
2,077
3.671875
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def getTree(inputValues): #inputValues = [1,2,3] root = TreeNode(int(inputValues[0])) nodeQueue = [root] front = 0 index = 1 while index < len(inputValues): node = nodeQueue[front] front = front + 1 item = inputValues[index] index = index + 1 if item != "null": leftNumber = int(item) node.left = TreeNode(leftNumber) nodeQueue.append(node.left) if index >= len(inputValues): break item = inputValues[index] index = index + 1 if item != "null": rightNumber = int(item) node.right = TreeNode(rightNumber) nodeQueue.append(node.right) return (root) root=getTree([1,2,3]) #q=getTree([1,"null",2]) class Solution: def recoverTree(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ arr1=[] self.toList(root,arr1) print (arr1) num1=None num2=arr1[-1] l=len(arr1) i=0 arr2=[]+arr1 arr2.sort() for i in range(l): if not arr1[i]==arr2[i]: if num1: num2=arr1[i] break num1=arr1[i] self.replace(root,num1,num2) print(root) def replace(self,tree,num1,num2): if tree.left: self.replace(tree.left,num1,num2) if tree.val==num1: tree.val=num2 elif tree.val==num2: tree.val=num1 if tree.right: self.replace(tree.right,num1,num2) return 0 def toList(self,tree,tlist): if tree.left: self.toList(tree.left,tlist) tlist.append(tree.val) if tree.right: self.toList(tree.right,tlist) return tlist Solution().recoverTree(root)
109805fe8be49eaae5c73a56914ee82d983c6456
mammuth/Project-Euler-Solutions
/solutions/Problem056.py
270
3.65625
4
#!/usr/bin/python3 # Created by Max Muth on 05. December 2014 # [email protected] maxSum = 0 for a in range(2, 100): for b in range(2, 100): digitSum = sum(int(digit) for digit in str(a ** b)) if digitSum > maxSum: maxSum = digitSum print(maxSum)
3bd92f04eb1179c92fbbc4be89028aad9b8ba7e0
shawnwnha/PythonProjects
/Python OOP(day2)/day(2)/OOP(practice).py
253
3.609375
4
class monster(object): def __init__(self, name, height, weight): self.name = name self.height = height self.weight = weight self.intelligence = 0 class juka(monster): def __init__(self): super(juka,self).__init__() self.intelligence =10
133f82ef1da063822841a9cecbc0c1b7ed671048
Bushmangreen/my_world
/Season_2/Exercises/longest_increasing_subsequence.py
741
3.78125
4
def longest_increasing_subsequence(array): l = 0 r = 0 index = 0 my_max = 0 #find max min_value = min(array) min_index = array[array.index(min_value)] my_list = [] for runner in range(min_index, len(array)): my_list = [] my_list.append(min_value) for index in range(runner, len(array)): if my_list[-1] < array[index] : my_list.append(array[index]) my_max = max(my_max, len(my_list)) if (my_list[-1] == array[-1] and len(my_list) == 1): return 0 index += 1 if (len(my_list) == 1): return 0 else: return my_max print(longest_increasing_subsequence([10,9,2,5,3,7,101,18]))
3bc7843fea00cf57fc58f223ca797f5dcb964ede
johnstantine/Python-Projects
/Percentage Calculator/Percentage Calculator.py
656
3.8125
4
print("How many documents did we get today? ") doc1 = int(input("EOB documents: ")) doc2 = int(input("EOBL documents: ")) doc3 = int(input("ERA documents: ")) total_docs = doc1 + doc2 + doc3 print(f'In total, we received {total_docs} documents.') print("What was the percentage of each? ") eob_docs = float(doc1/total_docs*100) eobl_docs = float(doc2/total_docs*100) era_docs = float(doc3/total_docs*100) eob_docs_final = round(eob_docs, 2) eobl_docs_final = round(eobl_docs, 2) era_docs_final = round(era_docs, 2) print(f'In total, EOB items make up {eob_docs_final}%, EOBL items make up {eobl_docs_final}%, and ERA items make up {era_docs_final}%')
6791259c3dca001cc4a415119fa626f24fafe4be
helen5haha/pylee
/game/NQueens.py
1,437
3.90625
4
# The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. ''' Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where'Q' and '.' both indicate a queen and an empty space respectively. For example, There exist two distinct solutions to the 4-queens puzzle: [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ] Classical backtracking ''' paths = [] def doSolveNQueens(n, prefix, level): for i in range(0, n): is_valid = True for m in range(0, len(prefix)): if i == prefix[m]: is_valid = False break if level - m == i - prefix[m] or level - m == prefix[m] - i: is_valid = False break if is_valid: new_prefix = prefix[:] new_prefix.append(i) if n - 1 != level: doSolveNQueens(n, new_prefix, level + 1) else: paths.append(new_prefix) def solveNQueens(n): doSolveNQueens(n, [], 0) lists = [] for path in paths: list = [] for num in path: str = "." * num + "Q" + "." * (n - num - 1) list.append(str) lists.append(list) return lists solveNQueens(4)