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 |
|---|---|---|---|---|---|---|
a194f811e9de0b020e0b22f9b6fd9531d55cf78b | YuTan9/leetcode | /2020JulyCodingChallenge/Maximum_Width_of_Binary_Tree.py | 2,397 | 3.59375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# My code: (Passes)
class Solution(object):
def widthOfBinaryTree(self, root):
"""
:type root: TreeN... |
b478025bb4c45dd4c32c1a8083b828da9d9f958b | Davinder-Dole/python-challenge-Py-Me-Up-Charlie | /PyBank/hw/main.py | 1,902 | 3.75 | 4 | import os
import csv
csvpath = os.path.join("..", "Resources", "budget_data.csv")
total_months = 0
total_profit = []
monthly_profit_change = []
min=0
max=0
# Open csv
with open(csvpath, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# Skip the header labels
csvheader = next(csvreader)
... |
b227542479f4396cb317fbb2a42e79ad0d90da31 | JhonattanDev/Exercicios-Phyton-29-07 | /ex7.py | 586 | 4.28125 | 4 | import math
# Pra explicar o programa
print("Digite um valor abaixo para ver seu dobro, triplo, e raíz quadrada dele! \n")
# Input para o usuário inserir o valor
valor = int(input("Digite o valor: "))
# Aqui será realizados os cálculos que definirão as variáveis
dobro = valor * 2
triplo = valor * 3
raizQu... |
7683a451955599046bc8443143fe84f1bdd07d7f | JEONJinah/Shin | /for statment.py | 921 | 3.859375 | 4 | # 이중 for 문 곱셈
for i in range(2,10):
for j in range(1, 10):
print(i*j, end=" ")
print(" ")
a = [1,2,3,4]
result = [num * 3 for num in a if num % 2 == 0]
print(result)
a = [(1, 3), (2, 4), (3, 5)]
for (f, r) in a:
print(f + r)
marks = [90, 5, 67, 45, 80]
number = 0 #print(student num... |
aebb76773c73791a6d997e678fd50c0f812f7144 | sorcerer0001/courses-interactivepython-01 | /c2.py | 1,304 | 3.71875 | 4 |
import simplegui
import random
import math
num_range = 100
remaining_guesses = 0
secret_number = 0
def new_game():
global num_range, remaining_guesses, secret_number
secret_number = random.randrange(0, num_range)
remaining_guesses = int(math.ceil(math.log(num_range, 2)))
print
print "New ga... |
83f5c1a07d2fa6535c3615e7c3c03af24d879a23 | urielgoncalves/training-python | /fizzbuzz.py | 572 | 3.921875 | 4 | import numpy
def fizzbuzz(numero):
#se o numero for multiplo de 3 e 5 escreve fizzbuzz
#se o numero dor multiplo de 3 escreve fizz
#se o numero for multiplo de 5 escreve buzz
#else escreve o numero
#pass
multiploDeTres = numero % 3 == 0
multiploDeCinco = numero % 5 == 0
if multiploDeT... |
f51e447b76c578428adac4a07943ee05a6bb28a9 | areebasif/myDS | /llist and stacks.py | 6,830 | 3.921875 | 4 | class node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self,data):
new_node = node(data)
if self.head is None:
self.head = new_node
return
prev_node = s... |
2b6d2383e34cb69fa3ade28f93b0faca196dfe7a | ChanKamyung/Covert-transmission-based-on-ICMP | /transmitting terminal/mLib/Huffman.py | 7,649 | 3.578125 | 4 | #!/usr/bin/python3
# _*_ coding=utf-8 _*_
import sys
sys.setrecursionlimit(1000000) #压缩大文件实时会出现超出递归深度,故修改限制
#定义哈夫曼树的节点类
class node(object):
def __init__(self, value=None, left=None, right=None, father=None):
self.value = value
self.left = left
self.right = right
self.father = fathe... |
8188340bb9b5f124562bfe9401c0259ba42ab673 | baixianghuang/algorithm | /python3/print_1_to_n_largest.py | 1,207 | 3.859375 | 4 | def print1_to_n_largest(n):
"""
Big number problem print 1 to the largest n digits
"""
if n <= 0:
return
L = []
for i in range(n):
L.append(0)
# print(L)
new_list = L[:]
while True:
new_list = add_one_list(new_list, n)
print_list_to_num(new_list)
list_co... |
bd6b8a39bd376c6bcf9a3a56a4a70453159e05f4 | baixianghuang/algorithm | /python3/merge_linked_lists.py | 2,215 | 4.3125 | 4 | class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def merge_linked_lists_recursively(node1, node2):
""""merge 2 sorted linked list into a sorted list (ascending)"""
if node1 == None:
return node2
elif node2 == None:
return node1
new_h... |
059bb202ef3eb4909e0e58327ddf149e64695b30 | baixianghuang/algorithm | /python3/produce_ugly_number.py | 1,779 | 3.703125 | 4 | def produce_ugly_number_solution_1(n):
"""
produce the n-th ugly number by generating n ugly number
the ugly number next to K is some number prior to K times 2 or 3 or 5
"""
ls = [1] # store ugly number
k = 0
t2, t3, t5 = 0, 0, 0
for i in range(n - 1):
while 2 * ls[t2] < ls[i]:... |
9ad0651f040163eb373e3ed365f597520c08c432 | baixianghuang/algorithm | /python3/min_in_rotated_list.py | 910 | 3.546875 | 4 | def min_in_rotated_list(ls):
if ls == None:
return False
start = 0
end = len(ls) - 1
while ls[start] >= ls[end]:
if end - start == 1:
return ls[end]
mid_index = (start + end) >> 1
# have to perform linear search
if ls[mid_index] == ls[start] and ls[... |
3d923845ebbf843842d3012738e3bfd89de988df | enomarozi/Crypto_Classic-Py | /Bruteforce_Char.py | 360 | 3.609375 | 4 | import sys
def ROT(n):
text = sys.argv[1]
if sys.argv[3] == "+":
hasil = [chr(ord(i)+n) for i in text]
hasil1 = "".join(hasil)
return hasil1
elif sys.argv[3] == "-":
hasil = [chr(ord(i)-n) for i in text]
hasil1 = "".join(hasil)
return hasil1
for rot in range(... |
772841e9812d286aff348f1b083d040596ccac51 | Dyfeomorfizm/pdfApp | /db_setup.py | 1,036 | 3.578125 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print e
return None
def create_table(conn, create_table_sql):
try:
c = conn.cursor()
c.execute(create_table_sql)
ex... |
09ac2411c4ab5a675d4bd478b4c76dd70e9c7a44 | juancamilo840/Taller-estructuras-de-control-secuenciales | /Taller de estructuras secuenciales/ejercicio13.py | 606 | 3.609375 | 4 | numero_billetes = 8
total = numero_billetes
billetes = [float() for ind0 in range(numero_billetes)]
billetes[0] = 50.000
billetes[1] = 20.000
billetes[2] = 10.000
billetes[3] = 5.000
billetes[4] = 2.000
billetes[5] = 1.000
billetes[6] = 500
billetes[7] = 100
cantidad_bill_mon = [str() for ind0 in range(tota... |
daacdc0089feccde08146ea17f5ccdf4726c7205 | juancamilo840/Taller-estructuras-de-control-secuenciales | /Taller de estructuras secuenciales/ejercicio7.py | 306 | 4 | 4 | # 1 metro a pies = 12
# 1 metro a pulgadas = 39.27
metro = float()
pulgada = float()
pies = float()
print("Escribe los metros")
metro = float(input())
pulgada = metro*39.27
pies = metro*12
print(metro,"metros convertidos a pulgadas es: ",pulgada)
print(metro,"metros convertidos a pies es: ",pies) |
4e2560f2c51492fd9570b6dfcfa6da6ec706eacd | juancamilo840/Taller-estructuras-de-control-secuenciales | /main.py | 416 | 3.75 | 4 | if __name__ == '__main__':
print("Escribe la cantidad invertida")
cantidad = float(input())
print("Escribe la tasa de interes")
tasa = float(input())
intereses = cantidad*tasa
if intereses>100000:
print("Los intereses ganados son $",intereses," superan los $100000")
else:
print("Los intereses ganados son $",... |
184af18b52ad0074b0f6326c9fbaf0f4c08a7fac | juancamilo840/Taller-estructuras-de-control-secuenciales | /Taller de estructuras secuenciales/ejercicio15.py | 286 | 3.765625 | 4 | print("Ingrese el precio del producto:")
precio = float(input())
print("Ingrese la cantidad de productos a comprar:")
cantidad = float(input())
print("Ingrese su Precio de venta al publico:")
pvp = float(input())
compra = precio*cantidad*pvp
print("el total a pagar es:",compra) |
b456c2de95435a83162b4729138702ac80fab821 | Faye-HuihuiChen/Python | /Investigating Texts and Calls/Task3.py | 3,582 | 4.28125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 3:
(080) is the area code for fixed ... |
4ddfbf5cf2ae8a5f3916f15995edc7791e7d2741 | akriti8692/Python | /PS4_Q2.py | 967 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 4 18:47:09 2020
@author: 16509
"""
input1=0
C=0
F=0
A=0
z=0
#User input : Farenheit to Celsius
def display_menu():
input1=input("Indicate which temperature conversion you would like to perform, by entering 1 or 2,1. Fahrenheit to Celsius2. Celsius to... |
1a06651d7f569ee946e116e7e0cd1918b15e6f32 | akriti8692/Python | /PS4_Q3.py | 1,518 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 4 20:43:10 2020
@author: 16509
"""
dict1={}
list1=[]
list2=[]
assignment=['Homework','Midterm','FinalExam']
def enter_grade(assignment,amount,max_grade):
for i in assignment:
if i=='Homework':
while z in range(1,4):
... |
56bb2d591702c721ed9891e9c60e2fabb0cf80ff | danmorales/Python-Pandas | /pandas-ex19.py | 358 | 4.125 | 4 | import pandas as pd
array = {'A' : [1,2,3,4,5,4,3,2,1], 'B' : [5,4,3,2,1,2,3,4,5], 'C' : [2,4,6,8,10,12,14,16,18]}
df_array = pd.DataFrame(data=array)
print("Arranjo original")
print(df_array)
print("\n")
print("Removendo linhas cuja coluna B tenha valores iguais a 3")
df_array_new = df_array[df_array.B != 3]
prin... |
d8418624bde68e75ac2edbbcf1d56830d6b9c75e | helloimyames/PythonEssentials3 | /syntax_strings.py | 214 | 3.640625 | 4 |
def main():
n = 40
print("this is a {}".format(n))
print('this is a {}'.format(n))
print('''this is a string
text
text
''')
if __name__=="__main__": main()
|
e6afd3612c19a356fa9c4ef6215a0846a04193b1 | xuan2020/teamlearn | /productrecommendation.py | 9,657 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sep 24
@author: cheryl
Programming Project: Recommendation
Examine item co-purchasing.
Assignment: working with data on purchases from retail stores.
The task will be to create recommendations for someone who has just bought a product,
based on which items are ofte... |
c53aa430dfa5da2ceeb01bc5e9ad1e5ab4f3da3d | shashwatrathod/CompetitiveCoding | /Arrays/SortColors.py | 919 | 3.6875 | 4 | #https://leetcode.com/problems/sort-colors/
#O(1) space req; O(n) time; only one pass in the array
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
zero_pointer = -1
two_pointer = len(nums)
... |
96133f56fdadf80059d2b548a3ae485dee91f770 | suhaslucia/Pythagoras-Theorem-in-Python | /Pythagoras Theorem.py | 1,114 | 4.40625 | 4 | from math import sqrt #importing math package
print(" ----------Pythagoras Theorem to Find the sides of the Triangle---------- ")
print(" ------------ Enter any one side as 0 to obtain the result -------------- ")
# Taking the inputs as a integer value from the user
base = int(input("Enter the base of the Trian... |
1fa756ca401e6b49f5d05608771ec788ae4f6324 | RakshaAchuth/Python-in-PYCharm | /oopsproject/book.py | 389 | 3.5625 | 4 | #book
class Book:
#pass
#constructor
def __init__(self, name):
# print(name)
self.name = name
# print('book instance created')
#
boo1 = Book('gggggggggggg')
strybook = Book('yyyyyyb hh')
pythonbook = Book('hey hello')
boo1.name = 'gggggggggggg'
strybook.name='yyyyyyb hh'
pytho... |
27cb0a98236f95d0c146c34574fb954d1bf03878 | RakshaAchuth/Python-in-PYCharm | /exceptionhandling/tryexceptionerror.py | 623 | 3.78125 | 4 |
#open file/resource
# just try and finally are allowed
# try eith except are allowed
#try eith else and finally are not allowed
# try is mandatory
try:
#try business logic to read
i = 1 #input from user
j = 10/i
values = [1, '2']
sum(values)
except TypeError:
print('TypeError')
j = 1... |
a1c99d43da0be47d5bf14e0ce3dbafe24cce88b1 | CypherPandaGit/Sorter | /sorter.py | 2,245 | 3.5 | 4 | import os
import sys
from pathlib import Path
# This will be new directories HTML, IMAGES, AUDIO etc.
dirs = {
'Web': ['.html', '.htm'],
'Zips': ['.exe', '.zip', '.rar'],
'Documents': ['.docx', '.doc', '.pdf', '.xls', '.odt'],
'Images': ['.jpg', '.jpeg', '.gif', '.bmp', '.png', '.psd', '.heif'],
'... |
4f984ed69a9607d47938b77c3ae8c00ba719d2c5 | Azuromalachite/KVIS-student-former-school | /visualization/bubble_plot.py | 1,777 | 3.515625 | 4 | import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dataset = pd.read_csv("KVIS student dataset.csv")
dataset.columns = ['thai', 'region', 'english', 'income', 'expense', 'students']
def show_plot(dataset, region = 'all', show_none = False):
__dataset = dataset
if s... |
e37c016452aeb9b50db48a86974732a9b33ccbcf | Kumar1998/github-upload | /code19.py | 89 | 3.8125 | 4 | arr=[1,2,3,4]
if arr[3]<arr[2]:
print(1 and 0 or 1)
else:
print(1 or 0 and 0) |
68e32356ee24ab2bbfc87c4ca3508e89eacd3a0b | Kumar1998/github-upload | /scratch_4.py | 397 | 4.25 | 4 | d1={'Canada':100,'Japan':200,'Germany':300,'Italy':400}
#Example 1 Print only keys
print("*"*10)
for x in d1:
print(x)
#Example 2 Print only values
print ("*"*10)
for x in d1:
print(d1[x])
#Example 3 Print only values
print ("*"*10)
for x in d1.values():
print(x)
#Example 4 Print only key... |
ac00f76da12e449ceb5bf58d199945845ac67d89 | Kumar1998/github-upload | /scratch_40.py | 183 | 3.671875 | 4 | """Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(array):
return []
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print(quicksort(test)) |
f13e3676b62ae860663a9603762471b5cc440741 | Kumar1998/github-upload | /scratch_28.py | 53 | 3.59375 | 4 | a='1'
a=a*3
print(a)
b='44'
b=b*4
print(b)
|
29f77abbba42434a5afab1d3f4dd4ad7460e6674 | Kumar1998/github-upload | /code14.py | 51 | 3.671875 | 4 | x=2
for count in range(3):
x=x**2
print(x)
|
dbb4af95e9b603a6383c6a0e9b72f3cac2a824ad | Kumar1998/github-upload | /scratch_27.py | 399 | 3.890625 | 4 | print(True or False)
print(True and False)
n=5 #number of levels for free
for level in range(1,n+1):
print(level * '*')
for level in range(1,n+1):
print(''*(n-level)+ level* '*')
print(len("Hello")+len("World"))
a={'d':3}
print(a.get('d'))
a['d']+=2
print(a.get('d')+3)
temp=35
if temp>30:
... |
f38bd5b4882bd3787e78bcb653ca07d48b1f7093 | Kumar1998/github-upload | /python1.py | 573 | 4.3125 | 4 | height=float(input("Enter height of the person:"))
weight=float(input("Enter weight of the person:"))
# the formula for calculating bmi
bmi=weight/(height**2)
print("Your BMI IS:{0} and you are:".format(bmi),end='')
#conditions
if(bmi<16):
print("severly underweight")
elif(bmi>=16 and bmi<18.5):
print(... |
ba3603dc23513b718bba58232878c5b12125c894 | Kumar1998/github-upload | /code27.py | 67 | 3.640625 | 4 | num=[8,8,8,8]
x=1
for i in range (1,len(num)):
x=1
print(x) |
0ef75de1d6af5a7988a1a3ea683b3769e986bc12 | septhiono/redesigned-meme | /Day 2 add two numbers in a single input.py | 284 | 3.890625 | 4 | import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
print(f'Pssst, the solution is {chosen_word}.')
display=["_"]*len(chosen_word)
print(display)
print(chosen_word)
guess = input("Guess a letter: ").lower()
print("weong")
|
98f763bd336731f8fa0bd853d06c059dd88d8ca7 | septhiono/redesigned-meme | /Day 2 Tip Calculator.py | 316 | 4.1875 | 4 | print('Welcome to the tip calculator')
bill = float(input('What was the total bill? $'))
tip= float(input('What percentage tip would you like to give? '))
people = float(input("How many people split the bill? "))
pay= bill*(1+tip/100)/people
pay=float(pay)
print("Each person should pay: $",round(pay,2))
|
ee3eea76d3b3f21ddc5a8e037185a25fadef7e08 | space-isa/profitable-app-profiles | /src/clean_data.py | 2,315 | 3.640625 | 4 | import numpy as np
def find_duplicates(dataset, app_name_index,
tag, use_array=True):
"""Find duplicate app names"""
if use_array:
dataset = np.asarray(dataset)
app_names = dataset[:,app_name_index]
unique_apps = set(app_names)
duplicate_apps = len(dataset)... |
107a1c4635a7c78576af5dd5d99a70112a8afd4a | rugbyprof/4443-2D-PyGame | /Resources/R02/Pygame_Introduction/008_pyglesson.py | 2,999 | 3.71875 | 4 | """
Pygame 008
Description:
Writing out the new colors file
Randomly picking ball and screen colors
New Code:
None
"""
# Import and initialize the pygame library
import pygame
import random
import json
import pprint
def fix_colors(infile):
""" One time fix of original json file with only names and h... |
ed4ed381cbe55ce33e621a12426d9fb41e3f2981 | rugbyprof/4443-2D-PyGame | /Resources/R02/Pygame_Introduction/011_pyglesson.py | 1,985 | 3.734375 | 4 | """
Pygame 011
Description:
Fixing our Ball Class Part 2
New Code:
None
"""
# Import and initialize the pygame library
import pygame
import random
import json
import pprint
import sys
def load_colors(infile):
with open(infile,'r') as f:
data = f.read()
colors = json.loads(data)
retu... |
fea4e23725b61f8dd4024b2c52065870bbba6da1 | rugbyprof/4443-2D-PyGame | /Resources/R02/Python_Introduction/PyIntro_05.py | 548 | 4.15625 | 4 | # import sys
# import os
# PyInto Lesson 05
# Strings
# - Functions
# - Input from terminal
# - Formatted Strings
name = "NIKOLA TESLA"
quote = "The only mystery in life is: why did Kamikaze pilots wear helmets?"
print(name.lower())
print(name.upper())
print(name.capitalize())
print(name.title())
print(name.isalpha... |
71d354053e21a975844f104a914148533322ad43 | rugbyprof/4443-2D-PyGame | /Resources/R02/Python_Introduction/PyIntro_22.py | 1,616 | 3.703125 | 4 | import math
import os,sys
import json
# PyIntro Lesson 22
# Classes Part 3
class Data:
@staticmethod
def validJson(jdata):
try:
json_object = json.loads(jdata)
return True
except ValueError as e:
pass
return False
@staticmethod
def readJson(... |
bb50a982bb5f4da46a09b714c1d37a52d43c778f | rugbyprof/4443-2D-PyGame | /Resources/R02/Pygame_Introduction/005_pyglesson.py | 1,497 | 4.09375 | 4 | """
Pygame 005
Description:
Simple config starter
And drawing a ball
New Code:
- pygame.draw.circle(screen, (red, green, blue), (250, 250), 75)
"""
config = {
'title' :'005 Pygame Lesson'
}
colors = {
'magenta':(255, 0, 255, 100),
'cyan':(0, 255, 255, 100),
'background':(0,130,200,100)
... |
e054d55058159c95b35621f682a3a2bb0594dbd8 | ehbjarnason/motion | /motion.py | 21,674 | 3.828125 | 4 |
import numpy as np
import matplotlib.pyplot as plt
class MotionProfile:
"""An abstract class, which other motion profiles should inherit and implement."""
def __init__(self):
self.n = None # Number of data points
self.dist = None # Total distance
self.time = None # Time duration
... |
69c2148bb3dbf711184fa5f4c2fee5dec138add4 | zrj1236/bnlearn | /bnlearn/inference.py | 3,414 | 3.5625 | 4 | """Techniques for inference.
Description
-----------
Inference is same as asking conditional probability questions to the models.
"""
# ------------------------------------
# Name : inference.py
# Author : E.Taskesen
# Contact : erdogant@gmail.com
# Licence : See licences
# ------------------------... |
0f8c07d4970004e3d3c0236a88c9d759f9cfcb78 | rtl019/MLpractice | /regression_analysis/CSV_Reader.py | 286 | 3.53125 | 4 | import csv
def Reader(fileName):
file=open(fileName)
dicr=csv.DictReader(file)
for row in dicr:
size=[]
size.append(row['sq__ft'])
price=[]
price.append(row['price'])
return price,size
|
5b6b94900cf1b9de14b11d743d1e553c326ad6bd | ulankford/python | /MIT_6.00.1x_EDX_Code/python.py | 212 | 3.71875 | 4 | name = raw_input('What is your name?')
if name == 'bob':
print 'Why hello,', name
elif name == 'ultan':
print name ,'you are fired'
else:
print 'You are not allowed to access this system.'
|
edb7bb5311d88228d4dcb8bf107a1dc6781af8b7 | weilingu/Brand-Logo-Feature-Analysis | /CNN_Letter_Recog_Model.py | 3,930 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 17 13:33:52 2019
@author: emily.gu
"""
from mnist import MNIST
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.layers.advanced_activations import LeakyReLU
from keras.utils i... |
b006e4dc55b7188a241efcf979b94328bbc53a42 | mingyuea/pythonLeetcodeMed | /maxNumAsRoot.py | 1,992 | 3.59375 | 4 | '''
Given a list of integers with no duplicates, find the max and set it as the root of a tree
The left subtree is then a tree built from the left partition of the list (list[0:max])
The right subtree is a tree build from the right partition of the remaining list (list[max+1:])
Return the root node
'''
class TreeNode... |
429289861e6299df2f7cb5b197c9c7d813a7e4f9 | nidhinp/Anand-Chapter2 | /problem30.py | 177 | 3.59375 | 4 | """ Write a python function parse_csv to parse csv files.
"""
def parse_csv(file):
return [line.split()[0].split(',') for line in open(file)]
print parse_csv('a.csv')
|
7b69e5ceb600a18a3f9d9c8bae52ec41ed24f145 | nidhinp/Anand-Chapter2 | /problem3.py | 240 | 3.640625 | 4 | """ Sum function that works for a list of string as well
"""
def my_sum(x):
sum = x[0]
for i in x:
if i == x[0]:
continue
else:
sum += i
return sum
print my_sum([1, 2, 3, 4])
print my_sum(['c', 'java', 'python'])
|
79d70dca2e86013310ae0691b9a8e731d26e2e75 | nidhinp/Anand-Chapter2 | /problem36.py | 672 | 4.21875 | 4 | """ Write a program to find anagrams in a given list of words. Two words are called
anagrams if one word can be formed by rearranging letters to another. For example
'eat', 'ate' and 'tea' are anagrams.
"""
def sorted_characters_of_word(word):
b = sorted(word)
c = ''
for character in b:
c += character
re... |
a1b103fb6e85e3549090449e71ab3908a46b2e9c | nidhinp/Anand-Chapter2 | /problem29.py | 371 | 4.25 | 4 | """ Write a function array to create an 2-dimensional array. The function
should take both dimensions as arguments. Value of element can be
initialized to None:
"""
def array(oneD, twoD):
return [[None for x in range(twoD)] for x in range(oneD)]
a = array(2, 3)
print 'None initialized array'
prin... |
fd5a09d770cd5f632c2897dab06b4b9e7e5b6af7 | mo/project-euler | /python/problem2.py | 401 | 3.921875 | 4 |
def fibonacci(n):
if n == 1 or n == 0:
return 1
return fibonacci(n-1) + fibonacci(n-2)
special_sum = 0
i = 0
ith_fibonacci_number = fibonacci(i);
while ith_fibonacci_number < 1000000:
if ith_fibonacci_number % 2 == 0:
special_sum += ith_fibonacci_number
i += 1
ith_fi... |
2044f47081263d56813e4a2068a167c339c23ae2 | MarufurRahman/URI-Beginner-Solution | /Solutions/URI-1011.py | 233 | 3.625 | 4 | # URI Problem Link: https://www.urionlinejudge.com.br/judge/en/problems/view/1011
# Programmed by Marufur Rahman.
radius = int(input())
pi = 3.14159
volume = float(4.0 * pi * (radius* radius * radius) / 3)
print("VOLUME = %0.3f" %volume) |
4cbcb6d66ee4b0712d064c9ad4053456e515b14b | SandipanKhanra/Sentiment-Analysis | /tweet.py | 2,539 | 4.25 | 4 |
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
#This function is used to strip down the unnecessary characters
def strip_punctuation(s):
for i in s:
if i in punctuation_chars:
s=s.replace(i,"")
return s
# lists of words to use
#As part of the project this hypothetical .t... |
d48f24d89a3c5cba1d45022da76173afc90843e7 | CaptClox/py-promedio | /Clases-python/ejemplo2.py | 308 | 3.90625 | 4 | #ejemplificaar uso de funcion MAP
palabras = ["hola","juan","curso","programacion","universidad"]
#tarea: contar cantidad de caracteres de cada palabra
"""
conteo_cars = []
for p in palabras:
cnt_cars = len(p)
conteo_cars.append(cnt_cars)
"""
conteo_cars = list(map(len,palabras))
print(conteo_cars) |
7fc0742a90d95abd67ac4ce3669285cd345e3410 | CNchence/Python_learning | /hello_world/hello_world/hello_world/hello_world.py | 85 | 3.90625 | 4 | x=[3,2,6,5,1,2,5,4,8,7,6]
y=x[:]
x.sort();
print(x);
y.sort(reverse = True);
print(y) |
5f1b71da8c2e15598cbcceb65c1b0869728f2c2c | tvdstorm/exercises-in-programming-style | /02-go-forth/tf-02.py | 3,630 | 4.03125 | 4 | #!/usr/bin/env python
import sys, re, operator, string
#
# The all-important data stack
#
stack = []
#
# The new "words" of our program
#
def read_file():
"""
Takes a path to a file and returns the entire
contents of the file as a string.
Path to file expected to be on the stack
"""
path_to_f... |
6c12e09f840a8e2fa23904b1dee0215600f35831 | ScottD61/Thinkful | /Unit1/join1.py | 744 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 17:05:52 2015
@author: scdavis6
"""
import sqlite3 as lite
import pandas as pd
con = lite.connect('/Users/scdavis6/getting_started.db')
join_query = "SELECT name, state, year, warm_month, cold_month FROM cities INNER JOIN weather ON name = city;"
joined = pd.read_sq... |
8c79d7caeb39a173173de7e743a8e2186e2cfc0a | osirisgclark/python-interview-questions | /TCS-tataconsultancyservices2.py | 344 | 4.46875 | 4 | """
For this list [1, 2, 3] return [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
"""
list = [1, 2, 3]
list1 = []
list2 = []
list3 = []
for x in range(1, len(list)+1):
list1.append(x)
list2.append(2*x)
list3.append(3*x)
print([list1, list2, list3])
"""
Using List Comprehensions
"""
print([[x, 2*x, 3*x] for x in r... |
7cc58e0ee75580bc78c260832e940d0fd07b9e2a | minerbra/Temperature-converter | /main.py | 574 | 4.46875 | 4 | """
@Author: Brady Miner
This program will display a temperature conversion table for degrees Celsius to Fahrenheit from 0-100 degrees
in multiples of 10.
"""
# Title and structure for for table output
print("\nCelsius to Fahrenheit")
print("Conversion Table\n")
print("Celsius\t Fahrenheit")
for celsius in rang... |
147dbdbb81dc3fd47a93f30882c169529b969f99 | Ricardop123/python-kmmx | /generadores.py | 151 | 3.578125 | 4 | def getNumbers(n):
for x in range(n):
yield x
print(getNumbers(9))
g = getNumbers(10)
print(g.__next__())
print(g.__next__())
print(g.__next__()) |
35bf98ba27b4d40061a72d9b7b9f996831faddbf | Nahia9/COMP301-Python-Assignment04 | /generator.py | 2,501 | 4.0625 | 4 | """
File Name: generator.py
Name:Nahia Akter
Student#: 301106956
Date: 23/08/2020
File description: Generates and displays sentences chooding random words from files
"""
import random
def getWords(filename):
files = open(filename)
temp_list = list()
for each_line in files:
each_line = each_line.st... |
6da72bf5cc9c6faf6032a114897ee1ee8dfa88e7 | fayiz/python | /chocolates_by_numbers.py | 224 | 3.703125 | 4 |
def find_gcd(a, b):
if b == 0:
return a
else:
#print(find_gcd(b, a % b))
return find_gcd(b, a % b)
def solutions(N, M):
return N // find_gcd(N, M)
print(solutions(10, 4)) |
cc2da260abc8ba0bb81ad5946349a3d32ba26448 | ardinur03/belajar_python | /pembelajaran_dalam_yt/parentclass.py | 1,027 | 3.96875 | 4 | # class parent
class Person:
# constructor
def __init__(self, name = "Anonymouse", umur = 0):
self.__umur = umur
self.__name = name
# ambil nama
def getName(self):
return self.__name
# ambil umur
def getUmur(self):
return self.__umur
def perkenalkan_diri(self... |
04a85c04f42f4253ca93966eaa54ae2f6ead145d | ardinur03/belajar_python | /belajar_di_sekolah_koding/basic/belajar.py | 4,619 | 4 | 4 | print("\t WELCOME TO LEARN PYTHON")
# identitas about me
Nama = "Muhamad Ardi Nur Insan"
Kelas = "11 RPL 1"
print("Nama :", Nama +"\nKelas :", Kelas)
print("----------------\"-----\"-----------------")
# aplikasi sederhana penanyaan Nama
# concatinetion (penggabungan string)
"""
nama = input("\nSiapa nama anda bos... |
83df1810e8a994862571c510473e77c305bc479e | josbex/HS-detection_in_social_media_posts | /util/vocab_parser.py | 641 | 3.5625 | 4 | def file_to_list(path):
#completeName = r"C:\Users\josef\Desktop\exjobb-NLP\\" + filename + ".txt"
completeName = path
f = open(completeName, "r")
vocab_list = []
while True:
word = f.readline()
vocab_list.append(word.rstrip())
if not word:
break
f.close()
... |
ec2ffda93473b99c06258761740065801e017162 | saimkhan92/data_structures_python | /llfolder1/linked_list_implementation.py | 1,445 | 4.28125 | 4 | # add new node in the front (at thr root's side)
import sys
class node():
def __init__(self,d=None,n=None):
self.data=d
self.next=n
class linked_list(node):
def __init__(self,r=None,l=0):
self.length=l
self.root=r
def add(self,d):
new_node=node()
... |
d7fb7ba1b47eb9787dc45de53dd221d75d52a05f | catterson/python-fundamentals | /challenges/02-Strings/C_interpolation.py | 1,063 | 4.78125 | 5 | # Lastly, we'll see how we can put some data into our strings
# Interpolation
## There are several ways python lets you stick data into strings, or combine
## them. A simple, but very powerful approach is to us the % operator. Strings
## can be set up this way to present a value we didn't know when we defined the
## s... |
e2ad159e8c2c563784f23a62df878149c4a99ed1 | Vihaanmaster/Jarvis | /helper_functions/database.py | 3,947 | 3.96875 | 4 | from os.path import isfile
from sqlite3 import connect
file_name = 'tasks.db'
class Database:
"""Connector for ``Database`` to create and modify.
>>> Database
``create_db`` - creates a database named 'tasks.db' with table as 'tasks'
``downloader`` - gets item and category stored in the table 'tasks... |
541e5f2ac9427538751cbfca1c3b9c54e8d17cc8 | MohammedRiyaz-au7/w3d1d2-cc-assign | /w3d1d2 assign q1.py | 357 | 3.859375 | 4 | import operator
d = {'a': 100, 'b': 200, 'c': 300, 'd': 400, }
print('Original dictionary :' ,d)
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in de... |
cc70dde013a71d8672a7d3cf7341d87083897078 | gmurr20/CollegeTVDevice | /PythonWebApp/News.py | 1,261 | 3.703125 | 4 | import requests
import json
import properties
'''
News article object to contain all relevant information from api
'''
class newsArticle:
imageUrl = ""
title = ""
description = ""
author = ""
def __init__(self, imageUrl, title, description, author):
self.imageUrl = imageUrl
self.title = title
self.descript... |
3eeeae8a44a57ef5d8e76240db823cfc5e4284f3 | citisy/Algorithms | /tree/Heap.py | 3,452 | 4.0625 | 4 | """堆,一颗完全二叉树,宜采用顺序存储,这里使用链式存储
基本特征:小根堆:根<左孩子or右孩子,大根堆:根>左孩子or右孩子
"""
from BinaryTree import BinaryTree
# 小根堆
class Heap(BinaryTree):
"""
functions:
insert(item, bn): insert an item
delete(item, bn): delete an item
"""
def init(self, arr):
for i in arr:
self.insert... |
092e6fad0c66413d23ce81ac354881cb212e7f50 | citisy/Algorithms | /tree/BinaryTree.py | 11,059 | 3.796875 | 4 | """
根据数组创建一个应用双链表的二叉树
二叉树的种类:
满二叉树:每一层都是满的
完全二叉树:除最后一层或包括最后一层,其余层全满,最后一层在右边缺若干个结点
理想平衡二叉树:除最后一层或包括最后一层,其余层全满,最后一层的结点任意分布
种类包含情况:
理想平衡二叉树>完全二叉树>满二叉树
二叉树的一些特征:
叶子结点n0,单分支n1,双分支n2
=> n0+n1+n2=n1+2n2+1
=> n0=n2+1
=> 叶子结点比双分支结点多1个
根结点:i 左孩子:2i 右孩子:2i+1
n个结点的完全二叉树的深度:lb(n)+... |
e554812faf2fc21c4597c7e161847760a611a173 | omar00070/Search-Algorithm-Vesualiser | /test.py | 185 | 3.78125 | 4 | a = {move: 1 for move in ['K', 'U']}
# print(a)
a = 3 #integer
b = 'string' # string
c = True # boolean
print(a, b, c)
a = 3 # a a value of 3
if a == 3:
print('a value is ', a)
|
7a0de5eaa89ae4b9e63c0c0b6ba1bbece71d1631 | RomainTOMINE2/Romain | /Sapin2.py | 556 | 3.703125 | 4 | def printTriangle(incr, base, a_center):
for y in range(4):
etoiles = base + (y*incr)
print((etoiles*"*").center(a_center))
def printSapin(height):
center = ((1+(( height-1)*2))+( height*2)) + 2*( height*2)
for y in range(1, height+1):
printTriangle(y*2, 1+((y-1)*2), center)
pr... |
edef5c4ef9472a6b9c380fc5baee59bdc56556d1 | rmartinez5748/CursoPython | /WorkingREGEX.py | 266 | 3.71875 | 4 | import re
cadena = 'Estoy trabajando con Python en domingo y Semana Santa'
busqueda = 'domingo'
if print(re.search(busqueda, cadena)) is not None:
print(f'Se ha encontrado el termino {busqueda}')
else:
print(f'No se ha encontrado el termino {busqueda}')
|
2a00e265a8f1b4f850e2c3f7aed7575dc486adfd | rmartinez5748/CursoPython | /RandomExercise.py | 214 | 3.578125 | 4 | import random
class Dice:
def roll(self):
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
result = (dice1, dice2)
return result
game = Dice()
print(game.roll())
|
2a3051f823f33587a585ea1f037e8673105fefc5 | sindhu819/Competitive-Coding-10 | /Problem-129.py | 751 | 3.90625 | 4 | '''
Leetcode- 122. Best Time to Buy and Sell Stock II - https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Time complexity - O(N)
Space complexity - O(1)
Approach - We need to find the peak and valleys in an given array
'''
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if le... |
8dbf93ca05e34953aeb02f90441141cda89c210f | Krokette29/LeetCode | /Python/3. Longest Substring Without Repeating Characters.py | 3,617 | 3.796875 | 4 | class Solution(object):
"""
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"... |
bdb0a9bb90ee4c686bbfc66f42ef0368caaff0f7 | Kozmoz1983/bootcamp_08122018 | /zadanie 4.py | 314 | 3.953125 | 4 | # przykłady input
x = int(input("Podaj wartość x: "))
y = int(input("Podaj wartość y: "))
print("Suma: ", x + y)
# przykłady wartości logiczne
# operatory porównania
# ==, <, >, <=, >=, !=
# ctr + alt + L - pep8
#ctr + /
import datetime
y = (datetime.datetime.now().year)
print (2000 < year)
|
00809250f83280daac47985b059b773728819074 | errai-/euler | /hundredandbelow/prob7.py | 310 | 3.65625 | 4 | # -*- coding: cp1252 -*-
def isprime(laavaa):
for kamal in range(2, int(laavaa**.5 + 1)):
if laavaa%kamal == 0:
return False
laavaa = 0
break
if laavaa != 0:
return True
jouno = []
qwerty = 2
while len(johno) < 10001:
if isprime(qwerty):
johno.append(qwerty)
qwerty += 1
print johno[10000]
|
a5ef192661b50bd86878986510e700e5d2f4b615 | errai-/euler | /hundredandbelow/prob46.py | 632 | 3.71875 | 4 | # -*- coding: cp1252 -*-
import time
aika = time.time()
#hidastuu oddprimen vuoksi, jos joukko alkulukuja laskettaisiin heti alkuun, vältyttäisiin toistoilta
def oddprime(luumu):
k = 1
if luumu%2 == 0: k = 0
for a in range(3,int(luumu*0.5+1),2):
if luumu%a == 0: k = 0; break
return k
eitulosta,roadrunner = 1,9
... |
ce4222854adfff6915cb465dbe0351571bd7fc68 | NataliVynnychuk/Python_Hillel_Vynnychuk | /Lesson/Lesson 9.2.py | 1,172 | 3.75 | 4 | import random
MIN_LIMIT = -1
MAX_LIMIT = 1
def create_point(min_limit=MIN_LIMIT, max_limit=MAX_LIMIT):
point = {"x": random.randint(min_limit, max_limit),
"y": random.randint(min_limit, max_limit)}
return point
def create_triangle(points_name_str: str) -> dict:
return {key: create_point() f... |
7d2beba8951d3f799ebd1bdfce8cc7fc5dceac65 | NataliVynnychuk/Python_Hillel_Vynnychuk | /Lesson/Lesson 9 - 17.07.py | 1,655 | 4.25 | 4 | # Стандартные библиотеки python
# Функции, область видимости, параметры, параметры по умолчанию, типизация
import string
import random
# import random as rnd
#
print(string.ascii_lowercase)
value = random.randint(10, 20)
my_list = [1, 2, 3, 10, 20, 30]
# my_list = [True, False]
my_str = 'qwerty'
choice_from_list = r... |
43d3766d0badef020984eb062c19463dcd898e61 | NataliVynnychuk/Python_Hillel_Vynnychuk | /Lesson/lesson5 - 23.06.py | 3,146 | 3.546875 | 4 | # my_list = [1, 2, 3]
# new_list = [my_list.copy(), my_list.copy(), my_list.copy()]
# print(new_list)
# new_list[0].append(4)
# print(my_list)
# print(new_list)
#
# tmp_value = 5
#
# go_game = True
# text_message = "Введи число от 1 до 10"
#
# while go_game:
# try:
# value = int(input(text_message))
# ... |
b49f67102e945f8e3974411b47590967c0f90e62 | Qiiu/MyPython | /FP.py | 574 | 3.546875 | 4 | import os
fo=open("Test.txt","w")
fo.write("Create a file")
fo.flush()
fo.close()
print("done")
mid=input(":")
fo=open("Test.txt","r")
str=fo.read(5)
print("read the line : ",str)
fo.close()
print("done")
mid=input("change the file name right?:")
os.rename("Test.txt","change.txt")
fo=open("change.txt","r")
print(... |
25f7ea6aa88445177bbe8939b893b70527fe32e5 | glennlopez/Python.Playground | /Lessons/Introduction/4 - Control Flow/modify_username_with_range.py | 189 | 3.609375 | 4 | usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
# write your for loop here
for i in range(len(usernames)):
usernames[i] = usernames[i].lower().replace(' ', '_')
print(usernames) |
6577dc8d52ba60ad9ad4fc3069b43b4ad5718df9 | glennlopez/Python.Playground | /Lessons/Introduction/6 - Scripting/handling_errors_no_handling.py | 287 | 3.515625 | 4 | def party_planner(cookies, people):
num_each = cookies // people
leftovers = cookies % people
return(num_each, leftovers)
num_each, leftover = party_planner(100,'g')
print("Number of cookies each: {}".format(num_each))
print("Number of cookies left: {}".format(leftover))
|
7baa266ef62038c068ba23aa925dc517664fb204 | glennlopez/Python.Playground | /SANDBOX/python3/4_dictionary/dictionary_practice2.py | 740 | 4.0625 | 4 | a = {"Name": "Glenn", "DOB": 1987}
b = []
c = ()
d = {0, 1}
print(type(a))
print(type(b))
print(type(c))
print(type(d))
myDict = {}
print(myDict)
myDict["Name"] = "Glenn"
myDict["DOB"] = 1987
myDict["Age"] = 2019 - myDict["DOB"]
print(myDict)
def get_data():
name = input("What is your name: ")
year = input("... |
e5bae08d87894645b3553505b1a407ed8b83f92c | glennlopez/Python.Playground | /Lessons/Introduction/6 - Scripting/handling_errors.py | 504 | 3.640625 | 4 | def party_planner(cookies, people):
leftovers = None
num_each = None
try:
num_each = cookies // people
leftovers = cookies % people
except ZeroDivisionError:
print("Oops, you entered 0 people will be attending.")
print("Please enter a good number of people for a party.")... |
dc0755a55ce75ca7b9b98acb9d32c4c04663b834 | glennlopez/Python.Playground | /SANDBOX/python3/5_loops_branches/break_continue.py | 332 | 4.28125 | 4 |
starting = 0
ending = 20
current = starting
step = 6
while current < ending:
if current + step > ending:
# breaks out of loop if current next step is larger than ending
break
if current % 2:
# skips the while loop if number is divisible by 2
continue
current += step
pri... |
3549002a69657d11af6c5cbabd75fc53b79eccb6 | kolasau/python_work_book | /countries.py | 338 | 4.09375 | 4 | countries = ['India', 'Germany', 'France', 'Thailand', 'Georgia']
print(countries)
print(sorted(countries))
print(countries)
x = sorted(countries)
x.reverse()
print(x)
print(countries)
countries.reverse()
print(countries)
countries.reverse()
print(countries)
countries.sort()
print(countries)
countries.sort(reverse=True... |
55e8154d08832f8b68cefdd005694e542377ae5d | kolasau/python_work_book | /files and exceptions /guest_book.py | 260 | 3.609375 | 4 | name = "\nPlease enter a name: "
guests_book = 'guests_book.txt'
with open(guests_book, 'a') as gs:
while True:
names = input(name)
if names == 'stop':
break
else:
print(f"Hello, {names.title()}!")
gs.write(f"Hello, {names.title()}!\n")()
|
230e31175a23e817b0d317c46cbf368da5e5cd63 | kolasau/python_work_book | /while/toppings.py | 565 | 3.671875 | 4 | cl_topping = "\n( введите 'жирнюка' чтобы закончить оформление заказа)"
cl_topping += "\nДобавьте топпинг к пицце: "
ctl = []
while True:
message = input(cl_topping)
if message == 'жирнюка':
print("Добавленные топпинги: ")
for t in ctl:
print(f"\t{t.title()}")
break
else:
ctl.append(message)
for t2 ... |
672003e9de2aa2f932ef7bf57cf73562a94d7fd6 | kolasau/python_work_book | /pizza.py | 502 | 3.953125 | 4 | pizzas = ['Cheese', 'Barbeque', 'Lisitsa']
for pizza in pizzas:
print("I like " + pizza + " pizza")
print("I really love pizza!\n")
animals = ['dog', 'cat', 'cow']
for animal in animals:
print("A " + animal.title() + " gives a milk to its babies!")
print("Any of these animals would make a great pet!\n")
friend_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.