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
5ba4c3c84ea65303d2255c1dc1bdf0c03b79d427
victor-erazo/ciclo_python
/Reto1-leo/ayuda-dayro.py
1,194
3.53125
4
prod = { 'proCodigo':'T00194', 'proNombre':'Televisor Smart TV', 'proCantidad': 50, 'proCosto': 2500000 } def ingresoProducto (prod : dict)-> str: proNombre = prod['proNombre'] proCodigo = prod['proCodigo'] proUtilidad = 1.19 proMinstock = 10 proMaxstock = 500 proPrecio = prod['...
350b1239f1f389a5181a11f3b9fa1c3ed74fa6e6
victor-erazo/ciclo_python
/Mision-TIC-GRUPO-09-master(16-06-21)/semana 3/ejercicio5.py
1,813
4.1875
4
''' for x in range(0,10): print('Valor de x : ', x) ''' ''' for j in range(0,10,2): print('La iteracion j : '+ str(j)) ''' ''' for k in range(10,0,-1): print('La iteracion decremental k es : ' + str(k)) ''' ''' oracion = 'Mary entiende muy bien python' frases = oracion.split() print('la oracion analizar ...
f7ecf78186d9bca99f623f4914a2a31461c50cb0
victor-erazo/ciclo_python
/Mision-TIC-GRUPO-09-master(16-06-21)/Semana 4/ejercicio11.py
216
3.828125
4
# Funcion zip nombres = ['Juan','Ricardo'] apellidos_uno = ['Ramirez','Cardenas','Caballero'] apellidos_dos = ['Diaz','Florez','Mantilla'] resultado = list(zip(nombres,apellidos_uno,apellidos_dos)) print(resultado)
4bc272bc4fa0122e237b91978d4fde460466d3ae
anantvir/DataStructures_Maps
/chain_hashmap.py
2,850
3.625
4
"""Author - Anantvir Singh, concept and code reference:= Data Structures and Algorithms by Michael T. Goodrich et al""" import unsorted_map import random from collections import MutableMapping class MapBase(MutableMapping): class _Item: def __init__(self,k,v): self._key = k self._va...
5a2854d84cb8c571242689869c497cede5d8120c
vasile98/SudokuSolver
/main.py
3,841
4.0625
4
# @todo function to find empty locations # @todo functions to find if a number is used in a row column or box # @todo implement the main solver function # Find empty locations in the grid # Given a grid find and empty location ,if it exist save it in the object l and return true # else return false def empty_l...
8f02915309b9a55052583ea24da45ca68e2307ac
SOJAEWAN/TIL
/sub_lecture/02_lecture.py
527
3.65625
4
""" n개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 값이 몇번째 수 인지 구하세요. 예를 들어, 서로 다른 n개의 자연수가 [3, 29, 38, 12, 57, 74, 40, 85, 61] 이라면 최대값은 85, 7번째 수 answer = [85, 7] """ lis = [3, 29, 38, 12, 57, 74, 40, 85] max_num = lis[0] result = [] for i in range(1, len(lis)): result = [] if max_num < lis[i]: max_num = lis[i]...
ce183d2eae5e4e129a0145de41efada56256241d
JessicaCoelho21/ASI
/ASI_FP_5/ASI_FP_05_ex4.py
654
4.28125
4
# Semana 5, exercício 4 import re # Verificar se a inicial de todos os nomes se encontra em letra maiúscula # e as seguintes em letra minúscula def upperCaseName(name): # Início da linha (^) com letra maíuscula seguido de letras minúsculas # Seguido do espaço (/s), depois novamente letra maíuscula seguido de...
e801118a34ac880ef296d541f8b91e62b24cfae2
JessicaCoelho21/ASI
/Exemplos_Exames/EN_2019_2020/LerFicheiro.py
1,531
3.71875
4
def ler(): despesas = {} val_data = {} valores = {} with open("despesas2019.csv") as fp: for linhas in fp: linhas = linhas.strip().split(";") # se o nome da despesa já existir na hashtable val_data if linhas[1] in val_data.keys(): # atribuir ...
757c5b54164ebe279401ef9cb63e920715352258
xatrarana/python-learning
/PYTHON programming/3.dictonary in python/dict problemss.py
269
4.15625
4
## i have to get the sentance as input form the user and cout the user input.. #sentence -> input,key->word, value->length of the word sent=input("Enter the sentence") words=sent.split(" ") count_words={words:len(words) for words in words} print(count_words)
5f9badac0bd6f71a18304a45c652de5f9f6736af
xatrarana/python-learning
/PYTHON programming/2.Python data structure&&list and tuple/nested list.py
197
3.875
4
'''name=[1,2,3,4,5,[1,2,3,4,5],6,7] print(name[2]) print(name[-3][2])''' '''squres=[1,4,16,25,36,48] print(squres[-1]=49)''' ###adding data in list ### append() or extend()
635385f3da34913511846c5f0010347b260aa5fa
houckao/grade-calculator-python
/grades_calculator.py
1,598
4.15625
4
""" This is a library of functions designed to be useful in a variety of different types of grade calculations. """ # import support for type hinting the functions from typing import List, Dict def average(grades: List[float]) -> float: """Calculates the average of an array of grades, rounded to 2 decimal places ...
af413e2ad30b1284c00bfd87db9fd70ab048b901
HoaiTV/Python
/hkteam_14_Tuple.py
2,636
3.671875
4
#Duoc gio han boi cap ngoac () print('*************************TUPE*********************') print('Day tupe rong') tup = () print(tup) #Dau tupe rong print('Day khong phai la tupe chi xem day la 1 bien nguyen') tup = (1) print(tup) # day khong phai la print('Tao 1 tupe = cac phan tu cach nhau bang dau , va duoc gioi...
5fec66e1174064a733c9151fa90abd9d51f4f95c
HoaiTV/Python
/hkteam_23_Kieu Boolean.py
667
3.765625
4
# # Boolean la mot kieu du lieu ma cac ngon ngu lam trinh ngay nay thuongf xuyen su dung. Python cung khong phai la ngoai le. # Boolean chi co 2 gia tri. # Mot la True # Mot la False print(3>1) print(ord('a')) print(ord('A')) ######################## Toan tu is ################################### #khi so sanh ha...
050bf4eb8875ee3769d5bd2bfca72b6682342521
dadaromeo/adventures-in-dataland
/foraging/utils.py
157
3.75
4
import math def euclidean(u, v): """The euclidean distance between two points.""" x,y = u i,j = v return math.sqrt((x-i)**2 + (y-j)**2)
5ba3343b97812bd1b2caadcb2230600b7b94bdf0
NameShort/Bit_Camp_Python
/function2.py
996
3.53125
4
#지역 변수와 전역변수 x=2 def func1(a): return x+a #호출 print(func1(1)) def func2(a): x=5 return x+a #호출 print(func2(1)) #불변형식을함수 내부에서 읽기+쓰기 g=1 def testScope(a): global g g=2 return a+g #호출 print(testScope(1)) print("전역변수:", g) #기본값을 셋팅 def times (a=10, b=20): return a*b #호출 print(times()) pr...
01b4368adae478bc23517006a899f18888ec1bbf
noob-ja/sem-vi
/WID3001 Functional and Logic Programming/tutorial 3.py
793
3.71875
4
from functools import reduce #Question 1 arr1 = [1,2,3] arr2 = [3,5,6] arrRes = [x for x in map(lambda x,y:x+y,arr1,arr2)] print(arrRes) arrRes = [x for x in map(lambda i:arr1[i]+arr2[i], range(len(arr1)))] print(arrRes) arrRes = list(map(lambda x,y:x+y, arr1, arr2)) print(arrRes) #Question 2 string = list('mississip...
d3bed2d94a92ee0a6b9640566016e0c9a447256d
tshealy/word-frequency
/word_frequency.py
532
3.8125
4
import re with open('sample.txt') as sample: file_text = sample.read() def word_frequency(): clean_text = re.sub(r'[^\w\s\']','', file_text).lower() #array clean_text = clean_text.split() #list frequency_dict = {} for word in clean_text: if word not in frequency_dict: freque...
0fc561eb62b29a0277be5cbfd43be2f6db21ea67
qihong007/leetcode
/2020_03_03.py
1,897
3.96875
4
''' Given a string, write a function to check if it is a permutation of a palin­ drome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. 给定一个字符串,编写一个函数判定其是否为某个回文串的排列之一。 回文串是指正反两...
2d83793c7dec9144dbe98c25a5ff4bf4a7593cf5
qihong007/leetcode
/2020_03_19B.py
2,446
4
4
''' 设计并实现一个算法,找出二叉树中某两个节点的第一个共同祖先。不得将其他的节点存储在另外的数据结构中。注意:这不一定是二叉搜索树。 例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4] 3 / \ 5 1 / \ / \ 6 2 0 8 / \ 7 4 示例 1: 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 输入: 3 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。 示例 2: 输入: root = [3,5,1,6,2,0,8,null,null,7,4],...
2def81ace31f5a3cdef3e678651f640e7ffa8b89
qihong007/leetcode
/2020_03_16.py
1,073
3.640625
4
''' 三步问题。有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶或3阶。实现一种方法,计算小孩有多少种上楼梯的方式。结果可能很大,你需要对结果模1000000007。 示例1: 输入:n = 3 输出:4 说明: 有四种走法 示例2: 输入:n = 5 输出:13 提示: n范围在[1, 1000000]之间 执行用时 :312 ms, 在所有 Python 提交中击败了62.20% 的用户 内存消耗 :12.8 MB, 在所有 Python 提交中击败了100.00%的用户 ''' class Solution(object): def waysToStep(self, ...
c4e289b3c851d27b251685e6ecce708b590c519e
qihong007/leetcode
/2020_04_16.py
2,169
4.125
4
''' 一个有名的按摩师会收到源源不断的预约请求,每个预约都可以选择接或不接。在每次预约服务之间要有休息时间,因此她不能接受相邻的预约。给定一个预约请求序列,替按摩师找到最优的预约集合(总预约时间最长),返回总的分钟数。 注意:本题相对原题稍作改动 示例 1: 输入: [1,2,3,1] 输出: 4 解释: 选择 1 号预约和 3 号预约,总时长 = 1 + 3 = 4。 示例 2: 输入: [2,7,9,3,1] 输出: 12 解释: 选择 1 号预约、 3 号预约和 5 号预约,总时长 = 2 + 9 + 1 = 12。 示例 3: 输入: [2,1,4,5,3,1,1,3] 输出: 12 解释: 选择 1 ...
546998c1aa5871a812553ec23159c00ba39d60a8
qihong007/leetcode
/2020_03_02.py
970
3.8125
4
''' Given two strings,write a method to decide if one is a permutation of the other. Example 1: Input: s1 = "abc", s2 = "bca" Output: true Example 2: Input: s1 = "abc", s2 = "bad" Output: false Note: 0 <= len(s1) <= 100 0 <= len(s2) <= 100 ''' class Solution(object): def CheckPermutation(self, s1, s...
7bda8a77649f5832e637e38a7f7564cc0b2fd4d1
qihong007/leetcode
/2020_03_04.py
1,138
4.3125
4
''' Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only u...
8acf3ab1ecf8220f736d5486303a301e768e1e2d
amiralishd/Data-Structures-and-Algorithms
/Graph/DFS.py
1,294
3.921875
4
class Node(object): def __init__(self, name): self.name = name self.adjacencyList = [] self.visited = False class DepthFirstSearch(object): def dfsprint(self, node): # DFS -> Stack -> FILO node.visited = True print(node.name) # ...
49760ac92b78be335b39c68f32c78e83f5974b2f
amiralishd/Data-Structures-and-Algorithms
/Sorting/SelectionSort.py
755
4.0625
4
#%% Selection Sort def selectionSort(list): # goes over all the elements from the first to one before the last for i in range(len(list)-1): # initialize the index of the minimum index = i # goes over all the elements from the one after "i" to the last one for j in range(i+1, len...
3761089895083f5fb8111f5b8db218c81fa86d71
khushalj/GOOGLE-HASH-CODE-2021
/pizza.py
2,318
4.1875
4
#!/usr/bin/python3 #Function that prints the solution to send to the judge def imprimirsolucion(deliveries): # We print number of shipments print (len (deliveries)) for between in deliveries: #We print each shipment generating a string and finally printing it #First, we put the...
ad23f03c48aa029033510918ca644643ad48af4c
pouya-mhb/My-Py-projects
/PublicProjects/1/tamrin4s.py
661
3.71875
4
number = int(input("please enter a number : ")) stringNumber = str(number) stringNumberArray=[] for i in stringNumber: stringNumberArray.append(i) l = len(stringNumberArray) print ("l=",l) m = int(l/2) print ("m=",m) if l%2==0: for i in range (0,m): for j in range (m,l): if stringNumberA...
9a20562783968cda53b51396d3a55fc0072ff9d0
pouya-mhb/My-Py-projects
/OOP Practice/prac1.py
1,658
4.15625
4
# A class for dog informations dogsName = [] dogsBreed = [] dogsColor = [] dogsSize = [] dogsInformation = [dogsName, dogsBreed, dogsColor, dogsSize] #Create the class class Dog (): #methods # init method for intialization and attributes in () def __init__(self, dogBreed, name, dog...
272ecae5432fdc867ed406d728418733938d6525
pouya-mhb/My-Py-projects
/PublicProjects/1/tamrin5.py
432
4.25
4
number = int(input("please enter a number : ")) number = 5 k = 2 * number - 2 for i in range(0, number): for j in range(0, k): print(end=" ") k = k - 1 for j in range(0, i + 1): print("* ", end="") print("") k = number - 2 for i in range(number, -1, -1): for j in range(k, 0, -...
1122197341ee0d210f6cf45b5f441adf44273260
blastedt/bash_manager
/src/module.py
344
3.609375
4
""" Jeffery Russell 9/29/17 """ def input_file(file_name): """ This file inputs the file defined by INPUT_FILE into a string line and returns it :return: a string array containing the lines of INPUT_FILE """ f = [] with open(file_name) as file: for line in file: f.append(li...
71601cdbe0f2b5bf68c36fe6ab72b73f6ebd66f0
tristanparry/Monochrome
/main.py
142,058
3.515625
4
# TRISTAN PARRY - ICS3U 2020 - SEMESTER 2 - CULMINATING TASK - PYGAME GAME - MONOCHROME (PLATFORMER GAME) # FILE: main # BEFORE RUNNING THIS CODE, AND/OR THE PROVIDED .EXE FILE FOR THE CODE, PLEASE ENSURE THAT ALL ASSET FILES ARE DOWNLOADED AND PLACED IN THE CORRECT FOLDER, PICTURES. #READ THE "READ_ME" FILE ATTACH...
d779c188dbd38b81d162f126fe2f502e2dd671d6
adityagrg/Intern
/ques2.py
234
4.3125
4
#program to calculate the no. of words in a file filename = input("Enter file name : ") f = open(filename, "r") noofwords = 0 for line in f: words = line.split() noofwords += len(words) f.close() print(noofwords)
33480d437af4002af4d426aa440c9b4774f0d40f
Young-Thunder/RANDOMPYTHONCODES
/lec2part2.py
1,179
3.765625
4
#!/usr/bin/python2 ##############################DATA TYPES OF PYTHON################################# ##Strings ##Numbers ##List ##Dictionaires ##Tuples ##Boolean ##############################String################################ #multiple ways to define a string name = "method1" print name name ='method2' p...
343677c250f436b5095c72985eadd30da635da00
Young-Thunder/RANDOMPYTHONCODES
/if.py
206
4.1875
4
#!/usr/bin/python car = raw_input("Which car do you have") print "You have a " + car if car == "BMW": print "Its is the best" elif car =="AUDI": print "It is a good car" else: print "UNKNOWN CAR "
ff9dd655c4b0f3e965ac4c6cf758f7e52a517f14
truthordata/advent-of-code-2020
/day-01/day1/day1_p2.py
437
3.515625
4
from math import prod from itertools import combinations from day1.helpers import get_raw_data, cleaned_data def dumb_brute_force(data, n_count, desired_sum): return [tup for tup, s in {tup: sum(tup) for tup in combinations(data, n_count)}.items() if s == desired_sum][0] if __name__ == '__main__': n = dumb_...
98532582d0a0d7375162d17d03f19fa20749d9ae
alexhzhai/hangman
/letter_game.py
7,543
3.921875
4
# Alex Zhai June 1 2018 # A simple game of hangman with 3 categories and 3 level settings. # Game first prompts with category choice (out of 3 categories) and level setting (easy, medium, hard). # The player has guesses letter in the word before reaching limit of strikes. # system functionality import os import rando...
3a54cc8906201d90fc6b883de2cbea8863406a2d
gjamesli2126/approximateKDtree
/try_python/binary_with_iter.py
2,181
4.03125
4
class Node: def __init__(self): self.key = 0 self.left = None self.right = None # Utility function to create new Node def newNode(key: int) -> Node: temp = Node() temp.key = key temp.left = None temp.right = None return temp # Utility function to perform # inorder tra...
e535d1c452c734ab747fda28d116d4b5fe2f9325
gia-bartlett/python_practice
/practice_exercises/odd_or_even.py
431
4.375
4
number = int(input("Please enter a number: ")) # input for number if number % 2 == 0: # if the number divided by 2 has no remainder print(f"The number {number} is even!") # then it is even else: print(f"The number {number} is odd!") # otherwise, it is odd ''' SOLUTION: num = input("Enter a number: ") mo...
135093fb5c69767946cfa237d10d4bee5276dab7
ChrisFourteen/DeepLearning
/SoftMax_digit.py
2,595
3.578125
4
''' Author:ChrisChan Date:2020-4-27 数据集:sklearn手写数字 softmax多分类 ''' from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris import time np.random.seed(10) data = load_digits() X...
519cff4e72a718e9f9828f617ef35c8496708e35
wyy998/Algorithm
/python/LetterCombinationsOfAPhoneNumber.py
752
3.859375
4
from typing import List #Letter Combinations of a Phone Number class Solution: _mapping = [ '', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz' ] def letterCombinations(self, digits: str) -> List[str]: if not digits or len(digits) == 0: return [] result = ...
626d8988b97db70d28e03e7e884120410120021a
igor91m/homework_1
/task_1.py
438
4.1875
4
# Создаем простые переменные name = input("Введите своё имя: ") print(f"Hello, {name}") price = 100 quantity = 50 total_cost = price * quantity print(f"Цена: {price} , Количество: {quantity}") print(f"Общая стоймость: {total_cost}") a = int(input(f"Введите цену: ")) b = int(input(f"Количество: ")) print(f"Общая стойм...
c6c7b5df1548a35cbeba660df3b02871c44cd0f8
egemenpamukcu/unga-analysis
/scrape_unga.py
4,875
3.546875
4
import pdftotext import requests import io import bs4 import re import pandas as pd import numpy as np import json def get_resolution_urls(start_year=1946, end_year=2021): ''' Crawls through the UN Digital Library and fetches the URLs for each resolution's profile between the given start and end years. ...
03d0df2365d10490641e078569b2164c81009fa2
malthunayan/python
/functions_task.py
2,165
4.21875
4
print("Hello and welcome to the Python Birthday Calculator!\n") def check_birthdate(d,m,y): from datetime import date if y>date.today().year: return False elif y==date.today().year: if m>date.today().month: return False elif m==date.today().month: if d>date.today().day: return False elif d<0: ...
4efc899fa34c5907de6b4d345766a71ae36f9d75
saikarthik007/Alarm-Clock
/alarm_clock.py
1,745
4.03125
4
""" Application to set alarm based on date and time Developed by : Karthik C """ import time from datetime import datetime from playsound import playsound class AlarmClock: """class to set alarm on time based on user input""" def __init__(self, alarm_date, alarm_time): """ init function""" sel...
312a56162a42931b50208db984b36d984df6701c
yuizho/atcoder
/python/abc049_c.py
308
3.671875
4
S = input() patterns = ['dreamer', 'dream', 'eraser', 'erase'] while len(S) != 0: isShaved = False for p in patterns: if S.endswith(p): S = S[:len(S)-len(p)] isShaved = True break if not isShaved: break print('YES' if len(S) == 0 else 'NO')
372bb856f8cbc2520a8970eff1aaf00cbd9daf66
JustinW01/Create-Task
/CardGameAP.py
2,291
3.984375
4
import random print('Welcome to the card game! What game would you like to play? Press 1 for blackjack, ') menuAnswer = int(input('press 2 for war, or press 3 for go fish.')) if menuAnswer == 1: print('Welcome to BlackJack!') print('--------------------Directions---------------------') print('You will be r...
56d9d62c470f79ff4e6c5a0f56cd1997ff0f9b0f
rboorugu14/Physics
/xc.py
470
3.8125
4
import numpy as np import matplotlib.pyplot as plt n = int(input("Enter total number of values: ")) fr = [] c = [] for i in range(n): fr.append(int(input("Enter FREQUENCY: "))) c.append(int(input("Enter CONDUCTOR: "))) xc = [] for i in range(n): xc.append((2*np.pi)*fr[i]*c[i]) plt.plot(xc,fr) plt.title(...
02ab98ce818d6569c105758d7651a2fd08c0ce4f
ramfir/ML
/Laba 1/1_b.py
122
3.9375
4
chars = ['a','b','c','d','e','a','a','b','c'] print({key: [i for i, j in enumerate(chars) if j == key] for key in chars})
7cba3c8593ab901bc8a4ff56d4eb834dc8430d0c
mikemaclean/MIT-Problem-Sets
/PSet2/test.py
1,167
3.921875
4
def match_with_gaps(my_word, other_word): ''' my_word: string with _ characters, current guess of secret word other_word: string, regular English word returns: boolean, True if all the actual letters of my_word match the corresponding letters of other_word, or the letter is the special symbol ...
15f0e1fbbe13791ccb8550886236b80045d6e17d
williron3960/Leetcode
/problems/#5.py
838
3.546875
4
class Solution: def longestPalindrome(self, s: str) -> str: def expand(left, right): while left >= 0 and right < len(s) and s[left] == s[right]: if right - left + 1 > self.maximum_length: self.start = left self.end = right ...
d7914275b3e9bb35967f05dfb23f8ba8f0fc7ec4
zero1hac/cp-practice
/IARCS/AVERAGE.py
449
3.78125
4
def check_average(arr, sim1): i = 0 N = len(arr) j = N-1 while i<j: if arr[i]+arr[j]==sim1: return 1 elif arr[i]+arr[j]<sim1: i+=1 else: j-=1 return 0 N = int(raw_input().strip()) arr = [] i=0 while i<N: num = int(raw_input().strip())...
42ed0687c49bb9297d3be0a468a31fb3c8575e24
zero1hac/cp-practice
/codeforces/133A.py
144
4.0625
4
string = raw_input().strip() if 'H' in string: print 'YES' elif 'Q' in string: print 'YES' elif '9' in string: print 'YES' else: print 'NO'
b64dcfd8310e0a91a5674a0426a212d4e4014f18
hoangstillalive/hoangstillalive
/seesion7/minihack5.py
192
4.3125
4
side = int(input("Enter side of shape you like:")) angle = 360/side from turtle import* shape("turtle") for i in range(side): forward(100) left (angle) mainloop()
6f718f9e0335bbd399f68b32403766a59b801479
hoangstillalive/hoangstillalive
/seesion7/minihack2.py
60
3.953125
4
m = int(input("Write down a number you like:")) print(m**2)
523eccddb6c9a8077ff8a4602e234d42daf5d036
hoangstillalive/hoangstillalive
/seesion9/minihack1.py
604
3.859375
4
items = ["red","blue","orange"] print("Our color list: ") for n, item in enumerate(items): print(n+1,".",item) # a = input("Enter a new color: ") # items.append(a) # print("Our new color list: ") # print(*items, sep=(", ")) # i = int(input("Enter position: "))-1 # print("Color at position",i+1,":",items[i]) m =...
8775c53541f3fe183ce5da778875456cc1992072
JavaPhish/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/2-uniq_add.py
214
3.765625
4
#!/usr/bin/python3 def uniq_add(my_list=[]): total = 0 used_ints = [] for i in my_list: if i not in used_ints: total = total + i used_ints.append(i) return total
8596578006399b3095b2a572e3f08aa0789031ba
JavaPhish/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
340
4.28125
4
#!/usr/bin/python3 """ Adds 2 integers """ def add_integer(a, b=98): """ Adds A + B and returns """ if (type(a) is not int and type(a) is not float): raise TypeError("a must be an integer") if (type(b) is not int and type(b) is not float): raise TypeError("b must be an integer") retur...
448993d94b43ee11153236459cf311af9a3b1f45
JavaPhish/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
256
4
4
#!/usr/bin/python3 """ Finds the peak of a list """ def find_peak(list_of_integers): """ Find the peak """ highest = None for num in list_of_integers: if highest is None or num > highest: highest = num return highest
5defcac513c144d55f289d4684adf875f3c03a8c
JavaPhish/holbertonschool-higher_level_programming
/0x03-python-data_structures/4-new_in_list.py
373
3.6875
4
#!/usr/bin/python3 def new_in_list(my_list, idx, element): if (len(my_list) - 1 >= idx and idx >= 0): new_list = [] for i in range(0, len(my_list)): if (idx == i): new_list = new_list + [element] else: new_list = new_list + [my_list[i]] ...
a6b0b97119142fff91d2b99dc01c945d5409c799
JavaPhish/holbertonschool-higher_level_programming
/0x06-python-classes/4-square.py
873
4.125
4
#!/usr/bin/python3 """ AAAAAAHHHHH """ class Square: """ Square: a class. """ def __init__(self, size=0): """ Init - init method """ if type(size) is not int: raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") ...
0f7d3a918e1e61f5399a26bd2bfbe1514207d227
JavaPhish/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/9-multiply_by_2.py
190
4
4
#!/usr/bin/python3 def multiply_by_2(a_dictionary): new_dict = dict(a_dictionary.copy()) for key in new_dict.keys(): new_dict[key] = new_dict[key] * 2 return new_dict
51d6b2b2a5a86b4aca89bc6f7d5f90d27a8b0c14
Class-99476-Winter-2020/Assignment-2
/helloworld.py
331
3.65625
4
""" helloworld.py A program to say hello """ if __name__ == '__main__': print('Hello, Git world!') question = input("Would you like to learn Python? [Y/N]") if question == "n": print("No problem") if question == "y" print("That's amazing! Go to https://caps.sheridancollege.ca/products/python-foundations.a...
b141a46b796ab52f0d04a5ae7370ca40232950e0
lucashaensch/compress-yo
/compression.py
1,433
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import helper lenght_string = 0 def encode_rle(): # Encoda string inputada lst = [] prev = '' count = 1 output_string = '' output_file = open('output.txt','w') # Get input string input_file = open('input.txt','r') input_string = input_file.read() input_file.clo...
18be460d78a4a7177852a40e463d53a7be0c8dfb
miraceti/Python_script
/CodingPrivacy2.py
486
3.6875
4
import tkinter as tk import PIL from PIL import Image, ImageTk root =tk.Tk() root.title("resize image in label") root.geometry("300x150") #1rst approach photo = tk.PhotoImage(file="mando2.png") #2nd approach photo2 = Image.open("mando2.png") resized_image = photo2.resize((300,150), Image.ANTIALIAS) converted_image =...
649b70c784a4bebd56897ba1f7b89fc98277a6e8
OlayinkaAtobiloye/Data-Structures
/Data Structures With OOP/linkedlist.py
2,391
4.3125
4
class Node: def __init__(self, value, next_=None): self.value = value self.next = next_ class LinkedList: """A linked list is a linear data structure. It consists of nodes. Each Node has a value and a pointer to a neighbouring node(i.e it links to it's neighbor) hence the name linked list....
59c9e4ce10bbfcff84f1d0b23d2938ea98e67783
motleytech/crackCoding
/RecursionAndDyn/tripleStep.py
568
4.1875
4
'''Count ways to get to nth step, given child can take 1, 2 or 3 steps at a time''' # let f(n) be the ways to get to step n, then # f(n) = f(n-1) + f(n-2) + f(n-3) def tripleStep(n): 'return number of ways to get to nth step' if 1 <= n <= 3: return n a, b, c = 1, 2, 3 n = n-3 while n > 0:...
a9d49de61d30544b762369c2fcb38dbb3e39ce08
motleytech/crackCoding
/arraysAndStrings/oneaway.py
1,825
3.8125
4
''' Check if the 2 given strings are just 1 or 0 differences away A difference is defined as 1 character missing or 1 character different This implies that 1. The lengths of the 2 strings can at most differ by 1 2. If strings have different length, we compare the larger with the smaller string, while skipping at most ...
aa12763f9a23245e6f9ca4ab11d96faee7c63162
motleytech/crackCoding
/hard/smallestK.py
1,068
3.578125
4
'adding solution for smallest k problem' from random import randint, shuffle def partition(arr, a, b): 'parition the arr between position a, b using pivot=arr[a]' pivot = arr[a] p1, p2 = a+1, b while p2 >= p1: if arr[p2] < pivot: arr[p1], arr[p2] = arr[p2], arr[p1] p1 +...
eb86e2905b048e52f03dc815e61022f8f581e7b8
motleytech/crackCoding
/bitManipulation/drawLine.py
1,060
3.96875
4
'''draw a bitwise line from (x1, y) to (x2, y)''' def drawLine(screen, width, x1, x2, y): sbyte, sbits = x1 / 8, x1 % 8 ebyte, ebits = x2 / 8, x2 % 8 if ebyte > sbyte: sbits = 7 - sbits while sbits >= 0: screen[y][sbyte] |= 1 << sbits sbits -= 1 cbyte = sby...
0eaabc6474396fc098c038667a838bf486705375
motleytech/crackCoding
/arraysAndStrings/uniqueCharacters.py
1,703
4.21875
4
''' determine if a string has all unique characters 1. Solve it. 2. Solve it without using extra storage. Key idea: Using a dictionary (hashmap / associative array), we simply iterate over the characters, inserting each new one into the dictionary (or set). Before inserting a character, we check if it already exists...
a764f625c5eaeb3de51a5b4b051ac963c0e6ee40
motleytech/crackCoding
/moderate/bestLine.py
991
3.671875
4
''' find the line which passes through max number of points ''' from collections import defaultdict from itertools import combinations INF = float('inf') def getLine(p1, p2): ''' returns (m, c) for a line (y = mx + c) in case of m==INF (vertical line), c corresponds to the x offset ''' if p2[0] =...
b572a4c0c9d693a2c48c86f62d87e4b9dd3c9cfe
motleytech/crackCoding
/hard/randomSet.py
360
3.703125
4
'''random selection of m elements from array''' from random import gauss def select(arr, m): 'return m random elements from arr' nums = sorted([(gauss(0, 10), i) for i, x in enumerate(range(52))]) return [arr[x[1]] for x in nums[:m]] def test(): 'test for select method' print select(range(52), 5)...
e7d7975306ff4dc19aace83acc35a0b95172a3e0
motleytech/crackCoding
/arraysAndStrings/isStringRotated.py
788
4.125
4
''' Given 2 strings s1 and s2, and a method isSubstring, write a method to detect if s1 is a rotation of s2 The key ideas are... 1. len(s1) == len(s2) 2. s1 is a substring of s2 + s2 If the above 2 conditions are met, then s2 is a rotation of s1 ''' def isSubstring(s1, s2): ''' Returns True if s1 is a subst...
c8f82e3a9b6c95889d81b182504a7cf772d0c785
motleytech/crackCoding
/treesAndGraphs/matchSubtree.py
1,736
3.84375
4
#Tl and T2 are two very large binary trees, with Tl much bigger than T2. Create an #algorithm to determine if T2 is a subtree of Tl. #A tree T2 is a subtree ofTi if there exists a node n in Ti such that the subtree of n is identical to T2. #That is, if you cut off the tree at node n, the two trees would be identical. ...
6a6a06d047a95ed76a60ed9f2392016f6d379ccf
motleytech/crackCoding
/arraysAndStrings/urlify.py
1,506
4.34375
4
''' Replace all spaces in a string with '%20' We can do this easily in python with the string method 'replace', for example to urlify the string myurl, its enough to call myurl.replace(' ', '%20') Its that simple. To make the task a little more difficult (to be more in line with what the question expects), we will c...
b3e4ba04d27750de4b6c64a8860617415ec28434
motleytech/crackCoding
/hard/multiSearch.py
1,309
3.875
4
'''solution for the multisearch problem''' def createLookup(t): 'create a lookup structure for matching words' lookup = {} for x in t: curr = lookup for y in x: if y not in curr: curr[y] = {} curr = curr[y] curr['word'] = x return lookup ...
d9bab7df52b5bfbd7132823cbe59fdb3116c8494
motleytech/crackCoding
/utils/estimateOrder.py
1,604
3.75
4
''' estimate the order of the running time of an algorithm emperically ''' import timeit from numpy.polynomial.polynomial import polyfit, polyval def estimateOrder(func, inputDataFunc, sizes=None, numRuns=None): ''' estimates the order of the runtime of the algorithm by recording runtimes for the func for ...
edf168e27bffaa08a8f44733f3b55a524ff3052f
ZswiftyZ/Nested_Control_Structures
/Nested Control Structures.py
1,064
4.25
4
""" Programmer: Trenton Weller Date: 10.15.19 Program: This program will nest a for loop inside of another for loop """ for i in range(3): print("Outer for loop: " + str(i)) for l in range(2): print(" innner for loop: " +str(l)) """ Programmer: Trenton Weller Date: 10.22.19 Program: Aver...
7cb4a4edd07a1fbfb875a624a64e26b2dc80d3d9
diogoduartec/Competitive-Programming
/Online_Judge-Solutions/URI/strings/2242.py
178
3.625
4
inp = input() out = '' for c in inp: if(c=='a' or c=='e' or c=='i' or c=='o' or c=='u'): out += c outr = ''.join(reversed(out)) if(out == outr): print('S') else: print('N')
0f16d123d1e526316327ac27f2accaa4a0b550ca
HuangHuiBeyond/algorithm-code
/target_offer/重建二叉树_6_7.py
1,022
3.5625
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回构造的TreeNode根节点 def reConstructBinaryTree(self, pre, tin): # write code here if not pre or not tin: return None root_val = pre[0] ...
dbb0839fe0a9e7a4457f44caac9e441ec4ad33ac
HuangHuiBeyond/algorithm-code
/yy_欢聚时代_top_k问题和堆排序_20190909.py
2,900
3.765625
4
# 调用的heapq库(首选) import heapq A = [5, 6, 4, 2, 8] def top_k(A, k): return heapq.nlargest(k, A) print(top_k([5, 6, 4, 2, 8], 3)) def findKthLargest(A, k): return heapq.nlargest(k, A)[-1] print(findKthLargest([5, 6, 4, 2, 8], 3)) def heap_sort(A): size = len(A) heapq.heapify(A) return [heapq.heappop(...
a292e2c6bce95cb3405ed9eae132868cd3a77fe4
HuangHuiBeyond/algorithm-code
/target_offer/合并两个排序的链表_17_25.py
1,283
3.796875
4
from linked_list import SingleLinkedList class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 返回合并后列表 # 迭代代码 def Merge(self, pHead1, pHead2): # write code here dummy = ListNode(None) pointer = dummy while pHead1 and ...
2a49c378866e0993912642a04a43089af5a34bd9
Harshhg/python_data_structures
/Sorting/selection_sort.py
391
4.0625
4
def selection_sort(ar): for i in range(0,len(ar)): min=i #Stroing index value only for j in range(i,len(ar)): if(ar[j]<ar[min]): #Comparing value at index min=j ar[i],ar[min]=ar[min],ar[i] #Swapping index values ar=[2,4,17,1,9,3] print(...
fe6259b11728d674f4e31caef1a1d284bc2b225a
Harshhg/python_data_structures
/Arrays/alternating_characters.py
634
4.125
4
''' You are given a string containing characters A and B only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string. Your task is to find the minimum number of required deletions. For example, given the ...
368a07b7981351a62e8090e04924e62e0a03bafa
Harshhg/python_data_structures
/Graph/py code/implementing_graph.py
1,481
4.28125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Implementing Graph using Adjacency List from IPython.display import Image Image("graph.png") # In[6]: # Initializing a class that will create a Adjacency Node. class AdjNode: def __init__(self,data): self.vertex = data self.next = None # In[1...
a3e2ed6d9cf15082d93f1fdd7239b3fb965d3f8a
Harshhg/python_data_structures
/tree/counting_leaf_nodes.py
297
4.09375
4
# Shortest Recursive Solution to count leaf nodes in a tree # This function takes root of tree as a parameter, and returns the number of leaf nodes count. def countLeaves(root): if not(root.left and root.right): return 1 return (countLeaves(root.left) + countLeaves(root.right))
a77c05df139a1e84563a377195257b4b586905dc
Harshhg/python_data_structures
/Hashing/remove_duplicate_characters.py
440
3.9375
4
# Removing Duplicates from the array of characters.. using HASHING # Used Dictionary for hashing implementation. ar = ['a','b','c','a','d','c','e','a','e','k','c'] dict = {} for x in ar: if x not in dict: dict[x]=1 else: dict[x] = dict[x]+1 new=[] for x in ar: if dict[x] > 0: ...
a75a98d9da16dabb636dc66ed40a1daa7c36cf05
Theneaaaaaa/unit_nine
/Documents/unit_eleven/breakout.py
3,318
4.1875
4
# Thenea Sun # Dec. 20th # A breakout game about letting ball hits the paddle and get points from it import pygame, sys from pygame.locals import * import brick import paddle import ball def main(): # Constants that will be used in the program APPLICATION_WIDTH = 400 APPLICATION_HEIGHT = 600 PADDLE_Y...
f6a78c9d60a1ca792c1dd79d86ca349f60b6b031
Priyansh2906/cryptographic-algorithms
/Dieffie_hellman.py
1,444
3.953125
4
'''select a prime number - p select value of aplha (primitive root of prime number p) pvt a , pvt_b , public_a,public_b select random value for pvt a and b less than p public_a = alpha**pvt_a%p public_b = alpha**pvt_b%p key_a = alpha^b^a mod p key_b = alpha^a^b mod p''' import random primes = [] for e in range(1, 100)...
8d36e43835209b43bdb43ed6c3572a91976eac33
alls77/battlefield
/unit_factory.py
1,500
3.546875
4
from abc import abstractmethod from Units.vehicle import Vehicle from Units.soldier import Soldier from Structures.squad import Squad from Structures.army import Army from Strategies.strategies import STRATEGIES from Configs.constants import VEHICLE UNITS = {} def unit_register(name): def register(...
6d9e626308c9d866e15c071a6b0e74a3f38eeda5
NiklasAlexsander/IN3110
/assignment3/wc.py
2,168
4.40625
4
#!/usr/bin/env python import sys def main(): """Main function to count number of lines, words, and characters, for all the given arguments 'filenames' given. A for-loop goes through the array of arguments given to wc.py when run from from the terminal. Inside the loop each argument will be 'open' for...
596450517f752fa8adf4c189febdcafe0176dbb6
NiklasAlexsander/IN3110
/assignment4/modules/blur1/blur_1.py
1,510
3.984375
4
import cv2 import numpy as np def run(src): """ Function to run manual blur with python-only (numpy to store array) calculations on a three-dimensional numpy-array with three for-loops. Loops representing depth, rows, and columns. args: src (numpy-array): image to be blurred returns:...
5d86b8b02a006566aefd819c9249151916514c82
TECHNOCRATSROBOTICS/ROBOCON_2018
/Computer Science/Mayankita Sisodia/ll.py
1,564
4.53125
5
# TO INSERT A NEW NODE AT THE BEGINNING OF A LINKED LIST class Node: # Function to initialize the node object def __init__(self, data): self.data = data # Assign data to the node. self.next = None # In...
4264f93548e885e328aff8fc93b63fc47586151e
TECHNOCRATSROBOTICS/ROBOCON_2018
/Computer Science/Sanket/task3/numpart1.py
801
3.734375
4
import numpy as np a=np.array([1,2,3],dtype=complex,ndmin=3) print(a) ##defining a datatype employee = np.dtype([('name','S20'), ('age', 'i1'), ('empid', 'i1')]) a = np.array([('sanket1', 21, 1),('sanket2', 18, 2)], dtype = employee) print(a) ##shape of array a=np.array([[1,2,3],[4,5,6],[7,8,9]]) print (a.sh...
dca26a9e0cc1952bd168baae5621036c8ac19e8d
TECHNOCRATSROBOTICS/ROBOCON_2018
/Computer Science/Mayankita Sisodia/tree.py
1,955
4.28125
4
class Node: def __init__(self, val): #constructor called when an object of class Node is created self.left = None #initialising the left and right child node as null self.right = None self.data = val ...
70ab1084b2cf5aa33a81f2001fe59a1b52629702
TECHNOCRATSROBOTICS/ROBOCON_2018
/Computer Science/Mayankita Sisodia/led blinking raspberry pi.py
370
3.734375
4
import time import RPi.GPIO as GPIO ## Import GPIO library GPIO.setmode(GPIO.BOARD) ## Use board pin numbering GPIO.setup(11, GPIO.OUT) ## Setup GPIO Pin 11 to OUT while True: GPIO.output(11,True) ## Turn on Led time.sleep(1) ## Wait for one second GPIO.output(11,False) ## Turn off Le...
e121a3928af22241900acbf4bbfb36d9cf6752ec
aryamanarora/project-euler
/001 - 010/009.py
313
3.625
4
#!/usr/bin/env python3 import sys import math def main(): (m, n, result) = 0, 0, 0 while m < 1000: while n < m: if m*(m + n) == 500: print((m**2 - n**2) * (2*m*n) * (m**2 + n**2)) n += 1 n = 0 m += 1 if __name__ == '__main__': main()
78b74fdc186a7348eb8cc5f66109f654409cb8ca
aryamanarora/project-euler
/001 - 010/004.py
314
3.5
4
#!/usr/bin/env python3 import sys def main(): answer = 10000 for i in range(100, 1000): for j in range(100, 1000): if i*j == int(str(i*j)[::-1]) and i*j > answer: answer = i * j print(answer) if __name__ == '__main__': # call main main()
e431b097c08ecc6f9a43a0b8f9e5288c5bb06992
MDCGP105-1718/portfolio-DanielSmith1411
/ex9.py
523
3.78125
4
semi_annual_raise = 0.07 annual_return_rate = 0.04 r = 1.04 down_payment = 0.25 * house_cost house_cost = 1000000.00 months = 36 epsilon = 100.00 low = 0.00 high = months guess = (high + low) / 2.00 annual_salary = float(input("Enter your annual salary: ")) portion_saved = float(input("Enter the percentage of your sala...
86a4ab9b523160101d86c80a4707a59dec6ff19c
pinnokio/adventofcode-2020
/day-2/puzzle.py
1,758
3.953125
4
#!/usr/bin/env python3 import argparse INPUT_FILE = "input" def parse_input(line): pw_row = {} raw = line.split(" ") pw_row["min"], pw_row["max"] = raw[0].split("-") pw_row["char"] = raw[1].strip(":") pw_row["pw"] = raw[2].strip("\n") return pw_row def input_read(input_file): input = ...