blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
217f36600e8b9ab1a86d6324347e9ebddcaf1ea7
MisterHat-89/geekBrainsPython
/lesson_1/exam_3.py
197
3.796875
4
numbers = int(input("Введите число > ")) print(f"{numbers}", "+", f"{numbers}" * 2, "+", f"{numbers}" * 3, "=", int(f"{numbers}") + int(f"{numbers}" * 2) + int(f"{numbers}" * 3))
5867f763f39af1f44c8805e01235068fa92cb1f7
MisterHat-89/geekBrainsPython
/lesson_3/exam_2.py
1,021
3.59375
4
# 2. Реализовать функцию, принимающую несколько параметров, # описывающих данные пользователя: имя, фамилия, год рождения, город проживания, # email, телефон. Функция должна принимать параметры как именованные аргументы. # Реализовать вывод данных о пользователе одной строкой. def base_data(name, surname, date, city,...
6f6a83c6661a2d80a173c1e8b069004e7e8ca744
MisterHat-89/geekBrainsPython
/Lesson_5/exam_2.py
577
4.21875
4
# 2. Создать текстовый файл (не программно), сохранить в нем несколько строк, # выполнить подсчет количества строк, количества слов в каждой строке. text = "" f_file = open(r'dz2.txt', 'r') print(f_file.read()) print("") count_words = 0 lines = 0 f_file.seek(0) for line in f_file.readlines(): lines += 1 count...
fe48ded497a4392d05c2d4135d752fe33a92bb13
MisterHat-89/geekBrainsPython
/lesson_4/exam_2.py
846
4.09375
4
# 2. Представлен список чисел. Необходимо вывести элементы исходного списка, # значения которых больше предыдущего элемента. # Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. # Для формирования списка использовать генератор. # Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 5...
68ef6e343455f73bc4af601651462ffaa6c6131f
MisterHat-89/geekBrainsPython
/Lesson_5/exam_6.py
1,734
3.71875
4
# 6. Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный # предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество. # Важно, чтобы для каждого предмета не обязательно были все типы занятий. Сформировать словарь, содержащий # название предмет...
642b1efa89b997f236872f4fcb1e7b14281661fe
emrecelik95/CSE321-Homeworks
/HW4/find_kth_book_2_141044024.py
833
3.578125
4
# Emre Celik - 141044024 , CSE 321 - HW4, Part4 # """ find_kth_book_2 fonksiyounda onceki parttan farkli olarak, oncekinde midlerin toplamina bagli olarak ikisini ayri ayri olarak boluyorduk(logm + logn).Burada ikisini ayni birlikte gibi dusunup bolme islemi yapiyoruz(log k). """ def find_kth_book_2(m, n, k): if...
3a8034bdfa8a15f2c01b1adc065f5b956874a302
rssbrrw/PythonProgrammingPuzzles
/generators/compression.py
5,928
3.71875
4
"""Puzzles relating to de/compression.""" from puzzle_generator import PuzzleGenerator from typing import List # See https://github.com/microsoft/PythonProgrammingPuzzles/wiki/How-to-add-a-puzzle to learn about adding puzzles def _compress_LZW(text): # for development index = {chr(i): i for i in range(256)} ...
55f5872fdfa74dc1e61764d2fe484e45be400652
rssbrrw/PythonProgrammingPuzzles
/generators/study.py
12,865
4.15625
4
""" Puzzles used for the study. """ from puzzle_generator import PuzzleGenerator from typing import List # See https://github.com/microsoft/PythonProgrammingPuzzles/wiki/How-to-add-a-puzzle to learn about adding puzzles class Study_1(PuzzleGenerator): @staticmethod def sat(s: str): """Find a string...
85f39d8cbab6bad1e778bea01c132b931b15e21b
benmazur/Arithmetic-Tutor-Python-Program
/program1.py
13,572
4.34375
4
# Stephen Buchanan, Benjamin Mazur, Section 20L, 10/12/13 # Program 1 # Program 6-13 #imporing libraries from cisc106_32 import* import random # seting a globle variable for Random Number RANDOM_NUMBER1 = random.randint(1, 100) RANDOM_NUMBER2 = random.randint(1, 100) # Choices for the Menu ADDITION = "a" SUBTRAC...
f91c87f85bb2a97e6dea6d3e0d622ad4b003e239
rasooll/Python-Learning
/azmoon4/part2.py
364
4.34375
4
def find_longest_word(input_string): maxlen = 0 maxword = "" input_list = input_string.split() #print (input_list) for word in input_list: #print (len(word)) if len(word) >= maxlen: maxlen = len(word) maxword = word #print (maxlen, maxword) return maxword print (find_longest_word("salam in ye matn az...
da7f8c996bf6f38707729fbd13cce8140fa1a23d
rasooll/Python-Learning
/week6/Tamrin/vowels.py
233
3.703125
4
def _vowels_ (simple_string): number = 0 simple_string = simple_string.lower() vowels_character_list = ['a', 'e', 'o', 'i', 'u'] for char in simple_string: if char in vowels_character_list: number = number + 1 return number
7ade4f97ff1803bbe46d68add6243f30e80823bd
rasooll/Python-Learning
/week7/dict.p6.py
489
3.765625
4
def _dictionary_of_vowel_counts_sample_(sample_string): sample_string_nospace = sample_string.replace(' ', '') sample_string_nospace_lower = sample_string_nospace.lower() vowels_character_list = ['a', 'e', 'o', 'i', 'u'] out_dict = {} for character in sample_string_nospace_lower: if character in vowels_character...
0bde03414b3719f3371f80a58e28891d0656ed43
rasooll/Python-Learning
/Tamrin_Lists/Adad-zoj-beyn-a-b.py
131
3.5625
4
def adadezoj(a, b): i = a mylist = [] while (i >= a) and (i < b): if (i%2) == 0 : mylist.append(i) i = i+1 return mylist
8f2063568eb595274faa40e44467ad465f459b2d
rasooll/Python-Learning
/mian-term/barname4.py
388
3.625
4
# Type your code here def crazy_list(some_list): mylist = some_list lenlist = len(mylist) aval = 0 akhar = -1 natije = 0 for i in range(0,lenlist): if mylist[aval] != mylist[akhar]: natije = natije + 1 aval = aval + 1 akhar = akhar - 1 if natije == 0: return True else: return False li...
05bcd827387fb6eb5e287f015f3a2f37d8e34bba
rasooll/Python-Learning
/Taklif2/part2.py
227
3.71875
4
def single_insert_or_delete(s1,s2): if len(s1) == len(s2): s1 = s1.lower() s2 = s2.lower() if s1 == s2: return 0 else: return 2 elif (len(s1) == len(s2)-1) or (len(s1) == len(s2)+1): return 1 else: return 2
cce4f590479204726328e9c785ca28c44afd9e23
rasooll/Python-Learning
/Tamrin_Lists/unique_list_sample2.py
155
3.6875
4
def unique_list_sample(A, B): mylist = A + B newlist = [] for element in mylist: if element not in newlist: newlist.append(element) return newlist
ccca796e469d40985f53e3665c8a054ffdeae183
rasooll/Python-Learning
/week6/methods/5.py
239
4.03125
4
#x="hello are you there" #print (x.split()) #my_str = "hello hello" #print (my_str.split('l')) my_str='Computer science' print (my_str.split ('e')) x="frequency of letters" print (x.split("e",2)) x="Mississippi" print (x.split("s",3))
0607152164dde883d6aa224c21964f90b80de5b9
sorb999/machine-Learning
/others/dataframe.py
437
4.09375
4
# dataframe import numpy import pandas myarray = numpy.array([[1, 2, 3], [4, 5, 6]]) rownames = ['a', 'b'] colnames = ['one', 'two', 'three'] mydataframe = pandas.DataFrame(myarray, index=rownames, columns=colnames) print('myarray:') print(myarray) print('rownames:') print(rownames) print('colnames:') print(colname...
0104bed0a328f02fdd5a350ce42f1cbbfb3c6714
FajnyNick2121/wd_zaocznie_1
/start.py
279
3.609375
4
print("Hello world!") # def main(): # for elem in kolekcja: # costam() # lancuchy znakow liczba = "ala" liczba = 0 liczba = 0.01 # PEP8 imie = "ala" print(imie) print(type(imie)) print(type(5)) print(type(5.5)) print(type(True)) imie= str("Ala") liczba= str(100)
1269f7390bfc63e8962b3bda78a114500e5f03fa
Nilesh2000/CollegeRecordWork
/Semester 2/Ex12d.py
1,087
4.25
4
myDict1 = {'Name':'Nilesh', 'RollNo':69, 'Dept':'IT', 'Age':18} #print dictionary print("\nDictionary elements : ", myDict1) #Printing Values by passing keys print("Student department : ", myDict1['Dept']) #Editing dictionary elements myDict1['Dept']="CSE" print("After Editing dictionary elements : " , myDict1) #Ad...
38d36983198c2526c4979fc7f1fc30883f19bb8f
Nilesh2000/CollegeRecordWork
/Semester 2/Ex10a.py
496
3.671875
4
class Student: def get_details(self): self.name = input("Enter you name : ") self.rollNo = input("Enter roll number : ") self.dept = input("Enter Department : ") def show_details(self): print("\nStudent name : ", self.name) print("Student roll number : ", self.rollNo) ...
fe6020694e7d2a60f3543d99df991d97a00563cc
Nilesh2000/CollegeRecordWork
/Semester 2/Ex11a.py
528
3.921875
4
class Base: def __init__(self, a, b): self.a = a self.b = b class Derived(Base): def addNumbers(self): self.Add = self.a + self.b return self.Add def subNumbers(self): self.Diff = self.a - self.b return self.Diff def main(): Obj = Derived(5, 2...
44012b8dd752a03b4f333c055d6fcdb4ecf136ed
paradisees/test
/interview/tree.py
1,137
3.984375
4
class TreeNode(object): def __init__(self,data=0,left=0,right=0): self.data=data self.left=left self.right=right class BTree(object): def __init__(self,root=0): self.root=root def preOrder(self,treenode): if treenode is 0: return print(treenode.da...
1a6ac55613557bcf7fba290cc6dbe335fbaf4031
Kanrail/5143_Shell_Project
/cmd_pkg/chmod.py
804
3.734375
4
import os def chmod (**kwargs): """ CHMOD User Commands CHMOD NAME chmod - changes the permissions of file or directory SYNOPSIS chmod MODIFIER [FILE...] DESCRIPTION chmod changes the permissions of FILE, or directory, with MODIFI...
2d3e32a6c4ae3116a6bc7827a20ab6eca7a1af5c
kingdehu/CourseraML_PY
/basicFunction/softmax_F.py
423
3.53125
4
#calculates the probabilities distribution of the event over n different events import numpy as np import matplotlib.pyplot as plt def softmax(inputs): softmax_scores = [np.exp(x)/float(np.sum(np.exp(inputs))) for x in inputs] return softmax_scores def plot(x,y): plt.plot(x, y, 'r--') plt.show() ...
774fc16ce9d5e591f88d58e1e26586c9dafe422d
CaptianZhangg/gitt
/practice/class.py
541
3.703125
4
class A(object): def __init__(self): self.n = 10 def minus(self, m): self.n -= m class B(A): def __init__(self): self.n = 7 def minus(self, m): super(B, self).minus(m) self.n -= 2 class C(A): def __init__(self): self.n = 12 def minus(self, m): ...
f0778146abc57271d1587461b9893289fd65dc86
bedoyama/python-crash-course
/basics/ch4__WORKING_WITH_LISTS/2_first_numbers.py
358
4.375
4
print("range(1,5)") for value in range(1, 5): print(value) print("range(0,7)") for value in range(0, 7): print(value) print("range(7)") for value in range(7): print(value) print("range(3,7)") for value in range(3, 7): print(value) print("range(-1,2)") for value in range(-1, 2): print(value) num...
8b8e3c886a6d3acf6a0c7718919c56f354c3c912
bedoyama/python-crash-course
/basics/ch5__IF_STATEMENTS/3_age.py
338
4.15625
4
age = 42 if age >= 40 and age <= 46: print('Age is in range') if (age >= 40) and (age <= 46): print('Age is in range') if age < 40 or age > 46: print('Age is older or younger') age = 39 if age < 40 or age > 46: print('Age is older or younger') age = 56 if age < 40 or age > 46: print('Age is o...
4477730632e14ec304e08b7bdb5124fc85feb3d7
DianeDeeDee/Python_Machine_Learning
/Yazabi/Python-curriculum /Inermediate_Py/Dic_Obj_List_Excep_Gene.py
7,617
4.84375
5
#import beginner_python_1 as bp1 print("--------------------Dictionaries") """ When to Use It: When describing what you want to do, if you use the word "map" (or "match"), chances are good you need a dictionary. Use whenever a mapping from a key to a value is required. """ state_capitals={ 'New York': 'Albany',...
85a1bf1bca9d44da7acd6e0ca060a452e82db171
Qeinayd/playground
/codewars/kyu_6/python/unique_in_order.py
323
3.84375
4
# https://www.codewars.com/kata/unique-in-order/ def unique_in_order(iterable): if not iterable: return [] if len(iterable) < 2: return list(iterable) result = [iterable[0]] for x in iterable[1:]: if result[-1] != x: result.append(x) return resu...
24d53b20741289a05b2e54e4df85941ef67af0ef
Qeinayd/playground
/codewars/kyu_5/python/simple_pig_latin.py
226
3.9375
4
# https://www.codewars.com/kata/simple-pig-latin/ def pig_it(text): return ' '.join( word[1:] + word[0] + 'ay' if all(x.isalpha() for x in word) else word for word in text.split(' ') )
a6d80b5bf212c2ad8acd27da0ac2cf1a1a6f2782
botaor/Python-Samples
/TextFiles.py
2,871
4.0625
4
#!/usr/bin/python # -*- coding: latin-1 -*- "Module to show how to handle text files" # This line must be at the beginning of the file from __future__ import print_function import sys import codecs def ReadFileComplete( filename ): "Read the whole contents of the file to a variable" f = open( filename, 'rU' ) ...
5bdecfc8658edb6c4bbeaa46048aa70f752f039f
xxzzxxzzzzs/pythonDemo
/venv/list.py
1,271
3.71875
4
# -*- coding: UTF-8 -*- import time; # 引入time模块 # ticks = time.time() # print "当前时间戳为:", ticks # str='''sdasda123 # 123]@@!3 # 213!@ # @!31#12#12''' # list=str.split("@"); # print str.split("@") # c=0 # for s in list: # if len(s)>0: # c+=1 # print c # list2=str.splitlines() # print list2 # str3= " ".join...
13cedc7bf113d6b698adb0c166482918fa687b47
xxzzxxzzzzs/pythonDemo
/单元测试/Person.py
220
3.515625
4
class Person(object): def __init__(self,name,age,): self.name=name self.age=age def getVar(self,v): print(self(v)) return self(v) def getName(self): return self.name
67a07d319635ecf8f5aa98be3653e129e50a4309
Mi1ind/RSA-Encryption
/RSA/Encryption.py
704
3.515625
4
import Keys txtInput = input() class Encrypt(object): # def __init__(self, txt): # self.txt = txt # self.asciiTxt = asciiTxt def strToNum(self, txt): num = [] a = '' for i in range(len(txt)): num.append(ord(txt[i])) a = a.join(map(str, num)) ...
488ed434fcc8916937bbe2c0acffbff9cf3f30f9
angelavuong/python_exercises
/coding_challenges/exceptions.py
340
4.03125
4
''' Name: Exceptions Tasks: Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String. Sample Input: 3 Sample Output: 3 Sample Input: za Sample Output: Bad string ''' #!/bin/python3 import sys S = input().strip() try: value = int(S) print (S) except: p...
2b03e816c33cfdcfd9b5167de46fda66c7dda199
angelavuong/python_exercises
/coding_challenges/grading_students.py
981
4.125
4
''' Name: Grading Students Task: - If the difference between the grade and the next multiple of 5 is less than 3, round grade up to the next multiple of 5. - If the value of grade is less than 38, no rounding occurs as the result will still be a failing grade. Example: grade = 84 will be rounded to 85 grade = 29 will ...
18b519a9ad9b8f05b3df2ca0d4537bd7ac0b8abc
angelavuong/python_exercises
/coding_challenges/bon_appetit.py
1,545
3.828125
4
''' Name: Bon Appetit Task: Anna and Brian order n items at a restaurant, but Anna declines to eat any of the kth item (where 0 <= k <= n) due to an allergy. When the check comes, they decide to spit the cost of all the items they shared; however, Brian may have forgotten that they didn't split the kth item and accide...
8de678a955de6c29c84b43e6f27b1f2c027cffcd
angelavuong/python_exercises
/coding_challenges/legos.py
737
3.640625
4
#!/bin/python3 import sys def productOfPages(a, b, c, d, p, q): # Return the product of the page counts of the missing books if(p == a): a = 1 elif(p == b): b = 1 elif(p == c): c = 1 elif(p == d): d = 1 if(q == a): a = 1 elif(q == b): b = 1 elif(q == c): c ...
570b9f3e710d94baf3f4db276201a9c484da4a71
angelavuong/python_exercises
/coding_challenges/count_strings.py
573
4.125
4
''' Name: Count Sub-Strings Task: Given a string, S, and a substring - count the number of times the substring appears. Sample Input: ABCDCDC CDC Sample Output: 2 ''' def count_substring(string,sub_string): counter = 0 length = len(sub_string) for i in range(len(string)): if (string[i] == sub_st...
aa378a188bce0e97a0545221e65f148838b3650c
angelavuong/python_exercises
/coding_challenges/whats_your_name.py
536
4.1875
4
''' Name: What's Your Name? Task: You are given the first name and last name of a person on two different lines. Your task is to read them and print the following: Hello <firstname> <lastname>! You just delved into python. Sample Input: Guido Rossum Sample Output: Hello Guido Rossum! You just delved into python. '...
fb5fb443047d66da08a71087282dd3070a543a14
lukes-tauafiafiiutoi/PROGRAMMING
/lucky unicorn/testing/test.py
408
3.84375
4
def yes_no show_instructions ="" show_instructions = input("Have you played this game before? ").lower() if show_instcutions == "yes": print("program continues") elif show_instrctions == "y": print("program continues") if show_instcutions == "no": print("display instructions") elif show_instrctions == "n": pr...
c694ab63a24674646d5309e4f18076b400b522e9
develly/CodingTest
/etc/add.py
407
3.625
4
#-*- encoding: utf-8 -*- # 두개 뽑아서 더하기 def solution(numbers): answer = [] for i in range(len(numbers)-1): for num in numbers[i+1:]: tmp = numbers[i] + num if tmp not in answer: answer.append(tmp) answer.sort() return answer if __name__ == "__main__": ...
f5c55ca26fb5eb99b71586a04149648f3c363f5c
develly/CodingTest
/etc/Sorting/sorting.py
561
3.953125
4
#-*- encoding: utf-8 -*- # K번째 수 # solution 1 def solution(array, commands): answer = [] for i,j,k in commands: answer.append(sorted(array[i-1:j])[k-1]) return answer # solution 2 def solution2(array, commands): answer = [] for i, j, k in commands: target = array[i-1:j] ...
be619de8667ab89766b5cf43c9f266b1644570f9
develly/CodingTest
/etc/ternery.py
283
3.859375
4
def solution(n): ternery = "" answer = 0 while n > 2: n, rest = divmod(n, 3) ternery += str(rest) ternery += str(n) answer = int(ternery, 3) return answer if __name__ == "__main__": n = 45 answer = solution(n) print(answer)
56fb9aa4cdc33a99c0adb576f0c180d697cec594
develly/CodingTest
/programmers/level1/추억 점수.py
760
3.546875
4
def solution(name, yearning, photo): answer = [] for people in photo: score = 0 for j in people: try: score += yearning[name.index(j)] except ValueError: continue answer.append(score) return answer def shorten(name, yearning,...
70d4723b6527d07696d9f6bf74965eee7e97946c
noahp/adventofcode
/2022/01/aoc.py
3,520
3.78125
4
#!/usr/bin/env python """ --- Day 1: Calorie Counting --- Santa's reindeer typically eat regular reindeer food, but they need a lot of magical energy to deliver presents on Christmas. For that, their favorite snack is a special type of star fruit that only grows deep in the jungle. The Elves have brought you on their a...
bbea8b19027cebe3f46d441f9d012584cc3dc75b
matthew99carroll/VoronoiDiagram
/Event.py
278
3.5
4
import abc class Event(object): __metaclass__ = abc.ABCMeta def __init__(self, x, y): self.x = x self.y = y @abc.abstractmethod def Handle(self, queue, beachline, dcel): return def ToString(self): return '("+x+", "+y+")'
adec6702a83b1676b337082d7eab0980b5c71cde
mo7amed3umr/new-task-sbme
/mtplt.py
600
3.53125
4
from numpy import * import plotly as py from plotly.graph_objs import * #just a sphere theta = linspace(0,2*pi,100) phi = linspace(0,pi,100) x = outer(cos(theta),sin(phi)) y = outer(sin(theta),sin(phi)) z = outer(ones(100),cos(phi)) # note this is 2d now data = Data([ Surface( x=x, y=y, z...
c3e852fa1059dd903585a226979c8f5e884e5597
riverfour1995/Leetcode
/451. Sort Characters By Frequency.py
298
3.546875
4
import collections class Solution(object): def frequencySort(self, s): """ :type s: str :rtype: str """ set = collections.Counter(s) return ''.join([n * m for m, n in sorted([(k, j) for j, k in list(zip(set.keys(), set.values()))], reverse=-1)])
63c3767f80315d510c3bc3170a04e37693e2d344
riverfour1995/Leetcode
/268. Missing Number.py
329
3.5
4
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ self.value = nums number = len(self.value) + 1 whole_list = list(range(number)) return int(list(set(whole_list)-set(self.value))[0]) #set can be used to s...
1abcd78ccecb92bf2e13d174ef63b5688f0a54aa
matali1/adventofcode
/day09/garbage.py
3,228
4.15625
4
import click # A large stream blocks your path. According to the locals, it's not safe to cross the stream at the moment because it's full of garbage. You look down at the stream; rather than water, you discover that it's a stream of characters. # # You sit for a while and record part of the stream (your puzzle input)...
e9146fd8cc88e10a9d44ec8c34cb748cfa8e22a9
matali1/adventofcode
/day05/cpu.py
2,053
4.09375
4
import click @click.command() @click.option('--file', help='File to read the lines') def leave_the_maze(file): steps = 0 if file: with open(file) as myfile: steps = calculate_steps(myfile) print steps print 'THERE ARE %d steps to leave the maze' % steps def calculate_steps(myfile)...
830488612df7dcb44dcff1a04c3fa1f04c54f30a
martingms/aoc
/2018/day10.py
1,230
3.515625
4
#!/usr/bin/env python3 from itertools import count inp = open('day10.input').read().strip().split('\n') class Point: def __init__(self, x, y, vx, vy): self.x, self.y, self.vx, self.vy = x, y, vx, vy def parse(inp): for line in inp: line = line[10:].split(',') x = int(line[0]) ...
531a8d56b426d44e8afa7be24874a3dad5b3d6e3
feliperi1/ProyectoM1Python
/consola_calculo_porcentaje_grasa.py
389
3.5
4
import calculadora_indices as calc peso=float(input("Ingrese el peso de la persona en kilogramos:")) altura=float(input("Ingrese la altura de la persona en metros:")) edad=int(input("Ingrese la edad de la persona: ")) v_genero=float(input("Ingrese el 10.8 si el genero es masculino o de lo contrario cero:")) prin...
9062cf160a34e6c0501408383d71bc73a55d0a05
blodstone/summarization
/structure/document.py
1,030
3.5625
4
from typing import List from structure.sentence import Sentence class Document: def __init__(self): self._id = '' self._bodies: List[Sentence] = list() self._gold_summaries: List[Example] = list() @property def gold_summaries(self)->list: return self._gold_summaries ...
d5d229788bf6391a3be21f75c54166a1b836b3e4
6reg/pc_func_fun
/rev_and_normalized.py
519
4.15625
4
def reverse_string(s): reversed = "" for i in s: reversed = i + reversed return reversed def normalize(s): normalized = "" for ch in s: if ch.isalpha(): normalized += ch.lower() return normalized def is_palindrome(s): normalized = normalize(s) rev = reverse_...
2025d813e4f4f8dc43e5b1391db65fc0fce3071f
6reg/pc_func_fun
/comb.py
227
3.671875
4
s = ['a','b','c'] def get_cmb(s): r = [] for i in range(len(s)-1): for y in range(i+1,len(s)): v = [s[i],s[y]] if v not in r: r.append(v) return r print(get_cmb(s))
c9b55e36a7c775becaedf05e581baf1da1af2a79
tkieft/adventofcode-2016
/day01/day01.py
859
3.96875
4
import sys def grid_distance(location): return abs(location[0]) + abs(location[1]) input = open(sys.argv[1], 'r').readlines()[0] directions = input.split(", ") heading = 90 current = (0, 0) headquarters = None visited = [] visited.append(current) for direction in directions: # Turn in new direction hea...
d953788ac89aa22b29a4b5cacc8ee97721e3aa03
PavelescuVictor/KnapsackProblem
/Classes/Backpack.py
474
3.578125
4
class Backpack: def __init__(self): self.backpack_storage = [] self.max_weight = 0 def get_element_by_index(self, index): return self.backpack_storage[index] def add_item(self, item): self.backpack_storage.append(item) def get_backpack(self): return self.backp...
8344f3ec431ff5589df6cfbdfdd6343d67130311
samurainote/OOP
/data_member.py
765
4.03125
4
print("\tI'm\tyours") # class method # cls means class itself class TaxCalc: @classmethod def class_method(cls, price): assert cls.__name__ == TaxCalc.__name__ return int(price * 0.08) @staticmethod def static_method(price): return int(price * 0.08) print(TaxCalc.class_metho...
43268d590c2115b33e05ff12d69e72239436c5f4
Talux-QsO/curso_python
/numbers.py
419
3.84375
4
# operaciones basicas # suma print(1 + 2.4) print(1 + 3,4) # resta print(1.5 - 0.5) #mutiplicacion print(45 * 2.4) #division print(12.0 / 4.0 ) # modulo muestra el residuo print(12.0 % 4.0) #muestra de parte entera de la division print(12.0 / 7.0 ) print(12.0 // 7.0) age = int(input("Inserta de tu edad:...
4624da42ac42e7952dce35ff6498ba932e2d2fff
Talux-QsO/curso_python
/datetype.py
510
3.71875
4
# Strings print("Hola mundo") print(type("hola mundo")) # Concatenacion print("hola mundo " + "Yolo") # Numbers a=10 print(a); print(type(a)) # Float b=12.5 print(b); print(type(b)) # Boolean True False print(type(True)) # List (Datos varibles) [10 ,20 ,12,True] ["Hola", "adios" , "buema suerte"] print(type([12 ,...
cf78d68dd19488159065cbdf6fa127690a43f7a8
eunseo5355/python_school
/lab6_2.py
813
3.84375
4
""" 사용자로부터 점수를 입력받아, 이를 리스트에 저장하고, 평균을 출력하라. 입력된 점수는 list 형식으로 출력한다. 점수의 끝은 음수로 확인한다. """ Score = [] # 리스트 초기화 sum =0 # 합 구하기 count =0 # 점수 개수를 세기 위한 변수 while True: # 음수가 들어올 때까지 반복 num = int(input("점수: ")) # 점수 입력 받기 if num < 0: # 음수이면 반복문 탈출 break sum += num # 점수 합하기 count += 1 # 갯수 증...
fe5f85c9b9444ec6dcf74cb854ad7ac7ca8253a8
eunseo5355/python_school
/list2_13.py
606
4.0625
4
""" 매장에서 주문 가능한 메뉴를 리스트로 정의한다.(햄버거, 샌드위치, 콜라, 사이다) 이를 화면에 이를 화면에 출력한다. 사용자로부터 메뉴의 번호(0~3)를 입력받고, 갯수를 입력 받아서 선택된 메뉴와 총 가격을 출력한다. 각 메뉴의 가격은 3000원으로 동일하다고 가정한다. """ order_list = ['햄버거', '샌드위치', '콜라', '사이다'] print(order_list) a = int(input("메뉴의 번호(0~3):")) b = int(input("갯수:")) print("선택된 메뉴: %s" % (order_list[a])) print...
923889a7f368d5ccb686186bb469dcfb492a24ed
eunseo5355/python_school
/list3_2(2_13의 수정).py
1,067
4.09375
4
""" 매장에서 주문 가능한 메뉴를 리스트로 정의한다.(햄버거, 샌드위치, 콜라, 사이다) 이를 화면에 이를 화면에 출력한다. 사용자로부터 메뉴의 번호(0~3)를 입력받고, 갯수를 입력 받아서 선택된 메뉴와 총 가격을 출력한다. 각 메뉴의 가격은 햄버거는 3000원, 샌드위치는 2000원, 콜라와 사이다는 1000원이다. """ order_list = ['햄버거', '샌드위치', '콜라', '사이다'] print("메뉴", order_list) a = int(input("메뉴번호(0~3):")) b = int(input("갯수:")) print("선택된 메뉴:",...
64e3642c06a80b4f90108995bc82db833233a1a7
eunseo5355/python_school
/compare.py
620
3.671875
4
def min_max(li): """ 매개변수로 넘어온 리스트에서 최소값과 최대값을 반환하는 함수 :param li: 리스트 :return: 최소값, 최대값 """ # min 와 max 를 리스트 0번째 요소로 초기화 min = li[0] max = li[0] # 반복문을 돌면서 최소, 최대값 찾기 for i in range(len(li)): if min > li[i]: # 현재 값이 min 보다 작으면 min = li[i] # 최소값 변경 e...
b4806b7a18128f909770cb668ec4a326469f1eb6
eunseo5355/python_school
/lab3_1.py
363
3.953125
4
""" 문제: 점수를 입력받아서, 60점 이상이면 합겻, 이하면 불합격을 출력하라. 작성자: 배은서 작성일: 2019. 9. 10. """ score = int(input("점수:")) if score >= 60: print("합격!!") print("축하합니다.") else: print("불합격!!") print("더 분발하세요.") """ if score < 60: print("불합격") """
a3286a50d4f3c572bc5176896cb4657ae4b86452
FraiVadim/Introducere_Afi-are_Calcule
/Problema_7.py
146
3.640625
4
v=int(input("dati varsta Anei ")) print ("greutatea perfecta a Anei este de",2*v+8,"kg") print ("inaltimea perfecta a Anei este de",5*v+80,"cm")
cd916150b60d80e1def43eb10aaafd65429badb1
lumeng/repogit-mengapps
/data_mining/wordcount.py
2,121
4.34375
4
#!/usr/bin/python -tt ## Summary: count words in a text file import sys import re # for normalizing words def normalize_word(word): word_normalized = word.strip().lower() match = re.search(r'\W*(\w+|\w\W+\w)\W*', word_normalized) if match: return match.group(1) else: return word_no...
7d577aff08bce823aee2e6e83a3fef942d78cdfd
chandan-kv/TR_Assessment
/palindrome.py
172
4.03125
4
x = int(input(("Enter a name: ")) if (x == x[::-1]): print("THis is Palindrome") else: print("This is not palindrome")
516721a52862c9532385d52da79d11085a759181
EvgenyMinikh/Stepik-Course-431
/task17.py
1,250
4.1875
4
""" Напишите программу, которая шифрует текст шифром Цезаря. Используемый алфавит − пробел и малые символы латинского алфавита: ' abcdefghijklmnopqrstuvwxyz' Формат ввода: На первой строке указывается используемый сдвиг шифрования: целое число. Положительное число соответствует сдвигу вправо. На второй строке указывае...
a72e0f000a7aeb985531d6a52d0622b4bdc0ce2a
graysoncroom/PythonGraphingPlayground
/histogram.py
325
3.65625
4
#!/bin/python import matplotlib.pyplot as plt population_ages = [22, 55, 62, 45, 34, 77, 4, 8, 14, 80, 65, 54, 43, 48, 24, 18, 13, 67] min_age = 0 max_age = 140 age_step_by = 20 bins = [x for x in range(0, 141, 20)] plt.hist(population_ages, bins, histtype='bar', rwidth=0.8) plt.xlabel('x') plt.ylabel('y') plt.sh...
0dc8a38b8d32c4208430cb0049ae113f1ea9c321
zhtsh/Learning-Algorithms
/python/List.py
4,365
3.828125
4
#! /usr/bin/python # coding=utf8 class Node(object): def __init__(self, data, next_node=None): self.data = data self.next_node = next_node def get_data(self): return self.data def set_data(self, data): self.data = data def get_next(self): return self.next_no...
f65486941b6ee5852a4aaf2bf6547b7d5d863dd9
blei7/Software_Testing_Python
/mlist/binary_search.py
1,682
4.3125
4
# binary_search.py def binary_search(x, lst): ''' Usage: The function applies the generic binary search algorithm to search if the value x exists in the lst, and returns a list contains: TRUE/FAlSE depends on whether the x value has been found, x value, and x position indice in list Argume...
418ad60a363bbae94511bb675c71204b18077086
no7dw/py-practice
/class/mixin.py
784
3.5
4
class Displayer(): def display(self, message): print(message) class LoggerMixin(): def log(self, message, filename='logfile.txt'): message ='\n' + message with open(filename, 'a') as fh: fh.write(message) def display(self, message): super().display(message) ...
c797f2b44d77aa811df5c4c1cef78586ba6255f5
beadoer1/algorithm
/HelloCodingAlg/practice_py/factorial.py
105
3.734375
4
def fact(x): if x == 1: return 1 else: return x * fact(x-1) x = fact(5) print(x)
8ce37389202f6c13c77bb05259daa3244ac846e6
beadoer1/algorithm
/20210319/week2_test/15649.py
2,811
3.5625
4
# 문제 # 자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. # 1부터 N까지 자연수 중에서 중복 없이 M개를 고른 수열 # 입력 # 첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 8) # 출력 # 한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. # 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. # 수열은 사전 순으로 증가하는 순서로 출력해야 한다. # 설명 : 1~N의 숫자로 이루어진(중복 X) M의 길이를 가진 수열들을 오름차순 출력 ...
d874434056ddb0a1898aaca8e0143c9372fa618e
beadoer1/algorithm
/programmersPython/lengthOfArrays.py
896
3.625
4
# 정수를 담은 이차원 리스트, mylist 가 solution 함수의 파라미터로 주어집니다. # mylist에 들은 각 원소의 길이를 담은 리스트를 리턴하도록 solution 함수를 작성해주세요. # 제한 조건 # mylist의 길이는 100 이하인 자연수입니다. # mylist 각 원소의 길이는 100 이하인 자연수입니다. # 예시 # input output # [[1], [2]] [1,1] # [[1, 2], [3, 4], [5]] [2,2,1] # 풀이 1 : low level에 가까운 답이라고 한다. # def ...
f4a43398ef50e08a5fd6d4f74d7ebbe081dcc763
beadoer1/algorithm
/spartacodingclub/week_3/02_selections_sort.py
353
3.609375
4
input = [4, 6, 2, 9, 1] def selection_sort(array): n = len(array) for i in range(n-1): min = array[i] for j in range(i,n): if min > array[j]: min = j array[i], array[min] = array[min], array[i] return array selection_sort(input) print(input) # [1, 2, ...
71883f776d1c5ad55cd75f50adba33ee13468f96
anna-yankovskaya/ann-yankovskaya
/test2.py
207
3.90625
4
def name (x) if x == "Вячеслав": print ("Привет, Вячеслав") else: print ("Нет такого имени") name(Вячеслав) name(Вечеслав) name(вячеслав)
9d7a5d0c0ff06d8b69fde92457d9fc71d4bb0a7c
k-kushal07/Algo-Daily
/Day 42 - Two Sum (sorted).py
500
3.828125
4
def two_sum(arr, key): left = 0 right = len(arr) - 1 while left < right: if arr[left] + arr[right] == key: return [left+1, right+1] elif arr[left] + arr[right] > key: right -= 1 elif arr[left] + arr[right] < key: ...
a2b0ea08fd042d1da4835e37422434229b70c17e
k-kushal07/Algo-Daily
/Day 26 - Intersection Two Linked List.py
740
3.5
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def Intersect(self, headA, headB): c1 = headA c2 = headB len1, len2 = 0 while c1: len1 = len1 + 1 c1 = c1.next while c2: len2 = l...
0425b8fc9bb8397be051b0216061489cb2889d99
k-kushal07/Algo-Daily
/Day 4 - Reverse Alpha.py
523
3.640625
4
def reverse_alpha(string): newList = list(string) rightptr = len(newList)-1 leftptr = 0 while leftptr < rightptr: if not newList[leftptr].isalpha(): leftptr +=1 elif not newList[rightptr].isalpha(): rightptr -=1 else: newList[lef...
ee3232f678a26cd9685307c790ba10986e42c073
k-kushal07/Algo-Daily
/Day 35 - Mean per Level.py
763
3.5
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def averageOfLevels(self, root: TreeNode) -> List[float]: if root is None: return [] this_level =[root] next_level = [] ...
5cdfa411d2291fc96f9c39809dbca9a5129579a1
k-kushal07/Algo-Daily
/Day 5 - Anagram.py
477
4.09375
4
def anagram(str1, str2): if(len(str1) != len(str2)): return False count = 0 for i in str1: count += ord(i) for i in str2: count -= ord(i) return (count==0) input1, input2, *rest = [word for word in input('Enter the strings to compare: ').split()] print(inp...
2a135ffbe1ab2cf748ba75914b6f2626f6774eac
KVonY/11775-HW1
/scripts/stopword.py
276
3.703125
4
import nltk from nltk.corpus import stopwords stop_words = set(stopwords.words('english')) file = open("vocab-1", "rb") output = open("vocab", "w") for i in file: word = i.strip() if word not in stop_words: output.write(word+"\n") output.close() file.close()
cfa49df838598ce1289e236b2904f5cf03043484
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/max-path-sum/main.py
3,238
3.90625
4
def describe(): desc = """ Problem : Given a non-empty binary tree root, return the maximum path sum. Note that for this problem, a path goes from one node to another by traversing edges. The path must have at least one edge and it does not have to pass by the root. NOTE : When we say that the ...
0b5b637e9a7ecfbfe4951932a757074faab74821
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/dfs/binary-tree-all-path-sum/main.py
2,608
3.90625
4
class TreeNode(): def __init__(self, val): self.value = val self.left = None self.right = None def describe(): desc = """ Problem : Given a binary tree and a number S, find all paths from root-to-leaf such that the sum of all the node values of each path equals S -------------- """...
612c8ca841d8da2fc2e8e00f1a14fb22126d1277
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/ways-to-climb-stairs/main.py
2,336
4.1875
4
# Problem : Given a staircase of n steps and a set of possible steps that we can climb at a time # named possibleSteps, create a function that returns the number of ways a person can take to reach the # top of the staircase. # Ex : Input : n = 5, possibleSteps = {1,2} # Output : 8 # Explanation : Possible ways ar...
2a43e68d93886047dc1df86a45da8a9e135c2a36
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/binary-search/order-agnostic-binary-search/main.py
2,596
3.90625
4
def describe(): desc = """ Problem : Given a sorted array of numbers, find if a given number 'key' is present in the array. Though we know that the array is sorted, we don't know if it's sorted in ascending or descending order. You should assume that the array can have duplicates. Write a function to return the ind...
dad6411cd63d2f083c537a34d20376cb9b395fa3
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/longest-substring-without-repeating-chars/main.py
4,287
4.1875
4
# Problem : Given a string with alphabetical characters only create a function that # returns the length of the longest substring without repeating characters. # Ex : "abcdbeghef" # Output : 6 -> because the longest substring without repeating characters is "cdbegh" # The brute force solution is to find all poss...
f7d450ccb704ac45e68680b97c363f6eef9e0185
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/in-place-reverse-linkedlist/reverse-every-k-elm-sublist/main.py
3,385
4.15625
4
from __future__ import print_function class Node(): def __init__(self, value, node=None): self.value = value self.next = node def print_list(self): node = self while node is not None: print(node.value, end='->') node = node.next print('null') ...
27071dd477e491361bca5574ff2c5ed4c9a9efcb
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/subsets/distinct-subsets/main.py
1,244
4.09375
4
def describe(): desc = """ Problem : Given a set of elements find all it's distinct subsets. Example: Input : [1,3] Output : [], [1], [3], [1,3] ---------------- """ print(desc) # Follow the BFS approach # start with an empty set. # Iterate over the given list of numbers and add the number at ...
819f6f6246c99bc7e296e81825840829074892e9
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/sliding-window/avg-subarr-size-k/main.py
2,210
3.78125
4
def describe(): desc = """ Problem : Given an array, find the average of all subarrays of K contiguous elements in it. Ex : Given Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5 Output: [2.2, 2.8, 2.4, 3.6, 2.8] """ print(desc) # Time complexity = O(n^2) def brute_force_find_averages_of_subarrays(K, ar...
c7f8f20059820e7a98f97e7045cf5aa8a3c98cef
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/remove_dupes/main.py
1,458
3.859375
4
# Problem : Given an array of integers create a fucntion that returns an array # containing the values of the array without duplicates - order doesnt matter # One solution is to traverse the array and push the element into an output array if it already doesnt exist in the output array. # The time complexity of this...
1f90abdf8b6e6696fd9fb977e322588e02036ca5
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/n-queens/main.py
3,636
3.9375
4
def describe(): desc = """ Problem : Find the number of ways possible to place n queens on a n x n chess board such that no 2 queens can attack each other. The queens attack each other when they are placed on the same row, same column or placed diagonal to each other. Example : Input : n = 4 Outp...
2137855080a086d767c6c1c750a92e2c50e47f5a
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/sort/main.py
1,234
4.28125
4
# Problem : Sort an array # Time complexity O(n^2) def bubbleSort(arr): if len(arr) <= 1: return arr # Run an outer loop len(arr) times i = 0 while i < len(arr): # Keep swapping adjacent elements, ie sort adjacent elements in the inner loop j = 1 while j < len(arr): ...
b87e71043ec03bb7d40b33b697c7d5adc1e985ad
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/product-arr-except-self/main.py
1,198
3.796875
4
# Problem : Given an array of integers write a function to return an array which # at arr[i] contains the product of all elements except element at index i # For ex : With input array [2,5,3,4] # Output : [60,24,40,30] # Precompute the products from the left and from the right, ie cumulative products from left a...
e0852864241832608165933832d2dfdc4f12177e
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/top-k-elements/k-largest-numbers/main.py
1,874
4.03125
4
import heapq def describe(): desc = """ Problem : Given an unsorted array find the K largest numbers in it. Example : Input : [3, 1, 5, 12, 2, 11], K = 3 Output : [5, 12, 11] --------------- """ print(desc) # The bruteforce solution is to sort the given array and return the k largest numbers fr...