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
b68b9c3faaa7e48aac0483cce079e738b36e445c
rene-d/edupython
/codes/palindrome.py
456
3.921875
4
# ??? # https://edupython.tuxfamily.org/sources/view.php?code=palindrome # Créé par IANTE, le 09/10/2010 from __future__ import division from lycee import * #mot=texte_demande("Entrez un mot") print (ord("A")) envers="" for i in range(len(mot)): envers=mot[i]+envers if mot==envers : print ("Le mot",mot,"est un...
ad8e9d22bce332c5ad25dd03389cf87c5d19cbf9
rene-d/edupython
/codes/ISBN.py
536
3.8125
4
# Code ISBN # https://edupython.tuxfamily.org/sources/view.php?code=ISBN # Créé par IANTE, le 21/02/2011 from lycee import * code=input("Entrer le code ISBN sans les - :") l=len(code) debut=code[:l-1] #On peut écrire code[:-1] fin=code[l-1:] #On peut écrire code[-1] total=0 for i in range(l-1): tota...
868bf07a0c53cfe8abb5fdba769b38592a638c9c
Harsh-Nikhil/FileSystem
/filecreation.py
1,801
3.625
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 15 16:27:44 2019 @author: nikhi """ #Making RSA encryption decryption work import Crypto import random from Crypto.PublicKey import RSA from Crypto import Random from pymongo import MongoClient import ast import json import math with open("filenamelist.json",'rb') as json...
4180ce6bcef93ac55eb0cd5b0d672f288e4b5152
timewaitsfor/LeetCode
/DataStructure/binary-trees/652.py
1,460
3.921875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def traverse(self, root): if root.left == None and root.right == None: this_tree_str = ...
cb76ab641d274b65fb3c310584580943586eb178
timewaitsfor/LeetCode
/knowledge/array_kn.py
710
4.15625
4
# 1. create an array a = [] # 2. add element # time complexity: O(1) a.append(1) a.append(2) a.append(3) # 3. insert element # time complexity: O(N) a.insert(2, 99) # 4. access element # time complexity: O(1) tmp = a[2] # 5. update element a[2] = 88 # 6. remove element # time complexity: O(N) a.remove(88) a.pop(1)...
5e26408033e9296a3814b08de9a5b0e83df78871
jingzhian/aoc-2019
/day14/stoichiometry.py
4,904
3.796875
4
import math from collections import defaultdict ## Stoichiometry # List of reastions it can perform : puzzle input # - Every reaction turns some quantities of specific input chemicals into some quantity of an output chemical # - Almost every chemical is produced by exactly one reaction; # - the only exception, ORE, is...
587d65a70570d495199af17c5281cb58db008c5b
SaidhbhFoley/Promgramming
/Week07/messingWithJson.py
221
3.5625
4
# Messing around with json import json filename = "testdict.json" sample = dict(name='Fred', age=31, grades=[1,34,55]) def writeDict(obj): with open (filename, 'wt') as f: json.dump(obj,f) writeDict(sample)
81850c6e723a19501f2234ca3f60a0615cdf701d
SaidhbhFoley/Promgramming
/Week07/dosave.py
1,739
3.703125
4
import json students= [] filename="students.json" def writeDict(obj): with open(filename,'wt') as f: json.dump(obj,f) def readDict(): with open (filename) as f: return json.load(f) def displayMenu(): print ("What would you like to do?") print ("\t(a) Add new student") print ("\t(v...
02e8b295591e79c057481be775219e2143915e4f
SaidhbhFoley/Promgramming
/Week04/even.py
370
4.15625
4
#asks the user to enter in a number, and the program will tell the user if the number is even or odd. #Author: Saidhbh Foley number = int (input("enter an integer:")) if (number % 2) == 0: print ("{} is an even number".format (number)) else: print ("{} is an odd number".format (number)) i = 0 while i > 0: ...
76fa749e8d26c68a057eb1163ad664999df59224
jakemuncada/manga-crawler
/log.py
2,009
3.84375
4
""" Functions related to initializing and setting up the logging. """ import os import logging from logging.handlers import RotatingFileHandler # The maximum size of a log file MAX_BYTES = 3000000 # The number of log files to keep BACKUP_COUNT = 10 def initializeLogger(): """ Initialize the logger. """...
813b34903e5f3ee77820d5f996575d4777884df1
prem17101996/CodeChef
/Turbo Sort.py
135
3.71875
4
t=int(input()) lst=[] for i in range(t): numbers=int(input()) lst.append(numbers) lst.sort() for item in lst: print(item)
260a9e26118fa340dee75f3dee9083c922ffc176
jjiayying/cp2019
/Practical 1/q6_find_ascii_char.py
142
3.640625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: code = eval(input("code : ")) print("Corresponding character: " + chr(code)) # In[ ]:
e88dccb0ff086409555d0d54b7c0fb0487ef2584
jjiayying/cp2019
/Practical 2/q05_find_month_days.py
206
3.6875
4
#!/usr/bin/env python # coding: utf-8 # In[14]: from calendar import monthrange year = int(input("year please: ")) month = int(input("month please: ")) monthrange(int(year), int(month)) # In[ ]:
8bfe8cdcace82017d26966263c1e8678acaacbb0
jjiayying/cp2019
/Practical 4/q8_find_uppercase.py
177
4.03125
4
#!/usr/bin/env python # coding: utf-8 # In[7]: def find_num_uppercase(str): return sum(1 for c in str if c.isupper()) find_num_uppercase('Good MorninG!') # In[ ]:
b6197b899bdbab3e6edcefdecafd113d99a874f3
IchijikuJP/Kesci_DataScienceIntroduction
/Pandas进阶/构建DataFrame.py
909
3.84375
4
# 构建DataFrame可以从csv构建,也可以从dict中创建 # 1使用zip()函数 2添加新列 3广播(Broadcasting):创建新列并为整个列赋值 import pandas as pd data = pd.read_csv("../Pokemon.csv") pd.set_option('display.max_columns', None) # 给最大列设置为10列 pd.set_option('display.max_rows', None) # 设置最大可见100行 pd.set_option('display.width', 1000) # 从字典中构建DataFrame country = ...
cc27cd04f7b818086c07a76107e97d7a9c0b0a6c
IchijikuJP/Kesci_DataScienceIntroduction
/用Pandas操作DataFrame/堆叠和非堆叠数据.py
364
3.71875
4
# 1处理多标签索引 2level:未堆叠索引的位置 3swap level:改变内外层索引位置 from pivot函数 import df1 import pandas as pd df2 = df1.set_index(["treatment", "gender"]) print(df2) # 堆叠数据 # level 决定索引 print(df2.unstack(level=0)) print(df2.unstack(level=1)) # 改变内外层索引位置 df3 = df2.swaplevel(0, 1) print(df3)
6337130d14006fb92661c0811f5d30b21a8b927c
IchijikuJP/Kesci_DataScienceIntroduction
/Python基础/Pandas简介.py
960
3.671875
4
# pandas两个主要数据结构: series和DataFrame # series: 一维数组对象, 带索引 # DataFrame: 表格形数据结构 import pandas as pd import numpy as np data = pd.read_csv('../Pokemon.csv') series = data['Defense'] print(type(series)) data_frame = data[['Defense']] print(type(data_frame)) # 用比较运算 逻辑运算 来过滤数据 print(3 > 2) print(3 == 2) print(True) print(...
8295f51f45e58fca6248eef8c1e1582988fd9e64
IchijikuJP/Kesci_DataScienceIntroduction
/Python进阶/zip函数.py
564
4.5625
5
# zip()函数用于将可迭代对象作为参数, 将对象中对应的元素打包成一个个元组 # 然后返回由这些元组组成的对象, 这样可以节约内存 # 如果各个迭代器的元素个数不一致, 则返回列表长度与最短的对象相同 # zip()示例: list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] z = zip(list1, list2) print(z) z_list = list(z) print(z_list) # 与zip相反, zip(*)可理解为解压, 返回二维矩阵式 un_zip = zip(*z_list) un_list1, un_list2 = list(un_zip) print(un_lis...
18869571c6cbbbfab861c5c3ca9552fa0a112ff7
ryanshay18/P3_Parrots
/minilabs/ryan/ryanminilab.py
1,325
3.859375
4
# generate random startup ideas, based on industry/topic chosen import random class startupStack: def __init__(self, industry="tech"): self.industry = industry def setIndustry(self, input): self.industry = input @property def getIndustry(self): return self.industry def...
c158785cfd4d1ef3704194e7a1fea2d1a1210308
tdchua/dsa
/data_structures/doubly_linkedlist.py
2,805
4.34375
4
#My very own implementation of a doubly linked list! #by Timothy Joshua Dy Chua class Node: def __init__(self, value): print("Node Created") self.value = value self.next = None self.prev = None class DLinked_List: def __init__(self): self.head = None self.tail = None def traverse(self)...
ae50856abe2cbedb236da6c883f4f879eed5fdc4
RobotJustina/tmc_justina_docker
/src/planning/knowledge_representation/scripts/interprete/classCola.py
1,335
3.765625
4
class classCola: def __init__(self): self.items = [] def pushC(self, x): self.items.append(x) #print (self.items) def popC(self): try: print (self.items[0]) return self.items.pop(0) except: raise ValueError("La cola esta vacia") def es_vacia(self): return self.items == [] def lenC(self...
66eecd362a2bb5ee3fda048ac94b8fca9fcad6a8
KSIUJ/KsiGo
/common/game_logic.py
14,751
3.671875
4
import string class Board(object): def __init__(self, size=19): self.player_black_points = 0.0 self.player_white_points = 7.5 self.actual_turn = "black" self.size = size self.Matrix = [['*' for _ in range(self.size)] for _ in range(self.size)] self.groups = [] ...
9639198081d56e855bc3c6c0ef18da5acdf20f21
ValessaLima/ExercicioRevisaopython
/questão3.py
644
3.734375
4
cont=0 pergunta1= input(" Telefonou para a vtima?") if pergunta1 == 'sim': cont = cont + 1 pergunta2= input("Esteve no local do crime?") if pergunta2 == 'sim': cont = cont + 1 pergunta3= input("Mora perto da vtima?") if pergunta3 == 'sim': cont = cont + 1 pergunta4= input("Devia para a vti...
f1cca618674bb2152d10f5e66bef1d979f61b48a
xqe/PythonTest
/classTest.py
316
3.59375
4
# coding=utf-8 # 类 class Test: def __init__(self,a,b): self.a = a self.b = b def add(self, a, b): return a + b def add1(self): return self.a + self.b def sub(self, a, b): return a - b class Test1(Test): def mul(self): return self.a * self.b
da4f1ec23f9ec0f2069e24eeff774ceccf139363
rayanepimentel/CourseraUSP-Python-Parte01
/Python/week04/Tarefas/exe1.py
300
4.0625
4
''' Escreva um programa que receba um número natural nn na entrada e imprima n!n! (fatorial) na saída. Exemplo: Digite o valor de n: 5 120 ''' numero = int(input('Digite o valor de n: ')) fatorial = 1 while numero > 0: fatorial = fatorial * numero numero = numero - 1 print(fatorial)
5ab07e8ffa079399d88e13fe33573387051cbc06
rayanepimentel/CourseraUSP-Python-Parte01
/Python/week02/Tipos de Dados/exercicioopcional.py
1,225
4.15625
4
''' Nesta lista de exercícios vamos praticar os conceitos vistos até agora. Cada exercício deve ser resolvido em um arquivo separado e a seguir enviado através da web. A correção automática pode demorar alguns minutos. Você pode submeter a mesma resposta mais de uma vez. Note que a correção verifica se o resultado cor...
22aa6b4daeb05936eb5fd39b361e2945d02a5f64
786awais/assignment_3-geop-592-sharing
/Assignment 3 GEOP 592
2,512
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[50]: #GEOP_592 Assigment_3 #Codes link: https://www.datarmatics.com/data-science/how-to-perform-logistic-regression-in-pythonstep-by-step/ #We are Provided with a data for 6800 micro-earthquake waveforms. 100 features have been extracted form it. #We need to perform logist...
3c08ccdd1eb368e79d246636b75e85a9c574b3f2
Xu-Guo/GQQLeetCode
/Array/287_FindtheDuplicateNumber.py
797
3.609375
4
class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) - 1 mi, ma = 1, n while mi <= ma: mid = mi + (ma - mi) / 2 less, equal, high = 0, 0, 0 for num in nums: ...
fe5ff0146e2f36f8d220d25364f366739d7851ad
Xu-Guo/GQQLeetCode
/DevideAndConquer/215_KthLargestElementinanArray_Me.py
974
3.5625
4
class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ # the question can be converted to find the k-1 index after quick sort. return self.quickSortFind(nums, 0, len(nums) - 1, k) def quickSortFi...
d0111b2834014dd972bc76a8656556050dd34762
data-infra/crawler
/mylxml.py
2,110
3.59375
4
# coding:utf-8 # 网络爬虫库lxml的应用 from lxml import etree print(u'解析html(具有自动修复功能)') text = ''' <div> <ul> <li class="item-0"><a href="link1.html">first item</a></li> <li class="item-1"><a href="link2.html">second item</a></li> <li class="item-inactive"><a href="link3.html"><span cl...
ed7a1ebf9d034ac95a37cc99726d9a6e069784ef
ryanvfung/python-grapher
/grapher-0.1.py
819
3.71875
4
# -*- coding: utf-8 -*- """ Quick Grapher 0.1 @author: Ryan Fung Create Date: 2013-11-28 """ print("\n===== Quick Grapher 0.1 by Ryan Fung =====\n") import numpy import matplotlib.pyplot as plt def grapher(function, a, b, iterations=101): """Graphs 'function' from x='a' to x='b' using 'iterations' number ...
61170d822175476a580f76389e8d38a4cd8655e8
jaredbebb/JBScrape
/FileScraper.py
1,039
3.953125
4
import re """ Only return links that have pages with relevant search terms. Scrape webpages for links. Print links to file. Feed links back into program. """ #search terms are terms that the client wants to search for ahref = "<a href=\"https://\S*\"" #startsite is the site that the scraper begins #startsite = inpu...
c392f0451c0fd07be154dea5920fb899793f386a
sreeharsham/GIT-Upload
/PythonPractise/RandomGenString.py
556
3.8125
4
import random def generate(strlen): a = "abcdefghijklmnopqrstuvwxyz " # strlen = 28 b = "" for i in range(strlen): b = b + a[random.randrange(27)] return b def scoring(goal, test): numSame = 0 for i in range(len(goal)): if goal[i] == test[i]: numSame = numSame...
3491f4c13ed04ace1f906861dc31683cd224ede2
Jaideep25-tech/AlgoBook
/python/sorting/bucket_sort.py
2,289
4.09375
4
def bucket_sort(items, num_buckets=10): """ Returns a sorted list of `items`, where each value in `items` is a value in [0.0, 1.0) """ # Create list of buckets, where each bucket is a list buckets = [] for _ in range(num_buckets): buckets.append([]) # Add each item to its proper...
0a5d79a27de94ce60f05ad76f255d3c67189a7b8
Jaideep25-tech/AlgoBook
/python/Matrix/inverse_matrix.py
2,245
3.546875
4
import copy,math #Matrix inverse Finder .Note that matrix starts at [1][1] so for that it contains redundant [None]'s in [0][:]and [:][0] def reducer(matrix,i,j):#gets the matrix by removing the (i,j)th element matcopy=copy.deepcopy(matrix) [matcopy[y].pop(j) for y in range(0,len(matcopy))] matcopy.pop(i) ...
3774dbdb75e1dc16c8e497a9fafc75b4976c54b3
barthoekstra/knmy
/knmy/parser.py
6,173
3.625
4
import pandas as pd from io import StringIO from collections import namedtuple def parse_raw_weather_data(raw): """ Parses raw weather data Parses raw weather data from KNMI's automated weather stations and returns the disclaimer, a dict of variables and pandas dataframes of the stations and the weather ...
56faf79f7cf8030226276ba72530949284aa7e3c
jspruitt/AmbuIance
/road_directions/graphs.py
8,561
3.828125
4
""" Directed graph class. """ class DiGraph: """ Directed graph. """ def __init__(self): """ Initializes an empty graph. """ self._graph = {} def __str__(self): """ Returns a string representation of the graph. """ ...
ef4a952de633f4da107648289cacc97829f5fb39
mavgerop/HangmanGame
/hangman.py
1,025
3.734375
4
import random with open('words.txt', 'r', encoding="utf8") as f: word = random.choice(f.readlines()).rstrip() tries = 6 letters = [] # print(word) def hide(): hidden = '' for letter in word: if letter in letters: hidden += letter else: hidden += '-' return hidde...
63b2b212b2e42f539fb802cc95633eae00c34a7f
jskimmons/LearnGit
/Desktop/HomeWork2017/1006/Homework1/problem2.py
825
4.1875
4
# jws2191 ''' This program will, given an integer representing a number of years, print the approximate population given the current population and the approximate births, deaths, and immigrants per second. ''' # Step 1: store the current population and calculate the rates of births, # deaths, and immigrations per...
773442a1cdd867d18af6c7578af1f5e208be9a7c
jskimmons/LearnGit
/Desktop/HomeWork2017/1006/Homework2/untitled.py
552
4.28125
4
''' This is a basic dialog system that prompts the user to order pizza @author Joe Skimmons, jws2191 ''' def select_meal(): possible_orders = ["pizza" , "pasta" , "salad"] meal = input("Hello, would you like pizza, pasta, or salad?\n") while meal.lower() not in possible_orders: meal = input("Sorry, ...
3010a84d6465bbf5611d9355c4e137640dca79f7
petecliff/python_workout
/ex1-guessing-game/guess.py
655
4.09375
4
import random def guessing_game(): my_number = random.randint(0,100) print('Guessing Game!') print('I''m thinking of a number between 0 and 100 - can you guess it?') while True: your_guess = input('What is your guess?\n') if not your_guess.isdigit(): print(f'That isn''t a number... ') ...
48c1fe217a78e10b5c7ddeea85b99fb95127cc33
bimajatiwijaya/explore
/queen_puzzle/chessboard.py
4,321
4.03125
4
import chess_block """ 1. Set 1 queen in position (x,y). 2. Mark as danger for chess_block which possible attack by queen. 3. Is all chessboard danger and total queen in board < 8 a. yes : return 0 and back to poin 1 with different position 4. Total queen == 8 return 1 """ class QueenChessBoard(): ...
56eb9ffdef7901e901681e383bd39c37f157ba80
romanveno2893/python
/alph.py
92
3.765625
4
x=raw_input("") print(x) if (x>='a')and(x<='z'): print ("yes") else: print ("no")
871e4c24a3261f626fdccc0a5a2c02ad30cda638
manui3rk/AnalizadorTextos
/main.py
30,277
3.546875
4
import csv import os from collections import Counter #contador de estadísticas: import operator import re, string from typing import Text import docx list_ad = [] #Lista para guardar palabras del diccionario: Adverbios list_adj = [] #Lista para guardar palabras del diccionario: Adjetivos list_art = [] #Lista para gu...
a62f372d6a34a0fa2a8ec9ce0f16c0891ddcdfae
seershikab/assignment7.py
/assignment7.1.py
120
4.15625
4
num=int(input("Enter a number")) sum=0 while(num > 0): sum=sum+num num=num-1 print("sum of n nactural number is",sum)
78227f46e4e7e2506a3099d36767f5252f30fd6a
seershikab/assignment7.py
/assignment7.5.py
39
3.59375
4
a=(1,2,3,4,5) for i in a: print (i**2)
96adaa4309bfafd3972a35f751090884478d0df7
kevin-bot/Python-Kevin-pythom
/25-sep-cicloPrimo.py
400
3.84375
4
#Ejercicio para saber si un numero es primo 10 ciclos '''Escribir un programa que pida al usuario un número entero y muestre por pantalla si es un número primo o no.''' n=int(input("Ingrese un numero por favor: ")) i = 2 while n % i != 0: print(f"n: {n} -> i: {i}") i += 1 print(f"n: {n} -> i: {i}") if i ...
2bc4c6523788b6a8707aa33540d01b0fd2731743
kevin-bot/Python-Kevin-pythom
/Script1.py
577
4.125
4
#practica para asentuar los conocimientos de dias dom,22 de sep,21:54 '''1.DEFINIR una funcion max() que tome como argumento dos números y devuelva el mayor de ellos''' def funcion(numerouno,numerodos): if numerouno < numerodos: print(f" {numerodos} es mayor que {numerouno}") elif numerouno>numerod...
6889fe679d6949d3d706ec9d27d489d63b11e3cc
Ceasar1978/NewCeasar
/tower_of_hanoi.py
1,885
3.859375
4
import turtle class Pole(): def __init__(self, location): self.location = location self.disks_list = [] self.shaft = turtle.Turtle() self.shaft.up() self.shaft.goto(self.location, -100) self.shaft.pensize(5) self.shaft.lt(90) self.shaft.down() ...
55cbf3dd9a0a1b2ba9670fec35dd237a131e86b3
kenneth7198/TNUA_RaspberryPi
/Basic/test_if_elif_else.py
112
4.125
4
a = True if a == True: print ("a = true") elif a == False: print("a = false") else: print("Why?")
7909e8915a365a91f0283af96deb430472c78fe6
ArekarChintan/HELLO_WORLD
/Hello.py
153
3.75
4
a=int[input("enter the number")] { defsqr(a): import math m=math.sqrt(int(a)) return(m) print("sqrt a number",sqr(a)) b=int[input("enter the number")] }
6deb93757b1c9923d34653cfb1e0a77588dd66a6
ParichayPai/Python_Tkinter_Project
/history.py
401
3.796875
4
import sqlite3 conn=sqlite3.connect("database1.db") # conn.execute("create table history\ # (\ # order_no int primary key,\ # cust_id int,\ # item_nos varchar(200),\ # quantity varchar(200),\ # bill number\ # )") # conn.execute("insert into history values(3001,2001,'1001 1002','4 2 2 1',1312.12)") conn.c...
6a37ab2190d30adf781257c9f50210d5757bf508
cnichols-git/python
/log_parse.py
904
3.84375
4
#!/usr/bin/python3 ## # cnichols - this should take a file and pull out some of the data with certain conditions # for practice - define some vars and interact with user # Get some input from the user. name = input("Welcome, \n May I please have your name? \n") # check for length num_length = len(name) # if inpu...
c9a5497ad1476ee27b0f3c635984edae98415059
sindhura-pv/programming-practice
/string/easy/valid_paranthesis.py
755
3.8125
4
class Solution: def isValid(self, s: str) -> bool: if not s: return True st = [] input_brackets = ['(', '{', '['] for i in range(len(s)): if s[i] in input_brackets: st.append(s[i]) ...
df459d8455b542a4277d9fd5f2f4cdcc835b2650
garg10may/Data-Structures-and-Algorithms
/sorting/heapSort.py
495
3.875
4
from heap import maxHeapify #we just need to extract the max element again and again from heap(just build it once) #to save space we will keep on swapping it with the last, and calling heapify again and again on the reduced heap #https://www.youtube.com/watch?v=MtQL_ll5KhQ def heapSort( arr) : n = len(arr) maxHe...
abec276a658a37b07bafb06e9d889aab58b96831
garg10may/Data-Structures-and-Algorithms
/graph/Tree/tree.py
3,287
4.09375
4
#BST -> Binary Search Tree class TreeNode(object): def __init__(self, data): self.right = None self.left = None self.data = data class Tree(object): def __init__(self): self.root = None self.left = None self.right = None def add(self, data): node...
6210f2e37e1ce5e93e7887ffa73c8769fae0a35a
garg10may/Data-Structures-and-Algorithms
/searching/rabinKarp.py
1,862
4.53125
5
#Rabin karp algorithm for string searching # remember '^' : is exclusive-or (bitwise) not power operator in python ''' The algorithm for rolling hash used here is as below. Pattern : 'abc', Text : 'abcd' Consider 'abc' its hash value is calcualted using formula a*x^0 + b*x^1 + c*x^2, where x is prime Now when we need...
25146d176dbb2f4bb72136f6e869a30793ccb49b
garg10may/Data-Structures-and-Algorithms
/graph/BFSiterative.py
1,993
3.9375
4
from Graph import Node, Edge, Digraph def printPath(path): """Assumes path is a list of nodes""" result ='' for i in range(len(path)): result = result + str(path[i]) if i != len(path) -1: result = result + '->' return result def BFS(graph, start, end): """Assumes graph...
3da6263683513d8eb89bd37c47ffa26ab330f962
Lyman-Smoker/NLP-Learning
/backward_segment.py
989
3.859375
4
# -*- coding:utf-8 -*- from load_dictionary import load_dictionary #逆向最长匹配算法 def backward_segment(text, dic): word_list = [] i = len(text) - 1 while i >= 0: # 扫描位置作为终点 longest_word = text[i] # 扫描位置的单字 for j in range(0, i): ...
1a2ffe2cef0e9a42aa4126f273316e09cb4017c9
nexiom1221/Phyton-Practice
/예제/practice2.py
377
3.84375
4
jonghwa = "961221-1234567" print("성별 : "+ jonghwa[7]) print("년 : "+ jonghwa[0:2]) print("생일 : "+ jonghwa[2:6]) python = "Python is Amazing" print(python.lower()) print(python.upper()) print(python[0].islower()) print(len(python)) print(python.replace("Python", "Java")) index = python.index("i", 9) print(index) print...
c6445bc8e95d3babfe511b2b65348ea4eb9511c4
nexiom1221/Phyton-Practice
/예외처리/exception7.py
404
3.53125
4
list_number = [52,273,32,72,100] try: number_input = int(input("정수 입력>")) print("{}번쨰 요소: {}".format(number_input, list_number[number_input])) except ValueError as exception: print("정수를 입력하세요") print("exception : ", exception) except IndexError as exception: print("리스트의 인덱스를 벗어났습니다") print("e...
c658d227aaba2e93f39b2745fe7b18633325d147
Sajmon2215/Python
/004_ Algorithms/Algorithms_04.py
685
3.5
4
import random def matrix_sum(matrix1, matrix2): if len(matrix1) == len(matrix2): result = [] for i in range(len(matrix1)): temp_result = [] for j in range(len(matrix1)): temp_result.append(matrix1[i][j] + matrix2[i][j]) result.append(temp_result)...
9bc29ee7422ad19df1adc74214b0977c89021e69
moligslagers/interviewbooking
/service/availability_service.py
1,224
3.875
4
from bitstring import BitArray """ Service to expose the functionality that computes the availability between a set of interviewers and interviewees """ def get_available_time_slots(interviewer_availabilities, interviewee_availability): """ Receives a list of availabilities from interviewers and an interview...
1eee3f70e471addb6b609f09bbf963c9538f3a1a
oshlern/FourierFMRI
/DFT.py
4,241
3.671875
4
# DFT Functions import numpy as np import numpy.fft as npf import matplotlib.pyplot as mpl from random import randint def add(list1, list2): if len(list1) != len(list2): raise IndexError("WTF") list3 = [0 for i in range(len(list1))] for i in range(len(list1)): list3[i] = list1[i] + list2[i] ret...
39fac41fbf9a121aef82b434bee64c1cca3749fd
DSLituiev/doccano
/app/server/colorspace.py
889
3.734375
4
def lightness(rgbstr): '''calculate lightness in 8-bit range from an RGB hex string or tuple https://en.wikipedia.org/wiki/Relative_luminance ''' if isinstance(rgbstr, str): rgbstr = rgbstr.lstrip('#') rgb_tuple = bytearray.fromhex(rgbstr) elif isinstance(rgbstr, (tuple,list)): ...
577fb0318892a372e2ac19c03febc3172b668ade
samesense/compmut
/Method1/Code/Method/finalScan.py
18,751
3.703125
4
import sys, random, cm_scan3, pickle, scanNonAdj2, randomScanNonAdj2 # CLASSES # Class TreeNode represents a single tree node class TreeNode: # Instance variables: # self.index is the taxon/ancestor ID of this TreeNode # self.children is the child set for this TreeNode # self.color is the col...
012cdcd55c33712c8c00d1ebd1920e7205256e72
GeorgiosKyritsis/LyndaPython
/Classes/inheritance.py
536
3.890625
4
__author__ = 'inamoto21' class Animal: def talk(self): print('talk') def walk(self): print('walk') def clothes(self): print('clothes') class Duck(Animal): def quack(self): # it is a method of a class print("Quaaaaaack!") def walk(self): super().walk() print("Walks like ...
928e4b2e027819178143e82c4c0566d504435241
GeorgiosKyritsis/LyndaPython
/Classes/polymorphism.py
883
3.90625
4
__author__ = 'inamoto21' class Duck(): def quack(self): # it is a method of a class print("Quaaaaaack!") def walk(self): print("Walks like a duck.") def bark(self): print('The duck cannot bark') def fur(self): print('The duck has feathers') class Dog(): def bar...
e1be3b9664e172dc71a2e3038a1908c5e49dd57b
Fueled250/Intro-Updated-Python
/intro_updated.py
881
4.1875
4
#S.McDonald #My first Python program #intro.py -- asking user for name, age and income #MODIFIED: 10/18/2016 -- use functions #create three functions to take care of Input def get_name(): #capture the reply and store it in 'name' variable name = input ("what's your name?") return name def get...
1639cd9ba512ff13de1604dd4be390844e6d8b31
bcso/InterviewPrepQs
/removeDupes.py
210
3.625
4
def removeRepeats(inputString): seen = [] for x in xrange(len(inputString)): if inputString[x] not in seen: seen.append(inputString[x]) else: continue return seen a = "abba" print removeRepeats(a)
0fe9cc644f59cc67945ccd59cad54ec16f9cd5c4
bcso/InterviewPrepQs
/recurseTest.py
151
3.515625
4
def recurse(inNum): currSum = inNum + 5 if currSum >1000: #Base Case return currSum #Up the stack we go return recurse(currSum) print recurse(0)
064c7bf314c99a85ef7e20d579245caaa3844963
vorfwolf/6-.-.-122-
/1.(6 Labaratorna).py
1,068
3.796875
4
import datetime days = range(1, 32) mounths = range(1, 13) years = range(1901, 2021) while True: try: d, m, y = int(input('day:')), \ int(input('mounth:')), \ int(input('year:')) if d>0 and m>0 and y>0: pass else: pr...
c483a678c8bcc376feb580d3629d1aff9127fec3
aiswaryasaravanan/practice
/udacity/searchingAndSorting/recursion.py
193
4.125
4
# Fibonocci def fibonocci(number): if number==1: return 0 elif number==2: return 1 else: return fibonocci(number-1)+fibonocci(number-2) print(fibonocci(5))
1c60d291a1d02ee0ebefd3544843c918179e5254
aiswaryasaravanan/practice
/hackerrank/12-26-reverseLinkedList.py
956
4.125
4
class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None def add(self,data): if not self.head: self.head=Node(data) else: cur=self.head while cur.next: ...
3b485263ae0b8e6680a201ea57118b773b1d96d3
aiswaryasaravanan/practice
/udacity/searchingAndSorting/quickSort.py
729
3.84375
4
#half way done def partition(arr, start, end): if start < end: pivot = arr[start] i = start + 1 j = end while i < j: while i < end and arr[i] <= pivot : i+=1 while j > start and arr[j] >= pivot : j-=1 if i < j: ...
2e168c11e138e7b4f1bc621b0a71b81d4eb1e7b8
ihabselmi/Optimization-Advanced-Model
/Question 15.2.2.py
4,771
3.578125
4
"Homework 12" "Question 15.2.2" # Import PULP and pandas library from pulp import * import pandas as pd # Load data mydata = pd.read_excel("/Users/ihabselmi/Desktop/Georgia Tech Classes/ISyE 6501/Week 12 - Optimization Advanced Models/Homework 12/diet.xls") mydata = mydata[0:64].values.tolist() # Store the vecto...
9c08c646b233acc8985fc2db42fa3fd1380f88d2
blank-vax/QSIoT
/plotPerformanceData.py
11,931
3.625
4
""" Plot the data corresponding to the performance of the KEMs. The performance data available corresponds to the following variables: -CPU cycles and time. -Memory usage. -Packet size. The data for the CPU usage is at: -CPUPerformance/cyclesCPUPerformance.csv -CPUPerformance/timeCPUPerformance.csv...
781b93dd583dc43904e9b3d5aa4d6b06eaa5705b
spno77/random
/Python-programs/oop_examples.py
1,399
4.625
5
""" OOP examples """ class Car: """ Represent a car """ def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Return a neatly formatted descritive name""" long_name = f"{self.year} {self.make} {self.model}" ...
052193ea7c43ccaf0406b3c34cf08b906d6c74fd
GitDavid/ProjectEuler
/euler.py
812
4.25
4
import math ''' library created for commonly used Project Euler problems ''' def is_prime(x): ''' returns True if x is prime; False if not basic checks for lower numbers and all primes = 6k +/-1 ''' if x == 1 or x == 0: return False elif x <= 3: return True elif x % 2 == 0 ...
bac2143ae77cef8b1e647505e3ba0fa3048e1308
GitDavid/ProjectEuler
/prob12.py
884
3.828125
4
# Atempt # 2...use tau def is_prime(x): if x == 1: return False elif x == 2: return True else: i = 2 while i**2 <= x: if x % i == 0 : return False i += 1 return True def tau(x): div = 1 p = 3 count = 0 while x % 2 == 0: x /= 2 count += 1 if count > 0: div *= (count + 1) while x != 1...
7e767a59754cc8b272e876948793c1ac39d6642c
felipeonf/Exercises_Python
/exercícios_fixação/070.py
419
4.1875
4
''' [DESAFIO] Faça um programa que mostre os 10 primeiros elementos da Sequência de Fibonacci: 1 1 2 3 5 8 13 21...''' termos = int(input('Digite a quantidade de termos que quer ver: ')) termo = 1 termo_anterior = 0 print(0,end=' ') print(1,end=' ') for num in range(3,termos+1): termo3 = termo_anterior...
2d54b7496bc8518d5c5450a6c0e6c2e87be6ce79
felipeonf/Exercises_Python
/exercícios_fixação/009.py
335
3.875
4
#Faça um algoritmo que leia quanto dinheiro uma pessoa tem na carteira (em R$)e mostre quantos dólares ela pode comprar. # Considere US$1,00 = R$3,45. value = float(input('Digite qual valor deseja converter: ')) dolarAtual = 5.2883 print('Com a quantia de R${} você pode comprar US ${:.1f}.'.format(value,value/do...
e3b995c9cb6953c61d8c3d209b235a5c1a0b1e04
felipeonf/Exercises_Python
/curso_py/ex031.py
575
4.0625
4
from random import randint numerosorteado = randint(0,10) acertou = False tentativas = 0 print('Vamos tentar acertar o número sorteado pelo computador') while not acertou: palpite = int(input('Palpite: ')) tentativas += 1 if palpite == numerosorteado: acertou = True else: prin...
939efabfcdaac897a869a71da8ececa2be35c102
felipeonf/Exercises_Python
/exercícios_fixação/038.py
151
4
4
#Escreva um programa que mostre na tela a seguinte contagem: 6 7 8 9 10 11 Acabou! for num in range(6,12): print(num,end=' ') print('Acabou!')
940dce299d8c4c9ee07502c6daf12f9933a26ce0
felipeonf/Exercises_Python
/exercícios_fixação/073.py
281
4.125
4
'''Crie um programa que preencha automaticamente (usando lógica, não apenas atribuindo diretamente) um vetor numérico com 10 posições, conforme abaixo: 9 8 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7 8 9''' lista = [] for num in range(9,-1,-1): lista.append(num) print(lista)
4dae2320b6bd0f8a80bf162c9f0639cfeaaec7a6
felipeonf/Exercises_Python
/exercícios_fixação/027.py
563
3.828125
4
'''Crie um programa que leia duas notas de um aluno e calcule a sua média, mostrando uma mensagem no final, de acordo com a média atingida: - Média até 4.9: REPROVADO - Média entre 5.0 e 6.9: RECUPERAÇÃO - Média 7.0 ou superior: APROVADO''' nota1 = float(input('Digite sua primeira nota: ')) nota2 = float(inpu...
3929e75e789e847955d4c7af80c267a990c2656e
felipeonf/Exercises_Python
/curso_py/ex053.py
320
3.765625
4
lista = [] lista.append(input('Digite uma expressão: ')) aberto = 0 fechado = 0 for elemento in lista[0]: if elemento == '(': aberto += 1 elif elemento == ')': fechado += 1 if aberto == fechado: print('Essa expressão é válida') else: print('Essa expressão é invalida')
fe75408b87082dd46cb45a20f1d5d1cd01089c3c
felipeonf/Exercises_Python
/exercícios_fixação/078.py
509
3.953125
4
''' Escreva um programa que leia 15 números e guarde-os em um vetor. No final, mostre o vetor inteiro na tela e em seguida mostre em que posições foram digitados valores que são múltiplos de 10.''' numeros = [] for numero in range(0,16): numeros.append(int(input('Digite um número inteiro: '))) print(numeros) ...
8834204a8a3fe93dca5e396fc720f2a4217d3842
felipeonf/Exercises_Python
/exercícios_fixação/023.py
405
3.84375
4
# Faça um algoritmo que pergunte a distância que um passageiro deseja #percorrer em Km. Calcule o preço da passagem, cobrando R$0.50 por Km para #viagens até 200Km e R$0.45 para viagens mais longas. distance = int(input('How far you want to travel? ')) if distance > 200 : print(f'The ticket will cost R${di...
2fb1f5c7d7167eb98364971d1b5fed8b122713cc
felipeonf/Exercises_Python
/exercícios_fixação/041.py
167
4.0625
4
#Desenvolva um programa que mostre na tela a seguinte contagem: 100 95 90 85 80 ... 0 Acabou! for num in range(100,-1,-5): print(num,end=' ') print('Acabou!')
3485166de1790acd43afae8d9d711a9f5fc192af
felipeonf/Exercises_Python
/curso_py/ex003.py
436
3.875
4
nome = input('Digite o seu nome: ') print(f'Seu nome em minúsculo é : {nome.lower()}') print(f'Seu nome em caixa alta é : {nome.upper()}') lista = [] for char in nome: lista.append(char) for elemento in lista: if elemento == ' ': lista.remove(elemento) print(f'O tamanho do seu nome ...
38631f0f7a72dc0fd878d738b3aee0fd6e33c294
felipeonf/Exercises_Python
/curso_py/ex048.py
549
4
4
values = [] for value in range(5): values.append(int(input('Submit a number: '))) print(values) print(f'The max value in the list is {max(values)} and the min value is {min(values)}') print(f'The max value appears in the',end=' ') for position in range(5): if values[position] == max(values): pri...
8ef9e1347e94621ccc9ed1cd1d225d3447098d25
felipeonf/Exercises_Python
/curso_py/ex014.py
208
3.5
4
import random lista = [] i = 0 while i < 4 : lista.append(input(f'Digite o nome do {1+i}° aluno: ')) i+=1 random.shuffle(lista) print(f'A ordem de apresentação escolhida foi {lista}')
f00aaa589f615d64ca3563a8ce4cf52cbe66cefd
felipeonf/Exercises_Python
/curso_py/ex008.py
131
3.890625
4
from math import floor number = float(input('Set a number: ')) print(f'The number {number} has a int part = {floor(number)}')
2750f4cdbd8b0fd10860de4c430a717160a1ec4c
felipeonf/Exercises_Python
/exercícios_fixação/017.py
406
4
4
#Escreva um programa que pergunte a velocidade de um carro. Caso ultrapasse #80Km/h, exiba uma mensagem dizendo que o usuário foi multado. Nesse caso, exiba #o valor da multa, cobrando R$5 por cada Km acima da velocidade permitida. velocidade = int(input('Qual a velocidade registrada do carro em km/h? ')) if velo...
853053634d1090d69e26aed4a1d84736192565ec
felipeonf/Exercises_Python
/exercícios_fixação/047.py
193
3.625
4
''' Desenvolva um aplicativo que mostre na tela o resultado da expressão 500 + 450 + 400 + 350 + 300 + ... + 50 + 0''' soma = 0 for num in range(500,-1,-50): soma += num print(soma)
a3d61bc2bfee28fddff4f8f0420c64ea77304bad
felipeonf/Exercises_Python
/curso_py/ex065.py
1,318
3.6875
4
estatisticas = {} gols = [] while True: nome = input("Digite o nome do jogador: ") partidas = int(input("Quantas partidas ele jogou? ")) contador = 1 while contador <= partidas: gols.append(int(input(f'Partida {contador}: '))) contador += 1 estatisticas[nome] = gols[:] ...
af103d58cbf6743160c45164920ce36ad68146c2
felipeonf/Exercises_Python
/exercícios_fixação/062.py
911
4.125
4
''' Faça um programa usando a estrutura “faça enquanto” que leia a idade de várias pessoas. A cada laço, você deverá perguntar para o usuário se ele quer ou não continuar a digitar dados. No final, quando o usuário decidir parar, mostre na tela: a) Quantas idades foram digitadas b) Qual é a média entre as idades d...
9ca22fff3b2adf105c3e595e881d6b865447fbe9
felipeonf/Exercises_Python
/exercícios_fixação/010.py
663
3.875
4
# Faça um algoritmo que leia a largura e altura de uma parede, calcule e #mostre a área a ser pintada e a quantidade de tinta necessária para o serviço, #sabendo que cada litro de tinta pinta uma área de 2 metros quadrados. def calculaArea(largura,altura): area = largura * altura return area largura ...
20b100b4c7cb63ee30be904065464f0092737ae5
felipeonf/Exercises_Python
/exercícios_fixação/003.py
178
3.9375
4
#algoritmo que lê dois números inteiros e mostre o somatório entre eles. valor_1 = int(input('Nota 1: ')) valor_2 = int(input('Nota 2: ')) print(f'{valor_1+valor_2}')