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
6713136fb748f54c2fba9851b76ec1f4612b4f8c
harshadwaghmare/test
/strfun.py
344
3.625
4
#!/usr/bin/python3 def numofvowels(stra): counter = 0 for i in stra: if i in 'aeiouAEIOU': counter += 1 return counter def commonletters (str1, str2): return list (set(str1)&set (str2)) if __name__ == '__main__': #print (numofvowels('tst')) for i in commonletters('abcd', '...
a95cb0bebfeca158167a0cd063e72816fa29d6d8
hanhiver/PythonBasic
/libs/classMethod/classA.py
247
3.578125
4
class A(object): def __init__(self, **kwargs): self.name = "Original" self.age = len(self.name) self.args = kwargs def printName(self): print("A.printName(): my name is: {}".format(self.name)) def printArgs(self): print(self.args)
52607f052dd465dee4a5a193ba81abcd0156b6a7
hanhiver/PythonBasic
/libs/StandardLibrary/2_DataStructure/countMostCommon.py
287
3.78125
4
import collections c = collections.Counter() with open('/usr/share/dict/words', 'r') as wordsfile: for line in wordsfile: c.update(line.strip().lower()) print('The most common words: ') for letter, count in c.most_common(5): print('word {} appear {} times'.format(letter, count))
1d9265bf18cb026a47b9d3053ecefa08e922eb2b
hanhiver/PythonBasic
/libs/multi_inherit/multi_inherit.py
737
3.59375
4
class MyBaseClass: def __init__(self, value): self.value = value class MyAddTwo(MyBaseClass): def __init__(self, value): #MyBaseClass.__init__(self, value) super().__init__(value) self.value += 2 class MyTimeFive(MyBaseClass): def __init__(self, value): #MyBaseClass.__init__(self, value) super().__init...
b1ffeb675a4aadb8e7d70ccd10f58c55327263af
julio73/calendar_algos
/main.py
1,790
3.671875
4
# Find block of time within calendars # Times: # T: 10 11 12 13 14 15 # A: | --------- --- ----- | # B: | ---- ---- ---- ----| # Constraints: # - Within block of calendar time # - Find higher bound for earliest time # - Find lower bound for highest time ...
a5e73e751d885e874fc98071a528c182085a3359
cornelltech/visaware
/pishow/src/on_off_timer.py
1,765
3.9375
4
#!/usr/bin/env python3 """on_off_timer.py - alternates on/off state for specific on/off durations""" import time class OnOffTimer(object): """Alternate between ON and OFF states for specific On/Off durations""" def __init__(self, on_duration, off_duration, startOn=False): """constructor""" ...
b36a9a9b65550021d6a95067e28fadf68555ec67
nishantgautamIT/python_core_practice
/pythonbasics/SetInPython.py
1,273
4.125
4
# Set in python # method in set # 1.union() set1, set2, set3 = {1, 2, 3}, {3, 4, 5}, {5, 6, 7} set_UN = set1.union(set2, set3) print(set1) print(set_UN) # 2. intersection() set_int = set2.intersection(set1) print(set_int) # 3. difference() set_diff = set1.difference(set2) print(set_diff) # 4. symmetric_difference() ...
e408f142a73ac324b9e5b7c27ac1aa2c88468cf5
brakmic-aleksandar/coding-problems
/1.py
1,494
3.90625
4
""" Challenge Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? """ def solution1(l, k): """ First solution iterate array and for each element it...
3725ada6ccb1c8c0723ba1ec0d18273048f2d5f9
EmilUpp/skola24_scraper
/reading_test.py
1,036
3.890625
4
import pickle def write_to_text_file(d, file_path): """ Writes the dict to a file in a more readable format (debug mostly) :param file_path: filepath, where to write :param d: dictonary :return: """ with open(file_path, "w") as file_handler: for key, rooms in d.items(): ...
469680eb6af7fd52035a96099b115b9a6b9d77b7
avynychenko/Python_studing
/Functions.py
1,797
3.65625
4
# Напишите функцию modify_list(l), которая принимает на вход список целых чисел, удаляет из него все нечётные значения, а чётные # нацело делит на два. Функция не должна ничего возвращать, требуется только изменение переданного списка. def modify_list(l): for i in range(len(l)-1, -1, -1): if l[i] % 2 == 1...
bc70b1d4c03e2e4b016b6f6c5fa212df98456553
Minakshi-Verma/Graphs
/projects/social/social.py
5,235
3.921875
4
import random class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) c...
e649d841015f8242cc12275e4b862e5eda8f23fe
nvincenthill/python_toy_problems
/fighter.py
2,089
4.0625
4
# Create a function that returns the name of the winner in a fight between two fighters. # Each fighter takes turns attacking the other and whoever kills the other first is victorious. Death is defined as having health <= 0. # Each fighter will be a Fighter object/instance. See the Fighter class below in your chosen ...
a250d32dc61ec7b738b96e5e911c09434cc6f25f
nvincenthill/python_toy_problems
/string_ends_with.py
417
4.25
4
# Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string). # Examples: # string_ends_with('abc', 'bc') # returns true # string_ends_with('abc', 'd') # returns false def string_ends_with(string, ending): length = len(ending) sliced = st...
c121d8d191b49b73f26b9dfe29f885e13e0f9744
alexanderkhivrych/kpi_programming
/kr3/kr3_2.py
746
3.875
4
from random import * def int_num(prompt): num = input(prompt) try: if int(num): return int(num) except ValueError: print("Error, you must enter a number") return int_num(prompt) m = int_num("Enter m:") n = int_num("Enter n:") matrix = [] pair_number_count = 0 not_pai...
0a0874c1472dd9fdbe2e4e370a20a079f480c71b
Shruti-nair243/list
/list.py
216
4
4
n=int(input("Enter number of elements in the list:")) a=[] b=[] for i in range(0,n): a.append(int(input())) print("The input list is:",a) for i in a: if(i>0): b.append(i) print("The output list is:",b)
cfb02acdac328bdcd45241d8f8cd563ca25f77af
aufstpauli/DTH22-Logger
/DataAnalyse.py
370
3.515625
4
#!usr/bin/python3 # DataAnalyse.py ''' Autor : Christian Dopatka Version : 26.09.2018 License: Creative Commons CC BY-NC https://creativecommons.org/licenses/?lang=de ''' import sqlite3 conn = sqlite3.connect("temp.db") c = conn.cursor() # Show all Values in the Table 'temperature' c.execute('SELECT * FROM temp...
59df19ddd5b854ee3b8557dc1866704efb9fcd1a
Joshverge/algorithms
/Nth_fibonacci.py
567
3.84375
4
def getNthFib(n): # Write your code here. lastTwo = [0 , 1] counter = 3 while counter <= n: nextFib = lastTwo[0] + lastTwo[1] lastTwo[0] = lastTwo[1] lastTwo[1] = nextFib counter += 1 return lastTwo[1] if n > 1 else 0 # def getNthFib(n, memorize = {1: 0, 2: 1}): # if n in memorize: # return memoriz...
ccb63e0b6cd17725f8b14a2f2019d64568dfcea5
LessInterests/importthis
/1、注释&print输出&input输入.py
287
3.65625
4
#注释 #注释单行 ''' 注释多行 第二行 ''' #输入输出 print("Hello", "world") #遇到,逗号输出一个空格 print(18) print(10 + 8) #print("请输入你的年龄") #等待输入,阻塞 age = input("请输入你的年龄:") print("age = ", age)
42d556c58b2aecc243750b9bdc5508ba0343fb32
sandeshjung/calculator
/calculator.py
3,285
4.09375
4
from tkinter import * root =Tk() root.title("Simple Calculator") e = Entry(root,width=35, borderwidth=5) e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) def _button(number): current = e.get() e.delete(0, END) e.insert(0, str(current)+str(number)) def button_add(): first_number = e.get() ...
ede6637c57a1f6a10ea376e242ddedc59fd8acbd
jeanvins57/NAO-Map-UV30-2018
/py/teamNao/map.py
1,164
3.546875
4
import random import math try: import pylab as pyl HAS_PYLAB = True except ImportError: print "Matplotlib not found. this example will not plot data" HAS_PYLAB = False def addPoint(carte, xRob, yRob, thetaRob, rangeSonar):#on veut addPoint au repere R0, la carte est vide au debut point = [] thet...
4bc449e73a744d394388eb983c5afd9ae4fe4e1e
Christopher-OSouza/Blind-and-Manhattan-search-algorithms
/coordinate.py
182
3.609375
4
# Coordinate of the objects class Coordinate: def __init__(self, x, y): self.__x=x self.__y=y def get_x(self): return self.__x def get_y(self): return self.__y
9571f470fef04be5a3bae726d478f6f125336c8f
Atzphere/Mentorship-Game
/Learn/Python stuff/classes.py
783
3.90625
4
class Student: grade = 6 age = 11 teacher = "Mr. Who" def standUp(self): self.say() def say(self): print("Hello Teacher") def __init__(self, grade): self.grade = grade student = Student(6) student.standUp() class Dog: name = "Henry" dogType = "Pug" colo...
c1ee67892fc8516c84d27f2e0d3bc9e2dec89a5c
wareenpower/AutoCheck
/script/part3_test1/Junacheng_Part3_Test1.py
2,410
4.0625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # import doctest import random class NumberTest: def __init__(self): self.__doc__ = "This is the answer for NumberTest in 2018-11-01 !" self.__author = "Junacheng" @staticmethod def compute_random(int_range, int_list_number, list_compare_scope...
14b542d245b63cbea7ed66e3ed535ba4c1b633ce
wareenpower/AutoCheck
/script/part2_test1/Hills_Part2_Test1.py
805
3.5
4
# coding=utf-8 __author__ = 'hillszhang' class Part2(): def __init__(self): pass @staticmethod def Test2(inputStr): """ 计算字符串个数和字符类别 :param string inputStr: 输入的待分析语句 :return [int num, dict my_dict ]:字符个数,字符种类个数 """ result = {} num = 0 ...
fd45e401c6ef4028f574e0da1f686b104d8b301e
nguyenlien1999/fundamental
/Session05/homework/exercise5.py
216
3.671875
4
import turtle def draw_star(x,y,length): f = turtle.Pen() f.speed(3) f.setpos(x,y) for i in range(4): f.forward(length) f.right(144) f.done() draw_star(100,150,200) # chưa ok
d3a94ec5a3fdd9964a35eb02c3d6aecf4b2cb5b7
nguyenlien1999/fundamental
/Session03/cuu.py
963
3.765625
4
n=int(input("number of sheep you have ")) size=[] for i in range(n): a=int(input("size of sheep"+ str(i+1) + ":")) size.append(a) print("Hello, My name is Lien and these are the ship sizes:",size) print("Now my biggest sheep has size ",max(size),"let's shear it") size[size.index(max(size))] = 8 print("After ...
c5167aaf0b17bc6b744043c389924270e3e235fe
nguyenlien1999/fundamental
/Session05/homework/exercise3.py
408
4.625
5
# 3 Write a Python function that draws a square, named draw_square, takes 2 arguments: length and color, # where length is the length of its side and color is the color of its bound (line color) import turtle def draw_square(size,colors): f = turtle.Pen() f.color(colors) # f.color(color) for i in range(3): ...
aaea295a763850c543686028a915025f005f4420
LiuLabIUPUI/CARE-SMT
/cellquantifier/io/_prefix.py
1,229
3.8125
4
from glob import glob def get_files_from_prefix(input_dir, prefix, tags=None): """ Pseudo code ---------- 1. If tags are specified, find all files containg prefix and any of the tags 2. Unpack nested array Parameters ---------- input_dir : str, Directory containing files of interest prefix : str, Prefi...
739ff501a71b08e1628e38fbad6ea380b6d903e9
LiuLabIUPUI/CARE-SMT
/cellquantifier/segm/_regions.py
1,324
3.59375
4
import pandas as pd; import numpy as np def add_region_class(int_df, cls_div_mat=[[1,.1],[1,-.1]], min_class_int=[.1,.1]): """ Perform classification based on mean channel intensities Pseudo code ---------- 1. Add cell types to DataFrame Parameters ---------- int_df : DataFrame DataFrame con...
3c927b72492f4f9a438ed8711aaff757b0f56009
Elijah-M/Module10
/class_definitions/invoice.py
2,468
4.40625
4
""" Author: Elijah Morishita elmorishita@dmacc.edu 10/26/2020 This program is used for creating an example of the uses of a class """ class Invoice: """ A constructor that sets the variables """ def __init__(self, invoice_id, customer_id, last_name, first_name, phone_number, address, items_with_price=...
0b27fb7abbeb28ea28a6c32139ad55b2bb8143ca
harsh2206/Py-Programs
/circular queue using array or list.py
2,140
4.0625
4
###implementation of a circular queue using array ##Harsh Trivedi ##09/1/2018 class CircularQueue: def __init__(self, maxSize): self.queue = list() self.maxSize = maxSize self.front = -1 self.tail = -1 self.queue = [None]*maxSize def enqueue(self, data): ...
6cd2d5a0c7b2f6b60ae8beacc33f4592bda2aef0
jordandpflum/dataAnalyticProgrammingHW1
/q3.py
5,514
3.859375
4
from collections import defaultdict import math def moving_window(tweet, window): """ Create Phrases of length(window) rolling through tweet Parameters ---------- tweet: str, tweet to break into phrases window: int, number representing number of words in phrase Returns ------- ph...
b8d6651b8523dba40294189bd6b7c91ae565d354
JuanCamilo1602/Bubble
/SortSearch.py
1,330
3.765625
4
from random import randint from lib2to3.pgen2.token import LESS def bubble_sort(a): for i in range (len(a) -1): swapped = False for j in range (len(a)-1): if a[j] > a [j +1]: swap = a[j] a[j] = a[j+1] a[j+1] = swap swapped =...
c0b1a536cadb1c9163647f4ffaa4efcd169ed310
LoJve/PythonDemo
/BaseDemo/SortedDemo.py
541
3.546875
4
#!/usr/bin/env python3 # _*_ encoding:utf-8 _*_ ''' @File : SortedDemo.py @Time : 2019/03/13 08:54:57 @Author : Jayden Huang @Version : v1.0 @Contact : Hjdong8@163.com @Desc : 假设我们用一组tuple表示学生名字和成绩: L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 请用sorted()对上述列表分别按名字排序: ''' #...
90f9ac6c19715c2383452d751132e57593a0723a
dgski/automate-boring-python
/lists.py
928
3.78125
4
#Comma code: returns string with last item concatenated with 'and' spam = ['apples','bananas','tofu','cats']; def stringer(listofthings): string = "" for i,x in enumerate(listofthings): if i == len(listofthings) - 1: string += "and " + x + "." elif i == 0: string += x[0].upper() + x[1:] + " " else: ...
60769c7f9ecb97369f20e2fcbdb9ba9fd8c70b85
jasanjot14/Data-Structures-and-Algorithms
/Algorithms/iterative_binary_search.py
1,661
4.375
4
# Function to determine if a target (target) exists in a SORTED list (list) using an iterative binary search algorithm def iterative_binary_search(list, target): # Determines the search space first = 0 last = len(list) - 1 # Loops through the search space while first <= last: # ...
11f792f8eabddd0f0949a6ec10cb75a9fab88c2a
316112840/Programacion
/Tareas/Tarea06/Ejercicio1.py
1,610
3.5
4
# -*- coding: utf-8 -*- # Mariana Yasmin Martinez Garcia # Correo: mariana_yasmin@ciencias.unam.mx # Ejercicio 6.1: Práctica con diccionarios. import random as r # A) a = [r.randint(-10000, 10000) for i in range(100)] Diccionario = { i : True if i%2==0 else False for i in a } print(Diccionario, "\n") # B) ...
cdb88499d6704ec00b71e07c6386dde534e1acfe
316112840/Programacion
/ActividadesEnClase/EjemplosListas.py
771
4.125
4
S = "==========================================================" #Sucesión de Fibonacci: ListaFib = [1,1] for i in range(10): ListaFib.append( ListaFib[i] + ListaFib[i+1]) print(ListaFib) print(S) #Secuencia de Lucas: ListaLucas = [2,1] for i in range(10): ListaLucas.append( ListaLucas[i] + ListaLucas[i+1])...
e0c90a2bfb1c3ee2cdeb680958fd0d9ab8beee5d
316112840/Programacion
/Tareas/Tarea02/Ejercicio1B.py
2,470
4.03125
4
# Mariana Yasmin Martínez García # Correo: mariana_yasmin@ciencias.unam.mx # Ejercicio 2.1: Setters y getters # B) class Triangulo: def __init__(self,lado_a,lado_b,lado_c): self.lado_a = lado_a self.lado_b = lado_b self.lado_c = lado_c def desplegar(self): print("Triangulo de ...
c1bb320cd3a86b1211bfb3207cbcdfe58fd5903d
316112840/Programacion
/Tienda/Cliente.py
396
3.625
4
# Esta es una clase llamada Cliente.py que tendra como atributos Nombre y Valor. Y tendra como metodos Imprimir Detalles. # Mariana Yasmin Martinez Garcia class Cliente: def __init__ (self, Nombre, Saldo): self.Nombre = Nombre self.Saldo = Saldo def __str__(self): detalles = "NOMB...
c92d1f1714526b0b3dd295e17ee384ac85aef485
IdanYosha/worldofgames
/Live.py
2,086
4.0625
4
from MemoryGame import play1 from GuessGame import play2 from CurrencyRouletteGame import play3 game = ["You choose the Memory Game \n", "You choose the Guess Game \n", "You choose the Currency Roulette Game \n"] diff = ["Difficulty chosen: Very easy \n", "Difficulty chosen: Easy \n", "Difficulty chosen: Normal \n", ...
ce2f8c5b996325d02c26c85a6ecbe11603e8dbe0
IdanYosha/worldofgames
/Score.py
746
3.546875
4
from Utils import * from os import path # calculate the score before adding it to file def calculate_score(difficulty): global new_score point_of_winning = int((difficulty * 3) + 5) scores_file = open(SCORES_FILE_NAME, "r") current_score = int(float(scores_file.readline())) scores_file.close() ...
26507844f5eadbba33ea55fb4685f9fab318b30e
omarsagoo/word_jumble
/all_anagrams_dict.py
720
3.875
4
from anagram import all_words_set import pprint def create_dict(set_of_words): new_dict = dict() word_dict = {} pp = pprint.PrettyPrinter(indent=4) for word in set_of_words: word_sorted = sorted(word) end = len(word_sorted) - 1 new_dict = word_dict for i, letter in enume...
c244cf43f5dc08aff158b2475dbd95e32078649e
RykusPodjadek/Maciej_rozwiazania
/if_zadanie_4oraz5.py
3,520
3.640625
4
# Zadanie 1 # Napisz algorytm, który sprawdzi, czy liczba jest parzysta # BONUS pobierz liczbę od użytkownika # Zadanie 2 # Poproś użytkownika o login (lub wpisz ręcznie) # Sprawdź, czy zgadza się z "adamnowak" i wypisz informację # (Dla loginów nie ma znaczenia wielkość liter) # Zadanie 3 # Poproś uż...
b46bf49def2e238ceba46f152eecdce48c1de60b
stuh84/python
/produce-output.py
1,705
3.5
4
#!/usr/bin/python # Import sys library to process CLI arguments import sys # Import file as first CLI argument if len(sys.argv) > 1: file = sys.argv[1] else: print "Please provide a file to parse" exit() f = open(file, 'r') # Define variables globally to use in functions global remark global mydict global interf...
3e28e08ff9ea835f14d14e76422b126159181899
threeHardWorker/charts
/graph/money.py
403
3.53125
4
# -*- coding: UTF-8 -*- # author: star # created_at: 18-2-1 21:12 from lines import GraphLine class MoneyGraph(object): def __init__(self, ax, trade): self.__ax = ax self.__trade = trade def draw(self): GraphLine( self.__ax, self.__trade.get_point_x(), ...
06bf16ed3dc113f6c43578271d1e63088317cfbc
ajit-jadhav/CorePython
/1_Basics/7_ArraysInPython/a1_ArrayBasics.py
2,409
4.40625
4
''' Created on 14-Jul-2019 @author: ajitj ''' ## Program 1 ## Creating an integer type array import array a = array.array('i',[5,6,7]) print('The array elements are: ') for element in a: print (element) ## Program 2 ## Creating an integer type array v2 from array import * a = arr...
ad4842337403f50e230b62b30fba5727e7af9162
stephkno/CS_21_Python
/radix_sort/src/bucket_sort.py
415
3.6875
4
# sorting a list of integers length n_digits def sort(list): n_digits = len(list[0]) for i in reversed(range(n_digits)): buckets = [ [] for _ in range(10) ] for number in list: digit = int(number[i]) buckets[digit].append(number) list.clear() for bucke...
442da574e1c8d11c6b85be6e28e16b35eac1ce95
stephkno/CS_21_Python
/maze_generator/setTest.py
448
3.828125
4
from src import disjointSet set = disjointSet.DisjointSet() n = 6 # create new subset with size n set.new_subset(n) # join some subsets set.union(3,2) set.union(0,3) set.union(2,0) # test connection between 6 & 1 print(set.same_set(2,3) == True) print(set.same_set(0,3) == True) print(set.same_set(3,0) == True) prin...
ac89b14848a9a8cff30fafbd86131ce037455551
stephkno/CS_21_Python
/maze_generator/src/disjointSet.py
2,549
3.625
4
# !/usr/bin/python3 # disjoint set import random import sys sys.setrecursionlimit(99999) # class to represent subset node class SetNode: def __init__(self, value): self.value = value+1 self.parent = self self.rank = 1 # class to represent set of subsets class DisjointSet: def __init__(self): self.sets = [] ...
56cac436a81e9f7bab8e9ccf980842a12ed07cfa
IamRaviTejaG/Python-Projects
/Linear Search.py
554
3.78125
4
""" LINEAR SEARCH by Ravi Teja Gannavarapu """ a = [] def linSearch(n): for i in range(len(a)): if (n == a[i]): return ("\n\n" + str(n) + " was found at index " + str(i+1) + ".") else: return ("\n\n" + str(n) + " was not found at any index.") def inp(): c = raw_input("Enter the number of entrie...
be000791125730b160d8ebc5134344ef8e77c09d
IamRaviTejaG/Python-Projects
/Search-Sort/Bubble Sort.py
539
3.8125
4
""" BUBBLE SORT IN PYTHON by Ravi Teja Gannavarapu """ a = [] def inp(): c = raw_input("Enter the number of entries in the list: ") d = int(c) for i in range(d): e = raw_input("\nEnter number " + str(i+1) + " : ") a.insert(i, int(e)) bubble(a) print ("\n\n\nSorted List is as follows: \n\n") for i in range(l...
991cdcd358a65005d521785841f02640fa1aadfc
IamRaviTejaG/Python-Projects
/Area Of Square & Rectangle.py
378
4.09375
4
def area (leng, brd): ar = leng*brd if (leng==brd): print ("\nArea of the square is " + str(ar) + " square units.") else: print ("\nArea of the rectangle is " + str(ar) + " square units.") leng = input("Enter the length: ") brd = input("\nEnter the breadth: ") ar...
7e19a9f38c959b9fb637c3f2335e8d0f7acad044
joer14/1D-Peg-Solitaire
/solitaire.py
8,466
3.53125
4
#1D Peg Solitaire #Joe Rowley #jrowley@ucsc.edu #For CS101 #Winter Quarter 2013 #Manfred Warmuth from optparse import OptionParser import math def getInput(): input_board = raw_input("Enter board:") return input_board.upper().strip().replace('X', '1').replace('|', '0').replace(" ", "") class KeyValue: def...
4c38fcdb12adc8821b29c4ff3e73deedb7e4b678
shivanand3939/TicTacToe
/tictactoe.py
3,180
3.765625
4
import random def my_valid_choice(total_lists): valid_lists = [] unpreferred_lists = [] for each in total_lists: if each.find('-') != -1: unpreferred_lists.append(each) elif each.find('*') != -1: valid_lists.append(each) if valid_lists: return random.choi...
f8b39ef0a50feb3e7fdc00e7671fc1e00efe0314
RobinWenqian/classic_machine_learning
/Decision_tree.py
1,610
3.546875
4
import pandas as pd #收集网络泰坦尼克乘客数据 titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu//wiki/pub/Main/DataSets/titanic.txt') titanic.head() #查看数据的统计特性 titanic.info() #特征选择 X=titanic[['pclass','age','sex']] y=titanic['survived'] #查看当前选择特征 X.info() #由于age里面的数据维数缺失,用平均数或者中位数填补空缺 X['age'].fillna(X['age'].mean(),inpl...
1cac9a4ad7adda55acc9fad5f96843bf1e4b8ac2
kovarikd/Exercises
/www.practicepython.org/7_ListComprehensions.py
131
3.65625
4
a = [1,4,9,16,25,36,49,64,81,100] output = [element for element in a if element % 2 == 0] print("Even numbers: {}".format(output))
1514642da87aef1c31bb58cbcc3b93781001fd77
loChris/Tech-Degree-Project
/number_game.py
2,335
4.0625
4
#Going for Exceeds rating. Thanks for taking the time to review! import random import os high_score = 0 leaderboard = [] def start_game(high_score, leaderboard): print("=== WELCOME TO GUESS THAT NUMBER ===\n") print("Your high score is {}\n".format(high_score)) print("Rules: This program will randomly sele...
fa7f92c3da6b14ed856db4369f7e1fb87c6bfe4a
VictorRSantos/Python
/Python_Impacta_Treinamentos/Aula 11 - Orientação a objetos/carros.py
715
3.90625
4
'''Declarando a classe''' class Carro(object): '''Método Construtor ''' def _init_(self, caminho) : self.caminho = caminho '''Metodo''' def andar (self) : print('Andando pela', self.caminho) class Fusca(Carro): ...
df61f4254ecade38d676fb488f98384187c3d4ad
rodpoblete/tareas_pipe
/python/imc.py
683
3.578125
4
# IMC = (Peso / altura^2) # IMC < 20 Bajo peso # IMC >= 20 || IMC <= 25 Normal # IMC > 25 Sobrepeso peso_actual = int(input("Ingrese su peso (en kilos): ")) altura = float(input("Ingrese su altura (en metros): ")) IMC = peso_actual / altura ** 2 if IMC < 20: peso_ideal = 20 * altura ** 2 subir_peso = peso_ide...
f2b6d5d25de442b679ea28bc03cbd927409e5cb5
Zuce124/Algorithm_Learning
/Stack_queue.py
345
3.546875
4
#STACK stack = [] stack.append(1) stack.append(2) stack.append(3) stack.append(4) print(stack) x = stack.pop() print(x) print(stack) #QUEUE from collections import deque queue =deque() queue.append(1) queue.append(2) queue.append(3) queue.append(4) print(queue) x = queue.popleft() p...
00bd7b5172a63fab99a3ee6b22d10a9b2a3fdfae
HarinadhAnkala/DIGITAL_SIGNAL_PROCESSING_LAB
/LINEAR _ALGEBRA.py
1,033
3.71875
4
import numpy as np a=np.array([[1,2,3],[4,5,6],[7,8,9]]) m=np.matrix([[1,2,3],[4,5,6],[7,8,9]]) b=m print("MATRIX IS:",m) dt=np.linalg.det(m) print("DETERMINANT OF MATRIX IS:",dt) print("\n") i=np.linalg.inv(m) print("INVERSE OF MATRIX IS:",i) print("\n") n=np.linalg.norm(m) print("NORM OF MATRIX IS:",n) print("\n") r=...
e60acfc4c57fb27aefc310ec5f9ed69c3714d9f9
lealobanov/Year2-COMP2231-AISearch
/SimulatedAnnealingAlgbasic.py
3,202
3.765625
4
import os import sys import time import random import decimal #Compute the total path length of a specified tour def path_cost(sample_tour): cost = 0 for city in range(0,len(sample_tour)-1): a = sample_tour[city] b = sample_tour[city+1] cost += distance_matrix[a][b] return cost #...
7c84827189d47cd9e813a0e6befafaf032148b43
lambda-school-student-projects/Algorithms
/stock_prices/stock_prices.py
919
4.0625
4
#!/usr/bin/python import argparse def find_max_profit(prices): # set initial values smallestPrice = prices[0] largestProfit = prices[1] - smallestPrice # iterate through the prices to find the largestProfit for index in range(1, len(prices)): eachPrice = prices[index] largestProfit = max(eachPrice...
952ca71dfe6002131ba00d1b2ec23e70838e4f3f
devitos/audio_bibl
/audio_bibl.py
1,188
3.796875
4
class Track: name = '' track_dur = 0 def __init__(self, name, track_dur): self.name = name self.track_dur = track_dur def show(self): print(self.name, '-', self.track_dur, 'минут') print() tr1 = Track('Мороз', 6) tr2 = Track('Звезда', 4) tr3 = Track('Сойка', 2) tr4 = Track('Медведь...
a4dd0300fc09ea9c12a9dcdd846449472acef2ee
filipeazevedoSolo/LearningPython
/dictionary_02.py
295
3.78125
4
d = dict([('name','mel'), ('age',45)]) print(d) L = ['a','b','c'] T = [1,2,3] D = dict(zip(L,T)) print(D) K = D.keys() X = D.values() print(K) print(X) del D['b'] print(K) #apagando em D, altera K e X print(X) for k in sorted(D) : print(k,D[k]) #imprimir com sort nas chaves
cb3e44a2a37384217f81387c25579185b0481cd2
pykili/py-204-hw1-AHAHACbl
/task_8/solution_8.py
120
3.53125
4
b=0 N = int(input('vvedite chislo chisel:')) for i in range (1, N+1): a = int(input()) b = (b + a) c = b/N print(c)
82e1ff0f7814f5676b45bfa28e21f009571c6c84
StasBlagadyr/Stas_Blagadyr_py_dz
/Dz3.py
347
3.953125
4
word = "процент" word_1 = "а" word_2 = "ов" for x in range(1, 101): procent = x % 10 if procent == 1 and not (11<= x <= 14): print (x, word) elif 2 <= procent <= 4 and not (11 <= x <= 14): print (x, word + word_1) elif 5 <= procent <= 9 or procent == 0 or (11 <= x <= 14): print(x...
9242f27766156c4c315451cb0f12846bec7306ca
samuraii/4_json
/pprint_json.py
898
3.53125
4
import json import sys def load_data(filepath): with open(filepath, encoding='utf-8') as data_file: data_from_file = json.loads(data_file.read()) return data_from_file def pretty_print_json(data_from_file): json_data = json.dumps( data_from_file, ensure_ascii=False, separ...
ad6afb855a2d950ce0d36fa3b40c8b96e151fcb0
karaltan/Denemeler
/024_randomModulu.py
735
3.796875
4
#!/usr/bin/env python import random def main(): sayi = random.randint(1, 50) # bir ve elli arasında bunlar da dahil olmak izere rastgele sayı üretir print(sayi) liste = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30...
3e67bc3145bc7d8992ce8c972871567fe845f6a1
AlanLCarleton/SYSC3010_Alan_Lin
/Lab-3/demoFiles/pydb.py
942
3.71875
4
#!/usr/bin/env python3 import sqlite3 from datetime import datetime from sense_hat import SenseHat sense = SenseHat() #connect to database file dbconnect = sqlite3.connect("mydatabase.db"); #If we want to access columns by name we need to set #row_factory to sqlite3.Row class dbconnect.row_factory = sqlite3.Row; #now...
6fcf3a13fab442f57b9521529867047dc67fc037
vedantvajre/Class5
/5.10.py
158
3.84375
4
favorite_numbers = {'Billy': 8, 'Johnny': 10, 'Lucy': 30} for name, number in favorite_numbers.items(): print(name + " likes the number " + str(number))
8480ee8d0ec32af4f9601f5b12005ea4eee506f8
vedantvajre/Class5
/5.3.py
367
3.84375
4
glossary = {'for loop': 'Executes command in loop over and over again', 'print': 'To produce a statement', 'variable': 'a placeholder', 'list': 'holds different elements', 'dictionary': 'Holds different keys and values'} for word, meaning in glossary.items(): Definition = meaning print("\nWord" + ": " + word...
aef7f54ab62f62b822a2fe9deace34024dcb7596
vedantvajre/Class5
/5.19.py
160
3.734375
4
prompt = "Please enter your age: " prompt += "\n(Type quit to close)" while True: number = input(prompt) number = int(number) print(number)
5340eb1ba31ed9d96299013d3b10282640df1427
GustavoSilvaFerreira/Python
/Aula1/strExercicio.py
129
3.734375
4
palavra = raw_input('Digite uma palavra: ') #Mostre esta palavra em ordem reversa acc='' for e in palavra: acc = e+acc print acc
b5e511682f955906645607b6ef910ef94805c6e4
YHPeter/Contest
/YACS Python Solution/2020.11 YACS 丙组乙组/YACS 2020.11 丙组 #3.py
261
3.921875
4
import calendar year,date = map(int,input().split()) for month in range(1,13): num = calendar.monthrange(year,month)[1] for day in range(1,num+1): if day==13 and date==5: print(month) if date<7: date+=1 else: date = 1
d976ff390e8bdd2e04ff2bae8603ce0f80ab845a
kdamla/Python-Programlama
/TemelVeriYapilariveObjeler/Temel Veri Yapilari ve Objeler/Problem3.py
359
3.984375
4
""" Problem 3 Bir aracın kilometrede ne kadar yaktığı ve kaç kilometre yol yaptığı bilgilerini alın ve sürücünün toplam ne kadar ödemesini gerektiğini hesaplayın. """ yakit = float(input("Aracın kilometrede yaktığı yakıt tutarı:")) yol = float(input("Kaç km yol kat edildi?")) print("Ödenmesi gereken tutar: {} TL".for...
ac88be64d5e5c0c2860732225f5e2ea3f5e98bab
kdamla/Python-Programlama
/Moduller/OOP.py
2,733
3.625
4
import random import time class Kumanda(): def __init__(self, tvDurum = "Kapalı", tvSes = 0, kanalListesi = ["Trt"], kanal = "Trt"): self.tvDurum = tvDurum self.tvSes = tvSes self.kanalListesi = kanalListesi self.kanal = kanal def tvAc(self): if self.tvDurum == "Açık":...
2cfc956e6e142f2074591ec0305a4abe87d7c2f7
bunuli12138/python_foundation
/03function/01recursion.py
764
3.78125
4
#!/usr/bin/env python # encoding: utf-8 """ @Author :xinbei @Software :Pycharm @File :01recursion.py @Time :2019/2/12 21:31 @Version : @Purpose :使用递归函数定义简单,逻辑清晰,但需要注意防止栈溢出。可以通过通过尾递归优化 """ import traceback # 普通递归: def fact(n): if n==1: return 1 return n * fact(n - 1) # 此处引入乘法表达式...
1e1e27e7ec01e1c32751398da4ba71e428deb585
bunuli12138/python_foundation
/07objective_oriented_coding/01class_instance.py
1,331
3.75
4
#!/usr/bin/env python # encoding: utf-8 """ @Author :xinbei @Software :Pycharm @File :01class_instance.py @Time :2019/2/18 14:37 @Version : @Purpose : """ import functools, time # 计算函数运行时间的装饰器 def run_time(func): @functools.wraps(func) def wrapper(*args, **kw): t = time.time() ...
9104034530430c6600fcaf58e7c56ca6cc2cde7f
bunuli12138/python_foundation
/05higher_function/05anonymous_function.py
562
3.765625
4
#!/usr/bin/env python # encoding: utf-8 """ @Author :xinbei @Software :Pycharm @File :05anonymous_function.py @Time :2019/2/18 10:44 @Version : @Purpose :用匿名函数改造下面的代码并 """ # 改造is_odd def is_odd(n): return n % 2 == 1 # 等效果匿名函数: L = list(filter(lambda n:n % 2 == 1, range(1, 20))) print(L) #...
0d9814d1c2a4fc0c35e3d49dd0ab6adce38ba8b6
risselborn/ppfa_notebook
/Counter.py
663
3.59375
4
#!/usr/bin/env python from collections import defaultdict lines = open('strings.csv').read().splitlines() def identify_duplicates(phrase): word_count = defaultdict(lambda : 0) words = phrase.strip().split() for w in words: word_count[w] += 1 return word_count def annotate_duplicates(phrase):...
3e5f70b9779deb3fc6080a443a293cfb52d40dc1
natebwangsut/hackerrank
/python/designer-door-mat/sol.py
1,084
3.734375
4
#!/usr/bin/env python """ Hackerrank Solution - Nate B. Wangsutthitham <@natebwangsut | nate.bwangsut@gmail.com> """ __author__ = "Nate B. Wangsutthitham" __credits__ = ["Nate B. Wangsutthitham"] __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "Nate B. Wangsutthitham" __email__ = "nate.bwangsut@gmail.com" ...
bb892949bb1d5fea720db794e1031ba058ee1386
KittapatR/n-queen-problem
/Nqueen.py
11,104
3.671875
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 22 20:40:25 2019 @author: KittapatR Eight-Queens Problem """ import random import time import sys class queensBoard: def __init__(self, square): assert type(square) == int, "Invalid initialization" self.board = [[0 for n in range(squar...
a0653feb8aa640f8c784021a0ceba95f0b2e75bb
alex-gagnon/island_of_miscripts
/pyisland/src/classic_problems/fibonacci.py
1,028
3.703125
4
from functools import lru_cache from typing import Dict def fib1( n ): # basic recursion with break if n < 2: return n return fib1( n - 1 ) + fib1( n - 2 ) def fib2( n ): # with some memoization, takes longer than fib1 memo: Dict[int, int] = {0: 0, 1: 1} if n not in memo: memo[n] =...
fac0907fa4db80c8d9aa200e6f2f25d260e7e3d0
alex-gagnon/island_of_miscripts
/pyisland/src/classic_problems/StringToInteger.py
1,677
4.15625
4
import re class Solution: """Convert a string to an integer. Whitespace characters should be removed until first non-whitespace character is found. Next, and optional plus or minus sign may be found which should then be followed by any number of numerical digits. The digits should...
1cacd1a8dca4d8013957331ec418e8ec8e38dbd2
mbobiosio/learn-python-3-the-hard-way
/ex15.py
508
3.96875
4
from sys import argv # use argv to get the filename from the user script, filename = argv # open the file and assign the contents to variable 'txt' txt = open(filename) # prints the name of the file back to the user print(f"Here's your file {filename}:") # perform the 'read' function on the variable 'txt' with no param...
249808e734d42d61776f576ccb61d2e3e66821bd
Diego0114/AE401-Python
/L7.py
277
3.71875
4
num=int(input("人數")) scoree=[] for i in range(num): score=input("分數") scoree.append(score) print("平均分:",sum(scoree)/len(scoree)) print("最高分:",max(scoree)) print("最低分:",min(scoree)) print("全部分數由小到大排:",sorted(scoree))
ecc0f55371f5ab4944283ab83d87b8f973ea52e7
Diego0114/AE401-Python
/L3 Home work.py
430
3.59375
4
import random a=random.randint(1,20) c=0 while c<5: b=input("隨機取數1~20(猜五次):") c=c+1 if 1<=int(b)<=20: if int(b)>a: print("太大了") elif int(b)<a: print("太小了") else: print("你答對了") print("玩了",c,"次") break els...
543f5e18515df3e94d8192cc14c6ce92ed48b96f
u1and0/mishmash
/applydict.py
567
4
4
#!/usr/bin/env python3 """Apply some function to keyword arguments""" def apply_dict(func=lambda x: x, **kwargs): """Apply some function to keyword arguments description: Unless designate `func`, `func` is identity function usage: # same as dict() function >>> apply_dict(apple=5,...
678661e8ad96931ce7c54a595d478e3305ee5f10
Elardinfo175/info175_Elard.Koch
/1905_bd/sqpython2.py
413
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sqlite3 con=sqlite3.connect("pos_empresa.db") cursor=con.cursor() cursor.execute("select product.name, avg(sale_product.net_unit_price) from product join sale_product on sale_product.product_id=product.id group by product.name") # 2) promedio de venta por producto ...
d2648ddfd0b5c8f86c6aa36d1c54995f38a1f638
Elardinfo175/info175_Elard.Koch
/1905_bd/sqpython3.py
471
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sqlite3 con=sqlite3.connect("pos_empresa.db") cursor=con.cursor() cursor.execute("select entity.names,entity.company_name, sum(sale.gross_total) from entity join sale on sale.entity_id=entity.id group by entity.id") #3) total de ventas por cliente for i in cursor: ...
5b6f1acde5fdf694c9b1441322e3519c6dce4803
ijoosong/exercism
/python/sieve/sieve.py
139
3.59375
4
def sieve(num): nums = range(2,num+1) for i in range(2,num+1): nums = filter(lambda x: x==i or x%i, nums) return nums
4d6deac2b9c744e586114185a24a2dfd4a72fd6c
youngmd/qval
/common.py
541
3.59375
4
def walltime_to_seconds(walltime): try: if ':' not in walltime: return int(walltime) else: vals = walltime.split(':') vals = map(int, vals) if walltime.count(':') == 3: return vals[0] * 86400 + vals[1] * 3600 + vals[2] * 60 + vals[3] ...
53fbcd0d9b0203360c291a6a6f98cac5b79a3db1
farhan-alam12690/Payment-Destination-Locator
/Model.py
6,209
3.546875
4
import sqlite3 # conn = sqlite3.connect("user.db") # csr = conn.cursor() class user_model: def __init__(self): self.conn = sqlite3.connect("user.db") self.csr = self.conn.cursor() # self.csr.execute("""CREATE TABLE user ( # first_name text, # last_name text, ...
c136815c69b97e3dd07778858fadbf3685df9d90
sagarpandey7742/Algorithms
/Trees/morrisInorderTraversal.py
1,542
4.09375
4
# Morris inorder traversal is a very space efficient algorithm used to traverse the tree in inorder in O(1) space class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def morrisInorderTraversal(root): current = root wh...
dc5ec5f58a2ea2a44b36b921354884c3ce20d05b
JuliyaVovk/PythonLessons
/Lesson2/task2.py
883
4.46875
4
""" Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input() """ my_list = [] while True: item = input(...
dc7a9078ba9f17f75b5a984f42a09d8780d6477a
JuliyaVovk/PythonLessons
/Lesson2/task4.py
572
4.09375
4
""" Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. """ text = input('Введите текст: ') words = text.split(' ') num = 1 for word in words: if len(word) < 10: ...
712a72efcc6238ceb4afdfa05dc7569323154958
MulengaKangwa/PythonCoreAdvanced_RegularExpressions
/148Findall()andMatch().py
265
3.875
4
import re str ="Take up one idea.One idea at a time" result = re.search(r'o\w\w',str) print(result.group()) #This will return none if the search does not apply. result = re.findall(r'O\w\w',str) print(result) result = re.match(r'T\w\w',str) print(result.group())
2735a1819949c6ff21baf54364691fbd8fd3fdd9
Mikicodes/pinterestkingz
/User.py
4,308
3.546875
4
from datetime import datetime from Board import Board from Pin import Pin class User(object): """Constructor of the user""" def __init__(self): self.followers = [] self.following = [] # self.profile_picture = profile_picture self.boards = [] self.signin_state = False ...