blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
784e4b4b303e2f6c1371d64c7a55944d8c9aca01
s1bel/Loan_Calculator
/Problems/Long live the king/main.py
248
3.90625
4
column = int(input()) row = int(input()) moves = 0 if column in (1, 8): if row in (1, 8): moves += 3 else: moves += 5 elif 1 < column < 8: if row in (1, 8): moves += 5 else: moves += 8 print(moves)
b0b8c586264f55d34c8013a452352504c9b67db9
hshank/hangman
/letterCount_solution.py
534
3.734375
4
def getLetterCount(word): dictionary = {} for letter in word: if letter in dictionary: dictionary[letter] += 1 else: dictionary[letter] = 1 return dictionary def getCurrentStatus(correctLettersSoFar, word): currentStatus = '' for letter in word: if letter in correctLettersSoFar: currentStatus = cu...
4dc5c05933443289e7e1946d3edc3c9cfb0d28b2
PavelStransky/PCInPhysics2020
/python/Contourf.py
558
3.53125
4
import matplotlib.pyplot as plt from matplotlib import cm # Colour maps for the contour graph import numpy as np def f(x, y): return x**4 - 2*x**2 + x + y**2 step = 0.025 numContours = 30 # Number of contours in the graph x = y = np.arange(-2.0, 2.01, step) # Range of x and y values ...
110620c2e7164a5b474bcb3ae6f928dfb5b4c68e
Sleet01/CSS458A
/week4/jl_mc_solution.py
1,860
3.578125
4
#============================================================================= # Monte Carlo model to calculate an area # Solution to Shiflet & Shiflet (2014)'s Figure 9.2.2 problem (p. 379-380) # By Johnny Lin # April 13, 2015 #============================================================================= import nump...
634b2c45bed12c8dcc524e606e11a3c5929331c6
ShuaiWangGit/algorithm
/lintcode/62_search_in_rotated_sorted_array.py
1,278
3.953125
4
""" for given A: [ 4, 5, 6, 7, 0, 1, 2 ] l M m r if the `mid` > `l`, then `mid` must be in left side, otherwise in right side if `mid` in left side, we can check if the `target` between `l` and `mid` (because we dont know the `M` at where) otherwise the `mid` in right side, we can also check if...
60535d471cbaa4c631c2a8df433c177898e340b7
HDembinski/pyik
/pyik/time_conversion.py
6,742
4.21875
4
# -*- coding: utf-8 -*- """Time conversion utilities.""" from __future__ import print_function def utc_to_gps(utcsec): """ Convert UTC seconds to GPS seconds. Parameters ---------- utcsec: int Time in utc seconds. Returns ------- Time in GPS seconds. Notes ----- The...
afac58bdb6750ac15846ef87a7c4272c4f987b2f
manelmengibar/EDX_Python_Codes
/BasicPython/First_codes/ConvertingUserInput.py
359
3.78125
4
#Convert elevator floors #Le pedimos al usuario de que planta europea se trata inp = input ("Europe floor?\n") #A continuación el programa transforma la variable inp en integer y le añade 1 #De esta manera tenemos el piso equivalente en USA usf = int(inp) + 1 #Finalmente mostramos el equivalente de piso en USA print...
b2ebdabca26616fc734fd059348f18aa8d2deb12
manelmengibar/EDX_Python_Codes
/WebProgramming/1Flask/Set.py
342
3.96875
4
#set es una función que crea un conjunto donde almacenar elementos s = set() #dentro de este set podemos ir añadiendo elementos sin orden s.add(1) s.add(3) s.add(5) s.add(3) #Este print mostrará: {1, 3, 5}. Como podemos ver solo muestra una vez el 3 #ya que lo que importa es el elemento que hay y no cuantas veces es...
81e7d95c81f945d8ccbf7a89cd239f4b9ae30ef5
manelmengibar/EDX_Python_Codes
/WebProgramming/BasicFlask/template.py
1,596
3.671875
4
#importamos flask del módulo flask que alguien ha desarollado antes. #En este caso importamos también la función render_template que se encuentra dentro de Flask from flask import Flask, render_template #Esto indica que quiero crear una aplicación web utilizando Flask app = Flask(__name__) # Esto indica que cuando ...
fb293b15d0f780b75a077b63ad5e562980890748
yifan526/password-retry
/password.py
215
4
4
password = 'a123456' x = 2 while x >= 0 : pass1 = input('please enter passcode') if x == 0: break elif pass1 != password: print (x,' attempts left') x = x - 1 else: print ('password correct') break
d80b117e62d2468b91c305a7419ee625a1160c00
damchilly/WWC-Regular-Expressions
/WWC-Regular-Expressions.py
10,533
4.5
4
# coding: utf-8 # # WWC - Regular Expresions in Python # # Facilitator: Diana Amador # # From Automate the Boring Stuff with Python # **Regular Expressions** allow you to specify a pattern of text to search for. # # **Search** and **Replace** functions in MS-Word or OpenOffice are examples of regular expression ...
d027928bddff9997613cffb0a622aa32926dab09
rprnc/python-snippets
/datechecker.py
1,774
4.09375
4
# datechecker.py - Checks date string formats import pyperclip import re # Phone Number Regex phoneRegex = re.compile(r'''( (\d{2}) # DD (\s/) # separator (\d{2}) # MM (\s|-|\.) # separa...
cc0316a380ffe15e521d56d9fcc7772ab729d34c
salman98ansari/Practical
/OSTL/moduleweb.py
426
3.65625
4
import webbrowser #import sys '''url="https://www.google.com" webbrowser.open(url) url1="https://www.wikipedia.org" webbrowser.open_new_tab(url1)''' query = input("enter you want to search: ") url="https://www.google.com/?#q=" webbrowser.open_new_tab(url+query) query=input("enter you wan' to search in y...
45cdd62a3601b42d794cf9d191f8194f2364efad
attakorn1/internship
/1/count_palindrome.py
968
3.75
4
import os import sys def check_palindrome(s): palindrome = True front = 0 back = len(s)-1 while front < back: if not s[front].isalpha(): front += 1 continue if not s[back].isalpha(): back -= 1 continue if s[front].isalpha() and s[...
e7be4d7d1179688a7326b8d55a2bc4f59b86b0a3
TitusChoi/Algorithm
/Solution/Programmers/[Programmers]타겟 넘버.py
773
3.6875
4
# Title : [Programmers]타겟 넘버.py # Description : dfs/bfs # Link : https://programmers.co.kr/learn/courses/30/lessons/43165 # bfs 풀이 from collections import deque def solution_bfs(numbers, target): answer = 0 queue = deque([(0, 0)]) # sum, level while queue: s, l = queue.popleft()...
4ee89789e06f952c98c5bc13558eb16e8ee28f65
TitusChoi/Algorithm
/Solution/Programmers/[Programmers]K번째수.py
1,072
3.90625
4
# Title : [Programmers]k번째수.py # Description : sort # Link : https://programmers.co.kr/learn/courses/30/lessons/42748 def solution(array, commands): answer = [] for index in commands: ''' 방법 1 : sorted temp = sorted(array[(index[0] - 1) : index[1]]) # sorted 함수 사용 ...
893b2979f4ee7f15fe4619017c5de12ef9504d33
TitusChoi/Algorithm
/Concept/[CodeLion]ExchangeSort.py
500
3.96875
4
# Title : [CodeLion]InsertionSort.py # Description : sorting def exchange_sort(array): n = len(array) # 크기 정의, 불필요한 반복문 제거 for i in range(n - 1): # 최대 크기보다 하나 적은 영역까지 비교 for j in range(i + 1,n): # 역순으로 비교해가면서 sort if(array[i] > array[j]): # 크면 교환 array[i], array[j]...
88a6b656970e854e26a43535e46561d1003f4a38
3cnf/descriptor-solver
/check_solution/check_solution.py
3,096
4.125
4
#!/usr/bin/python3 import re import sys def read_cnf(filename): '''Read a cnf file Attention: The file has to be sorted via the permutation program Keyword arguments: filename -- the file containg a cnf problem description. Returns: a t-uple containing a numpy array and an integer ...
d210470111e9ec923c4c5f47ad0c197c9024e2d8
idy-3/masterCI-DsAl
/Ds/exercise.py
700
3.890625
4
# Google Question # Given an array = [2,5,1,2,3,5,1,2,4] # It should return 2 # Given an array = [2,1,1,2,3,5,1,2,4] # It should return 1 # Given an array = [2,3,4,5] # It should return None #naive (n^2) # def firstRecurringChar(arr): # for i in range(1, len(arr)): # j = i-1 # while j>=0: # if arr[i]...
0cd0fe632b41c688be9ef78401fac44a142edfaf
idy-3/masterCI-DsAl
/Al/recursion.py
975
4.03125
4
# def findFactorialRecursive(number): # if number == 1: # return 1 # answer = number * findFactorialRecursive(number - 1) # return answer # def findFactorialIterative(number): # answer = 1 # for i in range(number,1,-1): # answer *= i # return answer # print(findFactorialRecursive(5)) # print(findF...
d8f88767abee1e7036a2098ec21c9f2f38701371
idy-3/masterCI-DsAl
/Al/BFSnDFS.py
6,490
3.8125
4
import json class Node: def __init__(self, value): self.left = None self.right = None self.value = value class BinarySearchTree: def __init__(self): self.root = None def insert(self, value): newNode = Node(value) if self.root is None: self.root = newNode else: curNode = ...
0043b2d9b42a9ed6e18b6150701edce4bc3fe3fc
aikrasnov/otus-examples
/protocols/patterns/generator.py
196
3.8125
4
def generator(): for i in range(3): x = yield i print(x) g = generator() next(g) g.send("foo bar!") next(g) next(g) next(g) next(g) next(g) # also raise StopIteration at end
a5867cc899a6b5c1b18b4d48f934238c16327c7e
basilebru/Machine-Learning-Bootcamp
/d01/ex03/mylinearregression.py
3,642
3.609375
4
import numpy as np import sys sys.path.insert(1, '../ex02') from gradient import gradient class MyLinearRegression(): def __init__(self, theta): """ Description: generator of the class, initialize self. Args: theta: has to be a list or a numpy array, it is a vector o...
aaca290a1b4178d7ff019885b3eaed55cd95e4fc
theCompSciTutor/computerScience
/Algorithms/Search/BinarySearch/binary_search.py
319
4.03125
4
# Binary Search Algorithm def binary_search(sortedArray, value): low = 0 high = len(sortedArray) - 1 while low <= high: mid = (low + high) // 2 if sortedArray[mid] > value: high = mid - 1 elif sortedArray[mid] < value: low = mid + 1 else: return True # value found return False # value not
1693064c8e6f44f9a93e4e15de044f87b1801c16
theCompSciTutor/computerScience
/Algorithms/Sort/MergeSort/merge sort python code.py
968
4.15625
4
# Merge Sort Algorithm def merge_sort(array): print('Separating...', array) if len(array) > 1: mid = len(array) // 2 left_half = array[: mid] right_half = array[mid :] merge_sort(left_half) merge_sort(right_half) i = 0 j = 0 k = 0 ...
dd1ddeb6237dca4df9ef76d467655099080da7b7
SiyuanYan1/leetcode
/递归/sumList.py
185
3.578125
4
def doSomething(aList): n = len(aList) if n == 0: return 0 else: return aList[0] + doSomething(aList[1:]) L = [10,30,20] value = doSomething(L) print(value)
c09dde45a6bb0d85c3d4d6a0eee385e1795bcfff
SiyuanYan1/leetcode
/二叉树/BST.py
3,164
3.765625
4
class Node: def __init__(self, key, item, left=None, right=None): self.key = key self.value = item self.right = right self.left = left def __str__(self): return str(self.key) + ":" + str(self.value) def isLeaf(self): return self.right is None and self.left i...
c411cc7d2d3987d5a8e2b9bd5b7ee25ca860194d
SiyuanYan1/leetcode
/递归2/fib.py
197
3.71875
4
def fib(n): return fib_aux(n ,0 ,1) def fib_aux(n ,before_last ,last): if n== 0: return before_last else: return fib_aux(n - 1, last, before_last + last) print(fib(5))
9138e7c8db7cc9ed2a7072bbd8cd4f2d91dffc7a
SiyuanYan1/leetcode
/二叉树/之子型打印二叉树.py
1,009
3.640625
4
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def Print(self, pRoot): if pRoot == None: return [] else: result = [] node_lis...
92bfece05652d102530f9672e7a003f72f10efc5
bob-blob/SimulatedAnnealing
/travel.py
1,474
3.640625
4
# -*- coding: utf-8 -*- from traverser import Traverser import random from city import City class Travel: tour = [] distance = 0 def __init__(self, tour = [None]*30): self.tour = tour.copy() def get_tour(self): return self.tour def generate_individual(self): ...
500f02d92d998119b4d16fd006f2ddbab279ac39
rlai-lab/lab-raspi
/demo/camera-module/demo_motion_detection.py
1,755
3.515625
4
""" Demonstrating the use of the `video_threading.py` script. This time we make a simple motion detector using OpenCV. It is very hacky, but it demonstrates the possibility of doing real-time processing on frames from the PiCamera module. (You may have to alter the thresholds/blur/difference calculation to get it to w...
f69a44c0cf52306f174ee3fc16e00a5b8e5d854b
ywl1992/pythonStudy
/字典问题.py
611
3.953125
4
# -*- coding:utf-8 -*- ''' 将[{1:”a”},{2:”b”}]转换为[{‘value’:’a’, ‘key’:1},{‘value’:’b’, ‘key’:2}] Python 字典 items() 方法以列表返回可遍历的(键, 值) 元组数组。 ''' dict={1:'a',2:'b'} # print(dict.items())dict_items([(1, 'a'), (2, 'b')]) l=[{'key':key,'value':value} for key,value in dict.items()] print(l) # '遍历字典的key' d={1:'ss',2:'dd'} for...
435f9f5fe78e3a985efc9d152c630e4924c1cc98
klw11j/Financial-and-Election-Analysis-Python
/PyBank/Analysis/main.py
1,958
3.78125
4
import os import csv csvpath = os.path.join('..', 'Resources', 'budget_data.csv') total_months = [] total_profit = [] profit_change = [] with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) for row in csvreader: total_months.append(row[0])...
71bbdad7e7eac86a8127bcded3d96393df597a31
chiefJota/Learn-ASL
/Predict.py
2,192
4.09375
4
from knn import KNN import matplotlib.pyplot as plt import numpy as np ############################################### #create an instance of the kNN class knn = KNN() knn.Load_Dataset('iris.csv') #first feature of flower x = knn.data[:,0:1] #second feature of flower y = knn.data[:,1:2] #Have to reshape because the...
f52cdfec9ebd9d4de07a32da0d4feb72457adab2
KatrinaHuberJuma/dict-word-count
/wordcount.py
718
3.90625
4
# put your code here. def word_count(filepath): """Takes a filename as input and prints word/count.""" unique_words = {} #creates empty dictionary openfile = open(filepath) for line in openfile: line = line.rstrip() #removes extra character whitespace from end of each line word...
7bbfb65f156aa4af905672b1fd4cf039b475e4ec
Matheus-Pontes/Curso-Python-3
/aula_15/ex67.py
313
3.828125
4
# MOSTRANDO A TABUADA DE VÁRIOS VALORES while True: num = int(input("Quer ver a tabuada de qual valor? ")) print("-"*30) if num < 0: break for c in range(1, 11): print(f"{num} x {c} = {num * c}") print("-"*30) print("FIM DO PROGRAMA.")
db8c103443fdf5fec18880911c7cd44ea7f0386b
Matheus-Pontes/Curso-Python-3
/aula_10/ex29.py
374
3.78125
4
# RADAR ELETRÔNICO velocidade = float(input("Informe sua velocidade: ")) print("Sua velocidade é {} km/h.".format(velocidade)) if velocidade >= 80: multa = 7*(velocidade - 80) print("[Alert]Você ultrapassou o limite de velocidade de 80 km/h.") print('O valor da multa é R$ {}'.format(multa)) else: pr...
06e2c2f435dc2f2050a0340d30135064983b5d4a
Matheus-Pontes/Curso-Python-3
/aula_19/ex93.py
679
3.671875
4
# Gerenciamento de um jogador jogador = dict() gols = list() jogador["nome"] = str(input("Nome do jogador: ")).upper().strip() quant = int(input(f"Quantas partidas {jogador['nome']} jogou? ")) for c in range(0, quant): gols.append(int(input(f"Quantos gols na {c+1}º partida? "))) jogador['gols'] = gols[:] j...
f9475898cd4ef214cd94aa2d0a3c7a028f07b989
Matheus-Pontes/Curso-Python-3
/aula_11/ex41.py
340
3.984375
4
# NATAÇÃO: CATEGORIA DE ACORDO COM A IDADE idade = int(input("Sua idade por favor: ")) if idade <= 9: print("Nadador MIRIM") elif idade > 9 and idade <= 14: print("Nadador INFANTIL") elif idade > 14 and idade <= 19: print("Nadador JUNIOR") elif idade == 20: print("Nadador SÊNIOR") else: print("...
1be9f869ffea5b124cb98630ed9160ce4680d812
Matheus-Pontes/Curso-Python-3
/aula_11/ex37.py
488
4.1875
4
# CONVERSÃO DE BASE NUMÉRICAS # BINÁRIO, OCTAL E HEXADECIMAL num = int(input("Digite um número inteiro: ")) print('''Escolha a conversão: [0] BINÁRIO [1] OCTAL [2] HEXADECIMAL ''') option = int(input("Faça sua escolha: ")) if option == 0: print("{} em BINÁRIO {}".format(num, bin(num))) elif option == 1: p...
8b7014b693ff8c2f417cd8d2536820c335387879
Matheus-Pontes/Curso-Python-3
/aula_20/ex100.py
484
3.671875
4
from random import randint from time import sleep def sortear(lista): print('Sorteando 5 valores:', end= " ") for c in range(0, 5): n = randint(0, 10) lista.append(n) print(f"{n}", end=" ", flush=True) sleep(0.3) def somapar(lista): soma = 0 for n in numeros: i...
ad39b8214acd37a7129d63e3f3d22321505d5631
Matheus-Pontes/Curso-Python-3
/aula_11/ex38.py
270
3.90625
4
# COMPARANDO NÚMEROS num1 = int(input("Primeiro valor: ")) num2 = int(input("Segundo valor: ")) print("-=" * 10) if num1 > num2: print("Primeiro valor MAIOR.") elif num2 > num1: print("Segundo valor MAIOR.") else: print("Os dois valores são iguais.")
4679fa079224f1a1596d365c0feda8be7e0aeda0
Matheus-Pontes/Curso-Python-3
/aula_21/ex103.py
325
3.71875
4
def ficha(n, g): if g.isnumeric(): g = int(g) else: g = 0 if n.strip() == "": n = "<desconhecido>" return f"O jogador {n} fez {g} gol(s)." # Programa principal nome = str(input("Nome do jogador: ")) gols = str(input("Quantos gols marcou no campeonato? ")) print(ficha(nome, g...
e16a984b4bff0247a43af97864413a1065b0160a
Matheus-Pontes/Curso-Python-3
/aula_14/aula.py
237
3.84375
4
# ESTRUTURA DE REPETIÇÃO WHILE '''c = 1 while c < 11: print(c) c += 1 print("FIM")''' r = "S" while r == "S": n = int(input("Digite um valor :")) r = str(input("Quer continuar [S/N] ")).upper() print("FIM")
a06f793e328cfe6cb3d34ed393eb230646b13975
Matheus-Pontes/Curso-Python-3
/aula_17/ex82.py
506
3.890625
4
num = list() pares = list() impares = list() while True: num.append(int(input("Digite um valor: "))) opçao = ' ' while opçao not in "SN": opçao = str(input("Quer continuar? [S/N]: ")).upper().strip()[0] if opçao == "N": break for n in num: if n % 2 == 0: pares.append(n) ...
07aa9c769e5c2f4be6265761ae34368016cd0eb2
Matheus-Pontes/Curso-Python-3
/aula_17/ex78.py
619
3.84375
4
# COLOCAR 5 NÚMEROS NUMA LISTA VAZIA # DEPOIS DIZER QUAL MAIOR E MENOR num = [] maior = menor = 0 for c in range(0, 5): num.append(int(input(f"Digite um número na posição {c}:"))) if c == 0: maior = menor = num[c] else: if num[c] > maior: maior = num[c] if num[c] ...
7f4b1682ceccdaa316e904ccfe045585075d8009
Matheus-Pontes/Curso-Python-3
/aula_13/ex54.py
389
3.859375
4
# ATINGINDO A MAIORIDADE totmaior = 0 totmenor = 0 for c in range(1, 8): ano = int(input("Ano de nascimento da {}º pessoa: ".format(c))) idade = 2020 - ano if idade >= 21: totmaior += 1 else: totmenor += 1 print("Ao todo tivemos {} pessoas maior de idade.".format(totmaior)) p...
c2ae929effa9f8a0d3e00882642127737d5dae37
mollywood/may_7
/bank_account.py
1,372
3.78125
4
class User: def __init__(self, first_name, last_name, middle_name): self.first_name = first_name self.last_name = last_name self.middle_name = middle_name self.bank_accounts = [] def addBankAccount(self, bank_account): self.bank_accounts.append(bank_account) class BankA...
b0c7c6cf47acb1142f1710481425f13eff819cc3
Zhivlova/-Zhivlova-GU_Python_728-28-08-2020-
/3 (1).py
618
3.953125
4
number_1 = int(input('Введите первое число: ')) number_2 = int(input('Введите второе число: ')) try: division = number_1 / number_2 except ZeroDivisionError: division = 0 print(division) print('Операция выполнена, результат = ' + str(number_1/number_2)) # второй вариант #number_1 = int(input('Вве...
73e94633e9054adb7eae1e6e0fef530fc480589d
Zhivlova/-Zhivlova-GU_Python_728-28-08-2020-
/7 (2).py
813
3.875
4
from abc import ABC, abstractmethod class Clothes(ABC): def __init__(self, param): self.param = param @abstractmethod def expenses(self): return f' Для пошива пальто нужно: {self} ткани ' pass class Coat(Clothes): def __init__(self, v): self.v = v @property ...
669445cc35c9e3845e2753f8d266d31570d9e591
Zhivlova/-Zhivlova-GU_Python_728-28-08-2020-
/2 (5).py
264
3.765625
4
my_list = [7, 5, 3, 3, 2] answer = input('Введите число: ') for index, number in enumerate(my_list): if int(answer) < int(number): continue my_list.insert(index, answer) break else: my_list.append(answer) print(my_list)
efaa9663b957a9bf0e583ffafede74d7c38bdaa8
VallieTracy/salesperson-report
/sales_report.py
1,602
3.84375
4
"""Generate sales report showing total melons each salesperson sold.""" # Creating global variables # Empty lists which will store names of salespeople and another list which will store # of melons sold # Might want to make a dictionary instead of two separate lists where person is key and value is melons sold salespe...
a68493c5577a98518f06a273a63c3b6c6eecd4d9
Genius98/TrueFalseGame
/quiz_brain.py
1,722
3.765625
4
class QuizBrain: def __init__(self, q_list): #initialize the attribute,q_list as a param which is passed over self.question_number = 0 #creating attribute self.score = 0 #user's initial score is zero self.question_list = q_list def still_has_questions(self): #to keep tracking ...
ee511b332e2dc15e461ba44dde0e56ee127d0043
ShihaoWang/Contact-Transition-Tree
/Functions/OwnLib.py
16,562
4.125
4
#!/usr/bin/python # This is used to serve as a library such that some functions do not need to be rewritten over and ove again import sys, os from random import randint import numpy as np import math from klampt.math import so3,vectorops # This part is for the operation on list def Cross_Product(a, b): # Only de...
c34a05a5bb066b47b7c55eedd44521adac2cd5fd
ExpertSeahorse/SimpleCode
/parse_int.py
1,855
3.78125
4
def parse_int(s): """ Converts from word form to integer form Example: seven hundred eighty-three thousand nine hundred and nineteen -> 783919 :param s: :return: """ # Initializing word -> number conversions answer = 0 num_dict = { "zero": 0, "one": 1, "two":...
a80ec37079d2a9b9bb218252daf7489a640efa66
ExpertSeahorse/SimpleCode
/Permutations.py
256
3.84375
4
def permutations(strin): from itertools import permutations import re arr= set(permutations(strin)) arr2= {strin} for entry in arr: arr2.add(re.sub(r"\(|'|\)|,| ", "", str(entry))) return arr2 print(permutations("aabb"))
fd8a06c8b32e1488ab3ff8b875a2d6a76f336a70
ExpertSeahorse/SimpleCode
/Same checker.py
492
3.75
4
def comp(array1, array2): if None in (array1, array2) or len(array1) != len(array2): return False newarray = [] for entry in array1: newarray.append(entry * entry) if ' '.join(map(str, sorted(newarray))) == ' '.join(map(str, sorted(array2))): return True else: retu...
8efa7d40d299f375207fde8fb2c714cecb6dc6e8
fmedrano2019/SudokuSolver
/SudokuGUI.py
7,270
3.59375
4
import pygame import SudokuEngine import time # Size of the window WINDOW_MULTIPLIER = 8 # this should be the only modification to affect the window size WINDOW_SIZE = 90 # to ensure the window is always divisible by 9 WINDOW_WIDTH = WINDOW_SIZE * WINDOW_MULTIPLIER WINDOW_HEIGHT = WINDOW_SIZE * WINDOW_MULTIP...
8121d98e6b70c5383c066422dc0e6a9cbef9598c
iamSurjya/dailycoding
/Day 21 pandas_add_col.py
769
4.1875
4
import numpy as np import pandas as pd from numpy.random import rand np.random.seed(101) #creating an column pandas DataFrame using an numpy array. print('pandas DataFrame') df=pd.DataFrame(rand(5,4),['A','B','C','D','E'],['W','X','Y','Z']) print(df) #adding new column to an Existing DataFrame df['new']=0.233333 prin...
3dd79cac4131e43543945fc82d6028d72a65141e
iamSurjya/dailycoding
/Day 13 numpy conditions.py
618
4
4
import numpy as np #Create a 3X4 matrix a=np.arange(12).reshape(3,4) print('Original Matrix') print(a) #check if the array elements are greater than 4. print('\nCheck if matrix element is greater than 4') print(a>4) #check if the array elements are even. print('\nCheck if the array elements are even') print(a%2==0) ...
1ecebff7cf8703717fc8bc5d19a795161869c53a
iamSurjya/dailycoding
/Day 12_numpy_advance_indexing.py
421
4.1875
4
import numpy as np x = np.array([[1, 2], [3, 4], [5, 6]]) print('Array') print(x) y = x[[0,1,2], [0,1,0]] print('\nFrom each row, a specific element should be selected') #fetching [1 4 5] print(y) print('\nFrom a 4x3 array the corner elements should be selected using advanced indexing') x = np.array( [[ 0, 1, 2], [...
795616a89547a20811302abf47a34278f14c3bdb
iamSurjya/dailycoding
/Day 20 access_pandas_data_frame.py
427
3.859375
4
import numpy as np import pandas as pd from numpy.random import rand np.random.seed(101) #creating an pandas DataFrame using an numpy array. print('pandas DataFrame') df=pd.DataFrame(rand(5,4),['A','B','C','D','E'],['W','X','Y','Z']) #access column from a DataFrame print(df['W']) print(type(df['W']))#Return the type...
fc067c6584a84e5c944cfb45ce8ebd0733454f48
milson389/python-project
/Fundamental/src/Branching/Ternary.py
403
4.0625
4
# Python ternary operator is_nice = True # if statement if(is_nice): state = "nice" print(state) else: state = "not nice" print(state) # Ternary # ( conditional_if_true if condition else condition_if_false ) # (condition_if_false, condition_if_true)[condition] state = "nice" if is_nice else "not_nic...
afa63dcc746f139d4ed2464662347061a1d784bd
milson389/python-project
/Fundamental/src/Function/Function.py
1,152
3.921875
4
# Python Function def square(x): return x * x a = 10 s = square(a) print('{} Square is {}'.format(a, s)) def changeMe(myList): myList.append([1, 2, 3, 4]) print('Value inside the function: {}'.format(myList)) yourList = [10, 20, 30] changeMe(yourList) print('Value outside the function: {}'.format(yo...
dd63d0583459d6f65ffc663184ea2a15fd6a6940
milson389/python-project
/Fundamental/src/Function/Scope.py
264
3.625
4
# Python variable scope total = 0 # global variable def sums(arg1, arg2): global total total = arg1 + arg2 print('Inside the function: {}'.format(total)) return total sums(10, 20) print('Outside the function (global) total: {}'.format(total))
bc0011cc5f112cd0cbce1835db26a78c89ba0a33
kches-git/learn-homework-1
/3_for.py
1,394
3.78125
4
""" Домашнее задание №1 Цикл for: Оценки * Создать список из словарей с оценками учеников разных классов школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...] * Посчитать и вывести средний балл по всей школе. * Посчитать и вывести средний балл по каждому классу. """ def main(): """ Эта функция ...
214b690ba966e238307fea72388afc9bf551b90a
tkarabela/learn-python
/expander/expander.py
379
3.578125
4
import re EXPAND_GROUP = re.compile(r"\{([^}]*)\}") def expand(expr): match = EXPAND_GROUP.search(expr) if match: before = expr[:match.start()] after = expr[match.end():] variants = match.group(1).split(",") for v in variants: for rest in expand(after): ...
f38d4534d6a5fdb6565f9124eefc8e7cf00e04e5
satyamachani/python-experiments
/guess game.py
896
4.21875
4
import random print("you are going to play guess game with computer") print("rules are as follows") print("computer guess and you too") print("if ur guess equals computer guess") print("you wins") print("maximum guess allowed are 3") print("we are strating game......") print("ready to play with satya's computer...
967b2b975a94e3928070e61262d4090f5954f9fe
Valdecy/Neural-Networks
/Python-DM-Neural Networks-01.py
15,798
3.921875
4
############################################################################ # Created by: Prof. Valdecy Pereira, D.Sc. # UFF - Universidade Federal Fluminense (Brazil) # email: valdecy.pereira@gmail.com # Course: Data Mining # Lesson: Neural Networks # Citation: # PEREIRA, V. (2017). Project: Neural Networks, File...
52d6be875451fdb961900e074fbd02d5f2653139
JamesEllerbee/recrusive_maze_solver
/py/maze_printer.py
303
4.0625
4
#Author: James Ellerbee #Project Purpose: Exercise Recursion and code design '''maze_printer.py defines a function for printing a maze for use in maze_mover.py and solver.py''' def print_matrix(container): for row in container: for column in row: print(column, end = " ") print()
51cff217b8b29029c80b34b427ac086e7f080530
ihkihk/projeuler
/factor.py
1,046
3.53125
4
import math from collections import defaultdict from eratosthenes import eratosthenes def factor(N): """Factor a integer number N. >>> factor(1) defaultdict(<class 'int'>, {1: 1}) >>> factor(2) defaultdict(<class 'int'>, {2: 1}) >>> factor(4) defaultdict(<class 'int'>, {2: 2}) >>> ...
bc5989d0c1f3678afd7c430a14af4d9793cdd2d9
neilbaruwati/Python
/python_basic_programs/class14_3.py
211
3.578125
4
def gencubes(n): out = [] for num in range(n): out.append(num**3) return out for x in gencubes(10): print x """ def lists(n): lst = [] for num in range(11): if num % 2 == 0: lst.append(num) """
5f770d0fe915322e594fdeb81b03526558c051e8
neilbaruwati/Python
/python_basic_programs/assignment1_1.py
443
3.953125
4
# PROBLEM NUMBER 1 x = raw_input("Enter the name of the variable: ") y = input("Enter a value for the variable: ") print x print y # PROBLEM NUMBER 2 x = input("Enter the first number,x : ") x = float(x) y = input("Enter the second number,y : ") print "x/y = " ,x/y # PROBLEM NUMBER 3 x = input("Enter value of x...
55099788623e03a76bb15d299fe578393b69da06
milesmajefski/reverse-polish-notation
/src/rpn_calculator.py
1,972
3.734375
4
import json from collections import deque from rpn_operators import _operators class RPN_calculator: """ This class manages a queue driven by user input in reverse polish notation and evaluates the expression. This class utilizes a deque (double-ended queue) structure to maintain the stack of operand...
21d93be862071af73097c5ad55580ad74e03f6cd
ShiraZaltsman/python-class-flow-control
/Deck.py
556
3.578125
4
import random colors = ['heart', 'diamonds', 'spades', 'clubs'] class Card: def __init__(self, value, color): self._val = value self._color = color def print_card(self): print(str(self._val) + ", " + str(self._color)) class Deck: def __init__(self): self...
78f3eeb58872c3ffa99079a9ca57f285b6f89f52
maeddz/cn-prj1
/3.py
1,041
3.84375
4
"""Custom topology example Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. """ from mininet.topo import Topo class ...
479cf900635c73804053d71baab679f13d22dff5
marisol-001/t07.Dali_Fernandez_Gastelo
/while5.py
222
3.875
4
#INPUT nota=0 nota_invalida=(nota<1 or nota>20) #mientras nota es invalida while(nota_invalida): nota=int(input("ingrese nota del alumno:")) nota_invalida=(nota<0 or nota>20) #fin_while print("nota valida",nota)
5581380a4c72b8a3b7300f4030f0425c0350a5b4
marisol-001/t07.Dali_Fernandez_Gastelo
/while4.py
382
3.734375
4
#INPUT marca_computadora="" marca_invalida=(marca_computadora!="lenovo" and marca_computadora!="HP" and marca_computadora!="cybert") while(marca_invalida): marca_computadora=str(input("ingrese marca de computadora:")) marca_invalida=(marca_computadora!="lenovo" and marca_computadora!="HP" and marca_computadora!...
0f0a9a6c3192c6458b9894b03664ab5eb07be25b
AndreyKrysiuk/Database-labs
/Database.py
4,419
3.515625
4
import pickle class Database(object): def __init__(self): try: file = open('data.pkl', 'rb') except IOError as e: print "Can't load database from file. Create new database." self.directors = [] self.films = [] else: with file: ...
503eb1fb3f378307e6ff0d9a9ccbd191e592d9b3
hugolribeiro/Python3_curso_em_video
/World3/exercise081.py
811
4.21875
4
# Exercise 081: Extracting data from a lista # Make a program that reads several numbers and put them into a list. After that, show: # A) How many numbers were inputted # B) The numbers list, in descending order # C) If the value 5 is in the list numbers_list = [] want_continue = 'Y' while want_continue != 'N': nu...
edaa06ad2bdc494c8011777a3aacf69f5ba2764a
hugolribeiro/Python3_curso_em_video
/World3/exercise096.py
467
4.40625
4
# Objective: Make a program that have a function called Area(). # Receive the dimensions of a rectangular land (width and length) and show its area. # Programmer: Hugo Leça Ribeiro def area(width, length): amount_area = width * length print(f'The area of this land is equal than: {amount_area}m²') width = fl...
335feadaf55fd4b4ead25bb44807065b63e8e181
hugolribeiro/Python3_curso_em_video
/World2/exercise036.py
625
4.09375
4
# Exercise 036: Approving loan # Write a program to approve the bank loan for the purchase a home. # Ask the value of the house, the employee's income and how many years he will pay. # The monthly installment cannot exceed 30% of the revenue, or the loan will be denied. house_value = float(input('What is the house va...
fe013ef3e8c8b450421510213df41ee490ebd513
hugolribeiro/Python3_curso_em_video
/World3/exercise092.py
1,080
3.890625
4
# Objective: Make a program that read the name, birth year and the CTPS and storage them (with the age) in a dictionary.abs # If the CTPS was different by ZERO, the dictionary will receive the hire year and the income. # Calculate and add, besides the age, how many years the person will retire. (with 35 years the perso...
1f25f848fb152d60b5af77405534750d4c83694c
hugolribeiro/Python3_curso_em_video
/World2/exercise060.py
408
4.3125
4
# Exercise 060: Factorial calculation # Make a program that read any number and show its factorial # Example: 5! = 5 X 4 X 3 X 2 X 1 = 120 number = int(input('Input here a number: ')) factorial = 1 print(f'{number}! = ', end='') for multiply in range(number, 0, -1): factorial = multiply * factorial print(f'{mu...
bfe40e9520f2ceac766f2a25d91eec8de961337f
hugolribeiro/Python3_curso_em_video
/World1/exercise021.py
229
3.71875
4
# Exercise 021: PLaying a MP3 # Make a program in Python that opens and executes the audio of an MP3 file from pygame import mixer from time import sleep mixer.init() mixer.music.load('musica.mp3') mixer.music.play() sleep(120)
1595511a7a1eb54f8739e8cbafe3d92fd24a2c06
hugolribeiro/Python3_curso_em_video
/World2/exercise045.py
1,095
4
4
# Rock-paper-scissors # Make a program that plays rock-paper-scissors with you from random import choice from time import sleep itens = ['rock', 'paper', 'scissor'] computer_choice = choice(itens) print('Your options:\n' '[0] - Rock\n' '[1] - Paper\n' '[2] - Scissor') player_choice = itens[int(input...
45a18da87d6d6a4b6d6dc201dbce51a6b44dab87
hugolribeiro/Python3_curso_em_video
/World2/exercise071.py
857
4.21875
4
# Exercise 071: ATM simulator # Make a program that simulates the operation of an ATM. # At the begin, ask to the user what value will be withdraw (an integer number) # and the program will informs how many banknotes of each value will be give. # Observation: Consider that the banking box has these banknotes: R$ 50, R$...
0fb47ce5c5d97a412bb5bbc402171a8a1d5943ff
hugolribeiro/Python3_curso_em_video
/World2/exercise066.py
499
4.09375
4
# Exercise 066: Several numbers with flag # Make a program that read several integers numbers. # The program only will stop if the user input the value 999. # At the end, show how many numbers was inputted and what was the sum of their. _sum = 0 amount = 0 while True: number = int(input('Input here a number. \'999...
63f0901cc32517c7090232184e6179db607d1f87
hugolribeiro/Python3_curso_em_video
/World1/exercise013.py
265
4.125
4
# Exercise 013: Income readjustment # Build an algorithm that read the employee's income and show his new income, with 15% increase. income = float(input(f"Input here the employee's income: ")) new_income = income * 1.15 print(f'The new income is: {new_income}')
3127270d8291d1794b18cc66b47a0d547ba9b353
hugolribeiro/Python3_curso_em_video
/World2/exercise052.py
572
4.125
4
# Exercise 052: Prime numbers # Make a program that read an integer number and tell if it is or not a prime number. def verify_prime(num): if num < 2 or (num % 2 == 0 and num != 2): return False else: square_root = int(num ** 0.5) for divisor in range(square_root, 2, -1): if...
8fb71045715791f1d73d8394de33b5af4400a102
hugolribeiro/Python3_curso_em_video
/World2/exercise043.py
740
4.625
5
# Exercise 043: body mass index (BMI) # Make a program that read the weight and the height of a person. # Calculate his BMI and show your status, according with the table below: # - Up to 18.5 (not include): Under weight # - Between 18.5 and 25: Ideal weight # - Between 25 and 30: Overweight # - Between 30 and 40: Obes...
c99de9678d8cc3cd067ab93f3480a5c75f850bee
hugolribeiro/Python3_curso_em_video
/World3/exercise086.py
510
4.4375
4
# Exercise 086: Matrix in Python # Make a program that create a 3x3 matrix and fill it with inputted values. # At the end, show the matrix with the correct format matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for line in range(0, 3): for column in range(0, 3): matrix[line][column] = int(i...
8d26c9071d46c5bdd08feeeaa290dbf452d4b672
as3379/Python_programming
/Arrays/missing_element.py
845
4.09375
4
"""find the missing element from two arrays """ def finder1(arr1, arr2): count = {} for i in arr1: if i in count: count[i] += 1 else: count[i] = 1 # print(count) for j in arr2: if j in count: count[j] -= 1 else: count[j] ...
5cad30469285efa036089dd993eaa595bb0ecdf4
as3379/Python_programming
/String_manipulation/reverse_alternate_words.py
629
4.3125
4
def reverseWordSentence(Sentence): # Splitting the Sentence into list of words. words = Sentence.split(" ") # Reversing each word and creating # a new list of words # List Comprehension Technique n = len(words) for i in range (0, n): if i%2 !=0: words[i] = words[i][::...
736b9805b211c06ec5a23b34908394b29ba7573c
as3379/Python_programming
/Data_Structures/Stack/stack2queue.py
406
3.5
4
class stack2queue(): def __init__(self): self.instack = [] self.outstack =[] def enqueue(self, item): return self.instack.append(item) def dequeue(self): self.outstack.append(self.instack.pop()) return self.outstack.pop() a = stack2queue() a.enqueue(0) a.enqueue(1) ...
7fae14e7dc30431b9b80aec4b786e81260ecaf23
as3379/Python_programming
/Arrays/diff_adjacent-elements.py
575
4.0625
4
"""Find the first occurance of a given number from the series which has the difference between the adjacent elements as 1. For Example {1, 0, -1,-2,-1,0,1,2,3} Note: Do not use Linear Search """ def search(arr, n, x): # Searching x in arr[0..n-1] i = 0 while (i <= n-1): # Checking if element is found. ...
0f01b53af7a7d9dfbe4362e477d0d992baf2d3af
as3379/Python_programming
/Arrays/repeated.py
772
3.90625
4
# Driver Code list1 = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20] #Method1: d = {} duplicates = [] for i in list1: if i not in d: d[i] = 1 else: d[i] += 1 for k in d: if d[k] > 1: duplicates.append(k) print("Finding repeats using dictionary: ", duplicates) ...
139db53634b47ba7e3aa7ca0efc929d98dd8b13c
as3379/Python_programming
/Data_Structures/Stack/cycle_check.py
585
4.03125
4
def cycle_cheker(node): """ Logic = If linked list is circular marker 1 and marker 2 will meet at some point""" marker1 = node marker2 = node while marker2 != None and marker2.nextnode != None: marker1 = marker1.nextnode marker2 = marker2.nextnode.nextnode if marker1 == mark...
0719f05511266eccb6a2a531dc86c970fd03d30c
as3379/Python_programming
/String_manipulation/string_reversal.py
330
3.875
4
#String reversal #Method1 - Iterative list s = 'ashritha' s = list(s) n = len(s) l = int(n/2) for i in range(0,l): temp = s[i] s[i] =s[n-1] s[n-1]=temp n -= 1 print(''.join(s)) # Method2 - Slicing s='ashritha' n = s [::-1] print(n) #Method3 - looping x = "ashritha" w = "" for i in x: w = i + w...
3f35439b76b1ef73f4fe31111e59da936a6f30bd
as3379/Python_programming
/Arrays/total_sum_array.py
137
3.796875
4
a = input('Enter the series of comma seperated number: ') b = a.split(" ") print (b) sum = 0 for i in b: sum += int(i) print (sum)