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
d073bae6b3f47a06f07414c59ab770d41c1f6791
Ftoma123/100daysprograming
/day10.py
146
4.03125
4
x = 2 y = 3 # Python Arithmetic Operators print(x + y) #Python Assignment Operator x += 5 print(x) #Python Comparison Operators print(x > y)
1674840b195a21b3963bbd9595b5ae783cac55fd
Ftoma123/100daysprograming
/day9.py
347
4.03125
4
age = 36 text = "my age is {}" print(text.format(age)) apple = 3 banana = 5 streberry = 10 text1 = "I bought {} apples, {} bananas and {} straeberry." print(text1.format(apple, banana, streberry)) apple = 10 banana = 55 streberry = 30 text2 = "I bought {2} straeberry, {1} bananas and {0} apples." print(text2.format...
7dd6607c78cd394594364da8f9749cc2f88c8321
Ftoma123/100daysprograming
/day41.py
541
3.984375
4
#create object class MyClass: x = 5 p1 = MyClass() #تعريف لل opject print(p1.x) print('_______________') #___________ class person: def __init__(self, name, age): self.name = name self.age = age p1 = person('Jhon', 13) print(p1.name) print(p1.age) print('_______________') #___________ class ...
6373d12759eabd9b3ffadbc995b49d28b9f6fae7
Ftoma123/100daysprograming
/day30.py
550
4.375
4
#using range() in Loop for x in range(6): print(x) print('____________________') #using range() with parameter for x in range(2,6): print(x) print('____________________') #using range() with specific increment for x in range(2,20,3): #(start, ende, increment) print(x) print('____________________') #else ...
5e4cacab4da0901737fdd51b59ed54802ac00d06
Ftoma123/100daysprograming
/day43.py
554
4.03125
4
#inheretance #parent class class person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) x = person('Jhon', 'Doe') x.printname() # Create a Child Class class student(person): pass s = st...
ee980ea2f6d822a3118eb7845b0f3a63a0a241ad
QiaojuLiu/leetcj
/heap.py
1,944
3.765625
4
class PriorityQueueBase: class Item: __slots__ = '_key','_value' def __init__(self,k,v): self._key = k self._value = v def __lt__(self,other): return self._key < other._key #如果self_.key比other._key小,则返回True,否则,返回False。 def is_empty(self): ...
1083052e37b5556980972557425aeac95fa7931b
arensdj/math-series
/series_module.py
2,753
4.46875
4
# This function produces the fibonacci Series which is a numeric series starting # with the integers 0 and 1. In this series, the next integer is determined by # summing the previous two. # The resulting series looks like 0, 1, 1, 2, 3, 5, 8, 13, ... def fibonacci(n): """ Summary of fibonacci function: compu...
d11dcc3373cbb78044e5ce875b2bfd546156176c
kageus/Advent-of-Code-2020
/3.1.py
476
3.9375
4
# find any given value of a repeating string at X coordinate def lineValueAtTarget(line, target): if target > len(line): target = target % len(line) return line[target] dataInput = open("./input/input_3.txt").read().split("\n") treeCount = 0 currentLocation = 0 for line in dataInput: valueA...
0ec6562b7b18d03407237ac1054a71a8f3787e7d
froens/EnzymAnalyzer
/utils/FileUtils.py
2,342
4.03125
4
import csv def loaddata(file_name, max_rows = -1): """ Pre-processing Reading file into a list """ # Open file handle from data.csv file = open(file_name) # Read first line of the file # The first line contains information about the types in each column typeStr = file.readline() ...
31cac0bf6296afbb5219e8633226060296726e41
m32/endesive
/endesive/pdf/PyPDF2_annotate/util/geometry.py
4,446
4.0625
4
# -*- coding: utf-8 -*- """ Geometry ~~~~~~~~ Geometry utility functions :copyright: Copyright 2019 Autodesk, Inc. :license: MIT, see LICENSE for details. """ import math def normalize_rotation(rotate): if rotate % 90: raise ValueError('Invalid Rotate value: {}'.format(rotate)) wh...
393d6c46bd42073f373048e21364995525294461
kale887/Python3.6
/Practice/dict-2.py
847
3.640625
4
names = [] names.append({ 'first': 'Dam', 'last': 'yelo', 'suffix': '22'}) names.append({'fist': 'jane'}) for name in names: x = name.get('first') y = name.get('last') z = name.get('suffix') print(x,y,z) lelanddict = { "name": { "first": "Leland", "middle": "Dewitt"...
8cfcb5d95955bfd7b3cd75487c8f43c27eb2d575
pleeplee-robot/interface
/pleepleeapp/plant.py
758
3.59375
4
#!/usr/bin/env python3 import pygame from pygame.locals import * import sys import time class Plant: """Simple plant representation. Contains information of a plant. Attributes: pos_x: x coordinate of the plant. pos_y: y coordinate of the plant. width: width of the plant. ...
dc4e084a53efc0dae345eddafb5432ff050732cb
sameerraghuram/logical-timestamp
/process.py
9,218
4.03125
4
''' Write a program that computes vector clocks of events that occur in financial transactions. Three processes (1, 2, and 3) all start with balance = $1,000. At each process, one of the three events, namely withdraw, deposit, and send money to another process, happens once every five seconds chosen randomly. The amoun...
b6e227e242259e9378e9dc5f39cf23a38ae48a66
Hariharan2199/python
/oddeve.py
83
4
4
x=int(input("enter the no ")) if(x%2==0): print("prime") else: print("odd")
fb99e7ad17beaa83dce50ff54768cab4571b9dd8
lixueyuan/Python_project
/third/GetUserInfo.py
300
3.78125
4
#----使用type()----判断系统自带的类型.例如int string 或则 ValueError等等这样的类型我们可以直接用type() #那么如果判断自己定义的class或者是通过集成创建的自定义类型我们就可以使用另一个函数来做判断 #isinstance() print('hello type')
adab5b52f203a6405486d65ac93cf132f5d0516b
nylasabrine/FinalProject
/countingletters.py
453
3.59375
4
''' Created on Nov 18, 2017 @author: ITAUser ''' def characterappearances(filename, mychar): f = open(filename , 'r') count = 0; run = True while run: text = f.read(1) text = text.lower() if text == mychar: count = count +1; if text == '': break...
d9fd6aa251f76310607d6d6d992342cab8634e02
kurowsk1/code-club
/area of a circle.py
1,216
4.09375
4
from math import pi from sys import exit # this imports the math library, which contains various mathematical functions radius = input(">Enter circle radius in meters: ") # what follows the '=' sign assigns that value to the variable 'radius'. # The 'input' command lets the program know to wait for the user to input ...
07408aa7f4a093c25ea893f6ffb8ab01fcd3fd41
EdsonFragnan/CursoPython
/Parte_1/Semana_4/Exercicios_entregar/NumerosImpares.py
165
3.8125
4
valor = int(input('Digite o valor de n: ')) i = 0 valor_impar = 1 while i < valor: print(valor_impar) i = i + 1 valor_impar = valor_impar + 2
244e6d0dd7633646f3fd496a036ae000d8889d56
EdsonFragnan/CursoPython
/Parte_2/Semana_3/Exercicios_entregar/TipoTriangulo.py
922
3.84375
4
class Triangulo: def __init__(self, a, b, c): self.lA = a self.lB = b self.lC = c def tipo_lado(self): if self.lA <= 0 or self.lB <= 0 or self.lC <= 0: return False else: if self.lA + self.lB > self.lC and self.lB + self.lC > self.lA: ...
42d82aef93c878a2b548dd308d0a6e580419e82f
EdsonFragnan/CursoPython
/Parte_1/Semana_4/Exercicios_entregar/NumerosAdjacentes.py
386
3.953125
4
numero = int(input("Digite um numero: ")) anterior = numero % 10 numero = numero // 10; n_adjacente = False; pos = 0 while numero > 0 and not n_adjacente: atual = numero % 10 if atual == anterior: n_adjacente = True else: pos += 1 anterior = atual numero = numero // 1...
a7fff59fb7b9c823e0690252b212479c30c0d117
EdsonFragnan/CursoPython
/Parte_2/Semana_4/Exercicios_entregar/SelectionSort.py
250
3.640625
4
def ordena(lista): for i in reversed(range(len(lista))): val = 0 for j in range(1, i + 1): if lista[j] > lista[val]: val = j lista[i], lista[val] = lista[val], lista[i] return lista
c454fdec7a34c4556ca9f65747ef810edb8b6ddc
EdsonFragnan/CursoPython
/Parte_1/Semana_3/Exercicios_entregar/LongePerto.py
319
3.984375
4
import math a = int(input('Digite um número para a:')) b = int(input('Digite um número para b:')) c = int(input('Digite um número para c:')) d = int(input('Digite um número para d:')) distancia = ((a - c)**2) + ((b - d)**2) if (math.sqrt(distancia) >= 10): print('longe') else: print('perto')
78194dddcdbfc0e301efc430d038907a7b7463e5
Spiderbeard/Python
/payrate.py
394
4.03125
4
hours = input("Enter the hours ") pay = input("Enter the payrate ") try: fhours = float(hours) fpay = float(pay) except: print("Error, Please enter a numeric input") quit() total = 0 if fhours <= 40: total = fhours * fpay else: extra = fhours - 40 print(extra) total = (fhours-extra) ...
d218d9bf4cecadd1baf22e2632df726eff5b9cd5
pavensharma/python-bmi-calculator
/bmi_calculator.py
204
3.828125
4
weight = input("Insert your weight (in KG)") height = input("insert your height (M)") weight = float(weight) height = float(height) bmi = weight / (height**2) print(bmi) #Test #paven's comment here.
740dd14a07630424e5db6b373cb7347040c417c4
doness/eris
/actions/commands.py
4,023
3.734375
4
import dice import settings class Command: """The base Command class Attributes: message (str): The message to parse from Discord command (str): The parsed command help_message (str): The help message for a command admin_required (bool): Whether or not a user needs to be an ad...
64ef27d91c24c113f5ec215237c6e6cd6a479c40
AlieFries/ProjectEuler
/project_euler_12_2.py
633
3.6875
4
def divisors(n): count = 0 if n % 2 == 0: n = n/2 count += 1 while n % 2 == 0: n = n/2 count += 1 divisors = count+1 div = 3 while n != 1: count = 0 while n % div == 0: n = n/div count += 1 divisors = divisors*(coun...
fd55697157167c82a9c6a4f2ea3b432de136a9f7
AlieFries/ProjectEuler
/project_euler_12.py
1,543
3.765625
4
##first generate a list of triangle numbers, formula for tri numbers, n(n+1)/2 triangles = [] ##for i in range(1,100): ## num = 0 ## for a in range(1, i+1): ## num += a ## triangles.append(num) ##print triangles ##generate larger tris based on formula largest_count = 0 most_factors = 0 for i in rang...
c519ba762f6623c5c473525d7d50334b32c1c4a1
jonathanryding/Assignments
/Spreading Law of droplets, Project 1.py
33,947
4.03125
4
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d #Spreading Law of droplets, Project 1 #Determine the spreading law (relationship between the speed of the contact line and the contact angle) of picolitre droplets using the spherical cap approximation. #function defini...
05fe3505d7bf1f29518c190a6d4c328c9e918098
longkyle/blackjack
/test_blackjack.py
10,863
3.78125
4
#!/usr/bin/env python """ unittests for blackjack.py """ __author__ = "Kyle Long" __email__ = "long.kyle@gmail.com" __date__ = "08/26/2019" __copyright__ = "Copyright 2019, Kyle Long" __python_version__ = "3.7.4" import unittest import blackjack as bj from blackjack import Card, Deck, Hand, Dealer, Gambler class ...
a8b4639a8a2de162236ba3ced3ce9229a2d1579d
Nadjamac/Mod1_BlueEdtech
/Aula11_Dicionários/Aula11_Dicionarios_Conteúdo.py
1,012
4.15625
4
#Criando uma lista de tuplas -> estrutura de dados que associa um elemento a outro # lista = [("Ana" , "123-456") , ("Bruno" , "321-654") , ("Cris" , "213 - 546") , ("Daniel" , "231 - 564") , ("Elen" , "111-222")] #Sintaxe de um dicionário # dicionario = {"Ana" : "123-456"} #Criando um dicionário # lista_dicionari...
2234f840e1255a3344d3d614ce17f7f7866ed5ab
Nadjamac/Mod1_BlueEdtech
/Aula12_Dicionários_CodeLAB/Exercicio 4.py
663
3.75
4
import random import operator import time print("JOGO DOS DADOS: ") tuplas = () lista = [] for n in range(4): jogador = input("Digite seu nome: ") print("DIGITE ENTER PARA SORTEAR O DADO") input() numero = random.randint(1,10) tuplas = (jogador , numero) lista.append(tuplas) lista_dict = dict...
3bd5f1f83a5af71b6c828a46a514980f003cbefb
Nadjamac/Mod1_BlueEdtech
/Aula06_Funções/Exercicio 5.py
401
3.75
4
def IMC(peso, altura): return peso / (altura ** 2) pes = input("Digite seu peso (em kg): ").replace(",", ".") altur = input("Digite sua altura (em metros): ").replace(",", ".") peso = float(pes) altura = float(altur) imc = IMC(peso , altura) #O termo ":.2f" determina o número de casas decimais a ser printado. I...
8705e55c581ac9450487d731fe71b6e473f4ce6f
Nadjamac/Mod1_BlueEdtech
/Aula13_Dicionarios/Exercicio 1.py
556
3.765625
4
aniversario = dict() while True: nome = input("Digite o nome da celebridade ou 0 para sair: ") if nome == "0": break data_aniversario = input("Digite a data de nascimento da celebridade (dd/mm/yyy): ") aniversario [nome] = data_aniversario print("Seja bem-vindo ao nosso calendário. Sabemos a data de...
a39314b3433f54bfb937e3cbc297bc65b5a9f06a
Nadjamac/Mod1_BlueEdtech
/Aula07_Funcoes/Projeto.py
1,551
3.984375
4
#Função Gasto com hospedagem def custo_hotel(noites): custoh = 140 * noites return custoh #Função Gasto com avião def custo_aviao(cidade): custoav = 0 if cidade == "São Paulo": custoav = 312 elif cidade == "Porto Alegre": custoav = 447 elif cidade == "Recife": custoav =...
c2b9eb159e9a7b6ab65f12c9cde16bc0c7a089c4
Nadjamac/Mod1_BlueEdtech
/Aula06_Funções/Desafio.py
2,564
3.96875
4
def data_escrita(data): #Dividindo a string para analisar mês, dia e ano dia = int(data[:2]) mes = data[3:5] ano = int(data[6:]) #Caso a pessoa coloque um mês acima de 13 if mes > "12" or mes == "00": print("Data Inválida!") #Teste para os dias dos meses. Alguns tem que ter até 31 dias, outros...
91f48e903b5e760c065457d3b12f1ef4e50438e0
hamzzy/pymeet_abk_datastructure
/trees.py
303
3.859375
4
class Tree: def __init__(self,root,left=None,right=None): self.root=root self.left=left self.right=right def __str__(self): return (str(self.root)+", left child :"+str(self.left)+ ", right child :" +str(self.right)) tree=Tree(5,Tree(3,1,4),Tree(8,7,9)) print(tree)
4c8924ce678b8ee4d0ab61fb3f8a07003723bd41
karinabk/CSCI235_Programming_Languages
/python/Python3/KarinaBekbayeva.py
798
3.625
4
from matrix import * from vector import * from rational import * def tests(): m1 = Matrix(Rational(1, 2), Rational(1, 3), Rational(-2, 7), Rational(2, 8)) m2 = Matrix(Rational(-1, 3), Rational(2, 7), Rational(2, 5), Rational(-1, 7)) m3 = Matrix(1, 2, 3, 4) v = Vector(1, 2) print("m1xm2:") print(m1@m2) print("in...
90b06d21bfe6f67f9dc9f56dd980ce5c12016329
softwarelikeyou/CS303E
/gridtest.py
2,520
3.609375
4
#function that finds product def max_prod (a): max_p = a[0] * a[1] for i in range (1, len(a) - 1): prod = a[i] * a[i + 1] if (prod > max_p): max_p = prod return max_p def main(): #open file for reading file = 'testcase1.txt' ##file = 'grid.txt' file = 'testcase2.txt' file = 'tes...
5cb6d2c013ba4417f7d1cd16bf4eb0155c25b9d1
softwarelikeyou/CS303E
/dad_dna.py
2,148
3.9375
4
# File: DNA.py # Description: Print the longest sequence of nucleotides for given the DNA sequence pairs # Student Name: Courntey C. Thomas # Student UT EID: cct685 # Course Name: CS 303E # Unique Number: 1 # Date Created: 3/25/2016 # Date Last Modified: 3/26/2016 import os.path import sys def substr (...
e833a47aaeee846b2b39d5ca1629fd6a5a79a76f
softwarelikeyou/CS303E
/dad_creditcard.py
1,796
4.0625
4
## This function checks if a credit card number is valid def is_valid(cc_num): parts = list(str(cc_num)) parts.reverse() odds = list() for i in range(len(parts)-1,-1,-1): if isEven(i) == False: odds.append(sumDigits(int(parts[i])*2)) evens = list() for i in range(len(pa...
795b824edc5cc5d8c0b265bba8a3a2f4d7b73c82
OWCramer/Pokemon-Text-Edition-WIP-
/main.py
11,403
3.515625
4
#Gets Program and Screens Ready import screens import random import os import time from termcolor import colored, cprint import sprites import scenarios #Defines how to clear def clear(): os.system('cls' if os.name=='nt' else 'clear') #defines a loading bar def fake_load(): load_bar = "=" x = 20 for i in ra...
036e6228ddb9c7728ec2464a86e0dea8b5165799
biofoolgreen/python_data_structure
/recursion/int2str.py
1,167
3.765625
4
''' @Description: 递归-整数转换为任一进制的字符串 @Version: @Author: biofool2@gmail.com @Date: 2019-01-03 11:53:27 @LastEditTime: 2019-01-03 17:29:19 @LastEditors: Please set LastEditors ''' class Stack(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self...
b255edf560d1fff3759e8e21091a86ab1169f4f9
TristanGRZ77/summer2018
/20180828/calculatrice2.py
3,438
3.546875
4
from Tkinter import* import Tkinter as Tk from math import * # t correspond au chiffre saisi # y correspond a l'operateur utilise # n correspond au nombre de valeurs que compose un facteur t, y, n = 0, 0, 1 # fonction qui permet l'affichage de facteurs a plusieurs chiffres def nombre(x): global t, n ...
2f49772d571ad2ead3fc16d68b281176e58c036d
betsybaileyy/MadLibs
/main.py
2,186
4
4
def madlib_go(): print("Welcome to MadLibs") print("Please fill in the prompts to complete the spooky Halloween story!") # asking user input emphasis_adjective = user_input("Enter an emphasis adjective: ") article_of_clothing = user_input("Enter an article of clothing: ") verb_one = user_inpu...
37e4df3125d423e99c519dcb31867178fb0a6823
PyconUK/dojo18
/team7/color_changes.py
1,445
3.609375
4
""" pgzero - training ground for pygame """ WIDTH = 300 HEIGHT = 300 # SUMMER = () def get_closer_color(src_color, target_color): """ e.g. is src is (128, 0, 0) and target is (64, 64, 0), will output (127, 1, 0) movin all rgb components closer to target """ result_color = list(src_color) f...
3eee5c8b446e281d0ed30646a57fa57a27a42057
badlovv/avito-analytics-academy
/Python/HW2/work.py
4,508
3.5
4
from csv import reader, writer, Sniffer from collections import defaultdict from warnings import warn from typing import List def user_interface() -> int: """Asks user for a query""" print('1. Вывести все отделы') print('2. Вывести сводный отчёт по отделам') print('3. Сохранить сводный отчёт в виде cs...
a2339a66c432796ec7dc5bb3407e67700101c5ef
arielsilveira/Bioinformatica
/Levenshtein.py
916
3.59375
4
from numpy import array,zeros import functions as func def levenshtein(seqA, seqB): if(len(seqA) != len(seqB)): print("Tamanho da sequência diferente!") return result = zeros(( len(seqA) + 1, len(seqB) +1)) for i in range(0, len(seqA) + 1): result[i][0] = i for i in rang...
d77641147c6c31c9722c45f68a7418e3223a9b28
kay-kay-t/Python
/exeptions.py
867
3.8125
4
try: age = int(input("Age: ")) xfactor = 10 / age except ValueError: print("You didn't enter a valid age.") except ZeroDivisionError: print("Age can't be 0") # Or: except (ValueError, ZeroDivisionError): print("You didn't enter a valid age.") else: print("No exceptions were thrown...
4ce78bcf0b9df48a5326e32eb7df819f5f438230
ankeoderij/vbtl-dodona
/sequentie 7.py
334
3.5625
4
gewicht = int(input("Hoeveel gram weegt het pakje? ")) afstand = int(input("Hoeveel kilometer moet het pakje afleggen? ")) begonnen_gewicht = (gewicht + 19) // 20 begonnen_afstand = (afstand + 9) // 10 prijs = 2 + begonnen_gewicht * 0.4 + begonnen_afstand * 0.3 print("Prijs voor het versturen van het pakje:", prij...
54d66d65233208c7b7849dff1b1793cba8ee6df3
tanmaya-lakhera11/NewPyRepo
/Scripts/Test1.py
324
3.78125
4
import datetime as dt def string_formatting(): ls = [2019, 9, 20, 12, 30, 20] date = dt.datetime(*ls) print(date) print('year is {0:%Y} month is {0:%B} day is {0:%d}'.format(date)) dict = {'a':1,'b':2} for i ,j in dict.items(): print(i,j) if __name__ == '__main__': string_formattin...
e7189b646cedb06f82885acbe6801cb776aa9a96
chocolate1337/python_base
/lesson_011/01_shapes.py
1,122
4.125
4
# -*- coding: utf-8 -*- import simple_draw as sd # На основе вашего кода из решения lesson_004/01_shapes.py сделать функцию-фабрику, # которая возвращает функции рисования треугольника, четырехугольника, пятиугольника и т.д. # # Функция рисования должна принимать параметры # - точка начала рисования # - угол наклона ...
774dbebeb95e9e3a23fa16b358ecdb31b09dee42
chocolate1337/python_base
/lesson_003/07_wall.py
999
3.6875
4
# -*- coding: utf-8 -*- # (цикл for) import simple_draw as sd # Нарисовать стену из кирпичей. Размер кирпича - 100х50 # Использовать вложенные циклы for # Подсказки: # Для отрисовки кирпича использовать функцию rectangle # Алгоритм должен получиться приблизительно такой: # # цикл по координате Y # вычисля...
432be1681cbb2b65cfb35fc16a9df3fcf810059e
puran1218/automate-the-boring-stuff-with-python
/strip_regex.py
470
3.703125
4
import re def strip_charactor(charactor, strip_char = ''): if strip_char == '': return charactor.strip() else: charactor = charactor.strip() charactorRegex = re.compile(strip_char) return charactorRegex.sub('', charactor) charactor = input("Please input the full charactor: ") s...
5661b3cfd0809585ec43e6b5a7605b6b4d06f70d
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/equilibrium-index-6.py
1,442
3.671875
4
"""Equilibrium index""" from itertools import (accumulate) # equilibriumIndices :: [Num] -> [Int] def equilibriumIndices(xs): '''List indices at which the sum of values to the left equals the sum of values to the right.''' def go(xs): '''Left scan from accumulate, right scan derived from left'...
89002b33bc9f0c1fd61e1e4ba9e4230389e66f65
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/determine-if-a-string-is-numeric-4.py
834
3.609375
4
def numeric(literal): """Return value of numeric literal or None if can't parse a value""" castings = [int, float, complex, lambda s: int(s,2), #binary lambda s: int(s,8), #octal lambda s: int(s,16)] #hex for cast in castings: try: return cast(literal) e...
498007231374040d3bc01f9ee9e7ba7a39c2b91b
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/identity-matrix-1.py
358
3.671875
4
def identity(size): matrix = [[0]*size for i in range(size)] #matrix = [[0] * size] * size #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists for i in range(size): matrix[i][i] = 1 for rows in matrix: for elements in rows: ...
40110347352307713768d75f5752b1347cfee561
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/generator-exponential-2.py
1,715
3.890625
4
'''Exponentials as generators''' from itertools import count, islice # powers :: Gen [Int] def powers(n): '''A non-finite succession of integers, starting at zero, raised to the nth power.''' def f(x): return pow(x, n) return map(f, count(0)) # main :: IO () def main(): '''T...
4da1ef2fb9c9d01be7726c46f132cf7030777d73
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/align-columns-4.py
867
3.703125
4
txt = """Given$a$txt$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$j...
6e15e94ea286d90775ca14edb709e771872003c0
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/set-puzzle-1.py
1,168
3.578125
4
#!/usr/bin/python from itertools import product, combinations from random import sample ## Major constants features = [ 'green purple red'.split(), 'one two three'.split(), 'oval diamond squiggle'.split(), 'open striped solid'.split() ] deck = list(product(list(range(3)), repea...
b713856a759343c2233678f18a77ef18edf174c8
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/abundant,-deficient-and-perfect-number-classifications-2.py
2,632
3.578125
4
'''Abundant, deficient and perfect number classifications''' from itertools import accumulate, chain, groupby, product from functools import reduce from math import floor, sqrt from operator import mul # deficientPerfectAbundantCountsUpTo :: Int -> (Int, Int, Int) def deficientPerfectAbundantCountsUpTo(n): '''Co...
9432070a5c89616231109b69d4e2bfbea89704bf
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/polynomial-long-division.py
838
3.5
4
# -*- coding: utf-8 -*- from itertools import izip from math import fabs def degree(poly): while poly and poly[-1] == 0: poly.pop() # normalize return len(poly)-1 def poly_div(N, D): dD = degree(D) dN = degree(N) if dD < 0: raise ZeroDivisionError if dN >= dD: q = [0] * dN ...
af2f4552ca30807bf7ad855f28986e53a43fccbb
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/sieve-of-eratosthenes-13.py
1,874
3.671875
4
def primes(): for p in [2,3,5,7]: yield p # base wheel primes gaps1 = [ 2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8 ] gaps = gaps1 + [ 6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10 ] # wheel2357 def wheel_prime_pairs(): yield (11,0); bps = wheel_prime_pairs() # additional...
873874e4acd45562961776f95250bd2fb3eb0b79
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/vector-products.py
968
3.921875
4
def crossp(a, b): '''Cross product of two 3D vectors''' assert len(a) == len(b) == 3, 'For 3D vectors only' a1, a2, a3 = a b1, b2, b3 = b return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) def dotp(a,b): '''Dot product of two eqi-dimensioned vectors''' assert len(a) == len(b), 'Vector siz...
a66cec30e74673564f3d79ac5637143ca0bf1185
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/singly-linked-list-element-definition.py
759
3.9375
4
class LinkedList(object): """USELESS academic/classroom example of a linked list implemented in Python. Don't ever consider using something this crude! Use the built-in list() type! """ class Node(object): def __init__(self, item): self.value = item self.next = None def __init__(self, item...
49de075fd9986b8219800e4c7ad9b8c07e733afc
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/last-friday-of-each-month-3.py
430
3.796875
4
import calendar c=calendar.Calendar() fridays={} year=raw_input("year") add=list.__add__ for day in reduce(add,reduce(add,reduce(add,c.yeardatescalendar(int(year))))): if "Fri" in day.ctime() and year in day.ctime(): month,day=str(day).rsplit("-",1) fridays[month]=day for item in sorted((month+"-"...
6c1b5451242f66fde307473089ed150ad69e1974
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/echo-server-3.py
2,751
3.546875
4
#!usr/bin/env python import socket import threading HOST = 'localhost' PORT = 12321 SOCKET_TIMEOUT = 30 # This function handles reading data sent by a client, echoing it back # and closing the connection in case of timeout (30s) or "quit" command # This function is meant to be star...
bbb80cbc56d5f9c83ecaf1c35223a5d0f98b18c1
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/day-of-the-week-2.py
1,944
3.75
4
'''Days of the week''' from datetime import date from itertools import islice # xmasIsSunday :: Int -> Bool def xmasIsSunday(y): '''True if Dec 25 in the given year is a Sunday.''' return 6 == date(y, 12, 25).weekday() # main :: IO () def main(): '''Years between 2008 and 2121 with 25 Dec on a Sunday''...
33ed6c5779d837798853c9187da251414c937e09
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/longest-string-challenge.py
568
3.828125
4
import fileinput # This returns True if the second string has a value on the # same index as the last index of the first string. It runs # faster than trimming the strings because it runs len once # and is a single index lookup versus slicing both strings # one character at a time. def longer(a, b): try: b...
641a53abbc374c18de6f5d98ce9466f9fa858925
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/zig-zag-matrix-4.py
356
3.6875
4
COLS = 9 def CX(x, ran): while True: x += 2 * next(ran) yield x x += 1 yield x ran = [] d = -1 for V in CX(1,iter(list(range(0,COLS,2)) + list(range(COLS-1-COLS%2,0,-2)))): ran.append(iter(range(V, V+COLS*d, d))) d *= -1 for x in range(0,COLS): for y in range(x, x+COLS): print(repr(next(ran[...
9a95dc9c43f8435729db22c217b6836af58c1dd5
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/range-extraction-4.py
2,219
3.609375
4
'''Range extraction''' from functools import reduce # rangeFormat :: [Int] -> String def rangeFormat(xs): '''Range-formatted display string for a list of integers. ''' return ','.join([ rangeString(x) for x in splitBy(lambda a, b: 1 < b - a)(xs) ]) # rangeString :: [Int] -> S...
7162d0631de035b9022d05a1ad13ea4db3feb812
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/natural-sorting.py
5,291
3.59375
4
# -*- coding: utf-8 -*- # Not Python 3.x (Can't compare str and int) from itertools import groupby from unicodedata import decomposition, name from pprint import pprint as pp commonleaders = ['the'] # lowercase leading words to ignore replacements = {u'ß': 'ss', # Map single char to replacement string ...
d2d443f4d1138561f6a67fca48407469290185d9
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/accumulator-factory-2.py
151
3.546875
4
def accumulator(sum): def f(n): nonlocal sum sum += n return sum return f x = accumulator(1) x(5) print(accumulator(3)) print(x(2.3))
d818d77f017fb908113dbdffbbaafa2b301d5999
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/fibonacci-n-step-number-sequences-3.py
549
3.671875
4
from itertools import islice, cycle def fiblike(tail): for x in tail: yield x for i in cycle(xrange(len(tail))): tail[i] = x = sum(tail) yield x fibo = fiblike([1, 1]) print list(islice(fibo, 10)) lucas = fiblike([2, 1]) print list(islice(lucas, 10)) suffixes = "fibo tribo tetra penta...
73d6b5c8babfaf09c356c6cc3a5514d4a54cde52
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/determine-if-a-string-is-numeric-3.py
387
3.671875
4
def is_numeric(literal): """Return whether a literal can be parsed as a numeric value""" castings = [int, float, complex, lambda s: int(s,2), #binary lambda s: int(s,8), #octal lambda s: int(s,16)] #hex for cast in castings: try: cast(literal) return...
e3d423874c1393e42d6847372fdccd073086a89f
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/maze-solving.py
1,747
4.03125
4
# python 3 def Dijkstra(Graph, source): ''' + +---+---+ | 0 1 2 | +---+ + + | 3 4 | 5 +---+---+---+ >>> graph = ( # or ones on the diagonal ... (0,1,0,0,0,0,), ... (1,0,1,0,1,0,), ... (0,1,0,0,0,1,), ......
0cc9c46d04c155a1f052a3d70505d2d1407fc053
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/tree-traversal-1.py
2,172
3.71875
4
from collections import namedtuple Node = namedtuple('Node', 'data, left, right') tree = Node(1, Node(2, Node(4, Node(7, None, None), None), Node(5, None, None)), Node(3, Node(6, ...
aac29ec5cf86cb36d9ad4095241a2c1eb022a29f
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/gui-maximum-window-dimensions.py
384
3.640625
4
#!/usr/bin/env python3 import tkinter as tk # import the module. root = tk.Tk() # Create an instance of the class. root.state('zoomed') # Maximized the window. root.update_idletasks() # Update the display. tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())), font=("Helvetica", 25))...
dc956f51e6ea0e2c13af3c1e9dc41af645b4ae14
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/primality-by-trial-division-3.py
373
3.90625
4
def prime3(a): if a < 2: return False if a == 2 or a == 3: return True # manually test 2 and 3 if a % 2 == 0 or a % 3 == 0: return False # exclude multiples of 2 and 3 maxDivisor = a**0.5 d, i = 5, 2 while d <= maxDivisor: if a % d == 0: return False d += i i = 6 - i # t...
9ac58f57d11ec323e55ef5095a52eab64632febc
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/globally-replace-text-in-several-files.py
131
3.796875
4
import fileinput for line in fileinput.input(inplace=True): print(line.replace('Goodbye London!', 'Hello New York!'), end='')
ce9d1cd697671c12003a39b17ee7a9bfebf0103d
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/letter-frequency-3.py
890
4.125
4
import string if hasattr(string, 'ascii_lowercase'): letters = string.ascii_lowercase # Python 2.2 and later else: letters = string.lowercase # Earlier versions offset = ord('a') def countletters(file_handle): """Traverse a file and compute the number of occurences of each letter retu...
3e5d74e7a18e7ff52ec1425c5cac78316ce2ce85
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/averages-arithmetic-mean-3.py
154
3.6875
4
def average(x): return sum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
0fa2f0f4c3a80658c2f69900cc6314e0093b63cf
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/empty-string.py
88
3.828125
4
s = '' if len(s) == 0: print("String is empty") else: print("String not empty")
87b7b74d149b8cddccd58eb80405bb5e43143ec5
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/runtime-evaluation-in-an-environment-2.py
248
3.59375
4
>>> def eval_with_args(code, **kwordargs): return eval(code, kwordargs) >>> code = '2 ** x' >>> eval_with_args(code, x=5) - eval_with_args(code, x=3) 24 >>> code = '3 * x + y' >>> eval_with_args(code, x=5, y=2) - eval_with_args(code, x=3, y=1) 7
c0c8f3361426d86dd5114d0f273a1d8a918b32b7
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/averages-simple-moving-average-2.py
619
3.734375
4
from collections import deque class Simplemovingaverage(): def __init__(self, period): assert period == int(period) and period > 0, "Period must be an integer >0" self.period = period self.stream = deque() def __call__(self, n): stream = self.stream stream.append(n) ...
a158e94229bef8fe5d6d009c4f748f192b4efcdb
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/named-parameters-2.py
3,392
3.65625
4
>>> from __future__ import print_function >>> >>> def show_args(defparam1, defparam2 = 'default value', *posparam, **keyparam): "Straight-forward function to show its arguments" print (" Default Parameters:") print (" defparam1 value is:", defparam1) print (" defparam2 value is:", defparam2) print (" ...
59c1aa53041954828dec498b8c91c262906ec85f
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/strip-comments-from-a-string-3.py
687
3.796875
4
'''Comments stripped with itertools.takewhile''' from itertools import takewhile # stripComments :: [Char] -> String -> String def stripComments(cs): '''The lines of the input text, with any comments (defined as starting with one of the characters in cs) stripped out. ''' def go(cs): ...
47a6664929d3bd1684270fe9aaa355f78f1d3f04
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/string-matching.py
246
4
4
"abcd".startswith("ab") #returns True "abcd".endswith("zn") #returns False "bb" in "abab" #returns False "ab" in "abab" #returns True loc = "abab".find("bb") #returns -1 loc = "abab".find("ab") #returns 0 loc = "abab".find("ab",loc+1) #returns 2
76bb0f0ed3cc16e9e8d073c2159b73af2b237de7
ediz12/project_euler_answers
/Power digit sum.py
149
3.53125
4
import time start = time.time() number = 2**1000 total = 0 for i in str(number): total += int(i) print str(total) print str(time.time() - start)
891bc3164a9c63cb5373afa9bb40886897a7ed1b
VisionistInc/advent-of-code-2018
/ct-00/11/AoC11.py
726
3.671875
4
import numpy as np def calculatePowerLevel(x, y, serialNum): rackId = x + 10 powerLevel = int(str((rackId * y + serialNum) * rackId)[-3:-2]) - 5 return powerLevel def findMax(array): max = 0 maxX = -1 maxY = -1 maxLength = None for x in range(298): for y in range(298): ...
1e70e37292ee93c319c3e1f42842b9982acc4427
Jusawi/Interview-practice
/validParanthesis.py
930
3.875
4
class Solution: # @param {string} s # @return {boolean} def isValid(self, s): stack=[] for i in s: if i in ['(','[','{']: stack.append(i) else: if not stack or {')':'(',']':'[','}':'{'}[i]!=stack[-1]...
1215bc74ec9edc0701ce6004ccd9031ad6c079ff
The-SIVA/python
/average length of the word in the sentence.py
343
4.15625
4
sentenct_list = input().split() length_of_sentence_list = len(sentenct_list) sum_of_all_words_lengths = 0 for word in sentenct_list: length_of_word = len(word) sum_of_all_words_lengths += length_of_word average_length_of_words_in_sentence = (sum_of_all_words_lengths/length_of_sentence_list) print(average_lengt...
9ece6892236fcc2379136ef487ef410b74ba21ad
Elias-gg/205-proj1
/p1t.py
1,177
3.640625
4
from PIL import Image from os import listdir import numpy #source link: http://www.scipy-lectures.org/advanced/image_processing/ #source link: http://cs231n.github.io/python-numpy-tutorial/ #Much of the code was completed on the 31st of august in class with the team #dylan was a major contributor in helping me with...
99a0d2566d8277286ec0caeb02a00cd429556045
Genxgen/test
/123.py
114
3.5625
4
ws= input('input X=') op= input('input +-*/:') ws2=input('input Y=') x='the dog' print(x) print(int(ws)*int(ws2))
863377dc74e6ea86be7ef0449af2683a5fa740b3
aruzhanss/webPython
/pythonHW/informatics3forK.py
131
3.671875
4
n = int(input()) nums = [] s = 0 for i in range (0, n): number = int(input()) nums.append(number) s = s+number print(s)
e0af3fdf240041c125d41a0b8a5948c9b7aa9d77
aruzhanss/webPython
/pythonHW/informatics3forJ.py
113
3.53125
4
values = [] s = 0 for i in range (0, 100): num = int(input()) values.append(num) s = s+num print(s)
78d43e4790268337ad497149d467ee9c340f8958
slamdunk0414/python
/12.系统编程-多线程/3.解决互相占用bug.py
446
3.609375
4
from threading import Thread,Lock g_num = 0; def test(): global g_num for i in range(1000000): mutex.acquire() g_num += 1; mutex.release() print(g_num) def test2(): global g_num for i in range(1000000): mutex.acquire() g_num += 1; mutex.release()...
1b02f0e08bfdb571196e7f2c3c1c24db898b1b47
slamdunk0414/python
/6.文件操作/1.文件的读写.py
497
3.71875
4
''' 文件读取 f = open('123.txt','r') #第一个参数为文件名 第二个参数为模式 # r为读 如果不存在 会崩溃 # w为写 如果文件不存在 会新建 如果文件存在 则会移除源文件的内容 # a为追加 如果文件不存在 会新建 # 在模式后面添加 + 说明可以读写 #read 如果不添加参数 则读完所有文件 #read(1) 每次读一个字符 print(f.read()) f.close() ''' #文件写入 f = open('456.txt','w') f.write('123456') f.close()
9cf26d07d36eca777778afb6ff16de1773dec6c0
slamdunk0414/python
/10.python高级/8.生成器.py
485
3.953125
4
#列表生成式 a = [x for x in range(10)] print(a) #生成器 第一种方式 b = (x for x in range(10)) #是用next查看生成器里面的元素 print(next(b)) #生成器 第二种方式 def creatNum(): a,b = 0,1 print('开始生成') for x in range(5): yield b a,b = b,a+b creatNum() #加入yield 会成为生成器 不会直接调用 需要是用next a = creatNum() next(a) next会在yield处停...
6014e844e33aca9eb6da32e905d32cb590ffeb66
slamdunk0414/python
/3.字符串列表数组/8.字典的增删改查.py
335
3.703125
4
info = {'name':'zp'} print(info) #写入没有的 即为增加 info['age'] = 18 print(info) #删除 del del info['age'] print(info) #改 直接改 info['name'] = '123' print(info) info['xxx'] = '1234' #查询 在不缺人是否有key的情况下 不要直接查询 如果不存在key会崩溃 str = info.get('xx') print(str)
6cdf945cb541f5fd8370368dbae3a762e6650858
slamdunk0414/python
/8.面向对象应用/3.单例.py
469
3.640625
4
class Dog: __instance = None __init_flag = False def __new__(cls, name): if cls.__instance: return cls.__instance else: cls.__instance = super().__new__(cls) print('真正的创建') return cls.__instance def __init__(self,new_name): if ...