blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
6bd1c805e910d22d3926dcc483e1992953438865
ivo-bass/SoftUni-Solutions
/programming_fundamentals/lists_advanced_exercise/10. Inventory.py
753
3.90625
4
def collect(inv, i): if i not in inv: inv.append(i) return inv def drop(inv, i): if i in inv: inv.remove(i) return inv def combine_items(inv, i): old, new = i.split(":") if old in inv: inv.insert(inv.index(old) + 1, new) return inv def renew(inv, i): if i in inv: inv.remove(i) inv.append(i) return inv inventory = input().split(", ") data = input() while not data == "Craft!": command, item = data.split(" - ") if command == "Collect": inventory = collect(inventory, item) elif command == "Drop": inventory = drop(inventory, item) elif command == "Combine Items": inventory = combine_items(inventory, item) elif command == "Renew": inventory = renew(inventory, item) data = input() print(", ".join(inventory))
45106d0a9a71b876a21b7ad0bcc44cfbd0c65c8c
Vakonda-River/Stanislav
/lesson3_4.py
352
4.15625
4
#x^(-y)=1/x^y x_1 = float(input('Введите действительное положительное число: ')) y_1 = int(input('Введите целое отрицательное число: ')) def step(x,y): s = 1 for i in range(abs(y)): s *= x res = 1/s return (res) print(step(x_1,y_1))
c448debe4dc822e37755d58fc878bfb62f00e7d0
srikanthpragada/PYTHON_03_AUG_2020
/demo/oop/minh/demo5.py
339
3.625
4
class A: def process(self): print(type(self)) print('In A') class B: def process(self): print('In B') class C(A, B): def process(self): # Call method in both superclasses A.process(self) B.process(self) print("In C") obj = A() obj.process() obj = C() obj.process()
c4633b79e90c0ced6077ab85860a4c233a91576f
daniel-reich/ubiquitous-fiesta
/6sSWKcy8ttDTvkvsL_22.py
308
3.75
4
def after_n_days(days, n): d = { "Sunday":0, "Monday":1, "Tuesday":2, "Wednesday":3, "Thursday":4, "Friday":5, "Saturday":6 } ​ ​ arr = [(d[day] + n)%(len(d))for day in days] l = [] for n in arr: l.append([k for k,v in d.items() if v == n]) return sum(l,[])
159226419cbf94e4b9b1bfe84ef1b01f5f0a2f7d
erjan/coding_exercises
/minimize_hamming_distance_after_swap_operations.py
3,137
3.90625
4
''' You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed). Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source. ''' class UnionFind: def __init__(self, n): self.roots = [i for i in range(n)] def find(self, v): if self.roots[v] != v: self.roots[v] = self.find(self.roots[v]) return self.roots[v] def union(self, u, v): self.roots[self.find(u)] = self.find(v) class Solution: def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: uf = UnionFind(len(source)) for idx1, idx2 in allowedSwaps: uf.union(idx1, idx2) m = collections.defaultdict(set) for i in range(len(source)): m[uf.find(i)].add(i) res = 0 for indices in m.values(): freq = {} for i in indices: freq[source[i]] = freq.get(source[i], 0)+1 freq[target[i]] = freq.get(target[i], 0)-1 res += sum(val for val in freq.values() if val > 0) return res -------------------------------------------------------------------------------------------------------------------------------- class Solution: def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: adj = defaultdict(list) visited = [0 for _ in range(len(source))] for a in allowedSwaps: adj[a[0]].append(a[1]) adj[a[1]].append(a[0]) res = 0 for i in range(len(visited)): temp = 0 if visited[i] == 0: q = collections.deque([i]) d = defaultdict(int) ind = [] while q: node = q.popleft() d[source[node]] += 1 ind.append(node) visited[node] = 1 for c in adj[node]: if visited[c] == 0: visited[c] = 1 q.append(c) for j in ind: if target[j] in d and d[target[j]] > 0: d[target[j]] -= 1 for k in d: if d[k] > 0: temp += d[k] res += temp return res
bb7219177527b96c77d15869c247ad16615a0693
sagdog98/PythonMiniProjects
/Lab_1.py
2,248
4.34375
4
# A list of numbers that will be used for testing our programs numbers = [1, 2, 3, 4, 5, 6, 7, 8] # Question 1: Create a function called even, which takes in an integer as input and returns true if the input is even, and false otherwise def even(num): # Provide your code here return True if num % 2 == 0 else False print("even(1):\t\t\t\t", even(1)) # should return False print( "even(2):\t\t\t\t", even(2)) # shourd return True print() # Question 2: Create a function called odd, which takes in an integer as input and returns true if the input is odd, and false otherwise def odd(num): # Provide your code here return False if num % 2 == 0 else True print("odd(1):\t\t\t\t\t", odd(1)) # should return True print("odd(2):\t\t\t\t\t", odd(2)) # shourd return False print() # Question 3: Given a list of integers, create a function called count_odd, which takes in a list and counts the number of odd. Your function should employ a divide and conquer approach. Select an appropriate base case and implement a recursive step. def count_odd(list): # Provide your code here return 0 if len(list) == 0 else (list[0] % 2 + count_odd(list[1:])) print("count_odd([1, 2, 3, 4, 5, 6, 7, 8]):\t", count_odd(numbers)) # should return 4 print() # Question 4: Given a list of integers, use a divide and conquer approach to create a function named reverse, which takes in a list and returns the list in reverse order. def reverse(list): # Provide your code here if len(list) == 0: return [] else: return reverse(list[1:]) + list[:1] if list else [] print("reverse([1, 2, 3, 4, 5, 6, 7, 8]):\t", reverse(numbers)) # should return [8, 7, 6, 5, 4, 3, 2, 1] print() # Question 5: Given two sorted lists, it is possible to merge them into one sorted lists in an efficient way. Design and implement a divide and conquer algorithm to merge two sorted lists. def merge(list1, list2): # Provide your code here if list1 and list2: if list1[0] > list2[0]: list1, list2 = list2, list1 return [list1[0]] + merge(list1[1:], list2) return list1 + list2 print("merge([1, 3, 5, 7], [2, 4, 6, 8]):\t", merge([1, 3, 5, 7], [2, 4, 6, 8])) # should return [1, 2, 3, 4, 5, 6, 7, 8]
9cfa73c453c362fdebac50b70055974c6bc1fcbb
AndrewLu1992/lintcodes
/110_minimum-path-sum/minimum-path-sum.py
839
3.671875
4
# coding:utf-8 ''' @Copyright:LintCode @Author: hanqiao @Problem: http://www.lintcode.com/problem/minimum-path-sum @Language: Python @Datetime: 16-05-27 03:45 ''' class Solution: """ @param grid: a list of lists of integers. @return: An integer, minimizes the sum of all numbers along its path """ def minPathSum(self, grid): # write your code here table = [[grid[0][0]]] for i in range(1, len(grid[0])): table[0].append(table[0][i - 1] + grid[0][i]) for i in range(1, len(grid)): table.append([table[i - 1][0] + grid[i][0]]) for i in range(1, len(grid)): for j in range(1, len(grid[0])): table[i].append(min(table[i - 1][j], table[i][j - 1]) \ + grid[i][j]) return table[-1][-1]
e6cc1e0d3809349eb9720f502792478be8d06b80
didh9i/Kodium
/diary.py
1,085
3.625
4
# Задание №2 # Создайте словарь с 3 ключами - любые 3 дня недели, и задачу, # которое пользователь должен в этот день выполнить. # Ниже, в данный словарь, добавьте еще одну задачу в один из дней. # На консоль выводится измененный словарь. # # Выполнил # Петров Данил Анатольевич # Mail: cclarice@student.21-school.ru # Словарь week = { "Понедельник": "Отжимания 30 раз 5 подходов", "Среда": "Подтягивания 10-15 раз 6 подходов", "Пятница": "Приседания 35-40 раз 5 подходов" } # Что нужно добавить week1 = { "Суббота": "Растяжка верхней части тела" } # Добавляем в словарь week.update(week1) # Вывести словарь print(week) # Вывести читаемый словарь for day in dict.keys(week): print(day + ":", week[day])
420dbe1ea5e83b2e6d95014ac6ff88f37e69bc0e
ianonavy/potatoipsum
/generate.py
1,144
3.859375
4
#!/usr/bin/env python from random import shuffle, randint, random def generate(wordlist, num_paragraphs): lipsum = [] for i in xrange(num_paragraphs): lipsum.append(random_paragraph(wordlist)) return '\n\n'.join(lipsum) def random_paragraph(wordlist, max_chars=512): paragraph = [] while len(' '.join(paragraph)) < max_chars: paragraph.append(random_sentence(wordlist)) return ' '.join(paragraph) def random_sentence(wordlist): if random() > .3: return make_simple_sentence(wordlist) else: return make_compound_sentence(wordlist) def random_clause(wordlist, min_length=5, max_length=7): shuffle(wordlist) return ' '.join(wordlist[0:randint(min_length, max_length)]) def make_simple_sentence(wordlist): shuffle(wordlist) return '%s.' % random_clause(wordlist).capitalize() def make_compound_sentence(wordlist): shuffle(wordlist) return ('%s, %s.' % (random_clause(wordlist, min_length=1), random_clause(wordlist))).capitalize() with open("wordlist.txt") as wordlist: print generate(wordlist.read().splitlines(), 5)
1e01c08ffcb29f62ca8f3ff50f77cb48619cb45a
Essi5764/python-challenge
/PyPoll/main.py
1,946
3.828125
4
import csv # Importing the election data candidates = [] candidate_votes = {} total_vote=0 winning_candidate="" winning_count=0 with open("election_data.csv", 'r') as csvfile: # Split the data on commas csvreader = csv.reader(csvfile, delimiter=',') header = next(csvreader) #Find Total vote # Loop through the data for row in csvreader: total_vote=total_vote+1 # If the canditate's name in a row is equal to..., run the 'print_percentages()' function candidate = row[2] if candidate not in candidates: candidates.append(candidate) candidate_votes[candidate]=0 candidate_votes[candidate]=candidate_votes[candidate]+1 #To find the winner with open("output.txt","w") as txtfile: print(f"-------------------------------------------") print(f"Total vote: {total_vote}") print(f"-------------------------------------------") txtfile.write(f"-------------------------------------------\n") txtfile.write(f"Total vote: {total_vote}\n") txtfile.write(f"-------------------------------------------\n") for candidate in candidate_votes: votes=candidate_votes[candidate] percent=float(votes)/float(total_vote)*100 print(f"{candidate}: {percent}% ({votes})") txtfile.write(f"{candidate}: {percent}% ({votes})\n") if (votes>winning_count): winning_count=votes winning_candidate=candidate # Print the analysis and export # file as text file with the results print(f"-------------------------------------------") print(f"Winner: {winning_candidate}") print(f"-------------------------------------------") txtfile.write(f"-------------------------------------------\n") txtfile.write(f"Winner: {winning_candidate}\n") txtfile.write(f"-------------------------------------------\n")
1fad51027b38612085af823850a8b02a14f10e34
sgreenh23/Engineering_4_Notebook
/Python/Python Challenge-MSP.py
1,255
3.671875
4
word = input("Player 1, what's the word? \n") print ("\n" * 50) aVariable = 0 def executioner(): x = ("-----|", " O ", " |", " |\ ", " /|\ ", " /"," / \ ") for stuff in range(0,aVariable): if aVariable <= 3: print(x[stuff]) if aVariable == 4: if stuff is not 2: print(x[stuff]) if aVariable == 5: if stuff is not 2 and stuff is not 3: print(x[stuff]) if aVariable == 6: if stuff is not 2 and stuff is not 3: print(x[stuff]) if aVariable == 7: if stuff is not 2 and stuff is not 3 and stuff is not 5: print(x[stuff]) word1 = list(word) myLen = len(word1) loc = 0 blanks = [] for letters in word1: blanks.append("_") print(" ".join(blanks), "\n" * 4) while aVariable < 7: guess = input("Player 2, guess a letter: \n") for loc,letters in enumerate(word1): if guess == letters: blanks[loc]=guess if guess not in word1: aVariable = aVariable + 1 executioner() print(" ".join(blanks)) if "_" not in blanks: print("\nYou won!") break print("\nGame Over")
a8e57910a6f4cac298f82ea24b61a85eee163d56
soyalextreme/estructura-datos-algoritmos
/src/first_partial_exercises/ex_9.py
1,692
3.734375
4
""" 30-09-2020 Excersice 9 Estructura de Datos y algoritmos Average Trip 6to Semestre Alejandro AS """ from lib.inputs import input_int, input_float from lib.util import clean_screen from lib.menu.epp_menu import Menu class ReportTrip(): trip_amount_persons = [] trip_weight = [] def __init__(self): pass def add_trip(self): print(f"Elevator Trip {len(self.trip_amount_persons) + 1}") amount = input_int( "Amount of people in the elevator trip: ", allow_negative=False) weight = round(input_float( "Weight in the elevator trip: ", allow_negative=False), 2) self.trip_amount_persons.append(amount) self.trip_weight.append(weight) print("Elevator Trip registered") def get_average_persons(self): return round(sum(self.trip_amount_persons) / len(self.trip_amount_persons), 2) def get_average_weight(self): return round(sum(self.trip_weight) / len(self.trip_weight), 2) def report(self): print("Day Stats") print("*"*30) print(f""" Amount of trips: {len(self.trip_amount_persons)} Amount of persons transported: {sum(self.trip_amount_persons)} Weight Transported: {sum(self.trip_weight)} kg Average of Persons per trip: {self.get_average_persons()} Average of Weight per trip: {self.get_average_weight()} kg """) def main(): t = ReportTrip() OPC = [(1, "ADD TRIP", t.add_trip), (2, "SHOW STATS OF THE DAY", t.report) ] m = Menu(opcs=OPC, exit_val=3, still=False) m.start()
dfaf6577accea2021e87ef9ac10c8f1331d7bde7
julijonas/bi-search
/backend/app/infrastructure/validation.py
5,601
3.578125
4
import re import json import sys class ValidationException(Exception): def __init__(self, key, message): super(ValidationException, self).__init__() self._key = key self._message = message def __str__(self): return "Failed to validate %s: %s" % (self._key, self._message) class JSONCast: def __init__(self): pass def __call__(self, value): return json.loads(value) def __str__(self): return "JSON" raw_json = JSONCast() class Schema: def __init__(self, cast, length=None, bounds=None, optional=False, nullable=False, schema=None, regex=None, values=None, default=None, force_present=False): """ Defines a Schema to validate an object against. :param cast: What to cast the object as. (Calls cast as a method, valid values are: int, str, any callable obj.) :param length: Length ranges. Tuple of (min, max) ranges inclusive. None = no limit. Eg: (3, None) :param bounds: Value ranges. Tuple of (min, max) values inclusive. None = no limit. Eg: (3, None) :param optional: Requires the object to be present. Used for validating dictionary key values. :param nullable: Allows None as a valid value of the object. :param schema: What to validate inner objects as. For lists, this is just another Schema. For dicts, this is a dict of schemas with keys corresponding to the inner keys of the object. :param regex: Regex for string types. :param values: Allowed values. Must be list or tuple. :param default: Object is set to this if it is not present in the puter object. Used for dicts. :param force_present: Value is set to None if it is not present in the object. Used for dicts. (Can't do this with default argument, because if default=None then there is no default value) """ self._cast = cast self._length = length self._bounds = bounds self._optional = optional self._nullable = nullable self._schema = schema self._regex = re.compile(regex) if regex else None self._values = values self._default = default self._force_present = force_present def optional(self): return self._optional def default(self): return self._default def force_present(self): return self._force_present def validate(self, key, value): """ Validates the value against this schema. :param key: What this value is. If value fails to pass validation, key will be printed out in the debug message. :param value: The value to validate. :return: The validated value. """ if value is None: if not self._nullable: raise ValidationException(key, "Value cannot be null!") return None try: value = self._cast(value) except ValueError: raise ValidationException(key, "Failed to cast %s as %s" % (value, str(self._cast))) except Exception as e: sys.stderr.write("Exception occurred in the validation casting stage: " + str(e)) raise e if self._length is not None: l = len(value) if self._length[0] is not None and l < self._length[0]: raise ValidationException( key, "Must not be shorter than %s. Received length: %s" % (self._length[0], l) ) if self._length[1] is not None and l > self._length[1]: raise ValidationException( key, "Must not be longer than %s. Received length: %s" % (self._length[1], l) ) if self._bounds is not None: if self._bounds[0] is not None and value < self._bounds[0]: raise ValidationException( key, "Must be at least %s. Received: %s" % (self._bounds[0], value) ) if self._bounds[1] is not None and value > self._bounds[1]: raise ValidationException( key, "Must be at most %s. Received %s" % (self._bounds[1], value) ) if self._values is not None and value not in self._values: raise ValidationException( key, "Value '%s' is not among the allowed values. Allowed values: %s" % (value, ", ".join(["'%s'" % v for v in self._values])) ) if self._cast == list: return [self._schema.validate(key + ("[%i]" % i), item) for i, item in enumerate(value)] if self._cast == dict: validated = dict() for k, v in self._schema.items(): if k not in value: if not v.optional(): raise ValidationException(key + ("['%s']" % k), "Key is missing!") if v.default() is not None: validated[k] = v.default() elif v.force_present(): validated[k] = None else: validated[k] = v.validate(key + ("['%s']" % k), value[k]) return validated if self._cast is raw_json: value = self._schema.validate(key, value) if self._regex and not re.fullmatch(self._regex, value): raise ValidationException(key, "Value does not match the required regular expression.") return value
97a3e6915bb9f22804ce9f517ca2adaa6edaed4d
JuanPGrisales/EjemplosTarea
/Tareas/Correcion.py
4,258
3.5625
4
import random class colegio: def __init__(self): self.diccionarioEstudiantes = {} def calcularSumaNotasEstudiantes(self): _listaNotasEstudiantes = self.listarNotaEstudiantes() # Notas de los estudiantes _sumaNotasEstudiantes = sum(_listaNotasEstudiantes) # sumar las notas de los estudiantes return _sumaNotasEstudiantes def listarNotaEstudiantes(self): _listaNotaEstudiantes = [] for identificadorEstudiante in self.diccionarioEstudiantes: # print(estudiante.calcularNotaTotal()) # imprimir nota total estudiante _notaTotalEstudiante = self.diccionarioEstudiantes[identificadorEstudiante].calcularNotaTotal() # ingresar nota total en una lista _listaNotaEstudiantes.append(_notaTotalEstudiante) return _listaNotaEstudiantes def contarCantidadEstudiantes(self): _listaEstudiantes = self.diccionarioEstudiantes # necesito una lista de estudiantes _cantidadEstudiantes = len(_listaEstudiantes) # necesito contar los elementos la lista estudiantes return _cantidadEstudiantes def reportarInfoEstudiantes(self): for _identificadorEstudiante in self.diccionarioEstudiantes: estudianteTemporal = self.diccionarioEstudiantes[_identificadorEstudiante] print(estudianteTemporal.nombre)# imprime nombre del estudiante tamañoDiccionarioCursos = len(self.diccionarioEstudiantes[_identificadorEstudiante].diccionarioCursos) for i in range(0,tamañoDiccionarioCursos): _identificadorCurso = 'Curso' + str(i) _notaTotalCurso = estudianteTemporal.diccionarioCursos[_identificadorCurso].calcularNotaTotal() _textobonito = "La nota total del {0} es {1}" print(_textobonito.format(_identificadorCurso,_notaTotalCurso)) # imprime la nota total del curso print("El promedio del estudiante es ", estudianteTemporal.calcularNotaTotal()) # imprime el promedio del estudiante if(estudianteTemporal.calcularNotaTotal()>3): print("El estudiante aprobo") else: print("El estudiante no aprobo") class estudiante: def __init__(self,_nombre): self.nombre = _nombre self.diccionarioCursos = {} def calcularNotaTotal(self): _notaTotal = 0 for _idCurso in self.diccionarioCursos: _notaTotalCurso = self.diccionarioCursos[_idCurso].calcularNotaTotal() _notaTotal += _notaTotalCurso return _notaTotal / len(self.diccionarioCursos) class curso: def __init__(self): self.listaNotaTareas = [0]*5 def calcularNotaTotal(self): _notaTareas = sum(self.listaNotaTareas)/len(self.listaNotaTareas) _notaTotal= (self.notaExamen*0.2) + (self.notaFinal*0.2) + (_notaTareas*0.6) # Nota total del curso return _notaTotal #comienzo gemelli = colegio() for i in range(100): _nombreEstudiante = "Estudiante" + str(i) gemelli.diccionarioEstudiantes[_nombreEstudiante] = (estudiante(_nombreEstudiante)) for j in range(5): _identificadorCurso = "Curso" + str(j) gemelli.diccionarioEstudiantes[_nombreEstudiante].diccionarioCursos[_identificadorCurso] = curso() gemelli.diccionarioEstudiantes[_nombreEstudiante].diccionarioCursos[_identificadorCurso].notaExamen = random.randint(0,50) / 10 gemelli.diccionarioEstudiantes[_nombreEstudiante].diccionarioCursos[_identificadorCurso].notaFinal = random.randint(0,50) / 10 _listaNotaTareas = gemelli.diccionarioEstudiantes[_nombreEstudiante].diccionarioCursos[_identificadorCurso].listaNotaTareas for _posicionNotaTarea in range(len(_listaNotaTareas)): gemelli.diccionarioEstudiantes[_nombreEstudiante].diccionarioCursos[_identificadorCurso].listaNotaTareas[_posicionNotaTarea] = random.randint(0,50) / 10 sumaNotasEstudiantes = gemelli.calcularSumaNotasEstudiantes() cantidadEstudiantes = gemelli.contarCantidadEstudiantes() promedioColegio = sumaNotasEstudiantes / cantidadEstudiantes gemelli.reportarInfoEstudiantes() # imprimir reporte por cada estudiante print("El promedio del colegio es: ", promedioColegio)
df39f35dba6cb63c4be7d728a8fc3d78392a5a17
PaulaStrel/tasks
/contest_sort/A.py
262
3.796875
4
N = int(input()) A = [0] * N for i in range(N): A[i]=int(input()) def bubble_sort(A): for i in range(1, N): for k in range(N - i): if A[k] > A[k + 1]: A[k],A[k+1] = A[k+1],A[k] return A print(bubble_sort(A))
00768aa0f7143cd3c48f338722dfe8424f4437f1
twishabansal/programmingLangsWTEF
/Python/Assignments/PascalTriangle.py
298
3.828125
4
def pascals_triangle(row): def fact(n): if n==0: return 1 else: return n*fact(n-1) string='' for i in range(row): string+=str(int(fact(row)/(fact(row-i)*fact(i)))) string+=' ' string+=str(1) return string
63f31efa728417520e9bf692180eb8fbb58e8d9a
jugalj05hi/Project-Euler
/Q1_SumOfMultiples_3and5.py
155
3.734375
4
i = 0 three = 0 five = 0 while (i<1000): if(i % 3 == 0): three = three + i elif( i % 5 == 0): five = five + i i += 1 tot = three + five print(tot)
a1a9423ac1dd1cdeacbfe5f351a0769bef507422
elmasbusenur/Format
/Format.py
266
3.671875
4
print("oyuncu kaydetme programi") ad=input("oyuncunun adi:") soyad=input("oyuncunun soyadi:") takim=input("oyuncunun takimi:") bilgiler=[ad,soyad,takim] print("oyuncunun adi:{}\noyuncunun soyadi:{}\noyuncunun takimi:{}".format(bilgiler[0],bilgiler[1],bilgiler[2]))
d4dd62baef1734197c92c60ae26b7105f229e5d3
fadedmax/testingscripts
/testcodeagain.py
1,538
4.03125
4
def calculator(): print ("1. Addition") print ("2. Subtraction") print ("3. Multiplacation") print ("4. Division") print ("5. Primes to 100") print ("6. Find factors") print ("") question = input("Please select a option") if question == "1": num1 = int(input("Enter first number: ")) print (num1) num2 = int(input("Enter second number: ")) print (num2) print ("") ans = num1 + num2 print (ans) if question == "2": num1 = int(input("Enter first number: ")) print (num1) num2 = int(input("Enter second number(what will be subtracted): ")) print (num2) print ("") ans = num1 - num2 print (ans) if question == "3": num1 = int(input("Enter first number: ")) print (num1) num2 = int(input("Enter second number: ")) print (num2) print ("") ans = num1 * num2 print (ans) if question == "4": num1 = int(input("Enter first number(dividend): ")) print (num1) num2 = int(input("Enter second number(divisor): ")) print (num2) print ("") ans = num1 / num2 print (ans) if question =="5": print ("") print ("2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 and lastly 97.") if question == "6": print ("test") username = input("Please enter your username") if username == "admin": password = input("Please enter your password") else print ("incorrect, please load program again") if username == "admin": print("correct")
51850a9176581ccf8b4c193d5a8d2985b6c9f77a
linnndachen/coding-practice
/Leetcode/959-dfs_uf.py
2,834
3.515625
4
from typing import List class Solution: def regionsBySlashes(self, grid: List[str]) -> int: # union find - better solution 不同upscale,直接把 grid 切割为点 # 同类里面生成线 - 则产生新的区间 n = len(grid) parents = [0]*(n+1)*(n+1) def find(x): if parents[x] != x: parents[x] = find(parents[x]) return parents[x] def union(a, b): p1 = find(a) p2 = find(b) if p1 < p2: parents[p2] = p1 else: parents[p1] = p2 # intialize for i in range(n+1): for j in range(n+1): idx = i*(n+1)+j parents[idx] = idx # connect the boundary if i == 0 or i == n or j == 0 or j == n: parents[idx] = 0 res = 1 for i in range(n): for j in range(n): if grid[i][j] == " ": continue # find the index of the connected components a, b = 0, 0 if grid[i][j] == "/": a = i*(n+1)+(j+1) b = (i+1)*(n+1)+(j) else: a = i*(n+1)+(j) b = (i+1)*(n+1)+(j+1) # union the components tgt if find(a) == find(b): res += 1 else: union(a, b) return res """ def regionsBySlashes(self, grid: List[str]) -> int: # dfs solution - upscale to 3. If we use 2, then we would need to # check 8 directions instead of 4. The reason is 2 has a problem # of dividing the center in example 3. # After dividing, this is exactly # 200 # Complexity: 3*N2 since upscaling n, res = len(grid), 0 # populate the new grid new_grid = [[0]*n*3 for _ in range(n*3)] for i in range(n): for j in range(n): if grid[i][j] == "/": new_grid[i*3][j*3+2] = new_grid[i*3+1][j*3+1] = new_grid[i*3+2][j*3] = 1 elif grid[i][j] == "\\": new_grid[i*3][j*3] = new_grid[i*3+1][j*3+1] = new_grid[i*3+2][j*3+2] = 1 # count the empty cells for i in range(n*3): for j in range(n*3): res += 1 if self.dfs(i, j, new_grid) > 0 else 0 return res def dfs(self, i, j, new_grid): if min(i, j) < 0 or max(i, j) >= len(new_grid): return 0 if new_grid[i][j] != 0: return 0 new_grid[i][j] = 1 return 1 + self.dfs(i-1, j, new_grid) + self.dfs(i+1, j, new_grid) + \ self.dfs(i, j-1, new_grid) + self.dfs(i, j+1, new_grid) """
7b4c6f0599d00d79c8f1da8afbaa296e6b135ba1
dornheimer/rl_bearlib
/src/map_generators/base_generator.py
3,961
3.734375
4
from abc import ABCMeta, abstractmethod from src.globals import TILES class Tile: """A tile on the game map, represented by a character and color. Can block movement and/or sight. """ def __init__(self, tile_type=None, *, color_lit='t_brown', color_dark='t_black', char='#', blocks=True, opaque=None): if tile_type is None: self.color_lit = color_lit self.color_dark = color_dark self.char = char self.blocks = blocks self.opaque = blocks if opaque is None else opaque self.tile_type = 'custom' else: self.set_type(tile_type) self.explored = False def update(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def set_type(self, tile_type): self.update(**TILES[tile_type]) self.tile_type = tile_type def is_type(self, tile_type, *, door=False): """Check if tile is of a specific type. The door parameter allows treating doors as the specified type (useful for walls). """ is_type = self.tile_type.startswith(tile_type) if door: return is_type or self.tile_type == 'door' return is_type def __repr__(self): class_name = type(self).__name__ return f"{class_name}(**{vars(self)})" class BaseGenerator(metaclass=ABCMeta): """ABC for dungeon generation algorithms.""" def __init__(self, game_map): self.game_map = game_map self.tiles = self._initialize() def _initialize(self, *, tile_type='wall'): """Fill game map space with tiles of a specific type.""" return [[Tile(tile_type) for y in range(self.game_map.height)] for x in range(self.game_map.width)] def carve(self, x, y): self.tiles[x][y].set_type('ground') def fill(self, x, y): self.tiles[x][y].set_type('wall') def assign_wall_tiles(self): """Select the appropriate wall tile character from the tile set.""" for y in range(self.game_map.height-1): for x in range(self.game_map.width-1): tile = self.tiles[x][y] if not tile.tile_type == 'wall': continue wall_tile = self.select_wall_tile(x, y) tile.set_type(wall_tile) def _check_adjacent_tiles(self, x, y, tile_type='wall', *, door=False): north = self.tiles[x][y-1].is_type(tile_type, door=door) south = self.tiles[x][y+1].is_type(tile_type, door=door) east = self.tiles[x+1][y].is_type(tile_type, door=door) west = self.tiles[x-1][y].is_type(tile_type, door=door) return north, south, east, west def select_wall_tile(self, x, y): """Determine wall tile type from its relative position.""" north, south, east, west = self._check_adjacent_tiles(x, y, door=True) if all((north, south, east, west)): return 'wall' elif all((north, east, west)): return 'wall_nwe' elif all((north, south, east)): return 'wall_nse' elif all((north, south, west)): return 'wall_nsw' elif all((south, east, west)): return 'wall_swe' elif north and south: return 'wall_ns' elif north and east: return 'wall_ne' elif north and west: return 'wall_nw' elif south and east: return 'wall_se' elif south and west: return 'wall_sw' elif east and west: return 'wall_we' elif north: return 'wall_n' elif south: return 'wall_s' elif east: return 'wall_e' elif west: return 'wall_w' else: return 'wall_pillar' @abstractmethod def generate(self): pass
c73dee4a04228d9226ebe1bf0f1e34870388ad40
indrajithi/code-lab
/pyLab/sample.py
495
3.578125
4
line = 'whippoorwills' stack = [] for i in range(len(line) - 1): # if(i < len(line)): if (line[i] == line[i + 1]): stack.append(i) print line[i],i print line print stack for i in range(len(stack) - 1): if (i + 3) <= len(stack): if stack[i] + 2 == stack[i + 1]: if stack[i] + 2 == stack[i + 1]: if stack[i] + 2 == stack[i + 1]: print "Holly shit!"
8ce4a075aacf0d2ac7ea91cdf50d81b04deab187
eldridgejm/dsc80-sp21
/discussions/05/disc05.py
758
4.125
4
import pandas as pd import numpy as np def impute_with_index(dg): """ impute (i.e. fill-in) the missing values of column B with the value of the index for that row. :Example: >>> dg = pd.read_csv('data.csv', index_col=0) >>> out = impute_with_index(dg) >>> isinstance(out, pd.Series) True >>> out.isnull().sum() == 0 True """ return ... def impute_with_digit(dg): """ impute (i.e. fill-in) the missing values of each column using the last digit of the value of column A. :Example: >>> dg = pd.read_csv('data.csv', index_col=0) >>> out = impute_with_digit(dg) >>> isinstance(out, pd.DataFrame) True >>> out.isnull().sum().sum() == 0 True """ return ...
35ee8afe01a077c7714d29db560b94fb2d33dbb8
JohnMai1994/CS116-2018_Winter_Term
/CS116/a02-j4mai/a02-j4mai/a02q3.py
2,603
3.65625
4
##=============================================== ## Jiadong Mai (20557203) ## CS 116 Winter 2018 ## Assignment 02, Question 3 ##=============================================== import check import math # Question 3 ## Useful constants for pressure trends steady = "Steady" rising_s = "Rising Slowly" rising_f = "Rising Quickly" falling_s = "Falling Slowly" falling_f = "Falling Quickly" ## Useful constants for forecasts no_change = "No Change" sun = "Sunny" storm = "Storms" tornado = "Tornado Watch" wind = "Windy" rain = "Rain" cloud = "Cloudy" ## weather_forecast(pressure, trend) returns the weather forecast according to ## the different pressure and trend combination in the weather prediction table ## weather_forecast: Float, Str => Str ## Requires: ## pressure between 80.0kPa and 120.0kPa ## Examples ## weather_forecast(101.7, "Falling Slowly") => "Rain" def weather_forecast(pressure,trend): if trend == steady: return no_change elif trend == rising_s: if pressure < 100: return no_change elif pressure <= 103: return sun else: return sun elif trend == rising_f: if pressure < 100: return sun elif pressure <= 103: return wind else: return sun elif trend == falling_s: if pressure < 100: return storm elif pressure <= 103: return rain else: return no_change else: if pressure < 100: return tornado elif pressure <= 103: return storm else: return cloud ## Test1: weather is no change check.expect("Q3Test1", weather_forecast(102, steady), "No Change") check.expect("Q3Test2", weather_forecast(99, "Rising Slowly"), "No Change") check.expect("Q3Test3", weather_forecast(110, "Falling Slowly"), "No Change") ## Test2: weather is sunny check.expect("Q3Test4", weather_forecast(98.7, "Rising Quickly"), "Sunny") check.expect("Q3Test5", weather_forecast(102,"Rising Slowly"), "Sunny") check.expect("Q3Test6", weather_forecast(111.2, "Rising Slowly"), "Sunny") check.expect("Q3Test7", weather_forecast(111, "Rising Quickly"), "Sunny") ## Test3: weather is storms check.expect("Q3Test8", weather_forecast(99.5, "Falling Slowly"), "Storms") check.expect("Q3Test9", weather_forecast(101, "Falling Quickly"), "Storms") ## Test4: weather is Tornado Watch check.expect("Q3Test10", weather_forecast(99.3, "Falling Quickly"), "Tornado Watch") ## Test5: weather is windy check.expect("Q3Test11", weather_forecast(102.1, "Rising Quickly"), "Windy") ## Test6: weather is cloudy check.expect("Q3Test12", weather_forecast(116.8, "Falling Quickly"), "Cloudy")
1667e4c6cefda6a99ab2f784a69764d0acfe74a5
yueyehu/pythonStudy
/Triangle Angles.py
804
3.96875
4
from math import acos from math import pi def angles(a, b, c): if a+b>c and a+c>b and b+c>a: theta1 = round(acos(((a**2+b**2-c**2)/(2.0*a*b)))/(2*pi)*360) theta2 = round(acos(((a**2+c**2-b**2)/(2.0*c*a)))/(2*pi)*360) theta3 = round(acos(((c**2+b**2-a**2)/(2.0*c*b)))/(2*pi)*360) ang = [theta1,theta2,theta3] ang.sort() return ang return [0, 0, 0] if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert angles(4, 4, 4) == [60, 60, 60], "All sides are equal" assert angles(3, 4, 5) == [37, 53, 90], "Egyptian triangle" assert angles(2, 2, 5) == [0, 0, 0], "It's can not be a triangle" print("Code's finished? Earn rewards by clicking 'Check' to review your tests!")
4b69358e19c7898767f2ddb06669dd1111b56eb1
takujiozaki/python-game-learn
/findAlphabet/quiz.py
1,873
3.796875
4
''' 欠落しているアルファベットを検出するCUIゲーム 書籍「Pythonでつくるゲーム開発」に掲載されていたものをアレンジしています。 ''' import random import datetime #入出力 class SystemIO(object): def print(self, word): print(word) def input(self): return(input()) #game flow class FindLetter(object): #プロパティ QUESTION = '' r = '' answer = '' playtime = [] def __init__(self): #問題文 self.QUESTION = [ 'A','B','C','D','E','F','G', 'H','I','J','L','M','N','O', 'P','Q','R','S','T','V','W', 'X','Y','Z' ] #正解 self.r = random.choice(self.QUESTION) #print(self.r) def description(self): #説明 q_str = 'アルファベットがランダムに並んでいますが、一文字欠けています。\n欠けている文字はなんでしょうか?\n' #問題文生成 random.shuffle(self.QUESTION) for i in self.QUESTION: if i != self.r: q_str = q_str + i return q_str def your_answer(self, answer): #解答を取り込む self.answer = answer.upper() def judge(self): #判定 judgement = '' if self.answer == self.r: judgement = '正解! 解答にかかった時間は{}秒でした'.format(self.get_diff_time()) else: judgement = '残念! 正解は{}でした'.format(self.r) return judgement def set_play_time(self): #時間を計測 self.playtime.append(datetime.datetime.now()) def get_diff_time(self): #時間差を取得 playtime = (self.playtime[1] - self.playtime[0]).seconds return playtime #gameをインスタンス化 game = FindLetter() #入出力をインスタンス化 io = SystemIO() #問題出力 io.print(game.description()) #開始時間計測 game.set_play_time() #解答入力 game.your_answer(io.input()) #終了時間計測 game.set_play_time() #判定 io.print(game.judge())
401e9235ed52a7a0d75f05ea1e39c3af43e8d98a
BoZhaoUT/Teaching
/Fall_2015_CSCA08_Intro_to_Computer_Science_I/Week_5_Importing/week5_pep8_examples.py
777
3.734375
4
def is_accepted(program_code,gpa,name): csc_accepted =(program_code=='CSC') mat_sta_accepted= (((program_code=='MAT')or(program_code == 'STA'))and(gpa>=3)) non_cms_accepted = (gpa> 3.5) name_accepted =(name=='Brian') result = (csc_accepted or mat_sta_accepted or non_cms_accepted or name_accepted) return result # non-pep-8 example , pep-8 example def is_accepted(program_code, gpa, name): csc_accepted = (program_code == 'CSC') mat_sta_accepted = (((program_code == 'MAT') or (program_code == 'STA') ) and (gpa >= 3)) non_cms_accepted = (gpa > 3.5) name_accepted = (name == 'Brian') result = (csc_accepted or mat_sta_accepted or non_cms_accepted or name_accepted) return result
e781f39cde75a2d03feebb7e9ba28664b37c903a
DimitryKrakitov/Genos
/room.py
3,482
3.5
4
class ist_map: n_nodes = 0 nodes = [] def __init__(self): n_nodes = 0 def construction(self, client): # God node (IST): god = node() ist_map.n_nodes = 1 #Make all the gets to fenix, and build the tree representing the map campus_spaces = client.get_spaces() for campus in campus_spaces: aux_campus = node(panode=god, id=campus['id'], type=campus['type'], name=campus['name']) print(campus['name']) ist_map.append(aux_campus) ist_map.n_nodes = ist_map.n_nodes + 1 campus_info = client.get_space(campus['id']) for building in campus_info['containedSpaces']: aux_building = node(panode=aux_campus, id=building['id'], type=building['type'], name=building['name']) ist_map.append(aux_building) print(" >"+building['name']) ist_map.n_nodes = ist_map.n_nodes + 1 building_info = client.get_space(building['id'])# a building can have floors or rooms (wth no floors) # In case of not having floors, we put generate a dummy floor = 0 node ???? for floor_room in building_info['containedSpaces']: if(floor_room['type'] == "FLOOR"): floor_aux = node(panode=aux_building, id=floor_room['id'], type=floor_room['type'], name=floor_room['name']) ist_map.append(floor_aux) print(" >>" + floor_room['name']) ist_map.n_nodes = ist_map.n_nodes + 1 floor_info = client.get_space(floor_room['id']) for room in floor_info['containedSpaces']: aux_room = room(panode=floor_aux, id=room['id'], type=room['type'], name=room['name']) ######### ADD THE LIMIT !!!!! ist_map.append(aux_room) print(" >>>" + room['name']) ist_map.n_nodes = ist_map.n_nodes + 1 else: ##### NO NEED OF DUMMY FLOOR, search looks for name aux_room = room(panode=aux_building, id=floor_room['id'], type=floor_room['type'], name=floor_room['name']) ######### ADD THE LIMIT !!!!! ist_map.append(aux_room) print(" >>>" + floor_room['name']) ist_map.n_nodes = ist_map.n_nodes + 1 class node: def __init__(self,panode = [], id = 1, type = "God", name = "God"): # Default case is god node self.name = name self.type = type # If this is a floor, campus... self.id = id # ID - from fenixAPI_r_info self.parent = panode self.children = [] def append_children(self, children): self.children.append(children) class room: def __init__(self, panode, id, name): #parse fenixAPI_r_info from the fenixedu API self.name = name self.limit = 0 #Full student capacity - from fenixAPI_r_info self.type = "Room" self.parent = panode self.id = id #Room ID - from fenixAPI_r_info self.current_ocupation = 0 self.users = [] def insertEntryPlug(self, user): if self.current_ocupation < self.limit: user.GetInTheFuckingRobotShinji(self) self.current_ocupation += 1 self.users.append(user)
b7ab7cc9f1bfbdb67a20ce308b7a85129b01b7c1
ileana2512/change.py
/main.py
170
3.578125
4
print("Please enter an amount that is less than a dollar:") c=int(87) print("Q:", c//25) c = c%25 print("D:", c//10) c = c%10 print("N:", c//5) c = c%5 print("P:", c//1)
50e53698d6b6038cd4eff2a770b48d544e0c66c8
KhaderA/python
/day2/day3/classvariabletest.py
568
3.75
4
class Employee: empcount=0 #class attribute def __init__(self,sal): Employee.empcount+=1 self.sal=sal def __del__(self): Employee.empcount-=1 def displaycount(self): return Employee.empcount def displaysal(self): return self.sal #@staticmethod #def displaycount(): # return Employee.empcount emp1=Employee(1000) print emp1.displaycount() print emp1.displaysal() emp2=Employee(2000) print emp2.displaycount() print emp2.displaysal() print "deleting emp2" del emp2 print Employee.empcount
8dfc93eb81bd3ad5671056bacf0123eeb1355204
readiv/ls1
/Semana01/for.py
3,885
4
4
""" Домашнее задание №1 Цикл for: Оценки * Создать список из словарей с оценками учеников разных классов школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...] * Посчитать и вывести средний балл по всей школе. * Посчитать и вывести средний балл по каждому классу. """ import random def get_averege_and_sum(scores): """ На входе список [3,4,4,5,2] На выходе среднее и сумма """ sum = 0 for i in scores: sum +=i return sum/len(scores),sum def main(): print('*Создать список из десяти целых чисел.\n*Вывести на экран каждое число, увеличенное на 1.') integer10 = [10,15,27,388,466,5444,62,73,85,97] s='' for n in integer10: s+=str(n+1)+' ' print(s+'\n') print('*Ввести с клавиатуры строку.\n*Вывести эту же строку вертикально: по одному символу на строку консоли.') s = input('Введите строку:') for char in s: print(char) #Создать список из словарей с оценками учеников разных классов школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...] #Посчитать и вывести средний балл по всей школе. #Посчитать и вывести средний балл по каждому классу. #Скучно просто забивать данные. Сформирую случайно nclas = random.randint(1, 10) #число классов if nclas > 280: nclas = 280 #Выплывает из ограниений наименований класов rating_school = [] for iclas in range(nclas): clas = {} while True: s = 'абвгдежзийклмнопрстуфхцчшщ' s = str(random.randint(1,11)) + s[random.randint(0, len(s)-1)] #Всего примерно 280 вариантов #Проверка на уникальность if len(rating_school) == 0: #Ещё не с чем сравнивать break else: flag = True #считаем что уникально for clas_one in rating_school: if clas_one['school_class'] == s: flag = False #Печалька. Не уникально break if flag: break clas['school_class'] = s rating_school.append(clas) scores = [] for i in range(random.randint(5,20)): scores.append(random.randint(1,5)) clas['scores'] = scores print('Данные сформированы') print(rating_school) len_global_school=0 sum_global_school=0 for clas in rating_school: print('#####################################################') print(f"Класс: {clas['school_class']}") print(f"Оценки: {clas['scores']}") avg_clas,sum_clas = get_averege_and_sum(clas['scores']) len_global_school += len(clas['scores']) sum_global_school += sum_clas print(f"Средний бал: {avg_clas}") print('#####################################################') print(f"Средний бал по школе: {sum_global_school/len_global_school}") if __name__ == "__main__": random.seed() main() input("Press Any Enter :-) ")
786e488335ca8ef7fc681da8f695ac3fed724287
peterts/mlflow-demo
/mlflow_demo/plotting.py
922
3.5
4
import numpy as np from plotly import graph_objs as go from sklearn.metrics import confusion_matrix def create_confusion_matrix_fig(labels, labels_pred, colorscale='Greens'): """ Create a confusion matrix figure with Plotly Args: labels (numpy.array): Real labels labels_pred (numpy.array): Prediction labels colorscale: Plotly color scale to use Returns: dict: Plotly figure spec """ cm = confusion_matrix(labels, labels_pred) cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] labels_unq = ["class " + str(label) if not isinstance(label, str) else label for label in np.unique(labels)] data = [ go.Heatmap(x=labels_unq[::-1], y=labels_unq, z=cm[::-1], colorscale=colorscale, reversescale=True) ] layout = dict( width=1000, height=1000, title="Confusion Matrix" ) return go.Figure(data=data, layout=layout)
28695fbe355ab95266082edad7efb2a406164b9a
g-lyc/PRACTICE
/py-code/5-16.py
494
3.859375
4
# -*- coding: UTF-8 -*- def pay(paid,balance): print "Pymt# Paid Balance" print "----- ----- ------" i=0 b=balance while(balance>paid): balance=balance - paid i +=1 print "%d $%f $%f"%(i,paid,balance) i +=1 print "%d $%d $%f"%(i,balance,0) if __name__ == '__main__': balance=raw_input("please enter the balance:") paid=raw_input("please enter the paid:") balance=float(balance) paid=float(paid) pay(paid,balance)
08cf633a4dc926bcccdacc57a717156b80f899d9
NewMike89/Python_Stuff
/Ch.4/4-1pizzas.py
420
4.28125
4
# Michael Schorr # 3/18/19 # listing my favorite pizzas and using a loop to print some stuff about them. pizzas = ['buffalo chicken', 'zesty italian', 'pepperoni'] for pizza in pizzas: print(pizza.title() + ", is one of my favorite pizzas.") print("I really like pizza, so much so that I ate a whole large pizza the other day at work. Everyone was very suprized that I was able to do so but I have to say. I LOVE PIZZA!!")
6bc0c1e1ee041f26542cded0f0b2c6100f1cdeda
Hits-95/Python
/NumPy/random/5_normal_distribution.py
395
3.96875
4
#norma distrubution from numpy import random import matplotlib.pyplot as ptl import seaborn as sbn print(random.normal(size = (2,3))) #Generate a random normal distribution of #size 2x3 with mean at 1 and standard deviation of 2: print(random.normal(loc = 1, scale = 2, size = (2,3))) #Visualization of Normal Distribution sbn.distplot(random.normal(size = 1000), hist = False) ptl.show()
9739877aaee66de669032f49e767bd7c5ce963b5
DracoMindz/holbertonschool-machine_learning
/supervised_learning/0x08-deep_cnns/1-inception_network.py
2,481
3.625
4
#!/usr/bin/env python3 """ function that builds the inception network """ import tensorflow.keras as K inception_block = __import__('0-inception_block').inception_block def inception_network(): """ Data in the shape(224, 224, 3) Convolutions inside & outside inception block use a rectified linear activation - ReLU Return: Keras Model """ init = K.initializers.he_normal(seed=None) inputData = K.Input(shape=(224, 224, 3)) netLayers = K.layers.Conv2D(filters=64, kernel_size=7, strides=2, padding='same', activation='relu', kernel_initializer=init)(inputData) netLayers = K.layers.MaxPool2D(pool_size=3, strides=2, padding='same')(netLayers) netLayers = K.layers.Conv2D(filters=64, kernel_size=1, padding='same', activation='relu', kernel_initializer=init)(netLayers) netLayers = K.layers.Conv2D(filters=192, kernel_size=3, padding='same', activation='relu', kernel_initializer=init)(netLayers) netLayers = K.layers.MaxPool2D(pool_size=3, strides=2, padding='same')(netLayers) netLayers = inception_block(netLayers, [64, 96, 128, 16, 32, 32]) netLayers = inception_block(netLayers, [128, 128, 192, 32, 96, 64]) netLayers = K.layers.MaxPool2D(pool_size=3, strides=2, padding='same')(netLayers) netLayers = inception_block(netLayers, [192, 96, 208, 16, 48, 64]) netLayers = inception_block(netLayers, [160, 112, 224, 24, 64, 64]) netLayers = inception_block(netLayers, [128, 128, 256, 24, 64, 64]) netLayers = inception_block(netLayers, [112, 144, 288, 32, 64, 64]) netLayers = inception_block(netLayers, [256, 160, 320, 32, 128, 128]) netLayers = K.layers.MaxPool2D(pool_size=3, strides=2, padding='same')(netLayers) netLayers = inception_block(netLayers, [256, 160, 320, 32, 128, 128]) netLayers = inception_block(netLayers, [384, 192, 384, 48, 128, 128]) avgPool = K.layers.AveragePooling2D(pool_size=7, strides=1)(netLayers) dropOut = K.layers.Dropout(.4)(avgPool) outData = K.layers.Dense(1000, activation='softmax', kernel_initializer=init)(dropOut) return K.Model(inputData, outData)
cf759d7d25d53209c5a5698d3d92a31a2911ca0b
ebosetalee/ds-and-algos
/doubly_linked_list/doubly_linked_list.py
2,418
4.28125
4
from linked_list.linked_list import LinkedList from node.node import Node # This is a subclass of LinkedList class DoublyLinkedList(LinkedList): def add(self, value): """ Adds the value to the end of the list :param value: the value to be added """ new_node = Node(value) if not self.head: self.head = new_node self.tail = self.head self.head.previous = None else: new_node.previous = self.tail self.tail.next = new_node self.tail = new_node def prepend(self, value): """ Adds the value to the start of the list :param value: the value to be added """ new_node = Node(value) self.head.previous = new_node new_node.next = self.head self.head = new_node def remove(self, value): """ Finds the vales and removes it :param value: the value to be removed :return: True if the value was removed, or False if the value isn't in the list """ current_node = self.head previous_node = None while current_node: if current_node.value == value: if previous_node is None: self.head = current_node.next self.head.previous = None else: if current_node == self.tail: previous_node.next = None self.tail = previous_node else: previous_node.next = current_node.next current_node = current_node.next current_node.previous = previous_node return True else: previous_node = current_node current_node = current_node.next return False def walk_reverse(self): """ Prints out all the items in the list starting from the tail to the head :rtype: collections.Iterable[Node] :returns: A reversed array of the items in the list """ elements = [] current_node = self.head while current_node: # is the same as while current_node.next != None: or is not None elements.append(current_node.value) current_node = current_node.next return elements[::-1]
606cd3eb44ffff59adffa594592baf7d9735ec4b
heartyhardy/learnin-python
/basics.py
482
3.78125
4
''' Exceptions ''' try: age = int(input("Enter your age: ")) print(age) except ValueError: print("Invalid input!") ''' Functions ''' # def square(number): # return number * number # print(square(10)) # def setName(first, last): # print(f'{first} {last}') # # Positional args - order matters # setName("Charith","Rathnayake") # # Keyword args # setName(last="Rathnayake", first="Charith") # def hello(name): # print(f'Hello {name}!') # hello("Charith")
715873045c10cbd749964b759b937aecf0a9b716
arunslb123/DataStructureAndAlgorithmicThinkingWithPython
/src/chapter04stacks/StackWithLinkedList.py
1,930
3.734375
4
# Copyright (c) Dec 22, 2014 CareerMonk Publications and others. # E-Mail : info@careermonk.com # Creation Date : 2014-01-10 06:15:46 # Last modification : 2008-10-31 # by : Narasimha Karumanchi # Book Title : Data Structures And Algorithmic Thinking With Python # Warranty : This software is provided "as is" without any # warranty; without even the implied warranty of # merchantability or fitness for a particular purpose. # Node of a Singly Linked List class Node: # constructor def __init__(self): self.data = None self.next = None # method for setting the data field of the node def setData(self, data): self.data = data # method for getting the data field of the node def getData(self): return self.data # method for setting the next field of the node def setNext(self, next): self.next = next # method for getting the next field of the node def getNext(self): return self.next # returns true if the node points to another node def hasNext(self): return self.next != None class Stack(object): def __init__(self, data=None): self.head = None if data: for data in data: self.push(data) def push(self, data): temp = Node() temp.setData(data) temp.setNext(self.head) self.head = temp def pop(self): if self.head is None: raise IndexError temp = self.head.getData() self.head = self.head.getNext() return temp def peek(self): if self.head is None: raise IndexError return self.head.getData() our_list = ["first", "second", "third", "fourth"] our_stack = Stack(our_list) print our_stack.pop() print our_stack.peek() print our_stack.pop() print our_stack.peek() print our_stack.pop()
29869fa7667649925b622ebed3625b4eadcad806
zstall/PythonProjects
/CS 2050/CS 2050 HW 2 Dictionaries.py
9,934
3.671875
4
from __future__ import print_function import unittest import math import copy ''' Description: Creating a dictionary that will assign a value to a specific key and will use linear chaining for collisions. If the dictionary exceeds 78% load it will automatically increase the dictionary size by double and rehash all values. If the user knows that the dictionary is at less than 25% load they can halve the dicationary size and rehash all the values. Author: Zachary Stall Version: 1 Help Provided: None Help Received: None ''' Trace = False class dictionary: def __init__(self, init=None): self.__limit = 10 self.__items = [[] for _ in range(self.__limit)] self.__count = 0 if init: for i in init: self.__setitem__(i[0], i[1]) def __len__(self): return self.__count def __flattened(self): return [item for inner in self.__items for item in inner] def __iter__(self): return (iter(self.__flattened())) def __str__(self): return (str(self.__flattened())) def __setitem__(self, key, value): a = [key, value] ''' percentage must be less then 75% before rehashing ''' high = .75 low = .25 percent = (self.__count / self.__limit) if percent <= high: location = abs(hash(key)) % self.__limit if len(self.__items[location]) == 0: self.__items[location].append(a) self.__count += 1 return for item in self.__items[location]: if key == item[0]: item[1] = value return else: self.__items[location].append(a) self.__count += 1 return if percent > high: self.__dblhash__(key, value) return ''' Trying to implement half hash automatically causes infinite recursion. Need to find a way to control when percentage is checked and halfing is done. For now, can only manually half hash table by calling method. if percent < low: self.__halfhash__(key, value) return ''' def __getitem__(self, key): '''Returns a integer value ''' location = abs(hash(key)) % self.__limit for item in self.__items[location]: if key == item[0]: return item[1] else: return def __contains__(self, key): ''' Returns a boolean value ''' location = abs(hash(key)) % self.__limit for item in self.__items[location]: if key == item[0]: return True return False ''' B - Level Work: Doubleing and Delete Item''' def __dblhash__(self, key, value): list_copy = copy.deepcopy(self.__items) del self.__items[:] self.__limit = self.__limit * 2 self.__items = [[] for _ in range(self.__limit)] self.__count = 0 self.__setitem__(key, value) for item in list_copy: for i in item: self.__setitem__(i[0], i[1]) return def __delitem__(self, key): location = abs(hash(key)) % self.__limit if self.__items[location] is None: return False for item in self.__items[location]: if key == item[0]: self.__items[location] = [] self.__count -= 1 return True ''' A - Level Work: Halving, Keys, and Values''' def __halfhash__(self): if (self.__count / self.__limit) >= .25: return else: list_copy = copy.deepcopy(self.__items) del self.__items[:] if self.__limit >= 1: self.__limit = self.__limit // 2 self.__items = [[] for _ in range(self.__limit)] self.__count = 0 for item in list_copy: for i in item: self.__setitem__(i[0], i[1]) def keys(self): print() print("*** Printing all keys ***") for item in self.__items: for i in item: print(i[0]) return def values(self): print() print("*** Printing all values ***") for item in self.__items: for i in item: print(i[1]) return ''' Extra Credit: Items''' def items(self): tmp = [] print() print("*** Printing/Returning a list key, value pairs as 2-tuples ***") for item in self.__items: for i in item: tmp.append(i) print(tmp) return tmp def __eq__(dicta, dictb): a = dicta.items() b = dictb.items() if a == b: print() print("The dictionaries have the same key, value pairs. Result True.") return True else: print() print("The dictionaries do not have the same key, value pairs. Result False.") return False def print(self): if Trace: print() print('*******Start Dictionary*******') print(self.__items) print(self.__count) print('********End Dictionary********') print() else: pass ''' C-level Work ''' class test_add_two(unittest.TestCase): def test(self): s = dictionary() s[1] = "one" s[2] = "two" self.assertEqual(len(s), 2) self.assertEqual(s[1], "one") self.assertEqual(s[2], "two") s.print() class test_add_twice(unittest.TestCase): def test(self): s = dictionary() s[1] = "one" s[1] = "one" self.assertEqual(len(s), 1) self.assertEqual(s[1], "one") s.print() class test_store_false(unittest.TestCase): def test(self): s = dictionary() s[1] = False self.assertTrue(1 in s) self.assertFalse(s[1]) s.print() class test_store_none(unittest.TestCase): def test(self): s = dictionary() s[1] = None self.assertTrue(1 in s) self.assertEqual(s[1], None) s.print() class test_none_key(unittest.TestCase): def test(self): s = dictionary() s[None] = 1 self.assertTrue(None in s) self.assertEqual(s[None], 1) s.print() class test_False_key(unittest.TestCase): def test(self): s = dictionary() s[False] = 1 self.assertTrue(False in s) self.assertEqual(s[False], 1) s.print() class test_collide(unittest.TestCase): def test(self): s = dictionary() s[0] = "zero" s[10] = "ten" self.assertEqual(len(s), 2) self.assertTrue(0 in s) self.assertTrue(10 in s) s.print() class test_hash(unittest.TestCase): def test(self): s = dictionary() s[1] = "one" s[2] = "two" s[3] = "three" s[4] = "four" s[5] = "five" s[6] = "six" s[12] = "twelve" s[13] = "thirteen" s[16] = "sixteen" self.assertEqual(len(s), 9) self.assertEqual(s[1], "one") self.assertEqual(s[2], "two") self.assertEqual(s[12], "twelve") s.print() class test_delete(unittest.TestCase): def test(self): s = dictionary() s[1] = "one" s[2] = "two" s[3] = "three" s.__delitem__(2) s.print() class test_halving(unittest.TestCase): def test(self): s = dictionary() s[1] = "one" s[2] = "two" s.__halfhash__() s.print() class test_deleting_halving(unittest.TestCase): def test(self): s = dictionary() s[1] = "value one" s[2] = "delete me" s[3] = "value three" s.print() s.__delitem__(2) s.__halfhash__() s.print() class test_hash_delete_halve(unittest.TestCase): def test(self): s = dictionary() s[1] = "*one" s[2] = "*two" s[3] = "*three" s[4] = "*four" s[5] = "*five" s[6] = "*six" s[12] = "*twelve" s[13] = "*thirteen" s[16] = "*sixteen" s.__delitem__(1) s.__delitem__(3) s.__delitem__(4) s.__delitem__(6) s.__delitem__(13) s.__halfhash__() self.assertEqual(len(s), 4) self.assertEqual(s[5], "*five") self.assertEqual(s[2], "*two") self.assertEqual(s[16], "*sixteen") s.print() class test_keys_values_items(unittest.TestCase): def test(self): s = dictionary() s[1] = "one" s[2] = "two" s[3] = "three" s[4] = "four" s[5] = "five" s.keys() s.values() s.items() class test_eq_True(unittest.TestCase): def test(self): s = dictionary() s[1] = "one" s[2] = "two" s[3] = "three" t = dictionary() t[1] = "one" t[2] = "two" t[3] = "three" self.assertEqual(s.__eq__(t), True) class test_eq_False(unittest.TestCase): def test(self): s = dictionary() s[1] = "one" s[2] = "two" s[3] = "threes" t = dictionary() t[1] = "one" t[2] = "two" t[3] = "three" self.assertEqual(s.__eq__(t), False) if '__main__' == __name__: unittest.main()
63207540c303a4f7329410e4ae915d38295312db
juhiiyer/scripts
/scripts/python/prog_with_mosh/num_2_word.py
438
4.3125
4
#!/usr/bin/python3.7 ''' this program converts numbers into words: ex:123 output: one two three ''' NUMBER = input('Type the number: ') VALUES = { "1" : 'One', "2" :'Two', "3" : 'Three', "4" : 'Four', "5" : "Five", "6" : 'Six', "7" : 'Seven', "8" : 'Eight', "9" : 'Nine', "0" : 'Zero' } NUM_LEN = len(NUMBER) for i in NUMBER: if i in VALUES: print(VALUES[i]) NUM_LEN = NUM_LEN - 1
49f194be65b08f98683ec2e7e73e1e6f801649ec
abhinavsoni2601/experiment
/day 2/list_oddandeven.py
170
3.703125
4
# -*- coding: utf-8 -*- """ Created on Wed May 8 16:47:45 2019 @author: Gourav """ list1=list(range(0,21)) print(list1[::2]) list2=list(range(1,21)) print(list2[::2])
596dc381edc674847d0fc75952fdcb09c78026fa
rrbaetge/Prac_05
/five_numbers.py
479
4.03125
4
def main(): numbers = [] while len (numbers) != 5 : user_num = int(input("Enter a number")) numbers.append(user_num) print("The first number is {} ".format(numbers[0])) print("The last number is {} " .format(numbers[-1])) print("The smallest number is {} ".format(min(numbers))) print("The largest number is {} ".format(max(numbers))) numbers.sort() mean = sum(numbers) / 5 print("The average {} ".format(mean)) main()
3c977064d1c626ae50dc70e5d42882ccce393b6b
jagannara/Dijkstra-Shortest-Path-Algorithm
/shortest_path.py
3,656
4.21875
4
# References: # 1. https://www.pythonpool.com/dijkstras-algorithm-python/ # 2. http://nmamano.com/blog/dijkstra/dijkstra.html # 3. https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm # 4. http://semanticgeek.com/graph/exploring-dijkstras-shortest-path-algorithm/ def shortest_path(graph, source, target): # `graph` is an object that provides a get_neighbors(node) method that returns # a list of (node, weight) edges. both of your graph implementations should be # valid inputs. you may assume that the input graph is connected, and that all # edges in the graph have positive edge weights. # # `source` and `target` are both nodes in the input graph. you may assume that # at least one path exists from the source node to the target node. # # this method should return a tuple that looks like # ([`source`, ..., `target`], `length`), where the first element is a list of # nodes representing the shortest path from the source to the target (in # order) and the second element is the length of that path # To keep track of the shortest paths to reach each node with a dict of the form dict[node] = shortest path shortest_paths = {source: 0} # To keep track of all the nodes visited visited = [] # To keep track of the previous node visited previous_node = {} while target not in visited: # Keeping track of nodes that need to be visited unvisited = {} for node in shortest_paths: if node not in visited: unvisited[node] = shortest_paths[node] # In the case that there is no shortest path, return message if not unvisited: return "No Possible Solution" # Select the node among the unvisited notes with the shortest path as the current node current_node = min(unvisited.items(), key=lambda x: x[1])[0] current_node_weight = shortest_paths[current_node] # Get neighbors of the current node (using get_neighbors meethod from the previous question) neighbors = graph.get_neighbors(current_node) # If neighbors are not null: if neighbors: for n in neighbors: neighbor = n[0] neighbor_weight = n[1] new_weight = neighbor_weight + current_node_weight if neighbor not in shortest_paths: shortest_paths[neighbor] = new_weight previous_node[neighbor] = current_node else: prior_weight = shortest_paths[neighbor] # If the new weight is less than the prior documented weight, then update the weight if new_weight < prior_weight: shortest_paths[neighbor] = new_weight previous_node[neighbor] = current_node # Keeping track of the visited nodes: visited.append(current_node) # To find the nodes traversed in the shortest path: # Start with the target node and add it to the path start = target path = [target] while previous_node[start] != source: # Look up the value of the start variable and add it to the path path.append(previous_node[start]) # path.insert(0, previous_node[start]) # Use the value of the start variable as the new key start = previous_node[start] # Add source node path.append(source) # Reverse the order of the path (from backward to forward) path.reverse() # Find shortest path length between the start and target nodes: length = shortest_paths[target] return (path, length)
626ec234ff484f1232ee2fcbd806941403dc1ea6
Sedge77/Proyecto1Compi1
/Token.py
666
3.609375
4
class Token(): def __init__(self,Tipo,caracter): #Constructor de la clase animal self.Tipo=Tipo #usamos la notacion __ por que lo estamos encapsulando, ninguna subclase puede acceder a el, es un atributo privado self.caracter=caracter def setTipo(self,Tipo): self.__Tipo=Tipo def getTipo(self): return self.__Tipo def setcaracter(self,caracter): self.__caracter=caracter def getcaracter(self): return self.caracter def miestado(self): print("Tipo: ",self.__Tipo,"--------->"+"Token: ",self.__caracter)
4f051ce5e2e306ff1f6169e65699e3541dace60e
aecanales/ayudantia-arduino-pv
/Ejemplos/Comunicación Serial/1 - Leer Arduino desde Python/ejemplo_1.py
923
3.515625
4
# Ayudantia Arduino: Comunicación Serial # IDI1015 - Pensamiento Visual @ PUC # Alonso Canales(aecanales@uc.cl) # # Ejemplo 1: Leer Arduino desde Python # Importamos la libreria serial para poder comunicarnos con una placa Arduino. import serial # Creamos la conexión con la placa. Debemos tener en cuenta: # 1- El puerto COM debe corresponde a dónde está conectado nuestra placa. # Se puede revisar en la IDE de Arduino. # 2- La velocidad (9600) debe ser la MISMA que en el código Arduino. arduino = serial.Serial("COM11", 9600, timeout=.1) # Usamos la sentencia while True para crear un loop infinito. while True: # Leemos una línea del Arduino y la decodificamos. lectura = arduino.readline().decode('utf-8') # Si no hay nada que leer, la función anterior retornará un string vacio. # Por lo tanto, sólo imprimiremos la lectura cuando tenga algun contenido if lectura != '': print(lectura)
85c3b7c0853df5df5e2508c63b59dddd1c36e0f5
estraviz/codewars
/7_kyu/Case-sensitive/case_sensitive.py
114
3.5625
4
""" Case-sensitive! """ def case_sensitive(s): return [not s or s.islower(), [c for c in s if c.isupper()]]
625cd34b79eb4b6567069c410fe464aed7b2ee83
nirmalnishant645/LeetCode
/0560-Subarray-Sum-Equals-K.py
713
3.703125
4
''' Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 Note: The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. ''' class Solution: def subarraySum(self, nums: List[int], k: int) -> int: count = summ = 0 d = {0 : 1} for i in range(len(nums)): summ += nums[i] if summ - k in d: count += d[summ - k] if summ not in d: d[summ] = 1 else: d[summ] += 1 return count
5e293c6df293e544ede8939d4e03017bb892f045
AdamZhouSE/pythonHomework
/Code/CodeRecords/2340/60634/243447.py
604
3.515625
4
problems = int(input()) for x in range(problems): size = int(input()) array = input().split(" ") water = [0 for x in range(size)] volum = 0 wall = int(array[0]) i = 0 while i < size: array[i] = int(array[i]) if array[i] > wall: wall = array[i] water[i] = wall i += 1 wall = array[size-1] i = size - 1 while i >= 0: if array[i] > wall: wall = array[i] if water[i] > wall: water[i] = wall volum += (water[i] - array[i]) i -= 1 print(volum)
8c97254ac84722342a66b6c713c03450c69ecc1d
ashwin015/Ashwin
/69.py
121
3.921875
4
a = int(input("enter the num")) b = int(input("enter the num")) c=b-a if(c%2==0): print "even" else: print "odd"
33110ef7e47f689eb6b203b8962f8edd27238d73
AndreyLyamtsev/python
/dz1-1.py
2,403
4.3125
4
month = int(input("Введите месяц: ")) day = int(input("Введите день: ")) if month == 1 and 1 <= day <= 20: print("Ваш знак зодиака Козерог") elif month == 12 and 23 <= day < 31: print("Ваш знак зодиака Козерог") elif month == 1 and 21 <= day <= 31: print("Ваш знак зодиака Водолей") elif month == 2 and 1 <= day <= 19: print("Ваш знак зодиака: Водолей") elif month == 2 and 1 <= day <= 20: print("Ваш знак зодиака: Рыбы") elif month == 3 and 1 <= day <= 20: print("Ваш знак зодиака: Рыбы") elif month == 3 and 21 <= day <= 31: print("Ваш знак зодиака: Овен") elif month == 4 and 1 <= day <= 20: print("Ваш знак зодиака: Овен") elif month == 4 and 21 <= day <= 30: print("Ваш знак зодиака: Телец") elif month == 5 and 1 <= day <= 21: print("Ваш знак зодиака: Телец") elif month == 5 and 22 <= day <= 31: print("Ваш знак зодиака: Близнецы") elif month == 6 and 1 <= day <= 21: print("Ваш знак зодиака: Близнецы") elif month == 6 and 22 <= day <= 30: print("Ваш знак зодиака: Рак") elif month == 7 and 1 <= day <= 22: print("Ваш знак зодиака: Рак") elif month == 7 and 23 <= day <= 31: print("Ваш знак зодиака: Лев") elif month == 8 and 1 <= day <= 23: print("Ваш знак зодиака: Лев") elif month == 8 and 24 <= day <= 31: print("Ваш знак зодиака: Дева") elif month == 9 and 1 <= day <= 23: print("Ваш знак зодиака: Дева") elif month == 9 and 24 <= day <= 30: print("Ваш знак зодиака: Весы") elif month == 10 and 1 <= day <= 23: print("Ваш знак зодиака: Весы") elif month == 10 and 24 <= day <= 31: print("Ваш знак зодиака: Скорпион") elif month == 11 and 1 <= day <= 22: print("Ваш знак зодиака: Скорпион") elif month == 11 and 23 <= day <= 30: print("Ваш знак зодиака: Стрелец") elif month == 12 and 1 <= day <= 22: print("Ваш знак зодиака: Стрелец") else: print("Введены некорректные данные")
b01fd82aa1b888bf5514a2b3efbb84490ae68942
projeto-de-algoritmos/D-C_soulmate
/inversion_counter.py
858
3.671875
4
def mergeSort(alist): count = 0 leftcount = 0 rightcount = 0 blist = [] if len(alist) > 1: mid = len(alist) // 2 lefthalf = alist[:mid] righthalf = alist[mid:] leftcount, lefthalf = mergeSort(lefthalf) rightcount, righthalf = mergeSort(righthalf) i = 0 j = 0 while i < len(lefthalf) and j < len(righthalf): if lefthalf[i] < righthalf[j]: blist.append(lefthalf[i]) i += 1 else: blist.append(righthalf[j]) j += 1 count += len(lefthalf[i:]) while i < len(lefthalf): blist.append(lefthalf[i]) i += 1 while j < len(righthalf): blist.append(righthalf[j]) j += 1 else: blist = alist[:] return count + leftcount + rightcount, blist
13216620aa37bf105aedf32e4fda5aefb323211b
Kaiduev/Task2
/task2/Циклические алгоритмы/Armstrong_numbers.py
113
3.546875
4
for x in range(100, 1000): a = 0 for d in str(x): a+= int(d) ** 3 if a == x: print(x)
0c56f4b96031322cda4055c329aee7acfd0a6e61
taritro98/DSA_Prac
/missing_element.py
202
3.546875
4
def missing_num(lst,n): sum_n = (n*(n+1))//2 return sum_n - sum(lst) for _ in range(int(input())): n = int(input()) lst = [int(i) for i in input().split()] print(missing_num(lst,n))
c589f17fb1f99a6de9b5d0500ef2962b66e9e1ee
SRD2705/Python-Projects
/Live location of ISS(International Space Station).py
922
3.765625
4
################################## Live location of ISS(International Space Station) ######################## ''' In this python program we plot the live location of the ISS using an API Detail explanation in in the program ''' import pandas as pd # import panda for data exploration and customization import plotly.express as px # import plotly for plotting in a map url = 'http://api.open-notify.org/iss-now.json' # We use this API for get the live location of the ISS df = pd.read_json(url) # print(df) df['latitude'] = df.loc['latitude','iss_position'] # Making different data row df['longitude'] = df.loc['longitude','iss_position'] df.reset_index(inplace=True) df = df.drop(['index','message'], axis = 1) # We drop those which we do not need to plot # print(df) fig = px.scatter_geo(df,lat='latitude',lon='longitude') # Plotting the location in the map fig.show() #Showing the map
19493c89d2d7217ed7f7f169bb57d9d18da46fd1
manthan-98/CodeRepository
/DIce Rolling.py
384
3.96875
4
import random dice = random.randint(1,6) print(dice) i = 0 while i<1: roll = input('Do you like to roll the dice again\n For YES type Y\n For NO tpye N\n>').upper() if roll == 'Y': dice = random.randint(1, 6) print(dice) elif roll !='Y' and roll !='N': print('Not Valid') elif roll == 'N': break else: i += 1
3b6a5183db434c163878a916c494e2ab477a7990
Freshman23/algorithms_and_data_structures
/lesson_2/les_2_task_5.py
529
4.21875
4
"""5. Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно. Вывод выполнить в табличной форме: по десять пар «код-символ» в каждой строке.""" table = '' for code in range(32, 128): if (code - 1) % 10 == 0: table += f'{code:3}: {chr(code)}\n' else: table += f'{code:3}: {chr(code)} ' print(table)
2904eda811196e2c038fed37c110a8f5201f83cd
JZolko/Terminal_Solitaire
/Aces_High_Solitaire.py
10,954
4.21875
4
""" This program is based off a variant of traditional solitaire called Aces Up. The user starts out with 4 cards and can either move within the tableau, move to foundation or have more cards dealt to the tableau. The game can only be won once all colums are aces and have a length of 1. """ import cards # required !!! RULES = ''' Aces High Card Game: Tableau columns are numbered 1,2,3,4. Only the card at the bottom of a Tableau column can be moved. A card can be moved to the Foundation only if a higher ranked card of the same suit is at the bottom of another Tableau column. To win, all cards except aces must be in the Foundation.''' MENU = ''' Input options: D: Deal to the Tableau (one card on each column). F x: Move card from Tableau column x to the Foundation. T x y: Move card from Tableau column x to empty Tableau column y. R: Restart the game (after shuffling) H: Display the menu of choices Q: Quit the game ''' def init_game(): ''' This function creates a shuffled deck, a list of 4 cards, each with a length of 1, a foundation, which is an empty list ''' foundation, tableau = [], [] d = cards.Deck() # uses the imported class d.shuffle # shuffles the deck stock = d for i in range(4): # adds cards to the list tableau.append([stock.deal()]) return (stock, tableau, foundation) # stub so that the skeleton compiles; delete # and replace it with your code def deal_to_tableau( stock, tableau ): ''' This function adds a card to each column in the tableau ''' for i in range(4): tableau[i].append(stock.deal()) def display( stock, tableau, foundation ): '''Display the stock, tableau, and foundation.''' print("\n{:<8s}{:^13s}{:s}".format( "stock", "tableau", " foundation")) # determine the number of rows to be printed -- determined by the most # cards in any tableau column max_rows = 0 for col in tableau: if len(col) > max_rows: max_rows = len(col) for i in range(max_rows): # display stock (only in first row) if i == 0: display_char = "" if stock.is_empty() else "XX" print("{:<8s}".format(display_char),end='') else: print("{:<8s}".format(""),end='') # display tableau for col in tableau: if len(col) <= i: print("{:4s}".format(''), end='') else: print("{:4s}".format( str(col[i]) ), end='' ) # display foundation (only in first row) if i == 0: if len(foundation) != 0: print(" {}".format(foundation[-1]), end='') print() def get_option(): ''' This function prompts the user for an input with correct formatting based on the first item entered ''' acceptable = ['D','F','T','R','H','Q'] # the okay inputs sing_accept = ['D','R','H','Q'] # the okay inputs that only expect one char opt = input("\nInput an option (DFTRHQ): ") opt = opt.strip() # strips any spacing lst = opt.split() # splits at the spacing lst[0] = lst[0].upper() # capitalizes the first letter #print(lst[0]) if not opt or (lst[0] in sing_accept and len(lst) != 1): # if the list is longer than one or its a wrong letter print("Error in option: ", *lst) return None if lst[0] not in acceptable: # if its the wrong letter print("Error in option: ", *lst) return None if lst[0] == 'F' and ((len(lst) != (2)) or (len(lst) == 2\ and not(lst[1].isdigit()))): # if its not F and 2 ints print("Error in option: ", *lst) return None elif lst[0] == 'F' and len(lst) == (2) and lst[1].isdigit(): # if the input is correct return lst if lst[0] == 'T' and (len(lst) != 3 or len(lst) == 3 and\ not(lst[1].isdigit()) or not(lst[2].isdigit())): # if its T and doesnt have 2 ints print("Error in option: ", *lst) return None elif lst[0] == 'T' and len(lst) == 3: # if its the correct input return lst return lst #return final # stub; delete and replace with your code def validate_move_to_foundation( tableau, from_col ): ''' This function checks to see if the card can actually be moved to the foundation by looking at the suits and ranks of other cards in the tableau ''' mov = 0 if from_col < 1 or from_col > 4: print("Error, cannot move {}.".format(from_col)) return False from_col -= 1 try: tableau[from_col][-1] for i in range(4): # goes through the last card in all the columns if tableau[i]: if tableau[i][-1].rank() > tableau[from_col][-1].rank()\ and tableau[i][-1].suit() == tableau[from_col][-1].suit()\ and tableau[from_col][-1].rank() != 1 and i != from_col: # if theres a larger card of the same suit mov += 1 if tableau[i][-1].rank() == 1 and tableau[from_col][-1].rank() != 1\ and tableau[from_col][-1].suit() == tableau[i][-1].suit(): # if the card is an ace and of the same suit mov += 1 if mov == 0: # if there arent any moves available print("Error, cannot move {}.".format(tableau[from_col][-1])) return False else: # if you can move it return True except: print("Error, empty column:") return False #return False # stub; delete and replace it with your code def move_to_foundation( tableau, foundation, from_col ): ''' This function moves the movable card from the tableau to the foundation ''' valid = validate_move_to_foundation(tableau, from_col) if valid: # if the card is movable from_col -= 1 move = tableau[from_col].pop() # removes from tableau foundation.append(move) # adds to foundation def validate_move_within_tableau( tableau, from_col, to_col ): ''' This function checks to see if a card can be moved within the tableau A card can only be moved to an empty column ''' mov = 0 if from_col < 1 or from_col > 4: # if the input is out of the column range print("Invalid move") return False from_col -= 1 if to_col < 1 or to_col > 4: print("Invalid move") return False to_col -= 1 try: if not(tableau[to_col]) and tableau[from_col][-1]: # if the to column is empty and the from column isnt mov += 1 if mov > 0: return True else: print("Invalid move") return False except: print("Invalid move") return False def move_within_tableau( tableau, from_col, to_col ): ''' This function moves a card from one column to another within the tableau ''' valid = validate_move_within_tableau(tableau, from_col, to_col) from_col -= 1 to_col -= 1 if valid: # if the move is valid mov = tableau[from_col].pop() # takes it from the from column tableau[to_col].append(mov) # adds it to the to column def check_for_win( stock, tableau ): ''' This function checks to see if the user has won the game. They can only take the W if each column only contains one ace and the stock has to be empty ''' w = 0 try: for i in range(len(tableau)): # goes through each column and checks for aces if tableau[i][0].rank() == 1 and len(tableau[i]) == 1 and not(stock): w += 1 # if the column only has an ace except: return False if w == 4: # if the former condition is true for all columns return True else: return False def main(): ''' This is what the user interacts with * where the magic happens * The user is given a menu and some rules to try and win the game ''' stock, tableau, foundation = init_game() acceptable = ['D','F','T','R','H','Q'] # the good inputs print( MENU ) display( stock, tableau, foundation ) # displays the stock tableau and foundation #init_game() while True: opt = get_option() # gets an input from the user #print(opt) try: opt[0] while opt[0] not in acceptable: # if the input is invalid opt = get_option() except: # if the inout is empty while opt == None: print('Invalid option.') display( stock, tableau, foundation) opt = get_option() # Your code goes here if opt[0] == 'D' and stock: # this deals to the tableau for i in range(4): tableau[i].append(stock.deal()) elif opt[0] == 'F': # move to foundation move_to_foundation( tableau, foundation, int(opt[1])) # calls move function #print(foundation, '\n', tableau) elif opt[0] == 'T': # move within tableau move_within_tableau( tableau, int(opt[1]), int(opt[2]) ) # calls move function elif opt[0] == 'R': # resets the tableau and foundation for item in tableau: # delets everything in tableau item.pop() for item in foundation: # deletes everything in foundation item.pop() print("=========== Restarting: new game ============") print( RULES ) print( MENU ) stock = cards.Deck() stock.shuffle() stock, tableau, foundation = init_game() # restarts the whole deck, tableau, and foundation elif opt[0] == 'H': # prints the menu print(MENU) elif opt[0] == 'Q': # quits and breaks print("You have chosen to quit.") break w = check_for_win( stock, tableau ) # checks for win after every move if not w: # displays only if theres not a W display( stock, tableau, foundation) if w: # if the user wins print("You won!") break if __name__ == "__main__": main()
8995743cb3d0d382f69092eb9275509a8def8bff
PRKKILLER/Algorithm_Practice
/Company-OA/Robinhood/BlackWhiteMatrix.py
1,575
4.0625
4
""" You are given a rectangular matrix "numbers" consisting positive integers, where cells are colored in the black and white Your task is to sort the numbers on the chess board according to a set of queries. each element of the query is [x,y,w], representing a w*w submatrix with its upper-left corner at (x,y) on the "numbers" matrix For each query, sort the number within the submatrix separately: 1. sort all the numbers on black squares within the submatrix in their relative order of ascending value 2. sort all the numbers on white squares within the submatrix in their relative order of ascending value 3. "numbers" should be re-arranged within the submatrix such that each number ends up on the same color square that it started on. Return "numbers" matrix after processing all the queries on it 注: 黑色方块的位置满足: (i+j) % 2 == 0; 白色方块的位置满足: (i+j) % 2 == 1 """ import heapq as hq def solution(matrix, queries): for q in queries: s_i, s_j = q[0], q[1] w = q[2] black, white = [], [] for i in range(s_i, s_i + w): for j in range(s_j, s_j + w): if (i + j) % 2 == 0: hq.heappush(black, matrix[i][j]) else: hq.heappush(white, matrix[i][j]) for i in range(s_i, s_i + w): for j in range(s_j, s_j + w): if (i + j) % 2 == 0: matrix[i][j] = hq.heappop(black) else: matrix[i][j] = hq.heappop(white) return matrix
7ef43a9bf278ab4f2f967c0f92c464af374ca59b
jjloftin/cs303e
/CreditCard.py
2,620
4.28125
4
# File: CreditCard.py # Description: Assignment 5. Write a program that determines whether or not it's valid and if it is valid if it is a MasterCard, Discover, Visa, # or American Express credit card # Student Name: Johnathn Loftin # Student UT EID: jjl2328 # Course Name: CS 303E # Unique Number: 90110 # Date Created: July 18th, 2014 # Date Last Modified: July 18th, 2014 #define a function to check the number of digits. Returns true if input is 15 or 16 digits long. def DigitChecker(cc_num): if((len(str(cc_num)) == 15) or (len(str(cc_num)) == 16)): return True else: return False #assuming input has valid number of digits, apply Luhn's test to the number and check its validity. def is_valid(cc_num): cc_digits = [] len_num = len(str(cc_num)) for i in range (len_num): cc_digits.append(cc_num % 10) cc_num = cc_num // 10 #double the odd digits and then take the sum of the digits of the odd digits for i in range (1, len_num, 2): cc_digits[i] = (cc_digits[i] * 2) % 10 + (cc_digits[i] * 2) // 10 sum_all_digits = 0 for i in range(len_num): sum_all_digits += cc_digits[i] if (sum_all_digits % 10 == 0): return True else: return False #determine and return the credit card type. def cc_type(cc_num): cc_digits = [] len_num = len(str(cc_num)) for i in range (len_num): cc_digits.append(cc_num % 10) cc_num = cc_num // 10 #flip the digits so they read left to right as entered by user for i in range (len_num // 2): cc_digits[i], cc_digits[len_num - 1 - i] = cc_digits[len_num - 1 - i], cc_digits[i] #print(cc_digits) if (cc_digits[0] == 3 and ((cc_digits[1] == 4) or (cc_digits[1] == 7))): return 'American Express ' elif (cc_digits[0] == 6): if((cc_digits[1] == 0) and (cc_digits[2] == 1) and (cc_digits[3] == 1)): return 'Discover ' elif((cc_digits[1] == cc_digits[2]) and (cc_digits[1] == 4)): return 'Discover ' elif((cc_digits[1] == 5)): return 'Discover ' elif(cc_digits[0] == 5 and cc_digits[1] <= 5): return 'MasterCard ' elif(cc_digits[0] == 4): return 'Visa ' else: return '' #prompt user to enter a credit card number and check it for validity and type of card def main(): cc_num = int(input('Enter a 15 or 16 digit number: ')) #check number of digits if(not DigitChecker(cc_num)): print('Not a 15 or 16-digit number.') return '' if(is_valid(cc_num)): print('Valid ' + cc_type(cc_num) + 'credit card number') else: print('Invalid credit card number') main()
42a52002b1984a302ea71122cb2d6ccf1dc551e5
zhuxinkai/python3-book-practice
/beginning-python-3ed-master/Chapter11/listing11-6.py
1,315
3.75
4
''' 要确保文件得以关闭,可使用一条try/finally语句,并在finally子句中调用close。 # 在这里打开文件 try: # 将数据写入到文件中 finally: file.close() 实际上,有一条专门为此设计的语句,那就是with语句。 with open("somefile.txt") as somefile: do_something(somefile) with语句让你能够打开文件并将其赋给一个变量(这里是somefile)。在语句体中,你将数据 写入文件(还可能做其他事情)。到达该语句末尾时,将自动关闭文件,即便出现异常亦如此。 ''' def process(string): print('Processing:',string) with open('listing11-5.txt') as f: char = f.read(1) while char: process(char) char = f.read(1) print('--------------------------------------------------------------------------') print('# 使用readline() 迭代行') with open ('listing11-5.txt') as f2: while True: chars = f2.readline() if not chars:break # 当 chars 变为空时,chars 为假时,not chars 为真。 print(chars) print('--------------------------------------------------------------------------') print('# 使用readlines() 迭代行') # 使用readlines 迭代行 with open ('listing11-5.txt') as f3: for line in f3.readlines(): print(line)
1262837e04c8bafaed9476233974c418789247cf
luangcp/Python_Basico_ao_Avancado
/loop_for.py
2,302
4.625
5
""" Estruturas de repetição Loop for Loop -> é uma estrutura de repetição for -> Uma dessas estruturas (para) #Python for item in interavel: //Esecução do loop Utilizamos loops para iterar sobre sequencias ou sobre valores iteraveis Exemplos de iteraveis: - String nome= 'Luan' - List = [1, 3, 5, 7, 9] - Range numeros = range(1, 10) """ # -*- coding: UTF-8 -*- nome = 'Luan' lista = [1, 3, 4, 6, 9] numeros = range(1, 10) # Temos que transformar em uma lista # Exemplo de for 1 (Iterando sobre uma string) for letra in nome: print(letra) print('\n') # Exemplo de for 2 (iterando sobre uma lista) for numero in lista: print(numero) # Exemplo de for 3 (Iterando sobre um range) """ range(valor_inicial, valor_final) Obs: o valor final não é incluso ex: se for de 1 a 10 o 10 não vai outra forma de falar é que vai ate o valor final -1 """ for numero in range(1, 10): print(numero) # -------------------------------------------------- print('\n') """ Enumerate: ((0, 'L'), (1, 'u'), (2, 'a'), (3, 'n)) """ for i, v in enumerate(nome): print(nome[i]) print('\n') # Outro jeito: for indice, letra in enumerate(nome): print(letra) print('\n') # Outro jeito: for _, letra in enumerate(nome): print(letra) print('\n') # OBS: Quando não precisamos de um valor, podemos descartá-lo utilizando um underline(_) for valor in enumerate(nome): print(valor[1]) # -------------------------------------------------- # Também pode ser usado assim print('\n') qtd = int(input('Quantas vezes esse loop deve rodar?')) soma = 0 for n in range(1, qtd+1): num = int(input(f'Informe o {n}° de {qtd} valores: ')) soma = soma + num print(f'A soma é {soma}') # ---------------------------------------------------- nome = 'Atletico' for letra in nome: print(letra) # Como fazer pra imprimir td numa letra só?? # É so fazer assim: print(letra, end='') # Coisas legais: # Tabela de emojis: # https://apps.timwhitlock.info/emoji/tables/unicode # Como usar: # exemplo: # Original : U+1F60B # Modificado = U0001f60B for x in range(3): for num in range(1, 11): print('\U0001f60B' * num) # Outro emoji # Original: U+1F60D # Modificado: U0001F60D for x in range(3): for num in range(1, 11): print('\U0001F60D' * num)
bbe30bf41d54d72f00b97ef85cda1c15357dddd3
jsneed/TheModernPython3Bootcamp
/Section-034/exercise-349.py
896
3.859375
4
''' Write a function called parse_bytes that accepts a single string. It should return a list of the binary bytes contained in the string. Each byte is just a combination of eight 1's or 0's. For example: parse_bytes("11010101 101 323") # ['11010101'] parse_bytes("my data is: 10101010 11100010") # ['10101010', '11100010'] parse_bytes("asdsa") # [] Hints: take advantage of \b Not all bytes will have a space before and after, some come at the beginning of a file or at the end. Use findall! ''' # don't forget to import re import re # define parse_bytes below: def parse_bytes(msg): byte_re = re.compile(r'\b[01]{8}\b') return byte_re.findall(msg) print(parse_bytes("11010101 101 323")) # ['11010101'] print(parse_bytes("my data is: 10101010 11100010")) # ['10101010', '11100010'] print(parse_bytes("asdsa")) # []
3b9f7f8a58a7cafc886c24241804feab19d2e697
kaustubhhiware/hiPy
/think_python/dictionary.py
1,200
3.734375
4
def invert_dict(d): inverse = dict() for key in d: val = d[key] if val not in inverse: inverse[val] = key else: inverse[val].append(key) return inverse def invert_dict_imp(d): inverse = {} for key, val in d.iteritems(): inverse.setdefault(val, []).append(key)#just like histogram from wordabulary return inverse #moved here from Wordabulary as not dictionary ready def reverse_lookup(d,val): """ build a list of k's search k s.t d[k] = val """ listed = [] for k in d: if d[k]==val: listed.append(k) return listed eng2sp = dict() print 'Empty dictionary : ',eng2sp eng2sp['one']='uno' print '\nSingle element : ',eng2sp eng2sp = {'one':'uno','two':'dos','three':'tres'} print '\neng2sp = {\'one\':\'uno\',\'two\':\'dos\',\'three\':\'tres\'}' print eng2sp print 'Arranged arbitrarily ,each time in #table' print '\nlength of dict : ',len(eng2sp) print 'searching key : ' print 'one in eng2sp :','one' in eng2sp print 'uno in eng2sp : ','uno' in eng2sp print '\nsearching value : ' vals = eng2sp.values() print 'one in eng2sp :','one' in vals print 'uno in eng2sp : ','uno' in vals duply = eng2sp print 'inverting dicts : ',invert_dict_imp(duply)
1d6e45ffafc23e9f43b66861ae6ffd1dd6f2592d
maa-targino/Python-Course
/Mundo_01/Desafios/desafio024.py
349
3.828125
4
print('ENCONTRA SANTO\n') cidade = input('Entre com o nome da sua cidade: ') santo = cidade.count('Santo',0,5) santa = cidade.count('Santa',0,5) sao = cidade.count('São',0,3) if santo == 1 or santa == 1 or sao == 1: print('Sua cidade é santa!!!') elif santo == 0 and santa == 0 and sao == 0: print('Sinto muito, sua cidade não é santa.')
a644940b1948a83ceb14afb8c1adfa2cea5f8669
MoralistFestus/10days20projects-python
/Day 9/free-pdf/textfile_to_pdf.py
475
3.8125
4
# Python program to convert # text file to pdf file from fpdf import FPDF # save FPDF() class into # a variable pdf pdf = FPDF() # Add a page pdf.add_page() # set style and size of font # that you want in the pdf pdf.set_font("Arial", size = 15) # open the text file in read mode f = open("file.txt", "r") # insert the texts in pdf for x in f: pdf.cell(200, 10, txt = x, ln = 1, align = 'C') # save the pdf with name .pdf pdf.output("program.pdf")
e7a64a7591e9c2c55e29186b9b74cf9d7fb8b59f
ridersw/Karumanchi--Data-Structures
/regularTree.py
1,274
3.734375
4
class TreeNode: def __init__(self, data): self.data = data self.children = [] self.parent = None def addChild(self, child): child.parent = self self.children.append(child) def getLevel(self): level = 0 p = self.parent while p: level += 1 p = p.parent return level def printTree(self): spaces = ' ' * self.getLevel() * 3 prefix = spaces + '|--' if self.parent else "" print(prefix + self.data) if self.children: for child in self.children: child.printTree() def buildProductTree(): root = TreeNode("Electronics") laptop = TreeNode("Laptop") laptop.addChild(TreeNode("Asus")) laptop.addChild(TreeNode("Macbook Pro")) laptop.addChild(TreeNode("Macbook Air")) mobile = TreeNode("Mobile") mobile.addChild(TreeNode("OnePlus")) mobile.addChild(TreeNode("iPhone")) mobile.addChild(TreeNode("Samsung")) headphones = TreeNode("Head Phones") headphones.addChild(TreeNode("Jabra")) headphones.addChild(TreeNode("Airpods")) headphones.addChild(TreeNode("Xaomi")) root.addChild(laptop) root.addChild(mobile) root.addChild(headphones) return root if __name__ == "__main__": root = buildProductTree() root.printTree() #print("Tree: ", root.data)
c3f75b77c5d4644bcf0c8c71de08b4bdb9dc2218
bpicnbnk/bpicnbnk.github.io
/array/451_frequencySort.py
294
3.640625
4
class Solution: def frequencySort(self, s: str) -> str: from collections import Counter c = Counter(s) s = '' for (key, num) in c.most_common(): s += key*num return s s = Solution() ss = "foo" result = s.frequencySort(ss) print(result)
f34a0c9c105b802e33f02f42a81daa63b2532332
jackd/util3d
/voxel/brle.py
5,672
4.0625
4
""" Binary run-length encoding (BRLE) utilities. Binary run length encodings are similar to run-length encodings (RLE) but encode lists of values that can only be true or false. As such, the RLE can be effectively halved by not saving the value of each run. e.g. [0, 0, 1, 1, 1, 0, 0, 1, 0] would have a BRLE of [2, 3, 2, 1, 1] For simplicity, we require all BRLEs to be of even length. If a sequence ends in a False, it must be padded with an additional zero. Like RLEs the encoding is stored as uint8s. This means runs of length greater than 255 must be stored with intermediate zeros, e.g. 300 zeros would be represented by [255, 0, 45] First value is START_VALUE == False """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np START_VALUE = False _ft = np.array([False, True], dtype=np.bool) _2550 = np.array([255, 0], dtype=np.uint8) def brle_to_dense(brle_data): if not isinstance(brle_data, np.ndarray): brle_data = np.array(brle_data, dtype=np.uint8) ft = np.repeat(_ft[np.newaxis, :], len(brle_data) // 2, axis=0).flatten() return np.repeat(ft, brle_data).flatten() def zeros(length): data = np.empty((length // 255 + 1, 2), dtype=np.uint8) data[:-1, 0] = 255 data[-1, 0] = length % 255 data[:, 1] = 0 return data.flatten() def ones(length): data = np.empty((length // 255 + 1, 2), dtype=np.uint8) data[:-1, 1] = 255 data[-1, 1] = length % 255 data[:, 0] = 0 return data.flatten() def _empty_padded(n): if n % 2 == 0: # return np.zeros((n,), dtype=np.uint8) return np.empty((n,), dtype=np.uint8) else: # x = np.zeros((n+1,), dtype=np.uint8) x = np.empty((n+1,), dtype=np.uint8) x[-1] = 0 return x def dense_to_brle(dense_data): if dense_data.dtype != np.bool: raise ValueError('dense_data must be bool') n = len(dense_data) starts = np.r_[0, np.flatnonzero(dense_data[1:] != dense_data[:-1]) + 1] lengths = np.diff(np.r_[starts, n]) return start_and_lengths_to_brle(dense_data[0], lengths) def start_and_lengths_to_brle(start_value, lengths): nl = len(lengths) bad_length_indices = np.where(lengths > 255) bad_lengths = lengths[bad_length_indices] nl += 2*np.sum(bad_lengths // 255) if start_value: i = 1 out = _empty_padded(nl+1) out[0] = 0 else: i = 0 out = _empty_padded(nl) for length in lengths: nf = length // 255 nr = length % 255 out[i:i + 2*nf] = np.repeat(_2550, nf) i += 2*nf out[i] = nr i += 1 return out def rle_to_brle(rle_data): from .rle import split_rle_data values, counts = split_rle_data(rle_data) repeated = values[1:] == values[:-1] out_length = len(values) + np.count_nonzero(repeated) v0 = values[0] if v0 == 1: out_length += 1 out = _empty_padded(out_length) out[0] = 0 i = 1 else: i = 0 out = _empty_padded(out_length) out[i] = counts[0] i += 1 for count, rep in zip(counts[1:], repeated): if rep: out[i:i+2] = (0, count) i += 2 else: out[i] = count i += 1 assert(i == out_length) # start = 0 # end = 10 # print(rle_data[start:end]) # print(out[start:end]) # exit() return out def brle_to_rle(brle_data): data = np.repeat(_ft, np.reshape(brle_data, (-1, 2))) # remove empty runs data = data[data[:, 1] > 0] return data.flatten() def length(brle_data): return np.sum(brle_data) def reduce_brle_sum(brle_data): return np.sum(brle_data[1::2]) def brle_to_sparse(brle_data, dtype=np.int32): cs = np.cumsum(brle_data) starts = cs[::2] ends = cs[1::2] return np.concatenate( [np.arange(s, e, dtype=dtype) for s, e in zip(starts, ends)]) def reverse(brle_data): if brle_data[-1] == 0: brle_data = brle_data[-1::-1] else: brle_data = np.r_[0, brle_data[-1::-1]] if len(brle_data) % 2 != 0: brle_data = np.r_[brle_data, 0] return brle_data def sorted_gather_1d(raw_data, ordered_indices): data_iter = iter(raw_data) index_iter = iter(ordered_indices) index = next(index_iter) start = 0 value = START_VALUE while True: while start <= index: try: value = not value start += next(data_iter) except StopIteration: raise IndexError( 'Index %d out of range of raw_values length %d' % (index, start)) try: while index < start: yield value index = next(index_iter) except StopIteration: break def gatherer_1d(indices): if not isinstance(indices, np.ndarray): indices = np.array(indices, copy=False) order = np.argsort(indices) ordered_indices = indices[order] def f(data): ans = np.empty(len(order), dtype=np.bool) ans[order] = tuple(sorted_gather_1d(data, ordered_indices)) return ans return f def gather_1d(rle_data, indices): return gatherer_1d(indices)(rle_data) def sparse_to_brle(indices, length): from . import rle return rle_to_brle(rle.rle_to_sparse(indices, length)) def pad_to_length(brle_data, length): from . import rle return rle.pad_to_length(brle_data, length) def remove_length_padding(rle_data): data = np.reshape(rle_data, (-1, 2)) data = data[data != [0, 0]] return data.flatten()
dfadf44e71e2ac70aac701b0f549c2497dff9343
Mohan110594/BFS-1
/Binary_tree_traversal.py
2,392
3.859375
4
BFS traversal Time complexity:O(n) space complexity:O(n) Ran on leetcode:Yes problems faced: None Code Description: we do this using BFS by storing the level of each node at each traversal.when the length of the queue is equal to the level of the node we insert that specific node into the array of the specific level. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def __init__(self): self.out=[] def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root==None: return [] queue=deque([[root,0]]) while (len(queue)!=0): q=queue.popleft() q_root=q[0] count=q[1] if count==len(self.out): self.out.append([q_root.val]) else: self.out[count].append(q_root.val) if q_root.left!=None: queue.append([q_root.left,count+1]) if q_root.right!=None: queue.append([q_root.right,count+1]) return self.out Level order recursive order Time complexity: O(n) space complexity: O(h) - height of the tree. Ran on leetcode: Yes problems faced: None Code Description: we did BFS using recursion where the same logic from the above is implemented by storing the depth of each node. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Solution(object): def __init__(self): self.out=[] def helper(self,root,count): if root==None: return if count<len(self.out): self.out[count].append(root.val) else: self.out.append([root.val]) self.helper(root.left,count+1) self.helper(root.right,count+1) return self.out def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root==None: return return self.helper(root,0)
8947933986e76531a1bdd2ed5f2e6bd740bf6cd5
JDOsborne1/project-orwell
/perceptron.py
845
3.90625
4
import numpy as np class Perceptron: def __init__(self,weights,bias): ''' Weights is expected to be an array of real numbers representing the weights Bias is expected to be a real number quantifying how easy it is to return 1 ''' self.weights = weights self.bias = bias def evaluate(self, inputs): if sum(self.weights*inputs) + self.bias > 0: return 1 else: return 0 def train(self, inputs, output,l_rate): ''' As above the inputs are an array of the real inputs The output is the known output of that array of inputs l_rate is the learning rate ''' w_error =l_rate*( output - self.evaluate(inputs) ) for i in range(len(inputs)): self.weights[i] += w_error*inputs[i]
6a5d0d7d7e9b4eac8ebdc6122db9292846b24e52
xiaochaotest/Local-submission
/automation_testing_day01/show_testing/python_basics/str_Test.py
5,942
3.546875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Peng Chao import selenium import sys ''' 1.str的操作 2.元组,列表,字典的操作 ''' ''' 在单引号里面又包含了单引号的处理 ''' name1 = u'xiaochao,"你好",\'你在成都好吗?\'' print name1 def add(): ''' None :return: ''' name = u'小超' age = 24 address = u'成都' print u'我在%s,今年我%s岁,我的名字是%s'%(address,age,name) print u'我今年{1}岁了,我叫{0},在四川{2}'.format(name,age,address) print u'我叫{name},我今年{age}岁了,我在{address}'.format(name=name,age=age,address=address) '''字符串和unicode类型互转''' str1 = 'hello' print u'现在的类型是:',type(str1) #字符串转为unicode用decode() str2 = str1.decode('gbk') print u'str2的类型是:',type(str2) #unicode类型转为str str3 = str2.encode('utf-8') print u'str3的类型是:',type(str3) #将字符串转成int类型 src = '45' src1 = int(src)#浮点类型float(src) print u'将字符串强转为int类型:',type(src1) '''字符串的操作''' cont = 'hell word' print u'获取w在字符串中是第几位:',cont.index('w')#索引均是从0开始 print cont.index('l') print u'将字符串转成大写:',cont.upper() cont.upper() print u'取消字符串中的空格:',cont.strip() cont.strip() print u'判断字符串是否是数字:',cont.isdigit() cont.isdigit() print u'判断字符串是否是以h开头:',cont.startswith('h') cont.startswith('h') print u'判断字符串是否是以d结尾:',cont.endswith('d') #cont.endswith() print u'寻找字符串中的元素:',cont.find('o') cont.find('s') print u'替换字符串中的元素:',cont.replace('word','China') cont.replace('word','name') print u'字符串的拆分:',cont.split(' ')#字符串拆分处理以后就是列表 cont.split(' ') print u'首字母变大写:',cont.capitalize() cont.capitalize() print u'内容居中:',cont.center(30,'=') #cont.center(30,'==') cont1 = 'Hello\t999' print u'处理table键:',cont1.expandtabs() print u'是否是字母和数字:',cont.isalnum() print u'是否是字母:',cont.isalpha() print u'判断是否是数字:',cont.isdigit() print u'是否小写:',cont.islower() print u'是否有空格:',cont.isspace() print u'是否是大写:',cont.isupper() #判断标题-->首字母大写,可以理解为大写 print u'首字母是否大写:',cont.istitle() #join连接字符串 s1 = ['appium','selenium','android','ios'] print '连接字符串:', '***'.join(s1) #使用.join()把列表转为字符串 print '把列表转成字符串:',','.join(s1) #字符串转为列表 a = 'a b c' print a.split(" ") #移除空白 a1 = ' abc' print '移除空白:',a1.lstrip() #移除左侧空白 print '移除左侧空白:',a1.lstrip() #移除右侧空白 st = 'hell ' print '移除右侧空白:',st.rstrip() #字符串转小写 print cont.lower() #分割字符串,分割之后就是元组 ss1 = 'xiaochao is python' print u'分割字符串,分割之后就是元组:',ss1.partition('is') #替换字符串 print u'替换字符串:',ss1.replace("xiaochao",'admin') #rfind()从右向左找 print ss1.find('xiaochao') #bytes可以将字符串转换成字节 # strs1 = u'小超' # print u'字符串转成字节:',strs1.bytes(strs1) print '****列表的操作*****' ''' 字符串中内置的数据类型 元组:tuple 列表:list 字典:dict ''' list1 = [10,24,5,31,0,9] print u'打印列表:',list1 # print dir(list1)#通过dir方法查看内置了哪些方法 # print type(help(list1))#help()帮助信息 u'''实现列表的追加''' list1.append(28) print list1 #实现把想要插入的数据放到想要的位置 print u'查看0在列表中出现了几次:',list1.count(0) print u'查看元素在列表中是第几位:',list1.index(5) print u'查看列表中第6位元素是什么:',list1[6] #查看列表中的所有内容 for s in list1: print u'查看列表中所有的元素内容:', s #依据位置插入元素 list1.insert(3,'dont') #删除指定的列表元素 list1.remove('dont') #修改列表中的内容 list1[0]='android' print u'查看更新后的列表内容:',list1 #扩展列表 list2 = ['a','b','c,','d'] list1.extend(list2) print u'查看扩展以后的列表内容:',list1 #列表反转 list1.reverse() #列表的排序 list1.sort() #删除指定位置的列表 del list1[0] ''' pop()默认删除最后一位并且把删除的元素打印出来 ''' list2 = [11,51,21,4,'g',47,1,0,99] print list2.pop(1) ''' remove()删除想要删除的元素 ''' list2.remove('g') print list2 ''' reverse()字符串反转 ''' list2.reverse() print list2 ''' sort()列表中的元素按从小到大排序 ''' list2.sort() print list2 print u'****元组*****' ''' 元组 1.元组是不可变的 2.元组中的数据是可变的;元组中通常代表一行数据,而元组中的数据代表不同的数据项 ''' tuple1 = (15,2,50,'abc',["username","password"],{"name":"xiaochao"}) print u'获取元素在元组中出现了几次:',tuple1.count(50) print u'获取元素在元组中的索引:',tuple1.index(50) ''' 把元组中name对应的小超改为小超 ''' tru = 'admin' tuple1[5]['name'] = tru print tuple1 #取出元组中具体的值 print u'取出元组中具体的值:',tuple1[3] #取出元组最后一位元素 print u'取出元组中最后一个元素的值:',tuple1[len(tuple1)-1] #切片在元组中的使用 print u'切片在元组中的使用:',tuple1[0:4] #使用循环的方式,取出元组中所有的值 for item in tuple1: print u'循环获取元组中的所有值:', item #获取元组中的某个元素在元组中的个数 print u'获取元组中某个元素的个数:',tuple1.count('xiaochao') #修改元组嵌套在元组中的列表内容 print u'元组中的内容:', tuple1 tuple1[5]['username']='admin' print u'元组中的字典被修改后的内容L:',tuple1,u'类型为:',type(tuple1) #5.24日到元组
de6a224fc4a730b94b25861679992788c9ee58a4
AdamZhouSE/pythonHomework
/Code/CodeRecords/2804/60632/233728.py
153
3.953125
4
formula = input('please input: ') numbers = sorted(formula[::2]) result = '' for number in numbers: result = result + number + '+' print(result[:-1])
051b6e0793655fa6644832912154f66123811202
Christy538/Hacktoberfest-2021
/PYTHON/Stack_array.py
579
3.953125
4
class Stack: def __init__(self): self.arr = [] self.length = 0 def __str__(self): return str(self.__dict__) def peek(self): return self.arr[self.length-1] def push(self,value): self.arr.append(value) self.length += 1 def pop(self): popped_item = self.arr[self.length-1] del self.arr[self.length-1] self.length -= 1 return popped_item mystack = Stack() mystack.push('google') mystack.push('microsoft') mystack.push('facebook') mystack.push('apple') print(mystack) x = mystack.peek() print(x) mystack.pop() print(mystack)
cf4e7ad7e27dc8e4f218a8ce3c5a07dfb3600e38
JackyTao/algorithm
/int2words.py
655
3.71875
4
# -*- coding: utf-8 -*- f = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Forteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Ninteen'] s = [ 'Ten', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninty' ] def int2words(num): q = ['', 'Thousand', 'Million', 'Billion', 'Trillion'] p = 0 while num > 0: remain = num % 1000 num = num / 1000 def small2words(num): # int less than 1000 rst = ['', '', ''] p1 = num / 100 p2 = (num % 100) / 10 p3 = num % 10 if p1 > 0: rst[0] = f[p
103cea041e7e3e908e365ad55d9a56478db7ff7e
hidirb/Hangman
/Hangman.py
8,808
3.5
4
import random import time import os import sys words_list = [ "jawbreaker", "jaywalk", "jazziest", "jazzy", "jelly", "jigsaw", "jinx", "jiujitsu", "jockey", "jogging", "joking", "jovial", "joyful", "juicy", "jukebox", "jumbo", "kayak", "kazoo", "keyhole", "khaki", "kilobyte", "larynx", "lengths", "lucky", "luxury", "lymph", "marquis", "matrix", "megahertz", "naphtha", "nightclub", "nowadays", "nymph", "onyx", "ovary", "oxidize" ] def drawHangman(face=False, neck=False, body=False, left_hand=False, right_hand=False, left_leg=False, right_leg=False): for row in range(10): if row == 0: for column in range(20): if column >= 3: if column == 19: print("_") else: print("_", end="") else: print(" ",end="") elif face == True and row == 1: for column in range(20): if column == 0: print(" ",end="") elif column == 1: print("_",end="") elif column == 2: print("|", end="") elif column == 3: print("_", end="") elif column == 19: print("|") else: print(" ", end="") elif face == True and row == 2: for column in range(20): if column == 0 or column == 4: print("|", end="") elif column == 1 or column == 3: print(" ", end="") elif column == 2: print("_", end="") elif column == 19: print("|") else: print(" ", end="") elif neck == True and row == 3: for column in range(20): if column == 2: print("|", end="") elif column == 19: print("|") else: print(" ",end="") elif left_hand == True and row == 4: for column in range(20): if column == 0: print("/", end="") elif column == 1: print(" ",end="") elif column == 2: print("|", end="") elif column == 3: print(" ",end="") elif right_hand == True and column == 4: print("\\", end="") elif column == 19: print("|") else: print(" ", end="") elif body == True and row == 5: for column in range(20): if column == 2: print("|", end="") elif column == 19: print("|") else: print(" ",end="") elif left_leg and row == 6: for column in range(20): if column == 0: print("/", end="") elif column == 1: print(" ",end="") elif column == 3: print(" ",end="") elif right_leg and column == 4: print("\\", end="") elif column == 19: print("|") else: print(" ", end="") elif row == 9: for column in range(20): if column <= 10: print(" ", end="") elif column == 19: print("-") else: print("-", end="") else: for column in range(20): if column == 19: print("|") else: print(" ", end="") def computerSelect(): word = random.choice(words_list) return word.lower() def playerSecretWord(repeatText = None): question = repeatText if repeatText is not None else "Enter your secret word.\n" word = input(question) if type(word) == str and len(word) >= 3: return word.lower() else: return playerSecretWord("Please make it atleast three letters! Try again.\n") def drawGuessedLetters(guessed_letters): print("Word: ", end="") for letter in guessed_letters: print(letter, end=" ") print("\n") def checkGuess(letter, phrase_letters): guess = False if letter in phrase_letters: guess = True return guess def fillBlanks(letter, phrase_letters, guessed_letters): indices = [i for i, el in enumerate(phrase_letters) if el == letter] for index in indices: guessed_letters[index] = letter return guessed_letters def guessLetter(repeatText = None): question = repeatText if repeatText is not None else "What's your guess?\n" word = input(question) if type(word) == str and len(word) == 1: return word.lower() else: return guessLetter("One letter at a time! Tty again.\n") def ShowFaildAttempts(fails): print("Failed Attempts: ", end="") for miss in fails: print(miss, end=",") print("\n") def drawHangmanBasedOnWrongGuessed(committed_mistakes): if committed_mistakes == 0: drawHangman(False, False, False, False, False, False, False) if committed_mistakes == 1: drawHangman(True, False, False, False, False, False, False) if committed_mistakes == 2: drawHangman(True, True, False, False, False, False, False) if committed_mistakes == 3: drawHangman(True, True, True, False, False, False, False) if committed_mistakes == 4: drawHangman(True, True, True, True, False, False, False) if committed_mistakes == 5: drawHangman(True, True, True, True, True, False, False) if committed_mistakes == 6: drawHangman(True, True, True, True, True, True, False) if committed_mistakes == 7: drawHangman(True, True, True, True, True, True, True) def gameMode(): question = "Type your game option?\n\n" option = "1) One Player Mode\n2) Two Player Mode\n\n" game_type = input(question + option) if type(game_type) == str and game_type == "1" or game_type == "2": return int(game_type) else: gameMode() def get_platform(): platforms = { 'linux1' : 'Linux', 'linux2' : 'Linux', 'darwin' : 'OS X', 'win32' : 'Windows' } if sys.platform not in platforms: return sys.platform return platforms[sys.platform] def clearScreen(): platform = get_platform() if platform == "Windows": os.system("cls") else: os.system("clear") def startGame(): game_type = gameMode() phrase= "" if game_type == 1: phrase = computerSelect() else: phrase = playerSecretWord() phrase_letters = [char for char in phrase] guessed_letters = ["__" for el in phrase_letters ] committed_mistakes = 0 already_guessed_letters = [] missed_letters = [] clearScreen() no_win = True while(committed_mistakes < 7 and no_win): drawHangmanBasedOnWrongGuessed(committed_mistakes) drawGuessedLetters(guessed_letters) if len(missed_letters) > 0: ShowFaildAttempts(missed_letters) guessed_letter = guessLetter() if guessed_letter in already_guessed_letters: print("You already guessed that letter, try something else!") time.sleep(1) clearScreen() continue else: already_guessed_letters.append(guessed_letter) guessed = checkGuess(guessed_letter, phrase_letters) if guessed == True: guessed_letters = fillBlanks(guessed_letter, phrase_letters, guessed_letters) print("Nice Guess!") if guessed_letters == phrase_letters: no_win = False else: committed_mistakes += 1 missed_letters.append(guessed_letter) print("Opps!") time.sleep(1) clearScreen() if no_win == False: drawGuessedLetters(guessed_letters) print("You Won! Great Job!") if committed_mistakes == 7: drawHangmanBasedOnWrongGuessed(committed_mistakes) print("Oops, you lost. Better luck next time!") print("The word was:- ", phrase) startGame()
80172bb564d324435841d6f3aaa0b71ebdb6c3b7
chason-hu/luffy
/01开发基础/第一章-Python基础语法/课后练习/07LoginSimulation.py
843
3.890625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # i. username = input("请输入用户名:") password = input("请输入密码:") if username == "seven" and password == "123": print("登录成功!") else: print("登录失败!") # ii. chance = 3 while chance > 0: username = input("请输入用户名:") password = input("请输入密码:") if username == "seven" and password == "123": print("登录成功!") break else: print("登录失败!") chance -= 1 # ii. chance = 3 while chance > 0: username = input("请输入用户名:") password = input("请输入密码:") if (username == "seven" or username == "alex") and password == "123": print("登录成功!") break else: print("登录失败!") chance -= 1
4e733b1cbb5377886fa2cdd1d07b91d71456938a
kenpos/LearnPython
/正規表現とか色々/vowelMatch.py
543
3.5625
4
#[]で特定の文字集合のみをマッチさせる import re #特定の文字マッチング vowelMatch_regex = re.compile(r'[aeiueoAEIOU]') #検索し,パターンマッチした奴を全部抽出する mo1 = vowelMatch_regex.findall('RoboCop feed eats baby food. BABY FOOD') print(mo1) print() #特定の文字以外マッチング vowelMatch_regex = re.compile(r'[^aeiueoAEIOU]') #検索し,パターンマッチした奴を全部抽出する mo1 = vowelMatch_regex.findall('RoboCop feed eats baby food. BABY FOOD') print(mo1)
d927d9616714926438688184ad4c789b90d49aa6
Symforian/University
/Python/List 3/sudan.py
459
3.5625
4
sud = {} def sudan(n, x, y): key = str(n) + " " + str(x) + " " + str(y) if(n == 0): return x+y if(y == 0): return x if key in sud: return sud[key] val = sudan(n-1, sudan(n, x, y-1), sudan(n, x, y-1) + y) sud[key] = val return val print( sudan(0, 1, 1), sudan(1, 10, 0), sudan(1, 1, 3), sudan(1, 1, 4), sudan(1, 1, 5), sudan(2, 1, 2), sudan(1, 14, 14), sudan(2, 5, 1) )
da93e1559bb459035683e3064be454faa25449d8
nbenjamin/python-workspace
/collection-basics/collections.py
1,208
4.09375
4
import random # Dictionary names = {'basic': '1997', 'fortran': '1997', 'c': '2000', 'c++': '2001', '.net': '2003', 'java': '2003', 'python': '2019'} year = names.get('java') if year is None: print('Year is missing ') else: print('Year is ', year) # Two Dimensional Array menus = { 'Breakfast': ['Boiled Eggs', 'Milk'], 'Lunch': ['Salad', 'Salmon Grill'], 'Dinner': ['Noodles', 'Chicken Sandwich'] } # To get Lunch items print(menus.get('Lunch')) # Looping ages = [35, 40, 36, 33, 32] total = 0 for age in ages: total = total + age print('Average age is - ', format(total / len(ages), '.0f')) for i in range(5): print(i) # print starts from 20 and increment by 2 to reach 27 for y in range(20, 27, 2): print(y) # Dictionary's Key/Value in loop for program, year in names.items(): print(program, " - ", year, sep='') # While Loop x = 1 while x != 3: print(' x = ', x) x += 1 # Types of Random number generation print(random.random()) # Return a random number from [0.0 to 1.0] print(random.choice([10, 20, 30, 40, 50])) # Return a random number from the given list print(random.randint(1, 500)) # Return a random number within the given range
f19ee924713199a637902a9a6d5b3579dd9f3b7c
mkozigithub/mkgh_info_python
/20190111 FCSA Learning Time/Files/PythonBeyondTheBasics/10_exceptions_errors/median.py
646
3.71875
4
def median(iterable): items = sorted(iterable) if len(items) == 0: raise ValueError("median() arg is an empty sequence") median_index = (len(items) - 1) // 2 if len(items) % 2 != 0: return items[median_index] return (items[median_index] + items[median_index + 1]) / 2.0 def main(): print(median([3,1,6,4,8])) print(median([3,1,6,4,8,5])) # print(median([])) # raises ValueErrors try: median([]) except ValueError as e: print(dir(e)) print(f"e: {repr(e)}") print(f"Payload: {e.args}") if __name__ == "__main__": main()
d733dd3f89722a714087eacb9bebbc27e774d738
CheckiO-Missions/checkio-task-poker-dice
/verification/referee.py
6,700
3.65625
4
""" CheckiOReferee is a base referee for checking you code. arguments: tests -- the dict contains tests in the specific structure. You can find an example in tests.py. cover_code -- is a wrapper for the user function and additional operations before give data in the user function. You can use some predefined codes from checkio.referee.cover_codes checker -- is replacement for the default checking of an user function result. If given, then instead simple "==" will be using the checker function which return tuple with result (false or true) and some additional info (some message). You can use some predefined codes from checkio.referee.checkers add_allowed_modules -- additional module which will be allowed for your task. add_close_builtins -- some closed builtin words, as example, if you want, you can close "eval" remove_allowed_modules -- close standard library modules, as example "math" checkio.referee.checkers checkers.float_comparison -- Checking function fabric for check result with float numbers. Syntax: checkers.float_comparison(digits) -- where "digits" is a quantity of significant digits after coma. checkio.referee.cover_codes cover_codes.unwrap_args -- Your "input" from test can be given as a list. if you want unwrap this before user function calling, then using this function. For example: if your test's input is [2, 2] and you use this cover_code, then user function will be called as checkio(2, 2) cover_codes.unwrap_kwargs -- the same as unwrap_kwargs, but unwrap dict. """ from checkio.signals import ON_CONNECT from checkio import api from multi_score import CheckiORefereeMultiScore from checkio.referees import cover_codes import random from collections import Counter from functools import partial NUMBER_OF_GAMES = 5 NUMBER_OF_HANDS = 8 TARGET_SCORE = 2500 def score_run(n, score, aces, die): cs = Counter(die) if cs.get("AS", 0) >= n: return aces elif max(cs.values()) >= n: return score else: return 0 def score_two_runs(n, score, aces, die): cs = Counter(die).most_common() if cs[0][1] >= n + 2 or (len(cs) >= 2 and cs[0][1] >= n and cs[1][1] >= 2): if cs[0][0] == "AS": return aces else: return score else: return 0 def score_straight(die): cs = Counter(die) if cs == Counter(["9S", "TH", "JS", "QH", "KH"]) or cs == Counter(["TH", "JS", "QH", "KH", "AS"]): return 25 else: return 0 def score_flush(die): cs = Counter(die) if (cs & Counter(["9S", "JS", "AS"]) == Counter()) or (cs & Counter(["TH", "QH", "KH"]) == Counter()): return 15 else: return 0 score_fns = { "one pair": partial(score_run, 2, 2, 3), "two pair": partial(score_two_runs, 2, 4, 5), "three of a kind": partial(score_run, 3, 6, 8), "four of a kind": partial(score_run, 4, 50, 60), "five of a kind": partial(score_run, 5, 200, 240), "full house": partial(score_two_runs, 3, 25, 30), "straight": score_straight, "flush": score_flush } die = ["9S", "TH", "JS", "QH", "KH", "AS"] def roll(n): out = [] for i in range(n): out.append(die[random.randrange(6)]) return out def invalid_move(msg, score): return { "result": False, "result_text": msg, "total_score": score } def next_hand(state, cat, score): hands = state["hands_completed"] + 1 games = state["games_completed"] total_score = state["total_score"] scores = state["input"][1] scores.update({cat: score}) total_score = sum(scores.values()) state.update({ "input": [[roll(5)], scores], "hands_completed": hands, "games_completed": games, "total_score": total_score }) return state def next_roll(state, dice): prev = state["input"][0] scores = state["input"][1] if len(prev) >= 3: return invalid_move("You can only roll three times per hand.", state["total_score"]) prev.append(dice + roll(5 - len(dice))) state.update({ "input": [prev, scores] }) return state def verify_dice(state, dice): prev = state["input"][0][-1] return Counter(prev) & Counter(dice) == Counter(dice) def initial_referee(_): return { "result": True, "result_text": "", "total_score": 0, "games_completed": 0, "hands_completed": 0, "input": [[roll(5)], {}] } def process_referee(state, action): if isinstance(action, str): die = state["input"][0][-1] scores = state["input"][1] action = action.lower() if action in score_fns.keys(): return next_hand(state, action, score_fns[action](die)) else: return invalid_move("Invalid category name: " + action, state["total_score"]) else: if not verify_dice(state, action): return invalid_move("You must choose which dice to keep from the list of dice you rolled.", state["total_score"]) else: return next_roll(state, action) def is_win_referee(state): return state["hands_completed"] >= NUMBER_OF_HANDS # and state["total_score"] >= TARGET_SCORE api.add_listener( ON_CONNECT, CheckiORefereeMultiScore( tests=dict(("Game {}".format(i + 1), {}) for i in range(NUMBER_OF_GAMES)), initial_referee=initial_referee, process_referee=process_referee, is_win_referee=is_win_referee, cover_code={ 'python-27': cover_codes.unwrap_args, # or None 'python-3': cover_codes.unwrap_args }, function_name="poker_dice" ).on_ready) """ first_roll = roll(5) def referee(test, answer): state = { "result": True, "result_text": "", "total_score": 0, "games_completed": 0, "hands_completed": 0, "input": [[first_roll], {}] } while True: state = process_referee(state, answer) if not state["result"]: return False, state["result_text"] if is_win_referee(state): return True, "Final score: " + str(state["total_score"]) answer = checkio(state["input"][0], state["input"][1]) api.add_listener( ON_CONNECT, CheckiOReferee( tests={"GO": [{ "input": [[first_roll], {}], "answer": [] }]}, checker=referee, cover_code={ 'python-27': cover_codes.unwrap_args, # or None 'python-3': cover_codes.unwrap_args } ).on_ready) """
bdf4c0fbb518b4fffd8147439573a9a96cbc3e45
marco8111/python
/exercicio2.7.py
228
3.96875
4
x = int(input("digite o numero :")) divisores = 0 for i in range(1, x+1) : if x % i == 0 : divisores = divisores + 1 if divisores == 2 : print("numero", x, "é primo") else : print("numero não é primo:")
c38b4027da74d7cee4bd55364b68b671769d01e3
jahokas/Python_Workout_50_Essential_Exercises_by_Reuven_M_Lerner
/exercise_01_number_guessing/word_guessing_game.py
1,098
4.25
4
import random ''' Try the same thing, but have the program choose a random word from the dic- tionary, and then ask the user to guess the word. (You might want to limit your- self to words containing two to five letters, to avoid making it too horribly difficult.) Instead of telling the user that they should guess a smaller or larger number, have them choose an earlier or later word in the dict. ''' WORK_DICT = { 1: 'cat', 2: 'dog', 3: 'news', 4: 'head', 5: 'arm', 6: 'rot', } def guessing_game(): number = random.randint(1, 6) print(WORK_DICT) while True: guess = input('Guess word: ') if number > list(WORK_DICT.keys())[list(WORK_DICT.values()).index(guess)]: print(f'Your guess of {guess} is too low!') elif number < list(WORK_DICT.keys())[list(WORK_DICT.values()).index(guess)]: print(f'Your guess of {guess} is too high!') elif number == list(WORK_DICT.keys())[list(WORK_DICT.values()).index(guess)]: print(f'Right! The answer is {guess}') break guessing_game()
d619b05dbc9bd77371ae794acec12498629f40db
belayashapochka/Programming
/Practice/10/Python/PY 1.py
628
3.5625
4
print("Введите число и диапазоны через пробел!") s, l1, r1, l2, r2 = input().split(' ') z = 0 s = int (s) l1 = int (l1) r1 = int (r1) r2 = int (r2) l2 = int (l2) if s > (r1 + r2) | s < (l1 + l2): print (-1, end = '') else: if (s - l1) >= l2: if s <= (l1 + r2): print (l1, s - l1, end = '') else: z = abs (s - (l1 + r2)) if (l1 + z) < r1 & (r2 - z) > l2: print (l1 + z, s - (l1 + z), end = '') else: print (-1, end = '') else: print (-1, end = '')
7b9909fdb5085fdbcdf975401e537b98c7de5de2
Boomshakal/spider
/async_task/111.py
230
3.53125
4
import asyncio import time now = lambda: time.time() async def do_some_work(x): print('start:',x) await asyncio.sleep(2) print("waiting:", x) start = now() asyncio.run(do_some_work(2)) print("Time:",now()-start)
b85c387eaa32a9a2a185c4af1eb43865b79ab224
orozmamatovaelnura/hw_06.06
/ex3.py
336
3.546875
4
def func_compare(x,y): total=0 for i in range(10): if x[i]==y[i]: total+=10 return total x , y =input().split() if x.isalpha and y.isalpha: if len(x)==10 and len(y)==10: print(func_compare(x,y)) else: print('Inputs are too short or too long !') else: print('Inputs are not strings !')
b911c54259a65d0af0d875a263f74512b1c05b1d
tainenko/Leetcode2019
/python/260.single-number-iii.py
1,250
3.71875
4
# # @lc app=leetcode id=260 lang=python # # [260] Single Number III # # https://leetcode.com/problems/single-number-iii/description/ # # algorithms # Medium (57.80%) # Likes: 1043 # Dislikes: 84 # Total Accepted: 118.7K # Total Submissions: 202.5K # Testcase Example: '[1,2,1,3,2,5]' # # Given an array of numbers nums, in which exactly two elements appear only # once and all the other elements appear exactly twice. Find the two elements # that appear only once. # # Example: # # # Input: [1,2,1,3,2,5] # Output: [3,5] # # Note: # # # The order of the result is not important. So in the above example, [5, 3] is # also correct. # Your algorithm should run in linear runtime complexity. Could you implement # it using only constant space complexity? # # # @lc code=start class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: List[int] """ tmp = 0 for num in nums: tmp ^= num mask = 1 while mask & tmp == 0: mask = mask << 1 a = b = tmp for num in nums: if num & mask == 0: a ^= num else: b ^= num return [a, b] # @lc code=end
1460b604a769a7b6c3fed028205ffba39b45c654
neelybd/Character_Remover
/BN_Char_Remover.py
4,815
3.984375
4
import pandas as pd from tkinter import Tk from tkinter.filedialog import askopenfilename, asksaveasfilename def main(): print("Program: Char Remover") print("Release: 0.1.1") print("Date: 2019-03-26") print("Author: Brian Neely") print() print() print("This program reads a csv file and will delete a specified character from a specified column.") print() print() # Hide Tkinter GUI Tk().withdraw() # Find input file file_in = askopenfilename(initialdir="/", title = "Select file", filetypes=(("Comma Separated Values", "*.csv"), ("all files", "*.*"))) if not file_in: input("Program Terminated. Press Enter to continue...") exit() # Set ouput file file_out = asksaveasfilename(initialdir=file_in, title = "Select file", filetypes=(("Comma Separated Values", "*.csv"), ("all files", "*.*"))) if not file_out: input("Program Terminated. Press Enter to continue...") exit() # Ask for delimination delimination = input("Enter Deliminator: ") # Open input csv using the unknown encoder function data = open_unknown_csv(file_in, delimination) # Select Column for Sentiment Analysis column = column_selection(data) # Input character for replacement char = input("Input characters for removal: ") # Create list of symbols for split char_list = str.split(char) # Remove characters from data print("Removing characters: " + str(char_list) + " from " + str(file_in) + '...') for i in char_list: data[column] = data[column].str.replace(i,'') print("Characters Removed!") # Create an empty output file open(file_out, 'a').close() # Write CSV print("Writing CSV File...") data.to_csv(file_out,sep=delimination, index=False) print("Wrote CSV File!") print() print("Character Remover Completed on column: [" + column + "]") print("File written to: " + file_out) input("Press Enter to close...") def column_selection(data): # Create Column Header List headers = list(data.columns.values) while True: try: print("Select column.") for j, i in enumerate(headers): print(str(j) + ": to perform sentiment analysis on column [" + str(i) + "]") column = headers[int(input("Enter Selection: "))] except ValueError: print("Input must be integer between 0 and " + str(len(headers))) continue else: break return column def open_unknown_csv(file_in, delimination): encode_index = 0 encoders = ['utf_8', 'latin1', 'utf_16', 'ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_11', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] data = open_file(file_in, encoders[encode_index], delimination) while data is str: if encode_index < len(encoders) - 1: encode_index = encode_index + 1 data = open_file(file_in, encoders[encode_index], delimination) else: print("Can't find appropriate encoder") exit() return data def open_file(file_in, encoder, delimination): try: data = pd.read_csv(file_in, low_memory=False, encoding=encoder, delimiter=delimination) print("Opened file using encoder: " + encoder) except UnicodeDecodeError: print("Encoder Error for: " + encoder) return "Encode Error" return data if __name__ == '__main__': main()
5431216eecdd45d9eab158b943e6d9131ed89bde
wuyxinu/Plane
/plane/code/bee.py
1,682
3.75
4
#bee.py import flying import random import config import pygame #蜜蜂类 class Bee(flying.Flying): """ 蜜蜂类: 1.包含一个__init__ a)使用bee_count(index)来记录蜜蜂的数量 b)获取蜜蜂的x, y坐标,坐标的获取是根据游戏的窗口随机产生的 c)width 和 height是根据图片的宽高获取的 d)tag 属性,是用来删除图片的 2.蜜蜂的移动方式 def step(self, canvas) a)蜜蜂在x,y方向都可以移动,所以都要考虑 -X :要判断蜜蜂的速度和移动方向 -Y :只需要判断向下的移动速度即可 3.判断蜜蜂是否越界 def out_of_bound(self) a)只需要判断y轴是否越界 """ bee_count = 0 def __init__(self, image): #每创造一个蜜蜂,就会调用一个__init__函数 self.direct = True Bee.bee_count += 1 #随机产生的第一个参数到第二个参数中的随机整数 x = random.randint(0, config.GAME_WIDTH - image.width()) y = 0 - image.height() width = image.width() height = image.height() self.tag = 'Bee_' + str(Bee.bee_count) super().__init__(x, y, width, height, image) #蜜蜂的移动方式 def step(self, canvas, score): #Y方向 self.y += 3 #X方向 if self.direct: #规定向右为正方向 self.x += 3 #使用画布 #canvas.move(tag, x, y): canvas.move(self.tag, 3, 3) else: #self.direct = False self.x -= 3 canvas.move(self.tag, -3, 3) #判断蜜蜂的移动方向 if self.x > config.GAME_WIDTH - self.width: self.direct = False elif self.x < 0: self.direct = True #判断蜜蜂是否越界 def out_of_bounds(self): if(self.y > config.GAME_HEIGHT): return True return False
335997f1d50db17b49aaa1da524f38a56b518e43
DustinYook/COURSE_COMPUTER-ENGINEERING-INTRODUCTION
/PythonWS/FinalExam/test0713_1.py
801
4
4
# 1) 딕셔너리 값 설정하기 d = {} d['price'] = 100 print(d) d = dict(price= 100) # 이거 틀림 print(d) # 2) 리스트에 값 넣기 l = list() for i in range(0, 10, 1): l.append(i) l.reverse() print(l) # l = list() # for i in range(9, 0, -1): # l.append(i) # l.reverse() # print(l) # 3-1) 정규표현식을 이용하여 추출하기 import re str = 'width="40" name="KT" height="50"' extract = re.findall(r'width="([0-9]+)".+?height="([0-9]+)', str) print(extract) for width, height in extract: print(int(width) + int(height)) # 3-2) 정규표현식을 이용하여 추출하기 import re str = 'width="40" name="KT" height="50"' extract = re.findall(r'width="([0-9]+)".+?height="([0-9]+)', str) width = int(extract[0][0]) height = int(extract[0][1]) print(width + height)
4c869ac88da357802de81d3cf90fa773e7dd72c3
namtruc/catalogue_lfds
/fct_tk.py
682
3.53125
4
import pandas as pd from tkinter import Tk from tkinter.filedialog import askopenfilename def choix_fichier (File): #input("\nAppuyer sur Entree pour choisir le fichier du catalogue francais non modifie\n") xl = pd.ExcelFile(File) if len(xl.sheet_names) > 1 : print ("\n---Les differents feuilles presentes---") for x in range (len(xl.sheet_names)) : print (str(x)+" "+xl.sheet_names[x]) y = int(input("Entrer le numero de la feuille excel\n")) v_sheet1 = xl.sheet_names[y] else : v_sheet1 = 0 read_file = pd.read_excel(File,sheet_name=v_sheet1, skiprows = 1, header=None) return read_file
baecd21f3a6f5e09c274fda976723b735dbf241b
Mahima-M-A/Engineering-Course-ISE
/Semester 5/Scripting Languages Lab/Python Programs/FileProgram.py
1,373
3.859375
4
import os,sys from functools import reduce wordLen = [] dic={} if(len(sys.argv) != 2): print("Invalid Arguments") sys.exit() if(not(os.path.exists(sys.argv[1]))): print("Invalid File Path") sys.exit() if(sys.argv[1].split('.')[1] != "txt"): print("Invalid File Format. Only TXT files allowed") sys.exit() #to open the file and read it line by line and create the dictionary of words as key and their lengths as value with open(sys.argv[1]) as file: for line in file: for word in line.split(): dic[word] = dic.get(word,0) + 1 #to sort the words in the dictionary with respect to their values(lengths) sortedDict = sorted(dic.items(), key=lambda dictItem: dictItem[1], reverse=True) for i in range(10): try: wordTuple = sortedDict[i] wordLen.append(len(wordTuple[0])) print(wordTuple[0], ", Frequency: " , wordTuple[1] , ", Length: " , len(wordTuple[0])) except IndexError: print("File has less than 10 words") break print() print("Lengths of 10 most frequently occuring words:") print(wordLen) # one-line reduce function to get the average length print() sum = reduce(lambda x,y: x+y, wordLen) print("Average length of words: " , sum*1.0/len(wordLen)*1.0) # one-line list comprehension to display squares of all odd numbers print() squares = [x**2 for x in wordLen if x%2 != 0] print("Squares of odd word lengths: ") print(squares)
9ee7ec2ac0be1febd69e638868dabeb2aa65050d
vrajdalal07/PRACTICAL-1-2-AND-3
/frame_label_entry.py
442
3.96875
4
from tkinter import * root = Tk() def display(): if ent1.get() == "": print("Please enter your name: ") else: print("Name: " + ent1.get()) ent1.focus() l1 = Label(root, text="Enter name") frame = Frame(root) l1.grid(row=0, column=0) frame.grid(row=0, column=1) ent1 = Entry(frame) b = Button(frame, text="submit", command=display) ent1.grid(row=0, column=0) b.grid(row=0, column=1)
37b53aaf9287e3a156df132b43e59b10bab10160
hugh225/learnPython
/Python3/grammer/thread.py
581
3.8125
4
import time, threading def loop(): print("thread %s is running..." % threading.current_thread().name) n = 0 while n < 5: n += 1 print("Thread %s >>> %d" % (threading.current_thread().name, n)) # time.sleep(1) print("Thread %s ended." % threading.current_thread().name) print("Thread %s is running..." % threading.current_thread().name) t1 = threading.Thread(target = loop, name='LoopThread1') t2 = threading.Thread(target = loop, name='LoopThread2') t1.start() t2.start() t1.join() t2.join() print("Thread %s ended." % threading.current_thread().name)
2a66d0741498a45ffc28cb3d3d236feb9deabe53
emanoelmlsilva/ExePythonBR
/Exe.Funçao/Fun.04.py
127
3.859375
4
def positivoNeg(n): if n > 0: return "P" else: return "N" arg = int(input("Digite o numero: ")) print(positivoNeg(arg))
c0d7aac22f4526a0dfc4fa657714a81bfb387b87
yiswang/LeetCode
/reverse-bits/reverse-bits.py
1,850
4.03125
4
#!/usr/bin/python # -*- coding: utf-8 -*- ############################################################################### # # Author: Yishan Wang <wangys8807@gmail.com> # File: reverse-bits.py # Create Date: 2017-02-14 # Usage: reverse-bits.py # Description: # # LeetCode problem 190. Reverse Bits # # Difficulty: Easy # # Reverse bits of a given 32 bits unsigned integer. # # For example, given input 43261596 (represented in binary as # 00000010100101000001111010011100), return 964176192 (represented in binary as # 00111001011110000010100101000000). # # Follow up: # If this function is called many times, how would you optimize it? # ############################################################################### # # Run time on LeetCode: 62ms, beat 16.35%; 42ms, beat 82.31%; 49ms, beat 45.84% # class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): res = 0 bits_count = 0 while n: remainder = n % 2 n = n / 2 res = res * 2 + remainder bits_count += 1 res <<= 32 - bits_count return res # # An optimized version. Time complexity: O(1) # Run time on LeetCode: 65ms, beat 14.61%; 59, beat 20.11%; 69ms, beat 10.59% # class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): n = (n >> 16) | (n << 16) n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8) n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4) n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2) n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1) return n if __name__ == "__main__": test_cases = [ 0, 1, 43261596, ] solu = Solution() for num in test_cases: print solu.reverseBits(num) print ""
e99b15bfe666e962f840f35d4eb397817c2c2d0f
whitneysteward/css_practice
/how.py
52
3.75
4
def reverse(x): print(x[::-1]) reverse('hello')
24536a212489ba37ee83b20db99de91010709372
heke12345/learngit
/test0608.py
2,967
3.625
4
# # x=int(input("快点输入: ")) # # if x<0: # # print("no negative allowed") # # elif x==0: # # print("zero") # # else: # # print("太棒了,都是大于零!") # item="ball" # color="red" # sentence=("Claire‘s %s is %s"%(item,color)) # print("Claire's {0} is {0}".format(item,color)) # pets=("Claire") # petss=("hahha") # PETS=["cat","dog" , "snake","panda"] # print(PETS) # for pet in PETS: # print('{0} has a {1} {2}'.format(pets,pet,petss)) # if [1,2,3]<[3,4,5] and isinstance(0.46,float): # print("对了哦") # # name=[] # # personfile = {'name': "Claire", 'Age': 26, 'typ': 'a cute girl'} # # name = str(input("输入她的任何特征: ")) # # if name in personfile: # # print("She is {0}".format(personfile['typ'])) # # else: # # print("你输错了哦") # test1={"qwe":"ert"} # test2=["qwe","ert"] # list1=["love","hate","sleep","sad","eat","eat"] # list1.pop(2) # print (list1) # list1.sort() # print (list1) # print(list1.count("eat")) # list1[6:8]=["3","4","6"] # print (list1) # list3=[] # FRAMEWORKS=["React","Javascipt","Gastby"] # LBRARIES=["postgreSQL","RxJS","Node.js"] # INI={"framesworks":FRAMEWORKS,"libraries":LBRARIES} # print(INI) # FRAMES={'Frame1':"React","Frame2":"Javascipt","Frame3":"Gastby"} # print(list3) # print(FRAMES) # myfruit=["apple","straberry","orange","banana"] # yourdraw=["money","orange","cigar","apple"] # yourthings=[] # for fruit in myfruit: # if fruit not in yourdraw: # yourthings.append(fruit) # print(yourthings) # yourthins2=[fruit for fruit in myfruit if fruit not in yourdraw] # print(yourthins2) # gift={} # gift # price={} # gift['cheap']= 'flower' # gift['middle']= 'lipstick' # gift['luxury']= 'bag' # # print("这是可供选择的价位 {0} ".format(gift.keys())) # # gift.keys # #print (gift) # # answer=str(input("请选择你的价位选择: ")) # # print (gift[answer]) # # 礼物的价位选择 dict # print("请选择你喜欢的活动类型:❤") # i = {} # num = 0 # options = ["sport", "art", "food", "relax"] # result = { # 'sport': "football", # 'art': "gallery", # 'food': " eat susine", # 'relax': "message" # } # # for i in options: # # print(options[num]) # # num = num+1 # for i in options: # print(options[num]) # num = num+1 # resu = str(input("Claire 选择了:")) # print('那么本宝宝推荐你去↓: {0}'.format(result[resu])) # print('那么本宝宝推荐你去↓: ' + result[resu]) # print('那么本宝宝推荐你去↓:', result[resu]) # print('那么本宝宝推荐你去↓: %s' % (result[resu])) # print(''.join(['那么本宝宝推荐你去↓: ', result[resu]])) # from __future__ import unicode_literals # X = 2/5 # print(X) # xx = b'iloveu' # print(xx) # import math # print(dir(math)) # print(help(math.log2)) # help(math.pow) #!/usr/bin/env python # coding:utf-8 #!/usr/bin/env python # coding:utf-8 """ 请计算19+2*4-8/2 """ a = 19+2*4-8/2 print(a)
f414b9f2e4d21e1efad04de82066c9d60dfe8a97
bytesweaver/python_prictise
/ex29.py
368
4.15625
4
people = 20 cats = 30 dogs = 15 if people < cats: print("Too many cats! The world is doomed!") if people > cats: print("people > cats") if people < dogs: print("people < dogs") if people > dogs: print("people > dogs") dogs += 5 if people < dogs: print("people < dogs") if people >= dogs: print("people >= dogs") if people == dogs: print("people = dogs")