blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
24590cd2d7b96dc0993d2b898804907724bf1ba3
ludwigschmidt/fasta-python
/fasta/examples/sparse_logistic.py
3,703
3.546875
4
"""Solve the L1-penalized logistic least squares problem, min mu||x||_1 + logit(Ax,b), using the FASTA solver. The logistic log-odds function is defined as, logit(z,b) = sum_i log(1 + e^(z_i)) - b_i * z_i, where z_i and b_i are the ith rows of z and b, respectively.""" import numpy as np from numpy import linal...
465f306399e2ed24dfe8fbbbc9e9f77c05cba4e5
dkonidena/AICSWK-Timetable
/scheduler.py
70,735
3.875
4
import module import tutor import ReaderWriter import timetable import random import math ''' This is the class which depicts the node in the search tree. It stores the assignment of a given slot i.e. - 1. Module 2. Tutor 3. Day 4. Slot on Day 5. Session Type 6. Possible - all the possible assignments th...
bf51343082fa3da283827ba3b0759ca3da6ab55c
adhipradhana/grafika
/uts/image/draw.py
1,521
3.5625
4
import sys if (len(sys.argv) != 3): print('Usage: python draw.py <filename> <type>') print(""" Type: 1 Line 2 Circle 3 Polygon """) exit() filename = sys.argv[1] width = 25 file = open(filename + '.txt', "r") new_file = open(filename + '_large.txt', "w") if (sys.argv[2] == "1...
a1977f462a0efdd96528f8cb84a5d9beef7387ee
amtsha09/HackerRank_30DaysOfCodeChallenges
/day1.py
730
3.859375
4
####################### Day 1 ########################### if __name__=="__main__": i = 4 d = 4.0 s = 'HackerRank ' # Declare second integer, double, and String variables. integer = int() doub = float() string = str() # Read and save an integer, double, and String to your ...
f31cb96acc2bb7b7ce2f3e64bee86f649d6e1efb
ModelKaiSir/python
/alg/quick_sort.py
486
3.796875
4
''' 快速排序 ''' import random def quicksort(list): if len(list) < 2: return list midpviot = list[0] lessbeforemdpivot = [i for i in list[1:] if i <= midpviot] biggeraftermidpivot = [i for i in list[1:] if i > midpviot] finallylist = quicksort(lessbeforemdpivot) + [midpviot] + quicksort(biggera...
e754f94f299a39d8e5854d8eb30aa3413f403417
qiang2010/AlgorithmHackers
/JiQiang/leetcode_py/dp/JumpGameII45.py
611
3.5
4
class Solution(object): def jump(self, nums): """ :type nums: List[int] :rtype: int """ if not nums:return -1 if len(nums)==1:return 0 step = 1 maxPos = nums[0] i = 1 while maxPos<len(nums)-1: tempPos =0 while ...
e098204c51263d0a944da98aff185f2f00d1bec0
lethe2211/nlp100
/chap1/09.py
897
3.734375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import os import sys import itertools import math import random from collections import Counter, defaultdict from nltk.tokenize import RegexpTokenizer class Main(object): def __init__(self): pass def solve(self): ''' insert your code...
0a01b1632d2e93be5d8e8a29495d15aeeb32593d
lethe2211/nlp100
/chap2/13.py
765
3.59375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import os import sys import itertools import math from collections import Counter, defaultdict class Main(object): def __init__(self): pass def solve(self): ''' insert your code ''' with open('col1.txt', 'r') as f1: ...
c0be25b15deffab895529d1d153cd2fbd4c09893
VRUnleashed/CourseraPythonDS
/Ex10_2.py
386
3.609375
4
fname = input("Enter file name: ") try: fh = open(fname) except: print("Invalid file.") hours = dict() for line in fh: if not line.startswith('From:') and line.startswith('From'): words = line.split() time = words[5] hour = time[0:2] hours[hour] = hours.get(hour, 0) + 1 ...
231feff538db480a8be1e02aa1cb26851208d734
SouOChris/Jogo_da_forca
/jogo_da_forca.py
661
3.671875
4
palavra_secreta = ["M","A","C","E","I","O"] letras_descobertas = [] # Espaço para receber as tentativas de letras print("\n*** Jogo da Forca ***\n") for i in range(0, len(palavra_secreta)) : letras_descobertas.append("-") # Vai usar o '-' para substituir as letras acertou = False while acertou == False: ...
30b40bb7b57b11e9fe0e1bb4634bada8c21a3095
ashutoshsharma08/Speech-to-Text-to-Language-Conversion
/langspeech.py
2,798
3.5
4
import pandas from ibm_cloud_sdk_core import authenticators from ibm_watson import SpeechToTextV1 import json from ibm_cloud_sdk_core.authenticators import IAMAuthenticator, authenticator #api keys and url for the API url_s2t = "https://api.eu-gb.speech-to-text.watson.cloud.ibm.com/instances/73880520-2f82-4b29-b526-4...
2fa63c7930faeea3777a49b44b4e5f9ad1da0d85
aaditya2200/IPO-proj
/core/utils.py
574
3.609375
4
import string import random from datetime import datetime def create_id(): str = ''.join(random.choice(string.ascii_letters) for i in range(7)) str = str.join(random.choice(string.digits) for i in range(3)) return str def return_as_datetime_object(date): try: ipo_closing_date = datetime.strp...
b1cb85cf570e7d1bd484cd3893927726ed1308ce
RobMoore902/DropBoxPython
/dropbox.py
7,472
3.53125
4
import hashlib import os import sys import pdb class dropbox: #important information version = "DROP/1.0" dir = "" encoding = "" def __init__(self, directory): if os.path.isdir(directory): self.dir = "./" + directory else: print "directory does not exist...
fd56d7e0ef5897d82a5b029bb03a9e026de67191
tannupriyasingh/Coding-Practice
/Tree/preOrderSolution.py
626
3.765625
4
""" # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Solution(object): def arrangeNodes(self, node, listOfNodes): listOfNodes.append(node.val) for childNodes in node.children: self....
45463404f4cc0236ff87951bd168a9d88a61ddcb
shraddha136/python
/assn8.5.py
1,281
4.34375
4
# Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line: # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sen...
5227935834b5b8aa21f164b1aeed62ceabc0ba89
oscarmarinmiro/blanquerna_2018
/ejercicios/ficheros/ficheros_csv.py
263
3.53125
4
# https://docs.python.org/3/library/pprint.html # https://docs.python.org/3/library/csv.html import csv import pprint FILE_IN = "data/reddit_abridged.csv" my_file = open(FILE_IN, "r") reader = csv.DictReader(my_file) for row in reader: pprint.pprint(row)
a04438915d7641a75ba30c3803c9031e1eb1cb19
Chewie23/PythonAlgo
/Sort/quicksort.py
1,258
4.34375
4
#This one is gonna be doozy #Recursion, my old friend #The gist here is to choose a pivot point and organize the array around said #pivot #THEN repeat. Via recursion #https://en.wikipedia.org/wiki/Quicksort #The plan: The pivot will always be the "half" point. That way we can recurse #easily, rather than choosing a ...
e99f3d3a9078b8235e24055f4c7c81f348f05fb0
Chewie23/PythonAlgo
/One-Offs/General/three_sum.py
459
3.53125
4
""" Problem: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets. """ #Pl...
59eac33e74e3e074c930e2bef02a16a3bba9a785
Chewie23/PythonAlgo
/One-Offs/General/majority_elem.py
574
3.8125
4
""" Prompt: Given a sorted integer array, return the majority element if it exists or -1 otherwise. """ import collections as c my_array = [1, 2, 3, 4, 5, 5, 6, 6] my_count = c.defaultdict(int) for n in my_array: my_count[n] += 1 #This is a nice way to do it. I was thinking of using lambda with max(), but #ma...
19715310e12927fb1eaa5271f6df4f4ebcbbe809
fuanruisu/Py
/cadenas.py
964
3.796875
4
#Nombre: cadenas.py #Objetivo: Muestra la funcionalidad de las cadenas de carácteres #Autor: Juan Luis Magaña Paz #Fecha: 03 de septiembre de 2019 # definir cadena cad = "Hola mundo" cad1= " loco" car="slkklalsalaskaslñkaslk" print(cad) print(car) # Concatenación de cadenas print(cad + cad1) # Multiplicación de cad...
73b85bc2ab37aa5c1e4eb7f96e64851c053ddca0
fuanruisu/Py
/Punto.py
679
3.6875
4
""" Nombre: Punto.py Objetivo: Construye objeto tipo punto en el plano cartesiano Autor: Juan Luis Magaña Paz Fecha: 20 de septiembre de 2019 """ class Punto(object): #Método constructor def __init__(self, valorX, valorY): #definimos atributos de la clase self.x = valorX self.y = valorY...
80110783dcbcf9a1c774d807aad8f44f9dab495a
fuanruisu/Py
/tupla_2.py
383
3.59375
4
#Nombre: tupla_2.py #Objetivo: Muestra la funcionalidad de las tuplas en Python #Autor: Juan Luis Magaña Paz #Fecha: 03 de septiembre de 2019 import random def rnumber(): return random.randrange(1,100,1) def main(): for i in range(100): lista.append(rnumber()) t1=(False, "H",lista) print(t...
67731a923f9242e86459a5ce87b396edc54c99b1
fuanruisu/Py
/ejelistas.py
1,567
3.90625
4
# Nombre: listas.py # Objetivo: crear una listas import os lista=["Hola", "h0l4","como","estas","?"] def crear(): lista.append(input("==> Ingrese: ")) def leer(): print("***Lista***") j=0 for i in lista: j=j+1 print (j,") ",i) def actualizar(): os....
6d5e01ae4f3349d7840a77f010abafa1bd339e4d
BartMassey/movie-jobs
/geninst.py
827
3.890625
4
#!/usr/bin/python3 # Copyright (c) 2018 Bart Massey # [This program is licensed under the "MIT License"] # Please see the file LICENSE in the source # distribution of this software for license terms. # Generate a random "Movie Jobs" instance. # Generated intervals are "half-open": they # are considered to start at th...
769b1be806322a92f71e3c96f29a3c1b20c57970
KM3NeT/km3io
/src/km3io/utils/kprinttree.py
970
3.609375
4
#!/usr/bin/env python # coding=utf-8 # Filename: kprinttree.py # Author: Tamas Gal <tgal@km3net.de> """ Print the available ROOT trees. Usage: KPrintTree -f FILENAME KPrintTree (-h | --help) Options: -f FILENAME The file to print (; -h --help Show this screen. """ import warnings with warnings.c...
62241cafb27beb95ca4c0248555a094aa483f7e8
Matthijs4004/functions-tryout
/name-age.py
290
3.65625
4
from typing import AsyncGenerator i = 1 def nameAge(): while i < 4: name = input("Wat is je naam? ") if name == "stop": break age = int(input("Wat is je leeftijd? ")) print("Hallo " + name + ", je leeftijd is " + str(age)) nameAge()
7820a430a965f4e9de1df8eeefc0ced7301dc3e9
Andersengebretsen/SMC-CS21
/engebretsen_number_tree.py
10,229
3.90625
4
# Anders Engebretsen # CS 21: Fall 18 # Project: Number Tree """ Module Description: This is a program that includes several functions about a number tree. One recursive function will be called upon in the other functions to get the right number from the number tree. Here is a short description of...
301fba93f1e0809e145d8a3fa71494496051135c
chenwenping863/ChenwenPythonProject
/chenwen/method.py
183
3.59375
4
def addSum(num): sum = 0 for i in num: sum += i return sum num = [1, 2, 3, 4, 4] print addSum(num) x = 1 def changex(): global x x = 10 changex() print x
009a1b7f27713131da08dffd636b8fbfb8e96f30
DeveloperCute/ExerciciosPython
/PythonExercicios/desafio80.py
480
3.90625
4
# coding: iso-8859-1 -*- valores = list() for v in range(0,5): valor = int(input('Digite um nmero: ')) i = 1 if v == 0: valores.append(valor) if v >= 1: while True: if valor == valores[i-1]: valores.insert(i-1, valor) break if valor > valores[i-1]: if len(valores) == ...
36c0e2caab98b1cf61b63230cb2401d90f0afff0
DeveloperCute/ExerciciosPython
/PythonExercicios/desafio67.py
211
3.84375
4
while True: n = int(input('Digite o número que deseja saber a tabuada: ')) if n < 0: break for i in range(1, 11): result = n * i print(f'{n} X {i} = {result}') print('FIM!')
87c7b05b7c0966172d5aebe7fecd3af35a144ff5
sparrowljq/numpy
/lucky.py
1,381
3.6875
4
from matplotlib import pyplot as plt import numpy as np # Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。 # 它也可以和图形工具包一起使用,如 PyQt 和 wxPython # x = np.arange(1, 11) # y = 2*x + 5 plt.title("matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") # 绘制函数图像 #plt.plot(x, y) # plt.plot(x,...
7a726cee273e85b424efc3d824b4826d8fed46a6
daijinghang/zabbix
/python2_1.py
130
3.6875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- for i in [5]: if i%2 !=0: print(i) continue i += 2 print(i)
0401bf23cd5081ed20aa830f7e7d91dc09846f3f
dawe/anndata
/anndata/readwrite/read.py
9,670
3.578125
4
import h5py import numpy as np from ..base import AnnData from .utils import * def read_csv(filename, delimiter=',', first_column_names=None, dtype='float32'): """Read `.csv` file. Same as :func:`~anndata.read_txt` but with default delimiter ','. Parameters ---------- filename : `str` Fi...
162816ae5bf07f1be53950d4b5d210d5ba460ab8
OAAcostaM/Problemas-Python
/MÓDULO 01/scripts/Problema2.py
1,300
3.5
4
import re abecedario_mayus = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','Ñ','O','P','Q','R','S','T','U','V','W','X','Y','Z'] abecedario_minus = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','ñ','o','p','q','r','s','t','u','v','w','x','y','z'] clave = input("Introduza las letras clave: ") lo...
a5cbf7b21aafbac19b687f926e8eab5d8255720f
NataliaPlatova/lesson-2
/for_challenges.py
2,403
3.828125
4
# Задание 1 # Необходимо вывести имена всех учеников из списка с новой строки names = ['Оля', 'Петя', 'Вася', 'Маша'] for name in names: # Убрала индекс print(name) # Задание 2 # Необходимо вывести имена всех учеников из списка, рядом с именем показать количество букв в нём. names = ['Оля', 'Петя', 'В...
e2201e35aa69f06ba0fcedaf0c7ee2a4367c8e3e
myousefi2016/pyNS
/Bessel.pyx
1,994
3.640625
4
#!/usr/bin/env python ## Program: PyNS ## Module: Bessel.py ## Language: Python ## Date: $Date: 2012/09/04 10:21:12 $ ## Version: $Revision: 0.4.2 $ ## Copyright (c) Simone Manini, Luca Antiga. All rights reserved. ## See LICENCE file for details. ## This software is distributed WITHOUT ANY WARRAN...
0b3a7c1b09f1a9572bc85c31b43449532b0b62cf
taroken6/Big-Two-Game
/button.py
1,916
4.03125
4
import pygame pygame.font.init() class Button: def __init__(self, text, x, y, color, width, height): self.text = text self.x = x self.y = self.initial_y = y self.color = self.def_color = color self.width = width self.height = height self.rect = pygame.Rect(s...
0c2d15abf202807b1f13628c130bdd8511270e36
jbocane6/Hangman
/hangman.py
1,301
4
4
#!/usr/bin/python3 import os import random from words import word_list def paint(word, error): os.system('clear') attempts = 6 - error print("Remaining attempts: {:d}".format(attempts)) for i in range(0,error): print("{}".format(muñeco[i])) print("\n{}\n".format(word)) guess = random.choic...
39835831d383b0de71b5174b69f47ad2c23ed291
Haroon-maker/GitDemo
/OOPDemo.py
559
3.859375
4
class Calculator: num = 100 def __init__(self, a, b): """ :param a: :param b: """ print("I am constructor i will be called automatically then classes object is created") self.firstNumber = a self.secondNumber = b @staticmethod def get_data(): ...
dc0dd1b3c2c01fec33611a411c7aba397747f0c4
Haroon-maker/GitDemo
/ReadDemp.py
183
3.65625
4
file = open('test.txt') # print(file.read(8)) # line = file.read() # while line != "": # print(line) # line = file.read() for line in file.readlines(): print(line) file.close()
d2dee5dccd47adc5b8c0347873c156fdcd68b25d
SaketBahuguna/Assignment-Day1
/Assignment Day1.py
125
3.953125
4
# take input from user x = int(input("Enter the value: ")) y = int(input("Enter the value: ")) z= x**y print(z)
0c5a844d9d07521ec2eeea612f29af6a9903f017
Rasnejah/JogoDaJvelha
/main.py
772
3.640625
4
# encoding: utf-8 from jogoDavelha import JogoDaVelha import os velha = JogoDaVelha() jogador = velha.Jogador() while True: print('Vez do jogador {}'.format(jogador)) for i in range(len(velha.matriz)): print(velha.matriz[i]) user = int(input('Digite uma posição para jogar: 1 á 9 ou 0 para sair ')) if user =...
88728dacece25ad59a60239efa5ab1526a3b1446
niteshsachdev/ML2019
/Day26/Day_26_Code_Challenges.py
5,621
3.75
4
""" Q1. Code Challegene (NLP) Dataset: amazon_cells_labelled.txt The Data has sentences from Amazon Reviews Each line in Data Set is tagged positive or negative Create a Machine learning model using Natural Language Processing that can predict wheter a given review about the product is positive or negative """ impo...
94add2d11b23656eb502b1b6512f7ce885e61139
niteshsachdev/ML2019
/Day9/Day_09_Code_Challenge.py
8,471
3.859375
4
""" Code Challenge 1 Write a python code to insert records to a mongo/sqlite/MySQL database named db_University for 10 students with fields like Student_Name, Student_Age, Student_Roll_no, Student_Branch. """ import pymongo client = pymongo.MongoClient("mongodb://niteshsachdev:tUFBfkAC0GlUHJ6U@cluster0-shard-00-0...
7f3852bb0907b7042156be8f0712262ec630e906
nicolas2192/Ironhack-Module-1-Project-MyProject
/packages/Wrangling/CountryVsNationality.py
2,013
3.84375
4
import pandas as pd def country_nationality_table(): """ This function reads from the web a table with countries and nationalities. Output: Clean pandas dataframe """ # Reading the table from a webpage tables = pd.read_html("https://www.vocabulary.cl/Basic/Nationalities.htm") con = tables[...
d90e55c31e51dd1ab59f6c2fbcd68649b82b548c
asset311/comp-sci-fundamentals
/arrays/merge_meeting_times.py
4,113
3.65625
4
def overlap(tup1, tup2): if (tup1[0] >= tup2[0] and tup1[0] <= tup2[-1]) or (tup1[-1] >= tup2[0] and tup1[-1] < tup2[-1]): return (min(tup1+tup2), max(tup1+tup2)) return (tup1, tup2) # this compares each meetings with every other since it is unordered # this results in O(n^2) def merge_ranges(meetings...
2cb1f1a30e435228f7acf96f93c9efcd672358ca
asset311/comp-sci-fundamentals
/strings/pei_strings.py
3,920
4.0625
4
''' TIPS - Strings are immutable, hence any concatenation creates a new string - It is possible to have solutions that use strings themselves to have O(1) space complexity - Updating a mutable string from the front is slow, so write values from the back ''' ''' METHODS string.strip([chars]) - removes characters from...
5a8930ee1b4e8b023ace2c085f2674bf1b1c0bba
asset311/comp-sci-fundamentals
/stacks/valid_parentheses.py
1,047
4.09375
4
''' 20. Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Note that an empty string is...
67787f47474d28e57f12af9f74c4ff94c05e2e23
asset311/comp-sci-fundamentals
/searching/search_first_of_k.py
691
3.828125
4
''' Write a method that takes a sorted array and a key and returns the index of the first occurrence of that key in the array. Return -1 if the key doesn't appear in the array. Example: [-14,-10,2,108,108,243,285,285,285,401] Returns 3 if key = 108 Returns 6 if key = 285 ''' def search_first_of_k(A, k): left, ri...
8ae25d34a19534950456811a9a1ffebce071fa7d
asset311/comp-sci-fundamentals
/arrays/apple_stocks.py
2,226
4
4
''' Write an efficient function that takes stock_prices and returns the best profit I could have made from one purchase and one sale of one share of Apple stock yesterday. Example: stock_prices = [10, 7, 5, 8, 11, 9] get_max_profit(stock_prices) Returns 6 (buying for $5 and selling for $11) No shorting is allowed. ...
e38775b36ae57d2853c2dfa17dc5d5346c113598
iron-kang-maker/Test
/coursera_exercise/python_Rice/Stopwatch.py
1,752
3.625
4
# template for "Stopwatch: The Game" import simplegui import math # define global variables num = 0 width = 300 height = 200 success_num = 0 stop_num = 0 stop_flag = 1 d = 0 # define helper function format that converts time # in tenths of seconds into formatted string A:BC.D def format(t): global d...
ce105e7a1ef22746b05019c4b9d610072cd6b384
hxxtsxxh/codewithmosh-tutorials
/DisplayingCurrentTIme.py
352
3.5
4
# import time module import time import datetime # 24-hour format below print(time.strftime("%H:%M:%S")) # 12-hour format below print(time.strftime("%I:%M:%S")) # datetime module e = datetime.datetime.now() print(e.strftime("%Y-%m-%d %H:%M:%S")) print(e.strftime("%d/%m/%Y")) print(e.strftime("%I:%M:%S %p")) pri...
b8e829a00f9ac2ca1cbcc0d3fcf8fb2aebf23cca
hxxtsxxh/codewithmosh-tutorials
/Tutorial2 Recieving Input.py
331
4.53125
5
# The input command will receive input from the user store that data for further evaluation. # We assign this input statement to any variable that we want. For example, here we give a variable called "name". name = input('What is your name? ') fav_color = input('What is your favorite color? ') print(name + ' likes ' + ...
cf59ac67767f47c77a3978082429c9ab2e821dcd
hxxtsxxh/codewithmosh-tutorials
/Tutorial 24 Return Statement.py
555
3.765625
4
def square(number): return number * number answer = square(int(input('type a number\n'))) print(answer) def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print('Hello this is your calculator! \n') ask = input('''Pi...
9236d2564f99275147fdb4fdaa7f81f59a5a4a4b
mwstw/aaa
/aaa_2_6_chernousov.py
316
3.921875
4
def count_non_unique(a): values = list() non_unique_values = list() for i in a: if i not in values: values.append(i) else: non_unique_values.append(i) return(len(set(non_unique_values))) a = [1,2,3,1,2,3,4,5,6] b = count_non_unique(a) print(b)
4ddc745a90e783629283a00b83a524d4e752e4c8
swaelali/Old-Stuff
/Light_out Puzzle/light_out_puzzle.py
5,332
3.5
4
# Light out Puzzle Solution ALGORITHM # Solution of Light out puzzle up to 3x3 from GF2 import * def combine(puzz_matrix): ''' Return a list of all possible combinations according following constraints: - no repeation - don't care of the sequence of the numbers''' buttons = len(...
5474274f9137dcfa0cbe86db71d7a924d542fee4
swf-not-y/python
/work5-1.py
1,306
3.96875
4
print("---欢迎进入通讯录程序---") print("---1:查询联系人资料 ---") print("---2:插入新的联系人---") print("---3:删除已有联系人---") print("---4:退出通讯录程序---") aline = { } while 1: nums = input('请输入相关的指令代码:') if nums == '1': name = input('请输入联系人姓名:') if name in aline: print(aline[name]+aline[tel]) else:...
09a732808b4f30b25a37750a2f9b6c329d5ef6c6
swf-not-y/python
/work4-2.py
351
3.671875
4
while(1): nums = input("请录入一个整数(输入STOP结束):") if(nums == "STOP"): break target = input("请输入一个指定的数:") target = int(target) for i in nums: for j in nums: if(nums[i] + nums[j] == target): print("列表为%d,%d:",i,j) nums1 = [i,j] print(nums1)
387f2546ad970e026e1bb39980741819e362067d
SYC-Mirage/DateEngine
/car_city_cluster.py
1,773
3.796875
4
# 使用KMeans进行聚类 from sklearn.cluster import KMeans from sklearn import preprocessing import pandas as pd import numpy as np # 数据加载 #data = pd.read_csv('Mall_Customers.csv', encoding='gbk') data = pd.read_csv('car_data.csv',encoding='gbk') train_x = data[["地区","人均GDP","城镇人口比重","交通工具消费价格指数","百户拥有汽车量"]] # LabelEncoder fr...
670555cbee2b2c885bf53213193dbe2c4f60bb33
PPL-IIITA/ppl-assignment-JayeshChaudhari17897
/Q8/q3_girl.py
567
3.8125
4
from q3_gift import gift from abc import ABCMeta , abstractmethod class girl(object): _metaclass_ = ABCMeta def __init__(self , name = None , attractiveness = None , intelligence = None , budget = None): self.name = name self.attractiveness = attractiveness self.maintenance = budget self.intelligenc...
b46a06735c4e5713cd30dd78067153fb470d179f
rfyiamcool/mutex_timeout
/test.py
835
3.53125
4
# coding:utf-8 import random import time import threading from mutex_timeout import TimeoutLock def locking_thread_fn(name, lock, duration, timeout): with TimeoutLock(name, lock, timeout=timeout): time.sleep(duration) def test_lock(): _lock = TimeoutLock.lock() _threads = [] _total_d = 0 ...
4367f513be9cef17c41e283c7646550f8a86aa57
akashgkrishnan/simpleProjects
/calc/actual_calc.py
1,459
3.8125
4
class ActualCalulator: def getsum(self): print("\n"*40) print("SUM") a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) print("\n"*10) print(f"The sum of {a} and {b} is = {a+b}") print("\n"*10) def getdiff(self): ...
18f28b1a538dc96960ee3fd6e150d31921846b8e
D-MythX/RPS
/rps.py
4,786
4.09375
4
#!/usr/bin/env python3 #Title: RPS #Author: MyTH import random import time Computer_choice = [ "R", "S", "P" ] name = input("\nHi! Whats your name?...") print("Hey",name,"wanna play a game?") time.sleep(1.0) print("\nLet's play (R)ock (P)aper (S)cissors. Where ; rock beats scissors, paper beats rock and scissors bea...
2deffda4129af86ac933fc7cde73ec13ea533fe5
eknathyadav/Queue-implementation-python
/queue.py
1,496
3.921875
4
#Queue implementation using linked list """ Created on Tue Oct 1 21:33:23 2019 @author: Eknath """ import gc class node: def __init__(self,data): self.data = data self.next = None class Queue: def __init__(self): self.front = None self.head = None def enqueu...
e69f91123f3d8c0923096b1fa3f654d6a7af846a
Ori-Shiran/Net4U
/Beginner/Exercises_11/common_list.py
466
3.75
4
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] c = [] i=0 while i < len(a): if a[i] in b and a[i] not in c: c.append(a[i]) i=i+1 print("New list with common numbers: " + str(c)) # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10...
eb24b86cbc89edd6d8586b1b11107cb1f9ac7f90
DarrenLin1112/Darren
/motorcycles2.py
762
3.703125
4
message = ['honda','yamaha','suzuki'] print(message) message[2]="darren" print(message) message = ['honda','yamaha','suzuki'] message.append('ducati') print(message) message = ['honda','yamaha','suzuki'] del message[0] print(message) motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) p...
e1148a896f215d84075787aa68e04d83925cbcd5
abhayraut712/algorithm-implementations
/test.py
534
3.875
4
import time arr = [1, 2, 3, 4, 5, 6, 7, 8] def BinarySearch(arr, l, r, x): # here l indicates the lest most index of array # r indicates the right most index of the array while l<=r: mid = l + (r-l)//2 # mid should be always equal to integer so (r-1)//2 if arr[mid] == x: ...
4de9c9846d6646cca784b479e03753972255f6cb
mn4774jm/tic_tac_toe_game
/HelloBirthday.py
1,407
4.53125
5
''' Thomas Mullins 8/25/2020 Description: This program will ask the user for their name and date of birth and provide feedback including a personalized greeting, how many letters they have in their name, and a happy birthday message if they were born in January ''' # import datetime to check user birthday from datetim...
425ee92610d6959005ad01edf32c6ccf810713b8
mn4774jm/tic_tac_toe_game
/weekly_lessons/week_2_basics/Week2_labs/Author_class.py
806
3.828125
4
class Author: # creates new object def __init__(self, name): self.name = name self.books = [] # used to add items to the books element list, using the argument as the title when called def publish(self, title): if title in self.books: print(f'"{title}" already exists...
98de90d7168cb6b55b4790469f058e69491e8651
DigitalNegatives/DataScience-Celebrity_Image_Classification
/01_celeb_base/utils/imgs.py
6,851
3.90625
4
import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.animation as animation # Taken from lab3 def montage(images, saveto='montage.png'): """Draw all images as a montage separated by 1 pixel borders. Also saves the file to the destination specified by `saveto...
f783a8d136d1cf4e3c44e18f0983bfd3852cd53e
kaylani2/machineLearning
/src/simple_examples/generalization.py
2,540
3.515625
4
## Adaptado de Nikhil Ketkar - Deep Learning with Python, A Hands-on Introduction ## Mostra o efeito da especializacao de um algoritmo ao incrementar o grau do ## polinomio utilizado no metodo de Minimos Quadrados ## Pega os primeiros 80 pontos pra treinar e os ultimos 20 pra testar #Generate Toy Dataset import pylab ...
19d40a57fc02641726cc1641a9ef98bdd6bbdc52
kaylani2/machineLearning
/src/simple_examples/decision_trees.py
2,108
3.5
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd import mglearn ## Plot a decision tree mglearn.plots.plot_animal_tree () ################################# Carregando os dados ##################################### from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer () #...
7500677ebea1ef3dbab8738218c3f575ca6d5e59
kazimuth/6.885
/lecture-notes/implementing-probabilistic/1-simple_nonstandard_interp.py
1,037
3.84375
4
def f(): p = sample(Uniform()) xs = [] for i in range(3): xs.append(sample(Bernoulli(p))) return sum(xs) def run(f, args=[]): # Standard interpretation: when you see a `sample`, sample. def sample(distribution): return distribution.sample() # Create a version of f that uses ...
f451b697717274f9bf141abd5d5bfa4b567ff5e3
denisqa2h/learn-homework-1
/3_for.py
1,071
3.84375
4
""" Домашнее задание №1 Цикл for: Оценки * Создать список из словарей с оценками учеников разных классов школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...] * Посчитать и вывести средний балл по всей школе. * Посчитать и вывести средний балл по каждому классу. """ def main(): dict_ = [ { ...
4d337149acca36d79beb5b53265ef064eaac8904
Paprok/Training_Logbook
/training.py
3,926
3.53125
4
import os # training module class Training: def __init__(self, stats_file, exercise_file): self.stats_list = self.load_stats(stats_file) self.strength = self.stats_list[0] self.hypertrophy = self.stats_list[1] self.fat_burn = self.stats_list[2] self.exercise_dict = self.load_...
072f7f4a491ce6184484e9e3e17bf756520bad58
zceehsh/products
/products.py
375
3.8125
4
products = [] #二维清单 while True: name = input('Please input the name of product: ') if name == 'q': break price = input('Please input the price of this product: ') attribute = [] attribute = [name, price] # attribute.append(name) # attribute.append(price) products.append(attribute) print(products) for p in p...
5631c07c3ef44b8e23052da12e343fbac065bc82
starlightromero/web-1.1-homework-1
/app.py
2,753
3.796875
4
"""Import Flask and randint.""" from flask import Flask, render_template from random import randint app = Flask(__name__) @app.route("/", methods=["GET"]) def homepage(): """Shows a greeting to the user.""" return render_template("main.html") @app.route("/penguins", methods=["GET"]) def penguins(): """...
6d92325ffb2d8a5d81074d148fa6f14328a29bc1
necromaner/Python
/exercise/exercise1.py
524
3.890625
4
#exercise1:99乘法口诀 print("99乘法口诀:") for i in range(1,10): for j in range(1,i+1): print(str(i)+" * "+str(j)+" = "+str(i*j),end=" ") print("") #逆向输出乘法口诀 print("\n逆向输出乘法口诀:") print("1.") for i in range(1,10): for j in range(1,11-i): print(str(10-i)+" * "+str(j)+" = "+str((10-i)*j),end=" "...
28d1b3256dabaa3e920d6e796cc7654b55794d18
vchnun/leetcode
/sort.py
995
3.8125
4
class List(list): def __getindex(self, low, high): tmp = self[high] while(low < high): while(low < high and self[low] <= tmp): low += 1 else: self[high] = self[low] while(low < high and self[high] >= tmp): h...
227daea2bdf5189d2c19be48a92a0da841828ec6
xiaoming2333ca/Exercise81
/Exercise81.py
109
3.59375
4
import math def HypotenuseCalculaor(a, b): if a > 0 and b > 0: hy = math.sqrt(a ** 2 + b ** 2)
ee4116f4de5db04198db8468f3dd7435b918aba9
jy8474np/week05_lab05
/chainsaw_jugglers_records.py
3,703
4.25
4
import sqlite3 db = 'record_holders_db.sqlite' # Assign variable db to database path for ease # Create a table called rankings, if it doesn't already exist def create_table(): with sqlite3.connect(db) as conn: conn.execute('CREATE TABLE IF NOT EXISTS rankings (name text, country text, catches int)') ...
fddcb669773db62f049a87feea9cc8f66864f726
parksjin01/Machine-Learning
/Linear_Regression/example.py
922
4.34375
4
""" Linear Regression example. Use 1 layer linear regression model to calculate add operation. ex) feature = [3, 5] then output should be 8 If cost graph doesn't converge, then change learning rate more smaller """ from Linear_Regression.model import * from matplotlib.pyplot import * feature = [[1, 3, 5], [1, 5, 4...
40749ab1002932360b92cd9a391bafc85e7fca59
Yarikfry/Sign-in
/Вход на сайт.py
503
4.0625
4
# возраст, если больше 18 (пускает), младше(не пускает), больше 18: # как зовут, почта, номер телефона age = int(input('Введите ваш возраст:')) if age < 18: print('Вы слишком молоды') elif age >= 18: name = input('Введите Ваше имя:') email = input('Введите Вашу почту:') number = int(input('Введи...
5128cd33f89cf3b300604eb8d5152efa8e4f062f
comsavvy/Billionaire-club
/lesson.py
1,363
3.65625
4
from concurrent import futures def am(age, money, output_name): if ((age >= 20 and money >= 500000) or (age <= 20 and money >= 2000000)): return True else: return False def gender(gen, age, money, output_name): if gen.startswith("M"): if am(age, money, output_name): pri...
6f1b6c943f3e150e4de97da51136d8de05db014e
AnnaParakhina/DB-1
/lab2/view.py
7,143
3.765625
4
import os from datetime import date class View: def __init__(self): self.clear = lambda: os.system('cls') self.separator = lambda: print("_________________________") def print_menu(self): print("1 - get GROUPS by name\n" "2 - get MUSICIANS by name\n" "3 - g...
f5d67bb46883d5510b6856426349169ae8caa6ce
rembrandtqeinstein/learningPy
/c_ex_urllib.py
967
3.65625
4
# This files does the same as Socket with an external library to handle the stuff import urllib.request, urllib.parse, urllib.error # This is like the file open handler, opens the file, doesn't read it, just opens a channel. This allows us to treat the site like a file, so we can construct for loops to work around it ...
a0cebbedd4d88b7bdf23e24bfc27f4a5ba9e4fd5
rembrandtqeinstein/learningPy
/pp_e_24.py
452
4.15625
4
def board(width, height): hor = " ---" ver = "| " ver = (ver * width) + "|" height = height *2 for x in range(1,height+2): if x % 2 != 0: print(hor*width) else: print(ver) width = input("Enter the width of the board: ") height = input("Enter the height of t...
2b937c27b0d1c706643d0bc8c99446c7b3bee9f3
rembrandtqeinstein/learningPy
/pp_e_1.py
437
4.0625
4
import datetime now = datetime.datetime.now() year = now.year name = input("Please enter your name: ") age = input("Please enter your age: ") copies = input("How many times should I print the message?: ") try: age = int(age) copies = int(copies) except: print("The input on Age is not a number") turn = (10...
a06c10adbbf3d535a27e93e506aa032cfd2b1805
rembrandtqeinstein/learningPy
/pp_e_8.py
977
4
4
while True: inp1 = input("Player 1, Enter paper, rock or sissors (done to exit): ") if inp1 == 'done': break inp2 = input("Player 2, Enter paper, rock or sissors (done to exit): ") if inp2 == 'done': break if inp1 == 'paper' and inp2 == 'rock': print("Player 1 wins with", i...
2c75a17c4d3423216e98090fcbbe4e586069c6de
rembrandtqeinstein/learningPy
/c_ex_strings.py
3,681
3.859375
4
str = 'X-DSPAM-Confidence: 0.8475 ' pos = str.find(':') numb = float(str[pos+1:]) pos2 = str.find('0') numb2 = float(str[pos2:]) print(numb, type(numb)) print(numb2, type(numb2)) # Could I make a for loop to find a numeric character with isnumeric method and then save as long as that is true? it would break with the ....
93f6d2ea522227c923b5251b649e1dcc1c638348
joshey-bit/Python_Projects
/2-D Game/settings.py
1,945
3.859375
4
''' program to create a settings class for alien_invasion.py ''' class Settings(): '''class to set the default attributes''' def __init__(self): '''static settings''' #screen settings self.screen_width = 800 self.screen_height = 600 self.background_color = (87,9...
808f92492b66314831d4ab1c220f4c936151423c
joshey-bit/Python_Projects
/Random_Walk/random_walk.py
1,796
4.09375
4
'''create random walk class''' from random import choice import matplotlib.pyplot as plt class RandomWalk(): def __init__(self, num_points = 5000): self.num_points = num_points #start from origin self.x_values = [0] self.y_values = [0] def get_step(self): '''method to increase the steps''' ...
57fb8d33bfb6ba29b37a60aa8378cb29498aaae8
vpereira13/Trabalho-Inteligencia-Artificial
/Desenvolvimento/contador.py
1,727
3.75
4
'''Responsável por fazer a contagem de ocorrência de cada caracter do texto ''' from collections import defaultdict import string PONTUACOES_BRANCOS = string.punctuation PONTUACOES_BRANCOS += string.whitespace PONTUACOES_BRANCOS += string.digits ALFABETO = "qwertyuiopasdfghjklzxcvbnmáéíóúçüâêãõ" def contador(filena...
a5cf5b339d70a669a973633d643d8c48c5aeb551
MailyRa/oo-melons
/melons.py
2,222
4.25
4
"""Classes for melon orders.""" import random import datetime class AbstractMelonOrder(): """An abstract base class that other Melon Orders inherit from.""" def __init__(self, species, qty, order_type, tax): self.species = species self.qty = qty self.order_type = order_type ...
ecf85d06e1e21575bb952c695a66583873a83d9a
JavierVaronBueno/python_3.x_Estructuras_Datos_Busquedas_Hilos
/Estructura ListaDoblementeEnlazada/listaDoblementeEnlazada.py
1,761
3.96875
4
""" ESTRUCTURA LISTA DOBLEMENTE ENLAZADA: Una lista doblemnete enlazada de nodos, donde cada nodo tiene un par de campos de enlace, uno al nodo siguiente y el otro al anterior. Caracteristicas: 1- Recorre la estructura en smbos sentidos, de inicio a fin y de fin a inicio 2- Borra mas simple los datos 3- Estr...
6202cf3b25018e4bcd54907012ea3646e4fc2fd6
JavierVaronBueno/python_3.x_Estructuras_Datos_Busquedas_Hilos
/01_ordenamientoBurbuja.py
2,283
3.65625
4
""" METODO DE ORDENAMIENTO BURBUJA: Revisa cada elemento de la lista con el siguiente elemento, intercambiandolos de pocision si estan en el orden equivocado. Ejemeplo: Entrada: 4,2,6,8,5,7 Solucion: Recorrido [--,--] = [4, 2, 6, 8, 5, 7] Recorrido [ 0 , 0 ] = [4, 2, 6, 8, 5, 7] intercambio el valor 4 ...
fcd61731c89af703f89c9c644686dcb4ae11c867
JavierVaronBueno/python_3.x_Estructuras_Datos_Busquedas_Hilos
/ALgoritmos Libro McGraw-Hill/Tow_StepClassicMultiplication_seccion_7_1_1.py
2,141
3.609375
4
import time global start_time def suma(a,b):#XOR suma = (a+b)%2 return suma def multi(a,b):#AND mul = (a*b)%2 return mul def poly_Multiplicacion(a,b,m): start_time = time.time() d = [] for i in range(0, 2*m-1): d.append(0) for k in range(0,m): if k == 0: #print("[0][0]=d[",k,"]+(a[0]b[0])") ...
0eae1d23d246869ed0956d57f6069adec28c98cd
AlanFermat/Blogs
/TensorFlow/MLP.py
2,419
3.515625
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=True) import matplotlib.pyplot as plt import numpy as np import random as ran def train_test_data(train_num, test_num): x_train = mnist.train.images[:train_num,:] y_train = mnis...
d4deeafcb9620bae11c2e4ebbcc49bc8e5596f60
erroronline1/hello-world
/hangman.py
1,037
3.71875
4
""" hangman. second python experiment """ from random import randint list=('bar','house','table','foo') sol=list[randint(0,len(list)-1)] length=len(sol) print('guess a word with {0} letters.'.format(length)) wrong=[] right=[] while len(wrong)<len(sol): char=input('guess letter: ') if len(char) >1: print('only one l...
8ab2b0262392febfa65051416d734cd2955bb76d
NickO-ONicole/Quiz-de-l-gica-matem-tica
/Lógica matemática.py
1,574
4.4375
4
# Este é um programa que ajuda no aprendizado de matemática e lógica para crianças print ('< Lógica Matemática >') print () pontos = 0 print ('A seguir você deverá tentar resolver problemas de lógica e matemática.') print ('Ao final, será exibida sua pontuação.') print () print () print ('Você ganhou quat...