blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3a759dd35b448cf686820fcb57c8114df54e13ec | subha996/UI---ML | /Classification/classification_to_df.py | 1,098 | 3.625 | 4 | import numpy as np
import pandas as pd
## This fuunction will convert classification report in to Dataframe.
def classification_report_to_dataframe(str_representation_of_report):
"""A function wich convert classififcation report in to DataFrame"""
try:
split_string = [x.split(' ') for x in str... |
227bc148e930bfa9683490afa3470655369f949b | Jeremy-Yan-Liu/Data-Structure-and-Algorithms | /ch08/tree.py | 8,861 | 4.15625 | 4 | from linkedStackQueue import LinkedQueue
class Tree:
"""Abstract base class representing a tree structure."""
#------------------------- nested Position class ------------------------
class Position:
"""An abstraction representing the location of a single element."""
def element(self):
... |
66b8db38f2ab08c3e4fa806fc60c88bdf8db7070 | sassman/pyslet | /pyslet/rfc2616_core.py | 24,695 | 3.828125 | 4 | #! /usr/bin/env python
import string
from pyslet.unicode5 import BasicParser
class HTTPException(Exception):
"""Abstract class for all HTTP errors."""
pass
class SyntaxError(HTTPException):
"""Raised when a syntax error is encountered parsing an HTTP production."""
pass
HTTPParameterError = Synt... |
a90a1413d74ed0c47e1f3d9f596c0ecd40242ff8 | roshandafal98/JenkinsPython | /list.py | 78 | 3.921875 | 4 | import os
list1=[8,9,3,6,1,10]
list1.reverse()
print("The reversed is",list1)
|
2ddc6c0dbec5599ac061b8e031645ce8ce62570d | shantamsultania/Pythonbasics | /boolean_variables.py | 527 | 4.09375 | 4 | # I check to see if the requirements for honour roll are met
cgpa = float(input('What was your cureent grade (cgpa) '))
lowest_grade = float(input('What was your lowest grade '))
# Boolean variables allow you to remember a True/False value
if cgpa >= .85 and lowest_grade >= .70:
honour_roll = True
else:
honour_roll ... |
a08492d2dd821662d187e7d238688fcf5a7ecdfe | juancsosap/pythontraining | /training/c07_collections/e12_generators.py | 317 | 3.984375 | 4 | def gen_mul(num):
n = 0
while(True):
n += num
yield n
def main():
gen1 = gen_mul(3)
for i in range(10):
print(next(gen1))
num = 5
gen2 = ((n+1)*num for n in range(100))
for i in range(10):
print(next(gen2))
if __name__ == "__main__":
main() |
769b97bbda2b4e545fc16e49ec52a7d89c34b28f | juancsosap/pythontraining | /training/c19_mathplotlib/e01-grid-and-colors.py | 588 | 3.5 | 4 | import numpy as np
import matplotlib.pyplot as plt
# pip install matplotlib
# MAGIC COMMAND FOR JUPYTER NOTEBOOK
# %matplotlib inline
x = np.linspace(-1, 1, 100)
y1 = x ** 2
plt.plot(x, y1, color='red', alpha=0.8, linewidth=5) # string color
y2 = x ** 4
plt.plot(x, y2, color='g') # one letter color
y3 = x ** 6
pl... |
db96f18e45fc5c793387d66788d4deb4a5cefc5e | juancsosap/pythontraining | /training/c17_numpy/e18-finance-func.py | 4,133 | 3.75 | 4 | import numpy as np
# Present Value
# Anual rate (4.5%) to month
rate = (4.5 / 100) / 12
# Number of periods (15 years) to month
nper = 15 * 12
# Monthly investment ($200) out of cash payment
pmt = -200
# Future Value ($150.000)
fv = 150_000
# When will be made the investment each Month
# 'begin' = 1 , 'end' = 0
when ... |
0a78cab37bcdf0f98de74abe006e8cc39894ab99 | juancsosap/pythontraining | /training/c09_functions/e08_closures.py | 1,310 | 3.84375 | 4 | def get_calc(num1, num2, oper):
def add(): return num1 + num2
def sub(): return num1 - num2
def mul(): return num1 * num2
def div(): return num1 // num2
if(oper == 'A'): return add
if(oper == 'S'): return sub
if(oper == 'M'): return mul
if(oper == 'D'): return div
def get_rel(num1,... |
8c5345bb4b17d2c962316e4246744364ee6e28ce | juancsosap/pythontraining | /training/c03_strings/e03_format.py | 3,577 | 4.3125 | 4 | # The text could be modifed using the % operator
# This method is supported but was replaced, then it is not recommended
text = "My name is %s %s and I'm %d years old"
formated_text = text % ("Juan", "Sosa", 36)
print(formated_text, end="\n\n")
# The new way to format the text is using the format method
text = "My nam... |
5982d8d1673215de37d65cb73520e1dccfb3d8a1 | juancsosap/pythontraining | /training/c04_operators/e05_binary.py | 453 | 3.5 | 4 | num1 = 0b1011_1100
print('NUM1 {0:08b}'.format(num1))
num2 = 0b1100_1011
print('NUM2 {0:08b}'.format(num2))
print(' ----------')
num3 = num1 & num2
print('AND {0:08b}'.format(num3))
num4 = num1 | num2
print('OR {0:08b}'.format(num4))
num5 = num1 ^ num2
print('XOR {0:08b}'.format(num5))
num6 = ~num1
print('... |
71a10c85fd93c63ac38c4a286b7d372ddcd00b66 | juancsosap/pythontraining | /training/c19_mathplotlib/e08-fill-graph.py | 518 | 3.6875 | 4 | import numpy as np
import matplotlib.pyplot as plt
# pip install matplotlib
x = np.linspace(-3, 3, 100)
y1 = x ** 4 + x ** 3 + x ** 2 + x - 10
y2 = 10 * x - 10
plt.plot(x, y1, label='Poligon', color='red')
plt.plot(x, y2, label='Line', color='blue')
plt.fill_between(x, y1, y2, where=(y1 > y2), facecolor='orange', al... |
8f4c49e8279f46d819d3e6ff69b4bc712a95ccba | juancsosap/pythontraining | /training/c09_functions/e02_function_options.py | 811 | 3.765625 | 4 | def sumar(a, b):
return a + b
def multiplicar(a, b, c=1, d=1):
return a * b * c * d
def sumar_muchos(*args):
result = 0
for val in args:
result += val
return result
def printdata(**kwargs):
for key, val in kwargs.items():
print('{}: {}'.format(key.capitalize(), val))
def ... |
3fb2fb04d9930dfac4db7d852a8227fc6af9f78d | juancsosap/pythontraining | /training/c10_poo/examples/vector.py | 1,805 | 3.78125 | 4 | import math
class Vector:
__count = 0
def __init__(self, x=0, y=0, z=0, obj=None):
self.__x, self.__y, self.__z = 0, 0, 0
if(type(x) is int):
self.__x = x
if(type(y) is int):
self.__y = y
if(type(z) is int):
self.__z = z
Vector._Vecto... |
1c07b1f10c3a931015ffe025437124edf10c99c7 | juancsosap/pythontraining | /training/c10_poo/examples/persona.py | 1,538 | 3.734375 | 4 | class Persona:
__cantidad = 0
__last_id = 0
def __init__(self, nombre, edad=0):
self.__set_nombre(nombre)
self.__set_edad(edad)
self.__id = Persona._Persona__last_id + 1
Persona._Persona__cantidad += 1
Persona._Persona__last_id += 1
def get_id(self):
ret... |
e2c52eb53458c9e82d5d16b2ec592edeafaddbab | juancsosap/pythontraining | /training/c07_collections/e10_looping.py | 1,780 | 4.34375 | 4 | # For Each loop could be used to read the elements of the collection
days = ('DOM', 'LUN', 'MAR', 'MIE', 'JUE', 'VIE', 'SAB')
for day in days:
print(day)
print('-------------------------------------------------------------')
# For Each loop could not be used to modify the values of the elements of a collection
pr... |
9ee6d608d56c386f46fb2fa23333106bcc479b67 | juancsosap/pythontraining | /training/c03_strings/e04-unicode.py | 201 | 3.8125 | 4 | # -*- coding: utf-8 -*-
texto = 'El niño está comiendo.'
print(texto)
texto = u'El niño está comiendo.'
print(texto)
print(texto.encode('utf-8'))
print(texto.encode('utf-8').decode('latin-1'))
|
a81c23cbaa25270dab670069a65f893a7b2b95b4 | juancsosap/pythontraining | /training/c16_tkinter/examples/calc/view.py | 1,028 | 3.78125 | 4 | import tkinter as tk
from controller import CalculatorController as Controller
class CalculatorView(tk.Tk):
def __init__(self):
super().__init__()
self.title("Calculator")
self.__add_elements()
self.controller = Controller(self)
self.mainloop()
def __add_el... |
33d9136b7ab3190f8bd33f79a73bc137818adcc0 | juancsosap/pythontraining | /training/c06_loopblocks/e04_infinite_loop.py | 271 | 4 | 4 | while(True):
hora = input("¿Que hora es? ")
if(hora.isnumeric()):
hora_int = int(hora)
if(hora_int >= 0 and hora_int < 24):
break
print("dato no valido")
condi = hora_int > 6 and hora_int < 18
print("dia" if condi else "noche") |
be50147266e3776459fcab48ea7d4bfc5c594ce6 | juancsosap/pythontraining | /training/c11_exceptions/e07_error_applied.py | 253 | 3.921875 | 4 | def is_int(text):
try:
int(text)
return True
except:
return False
if __name__ == "__main__":
num = input('Number: ')
if(is_int(num)):
print('Result:', int(num)**2)
else:
print('Invalid Input') |
37f88d25d0ffb54288013ab9e070fdb740b79b15 | juancsosap/pythontraining | /training/c10_poo/e03_fields.py | 235 | 3.828125 | 4 | class Person:
def __init__(self, name, age=0):
self.name = name
self.age = age
if __name__ == "__main__":
p1 = Person('Juan')
print(p1.name, p1.age)
p2 = Person('Carlos', 10)
print(p2.name, p2.age)
|
b9e40414efd6c4dc38d4dc067655c74fe3521bcf | juancsosap/pythontraining | /training/c10_poo/e04_methods.py | 294 | 3.78125 | 4 | class Person:
def __init__(self, name, age=0):
self.name = name
self.age = age
def print(self, text):
print(text, self.name, self.age)
if __name__ == "__main__":
p1 = Person('Juan')
p1.print('P1:')
p2 = Person('Carlos', 10)
p2.print('P2:')
|
11c6d9c8697fba6b3728335c356bcce59ad28901 | juancsosap/pythontraining | /training/c30_tools/timeit-example.py | 542 | 3.578125 | 4 | import timeit
def testlc(max):
lista = [x**3 for x in range(max)]
print(len(lista))
def testfl(max):
lista = []
for x in range(max):
lista.append(x**3)
print(len(lista))
if __name__ == '__main__':
max = 30_000_000
time = timeit.timeit("testlc({})".format(max), setup="from __mai... |
85271662d6b918dba99abb224740a9166c9c69b0 | juancsosap/pythontraining | /training/c25_flask/examples/world_api/cities/city.py | 2,653 | 3.71875 | 4 | # -*- coding:utf-8 -*-
class City:
def __init__(self, city_id, name='UND', country_code='UND', district='UND', population=0):
self.__city_id = city_id
self.__name = name
self.__country_code = country_code
self.__district = district
self.__population = population
@prop... |
3ae140fefb45114f48eb3c63003f0e7a327ae6fb | sujoysinha/python_repo | /Tuples/tuple-operations.py | 162 | 3.609375 | 4 | t1 = tuple()
t2 = (10)
t3 = (10, 20, 30, 'H', 'P')
t4 = (10, 20, 30)
t5 = 10, 20, 30
print(t1)
print(t2)
print(t3)
print(t4)
print(t5)
print(t5[0])
print(t5[-1]) |
6d3dd6418c9031443914fdb93e4738a9c9502f7f | rainyandsunny/PythonLearning | /pythonLearn/test13.py | 1,241 | 3.59375 | 4 | #!/usr/bin/python
# -*-coding: UTF-8 -*-
# 正则表达式
import re
re.match(r'^\d{3}\-\d{3,8}$', '010-12345678')
# 切分字符串
re.split(r'\s+','a b c')
# 分组(用()表示的就是要提取的分组(Group))
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
# 贪婪匹配
result = re.match(r'^(\d+)(0*)$', '102300').groups() # ('102300', '') 由于\d+采用贪婪匹配,直接... |
0e0a57005e02985ce9b8f4396a8cb5a218af6543 | chelmes/JobLog | /logger/item/item.py | 3,019 | 3.78125 | 4 | import datetime as dt
class Item:
"""One entry for the DataFrame of the Log. It is able to store time
information names and ids for each entered activity
"""
def __init__(self, name, net_time, date_start=None, date_end=None):
"""Constructor of the class
Inputs
------
n... |
d8d4dbd68cae22d5da9b2a677534f946e05cb3e2 | CGEO97/Clustering-stocks-project | /03_Get_full_data_set_SP500.py | 4,656 | 3.5 | 4 | ##### Program 3: Get stock prices of SPY500 and merge data with index/commodity prices
import pandas as pd
import quandl
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import pickle
# Set Quandl API key
quandl.ApiConfig.api_key = "GsT-jhY8mPatmzkh9yz8"
## 1. Import .csv fil... |
f46e82a7df24725fdacec7317b69772cb1ee2339 | diyansharout/python | /Spiralmyname.py | 416 | 3.9375 | 4 | import turtle
t = turtle.Pen()
t.speed(0)
turtle.bgcolor("black")
colors = ["red", "yellow", "green", "purple"]
# Pop up window ( asking user for their name)
your_name = turtle.textinput ("Enter your name", "What is your name?")
for x in range(100):
t.pencolor(colors[x % 4])
t.penup()
t.forward( x*4)
t.... |
251f15d3845795e6b672734cc7b725440daf5c15 | diyansharout/python | /table.py | 146 | 3.890625 | 4 | # value = 6
# for x in range(11):
# print(x*6)
value = 6
number = (1)
start = 6*number
for x in range(11):
print(start)
print(6*x)
|
606055ee449eb9c9177847f3eb0b2df07764936f | diyansharout/python | /test.py | 235 | 3.515625 | 4 | import turtle
pen = turtle.Pen() # this will give you reference to a pen
pen.speed(1)
colors = ["blue","purple","pink","turquoise"]
for x in range (100):
c = colors[x%4]
pen.pencolor(c)
pen.forward(x+10)
pen.right(90) |
30d010a246072766ec6f7163f96d2f20bb7f8e03 | Kevin-Zheng-1/Leetcode | /Algorithm/String/0014. Longest Common Prefix.py | 1,167 | 3.75 | 4 | # Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
# Method 1
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
s1 = min(strs)
... |
9fc4c4d88bcc47eba49c57e6a0c34164bad5bc29 | cgcianschapter/Weekly-Challenges | /Week 2/Python/TWOVSTEN.py | 151 | 3.859375 | 4 | for _ in range(int(input())):
x = int(input())
if(x%10 == 0):
print(0)
elif(x%5 == 0):
print(1)
else:
print(-1) |
dbf8a52dd6fbd0937a1cae85720f584739fc69a2 | Eusebiu10/Hotel-app | /HotelAnwendungApp/Controllers/Functions.py | 2,084 | 3.578125 | 4 | from datetime import datetime
class Functions:
def __init__(self):
pass
def set_zimmerMenu(self, zimmerMenu):
self.zimmerMenu = zimmerMenu
def set_gasteMenu(self, gasteMenu):
self.gasteMenu = gasteMenu
# Get all guests with current or future booking - compare ... |
1ce97e6d2b6a996c89c46613e49f21d63d951501 | SemperFidelisTyrannosaurus/NeuralNetworkProject | /input_example.py | 1,808 | 3.53125 | 4 |
import numpy as np
import tensorflow as tf
def np_example():
"""Demonstrate possible mehtod for encoding input for project.
The four letter alphabet is encoded along the 2nd dimension (rows).
Columns are concatenated together to form strings to be used as a signal or
filter.
When convolved, if the filte... |
913179f9aba3a9cedc656dadd0a1b73c34eb7dc4 | peppelongo96/coding-LT-ing-informatica-unical | /fondInformatica/python/Terne pitagoriche.py | 590 | 4.09375 | 4 | while True :
import math
print(" ")
max= int (input("Inserisci limite delle terne: "))
print (" ")
numero=0
for a in range (1,max):
for b in range (1,max):
c=int(math.sqrt (a**2+b**2))
if c**2==a**2+b**2:
numero=numero + 1
p... |
751be0bb6e05086600584e7c697d64049a9eec15 | peppelongo96/coding-LT-ing-informatica-unical | /fondInformatica/python/(funzione tocco e stop).py | 352 | 3.5 | 4 | import turtle
def main():
wn=turtle.Screen()
peppe=turtle.Turtle()
peppe.left(100)
g=turtle.Turtle()
g.penup()
g.goto(-50,80)
g.pendown()
g.forward(300)
print(peppe.ycor(),g.ycor())
while not int(peppe.ycor())-g.ycor() == 0:
print(int(peppe.ycor()),g.ycor())
pe... |
eebb76e3c1354502d6b89d8408a069857af82108 | peppelongo96/coding-LT-ing-informatica-unical | /fondInformatica/python/calendario_perpetuo.py | 2,771 | 3.515625 | 4 | def leggi_anno():
anno = int(input("Inserisci l'anno: "))
while anno < 1583 :
print("L'anno inserito non è gregoriano.")
anno = int(input("Inserisci di nuovo l'anno: "))
return anno
def anno_bisestile(anno):
if anno%100==0 and anno%400!=0:
return False
elif anno%4==0:
... |
ac0eff38a8381317e9e40b6f649f2f2dc5f313c0 | kelmore5/Morrison | /m10d11/Copying a file.py | 672 | 3.5625 | 4 | import sys
import os.path
if len(sys.argv) < 3:
print("You need a donr and recipient file")
sys.exit()
donor = sys.argv[1]
recipient = sys.argv[2]
if not os.path.exists(donor):
print("The file %s does not exist, fool." % donor)
sys.exit()
if os.path.exists(recipient):
choice = input("Do you want t... |
541674c663a6fd3c29df834b4911843a9a60cd14 | kelmore5/Morrison | /m10d04/Triangle.py | 311 | 3.640625 | 4 | def triangle(char, size):
if size == 0:
return
triangle(char, size - 1)
print(char * size)
def triangle2(char, size):
if size == 0:
return
print(char * size)
triangle2(char, size - 1)
triangle("*", 10)
print("**************on acid***************")
triangle2("&", 12)
|
8b763357a2e7b11313257b4f18f959e2d6a6bbdf | kelmore5/Morrison | /m09d26/Return Last Char.py | 1,123 | 4.25 | 4 | def last_char(xy):
"""prec: x is a string
postc: returns the last character of the string."""
return xy[-1] # method stub or function stub
def last_non_whitespace_char(xy):
"""prec: x is a string
postc: returns the last non-whitespace character"""
y = xy.rstrip()
return y[-1] #... |
6adbfaa344863f083a37031b37d857632a3b2642 | quique280/servidor_django | /pruebas/src/tree.py | 530 | 3.515625 | 4 | '''
-María Álvarez Hernández
-Luis ALonso Calderón Achío
-Enrique Díaz Delgado
-Derian Sibaja Chavarría
'''
class Tree():
def __init__(self, value):
self.children = []
self.value = value
def addChild(self, otherTree):
self.children.append(otherTree)
def isLeaf(self):
return ... |
9b84b0020548eaae87886d51020b3cdafd184e9d | ancer7/py | /bmi.py | 458 | 4.1875 | 4 | Height=float(input("enter height in kg: "))
Weight=float(input("enter weight in cm: "))
Weight = Weight/100
BMI = Height/(Weight**2)
print("your Body Mas Index is:", BMI)
if(BMI<16):
print("your are severely underweight")
elif (BMI >= 16 and BMI < 18.5):
print("you are underweight")
elif(BMI >=18.5 and BMI < ... |
d867122d5ad39a9dc042fad186d97ca28b581db3 | javon27/sorts_analysis | /heap.py | 1,163 | 3.953125 | 4 | def heapsort(lst):
for start in range((len(lst)-2)/2, -1, -1):
siftdown(lst, start, len(lst)-1)
for end in range(len(lst)-1, 0, -1):
lst[end], lst[0] = lst[0], lst[end]
siftdown(lst, 0, end - 1)
return lst
def siftdown(lst, start, end):
root = start
while True:
child = r... |
869d19f8e8c9284132ec90a5791fcbed69cf9f9c | akilonzo/pythonwork | /Assignment3.py | 551 | 4.0625 | 4 | print ("Enter First and Last Name:")
fname = input('First name :')
lname = input('Last name :')
fullnames = fname + " " + lname
print("Enter Customers Phone Number: ")
phone = input('Phone No')
print("Enter Customer's email address: ")
email = input('email')
price = 10000
has_good_credit = True
if has_g... |
30f5a8a4bedcdd83bc7d8bed10131f647c4264ea | dbolling-git/ecoplate_processing | /verify.py | 426 | 3.640625 | 4 | import pandas as pd
def verify_df(dataframe):
is_good_df = True
if len(dataframe) % 8 != 0:
is_good_df = False
print('Rows are missing.')
for col in dataframe.columns:
if dataframe[col].isnull().any():
is_good_df = False
print(f'Column {col} is missing value... |
a45ffeadf7c60bf9d957c6bf54e532ecc03b36cd | hoctor/median | /main.py | 461 | 4.03125 | 4 | fname = raw_input("(Entre com o nome do arquivo) Enter file name: ")
num_words = 0
num_char = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
num_char += sum(len(word) for word in words)
median = float(num_char/float(num_words))
print("(Numero ... |
8612c9d8c64fb1681fd9e3e8bf6b708a6b1d4b16 | lienpo/Dating-Simulation-Rough-Draft- | /DS/player.py | 5,171 | 3.71875 | 4 | from location import Location
#from item import Item
class Player:
def __init__(self, Location_I):
self.current_loc = Location(Location_I)
'''
self.academics = 0
self.fitness = 0
self.social = 0
self.confidence = 0
self.academics_level = "MEDIUM"
self.fitnes... |
c99a4bc31e4330d790eb2de99e5a3c36c49c5676 | abhishekupadhyaya/PythonScripts | /unique_chars.py | 153 | 3.75 | 4 | # determine if a string has all unique characters
def main(string):
print(len(set(string)) == len(string))
if __name__ == '__main__':
main("input")
|
4172c79e0e53a9952ddb93a715e2c189860b6f2c | CandleStein/VAlg | /Sorting/algos/radix.py | 810 | 3.734375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def countingsort(arr, exp):
n = len(arr)
output = [0] * len(arr)
count = [0] * 10
for i in range(0, n):
idx = int(arr[i] / exp) % 10
count[idx] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
whil... |
ee61ae001fae758a33c957fb48b78e80f20e4022 | CandleStein/VAlg | /Sorting/algos/merge.py | 1,029 | 3.640625 | 4 | import numpy as np
import matplotlib.pyplot as plt
def merge(arr, start, mid, end):
temp_arr = np.array(arr)
i = start
j = mid
k = start
while i < mid and j < end and k < end:
if arr[i] <= arr[j]:
temp_arr[k] = arr[i]
i = i + 1
else:
temp_arr[k] ... |
142fa6e0f8bc2a5d0fcaa997684af67fdb2b7870 | kaixi-learn/LeetCode | /linkedlist-medium/328.Odd-Even-Linked-List.py | 823 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p_odd = ListNode(-1)
p_odd... |
2c5a0be63c84ddbb700c1f19842a18877119cf9e | jadikerjadiker/firstworkspace | /Random Testing/SlicingStrings.py | 305 | 4 | 4 | #Yes, the last number in a slice can be one higher than the possible index of the string.
#it returns the substring right up to (but not including) the second index given
#if the two indexes are the same it gives an empty string
a = "h"
b = a[0:1]
print(b)
a = "abcde"
print(a[:3])
print(a[1:1], a[1:2]) |
19741b2184c17797b598d98700c45517d5a86fb2 | jadikerjadiker/firstworkspace | /Random Testing/Does python re-eval.py | 197 | 4.125 | 4 | i = 0
test = "test"
while i<len(test):
print(i)
if i<3:
test = test+"hello"
i+=1
# i prints up to 18, so yes, it re-evaluates len(test) every time it goes through the loop. |
7810f6c549cbc35813dc45cb97c40e160f84ca42 | jadikerjadiker/firstworkspace | /Random Testing/ListToSetMutable?.py | 193 | 3.9375 | 4 | #The list does not change when values are added to the set and vice versa
a = [1, 2, 3, 1, 2, 3, 4, 5, 6]
b = set(a)
print(a)
print(b)
b.add(9)
print(a)
print(b)
a.append(10)
print(a)
print(b) |
da58a547b2c03c8dd59aced90893b6dad5a72fd6 | jadikerjadiker/firstworkspace | /Random Testing/Testing_IO/readlineLastReturn.py | 331 | 4.0625 | 4 | with open("TheFile.txt") as f:
for i in range(10):
read = f.readline()
if read == "":
print("that was empty") #this signifies the end of a file
if read == None: #this should never be returned
print("that was none")
print("Type: {}".format(type(read)))
... |
5a8b6a7ee1f80ad63f45e96597e7f366dbbedbff | jadikerjadiker/firstworkspace | /RegexHelpers/Readable Scramble.py | 938 | 3.96875 | 4 | import re
import random
def editText(text):
ans = text.split()
def scrambleWord(w):
if len(w)<=3: #if the word is too short to be scrambled
return w
def scrambleInnerLetters(lttrs):
return ''.join(random.sample(lttrs, len(lttrs)))
... |
ab74e70e495161f0e564d9b6581aab572b619b9d | jadikerjadiker/firstworkspace | /Random Testing/AreEmptyStringsFalse.py | 148 | 3.890625 | 4 | #Yes: ""==False
a = ""
if a:
print("True!")
else:
print("False!")#Yes: ""==False
a = ""
if a:
print("True!")
else:
print("False!") |
6e4574c94e93c1d739e0da02149996af2d6392e9 | ntuple/pyfossnp | /Day 2/final_hangman.py | 1,660 | 4 | 4 | # $Id: hangman.py ,v 1.00 2010/08/23 12:01:54 Abhainv Exp $
#@file hangman.py - a simple game of guessing letters of a word
#@Author Abhinav S. Dangol (YIPL)
import random
def generate_word():
word_dict = { 'orange': 'Name of a fruit' ,
'leg': 'a body part',
'basketball': '... |
62b38405617d5610c2529ac76d24c6d953573356 | ntuple/pyfossnp | /Day 5/day5_6.py | 418 | 4.09375 | 4 | '''Mobile phone Number generator:
Your input and output should resemble the following examples.
Example 1:
Input phone number: 1-800-FLO-WERS
The real phone number is 1-800-356-9377'''
import string
input = "1-800-FLO-WERS"
value = 1
dict = {}
#d = dict.fromkeys(string.ascii_lowercase, 0)
for x in string.ascii_lower... |
492d6f55dc92015d8155fb06179afe24d795c727 | roudra323/100-Days-of-code-Python-pro-Bootcamp | /codes/Day-5/highest_num.py | 174 | 3.828125 | 4 | # find the highest number from a list
# ls = int(input())
ls = [43, 21, 23, 65, 16, 44, 56]
temp = 0
for i in ls:
if i > temp:
temp = i
print(temp)
|
8af49ddb46a15b51464e6d740ad3b3870c8d58f1 | Wurdalac/homework | /function.py | 1,467 | 4.125 | 4 | menu = {}
menu['1']="Function 1."
menu['2']="Function with login"
menu['3']="Function 3"
menu['4']="Exit"
while True:
options=menu.keys()
for entry in options:
print(entry), menu[entry]
selection=input("Please Select: ")
if selection =='1':
lastname = input('Enter firstname: ')
... |
1223c6ea83648a139bc63bde76943dcba56489dd | DilshodN/8-puzzle | /app/CheckPuzzle.py | 2,680 | 3.859375 | 4 | class CheckPuzzle:
"""
Class that checks puzzle
"""
def __init__(self, puzzle: list):
"""
Constructor
"""
self.puzzle = puzzle
self.len = len(puzzle)
if self.len == 3:
self.set = {i for i in range(9)}
self.set.add(0)
sel... |
8c1e071a96303708876bee1bec150c52115a75e8 | Brac24/GameOfLife | /list_comp_practice.py | 292 | 3.9375 | 4 | import random
rows = 4
cols = 5
board = []
#add the row of zeros to the board
#This shows a nested list comprehension
board = [[0 for row in range(rows)] for col in range(cols)]
board = [[1 if random.random() >= .9 else 0 for row in range(rows)] for col in range(cols)]
print(board)
|
7e9b5975cb95d32e66aa6be8bdd7312cbfe17a64 | yashsam99/Encryption-Tool | /crypto.py | 1,007 | 3.515625 | 4 | import tkinter as tk
from tkinter.filedialog import askopenfilename
def encryptt():
f=askopenfilename(filetypes=[('Text',['*.TXT'])])
file = open(f,"r")
msg = file.read()
file = open("key.txt","r")
key = file.read()
encryped = []
for i, c in enumerate(msg):
key_c = ord(ke... |
5ef3c657a472bbfc29af735f751acfe92ded5bdb | juliakimchung/my_python_ex | /if_statement.py | 1,346 | 4.1875 | 4 | should_continue = True
if should_continue:
print("hello")
known_people = ['John', "anna", "mary"]
person = input("enter the person you know")
if person in known_people:
print("you know {}!".format(person))
else:
print ("you don't know{}!".format(person))
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Modify th... |
aa78cf76328fe3a4a07cd6ce9bdea7c9b17aa573 | nargiza-web/htx-immersive-08-2019 | /02-week/2-wednesday/labs/nargiza-web/hard-python-functions/1p_tic_tac_toe.py | 336 | 3.53125 | 4 | game = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
def game_board(player=0, row=0, column=0, just_display=False):
print(" a b c")
if not just_display:
game[row][column] = player
for count, row in enumerate(game):
print(count,row)
game_board(just_display = True)
#game_board(playe... |
dcd7000d110e865b1fa9815d5cd985e5f5b7278e | PRaNenS/python | /ErrorOccur.py | 2,318 | 3.625 | 4 | # 임의 에러 발생
class BigNumberError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
# 예외 처리
try:
print("한자리 숫자 나누기")
num1 = int(input("숫자1 >"))
num2 = int(input("숫자2 >"))
if num1 >= 10 or num2 >= 10:
raise BigNumberError("입력값: {0}, {1}... |
09bfe8471771c66a5f57a289eceeb9f899f58284 | PRaNenS/python | /Value.py | 853 | 3.84375 | 4 | #숫자
print(5)
print(-10)
print(3.14)
print(1000)
print(5+3)
print(2*8)
print(3*(3+1))
#문자열
print('풍선')
print("나비")
print("ㅋㅋㅋㅋㅋㅋㅋㅋㅋ")
print("ㅋ"*9)
#참/거짓
print(5 > 10)
print(5 < 10)
print(True)
print(False)
print(not True)
print(not False)
print(not (5 > 10))
#애완동물
animal = "강아지"
name = "연탄이"
age = 4
hobby = "산책"
is_a... |
3945b3b05ffaa64839c2789e864686c3645d338c | mleijon/AoC2019 | /day3B.py | 1,641 | 3.6875 | 4 | def maketrack(start_point, move):
stp_lst = []
move_direction = move[0]
move_size = int(move[1:])
origin = start_point
if move_direction == 'R':
stp = (0, 1)
elif move_direction == 'L':
stp = (0, -1)
elif move_direction == 'U':
stp = (1, 0)
elif move_direction == ... |
dcba1bcc39481052f5e2b519bcc18a2339a98531 | mleijon/AoC2019 | /day4A.py | 599 | 3.796875 | 4 | if __name__ == '__main__':
selected_numbers = []
final_selected_numbers = []
doubles = ['11', '22', '33', '44', '55', '66', '77', '88', '99']
for count in range(382345, 843168):
number = list(map(int, list(str(count))))
if (number[0] <= number[1] <= number[2] <= number[3] <= number[4] <=... |
15d2529189bcecc3e52ebb7783a8828f19dd83b0 | veronicakkv/CS3027-Robotics | /src/robotics/scripts/maplisten.py | 1,794 | 3.515625 | 4 | #!/usr/bin/env python
"""
Map Listen Script
Listens to map server and inflates map producing a represntation of the map used for path planning. Written that map to a file called grid.txt
Written by Bradley Scott
Student ID:51661169
Email: b.scott.16@aberdeen
"""
import rospy
from nav_msgs.msg import OccupancyGr... |
ac90351502a245e3e3d696ed3584b7482d8bf1f1 | nionu0430/waggles | /moduleTest/motor/servoTest.py | 978 | 3.96875 | 4 | # Use Raspberry Pi to control Servo Motor motion
# Tutorial URL: http://osoyoo.com/?p=937
import RPi.GPIO as GPIO
import time
import os
GPIO.setwarnings(False)
# Set the layout for the pin declaration
# The Raspberry Pi pin 11(GPIO 18) connect to servo signal line(yellow wire)
# Pin 11 send PWM signal to control ser... |
b3989b15d7efbf2bf4f206f4c19c6fc1b986f966 | rictts/Gestao-de-Turmas | /cria_BD_Turmas.py | 1,115 | 3.578125 | 4 |
import os
import sqlite3
dbName = "Turmas.db"
global conn
conn = sqlite3.connect(dbName)
sql = """
CREATE TABLE aluno(
id_aluno integer primary key not null,
Nome_Aluno text,
Morada_Aluno text,
CC_Aluno integer,
Idade_Aluno integer);
"""
conn.executescript(sql)
sql = """
CR... |
6ffd98d1acdce3dc5ab8c7f81b526f516f14a4c5 | nirhjah/COSC262-Algorithms | /adjacency_list.py | 930 | 3.65625 | 4 | def adjacency_list(graph_str):
"""Takes a graph string and returns the adjacency list"""
lines = graph_str.splitlines()
header = lines[0].split()
if len(header) > 2:
graph_type, vertices, weight = header[0], header[1], header[2]
else:
graph_type, vertices = header[0], header[1]
... |
6db3a99474384b7e04691d495a46aec399f3d651 | nicecode996/Python_Test | /数据结构/字典.py | 160 | 3.625 | 4 | # coding=utf-8
# !/usr/bin/env python3
dict({102:'张三',105:'李四',109:'王五'})
print(dict)
student_list = {'102':'张三','105':'李四','108':'王五'} |
2c278cf8a7e8b1486704e7ea47431c65678c766b | nicecode996/Python_Test | /面向对象编程/python_Object.py | 816 | 3.984375 | 4 | # !/usr/bin/env python3
# coding:utf-8
# __srt__()方法
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
template = 'Person [name={0},age{1}]'
s = template.format(self.name, self.age)
return s
person = Person('Tony', 18)... |
3a9db9dacbce79b30b675f72958c6c7c26f38c18 | nicecode996/Python_Test | /python基础/位运算符.py | 452 | 3.9375 | 4 | # coding=utf-8
a = 0b10110010
b = 0b01011110
print("a | b = {0}".format(a | b)) # 0b1111110
print("a & b = {0}".format(a & b)) # 0b00010010
# print("a ^ b = {0}").format(a ^ b) # 0b11101100
# print("~a = {0}").format(~a) # -179
print("a >> 2 = {0}".format(a >> 2)) # 0b00101100
print("a << 2 = {0)".format(a << 2)... |
09832a7167a22aa199415c794f00b6cfc03cf8ef | nicecode996/Python_Test | /python基础/for.py | 808 | 3.90625 | 4 | # !usr/bin/env python 3
# coding=utf-8
print("----范围------")
<<<<<<< HEAD
for num in range(1,100):
print("{0} * {0} = {1}".format(num ,num * num))
=======
for num in range(1, 10):
print("{0} * {0} = {1}".format(num , num * num))
>>>>>>> 7250e8d (第三次提交)
print("----范围------")
# for语句
for item in 'Hello':
... |
1538d7cbd003892481faf972b19b2b0812b49649 | nicecode996/Python_Test | /python基础/赋值运算符.py | 418 | 4.09375 | 4 | # coding=utf-8
a = 1
b = 2
a += b
print("a | b = {0}".format(a))
a += b + 3
print("a + b + 3 = {0}".format(a))
a -= b
print("a - b = {0}".format(a))
a *= b
print("a * b = {0}".format(a))
a /= b
print("a / b = {0}".format(a))
a %= b
print("a % b = {0}".format(a))
print("--------------------------")
a = 0b10110010... |
7c8382f9b5d3bc5a7a371dfa67c0146ed93f6a96 | eballo/pythonchallenge | /07/07.py | 840 | 3.6875 | 4 | # http://www.pythonchallenge.com/pc/def/oxygen.html
from urllib.request import urlopen
from PIL import Image
image = Image.open(urlopen("http://www.pythonchallenge.com/pc/def/oxygen.png"))
print(image)
size = width, height = 629, 95
#image.show()
print(size)
for x in range (0, size[0]):
for y in range (0, size[1... |
ff266d0d3704ce26db11ef8edd1fc41499719da0 | rocky-wang/learnPy2 | /senior/iteration/create_iter.py | 1,181 | 4.25 | 4 | # coding: utf-8
# 3-1 如何实现可迭代对象和迭代器对象(1)
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# for循环的背后,确保in后边为可迭代对象,因为in会自动将后面对象进行iter()升级
# 可迭代对象可以由内置函数iter得到一个迭代器对象
# 注意:可迭代和迭代器对象概念区别,不要混淆
# iterable:需要实现__iter__或者__getitem__接口
# itertor:需要实现next方法,访问时只能通过next()获取数据
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>... |
bc168c4148e659dcbfe1785d1c606f5c30b53e99 | rocky-wang/learnPy2 | /senior/baseDS/count_value.py | 1,957 | 3.6875 | 4 | # ^_^ coding: utf-8
# 2-3 如何统计序列中元素的出现频率?
"""
1、某随机序列[12, 5, 6, 4, 6, 5, 5, 7,...]中,
找到出现次数最高的3个元素,他们出现次数是多少?
2、对某英文文章的单词,进行词频统计,找到出现次数最高的10个单词,
他们出现次数是多少?
"""
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
# 普通方法:
# 1、先产生一个字典,用随机数作为key值
# 2、遍历随机数,将key值相同的累加
# 3、排序输出
# -------------------------------------------... |
c8263319069507a9dd4a04802ee7caec10a359a3 | rocky-wang/learnPy2 | /cookbook/01.ds/10set.py | 408 | 3.875 | 4 | # ^_^ coding: utf-8
# 删除重复元素,并保证依然按照顺序,如果只用set方法,不能保证顺序
a = [1, 5, 2, 1, 9, 1, 5, 10]
# b = set(a)
print a
# print b
def mydeque(items):
seen = set()
for item in items:
if item not in seen:
yield item # 若不加,则变为普通集合返回,仍然无序
seen.add(item)
print list(mydeque(a))
|
d29b0b0d0b3742e1a601f666f3ca467328429c3d | darkmatter18/Udacity-Computer-Vision-Nanodegree | /CVND_Exercises/3_5_State_and_Motions/4. matrix.py | 2,136 | 3.890625 | 4 |
def zeroes(height, width):
""" Creates a matrix of zeroes. """
g = [[0.0 for _ in range(width)] for __ in range(height)]
return Matrix(g)
class Matrix(object):
# Initializes a matrix from a 2D grid of values
# Assumes and initializes a grid-specified number of rows and columns
def __ini... |
017be4b455baf14441f5137ac493a0513dc39af5 | Songsonge/2DGP | /2주차 과제/py_01_03_2017180018_2.py | 378 | 3.578125 | 4 | import turtle as t
size=100
count=5
linelength=count*size
t.penup()
t.goto(-200,-200)
t.pendown()
def line(start,end):
t.penup()
t.goto(*start)
t.pendown()
t.goto(*end)
x1,y1=t.pos()
x2,y2=x1+linelength,y1+linelength
for i in range(count+1):
n=i*size
line((x1,y1+n),(x2,y1+n))
line((x... |
d055a40f41da3dfb9201bc6e16a0daab79ff2aa4 | dearieme/Hangman-Game-Modular | /code/Hangman_Main.py | 5,296 | 3.90625 | 4 | import random
from pygame import mixer
import time
def Display_Menu():
print("""Hello and welcome to hangman. Choose an option:
1: Play against the computer
2: Play against another player
""")
def Get_Choice():
choice = "0"
while choice != "1" and choice != "2":
choice... |
793171b07cd1fad373696b0f840cfb518820a1e2 | 16nishma/wordcloud-twitter | /TextBlobTwitter.py | 3,499 | 3.609375 | 4 | import json
from textblob import TextBlob
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# am opening tweets_small.json and assigning to a variable called tweetFile
tweetFile = open("tweets_small.json", "r")
# load json from our tweet file
tweetList = json.load(tweetFile)
#close our file ... |
3e0128e799f7ed30e65f4989744a0dd84c3219a1 | NiramayThaker/Python | /logical_practice/HACKERRank_mix_max.py | 837 | 3.859375 | 4 | import math
import os
import random
import re
import sys
def miniMaxSum(arr):
min_of_arr = min(arr)
max_of_arr = max(arr)
try:
max_sum = 0
for i in arr:
if i!=max_of_arr:
max_sum += i
if max_sum != 0:
print(max_sum)
min_... |
671f0871102a490dddc06671c2ce8dfd6b878599 | mazurkievicz/university | /Primeiro semestre/Raciocínio Algorítmo/Convencoes.py | 3,962 | 3.734375 | 4 | '''
AAP2:
A atividade consiste em trabalhar os algoritmos em 5 funções:
1. Colocar todos os algoritmos dentro de funções.
2. Adicionar os parâmetros corretos nas funções.
3. Adicionar os retornos corretos das funções.
4. Adicionar os argumentos corretos nas chamadas das funções.
5. Adicionar os comentários dos comport... |
18ed8e1924877a425fbc087af981d0475f08da5a | Aa-Rho-Hi/DATA-SCIENCE-AND-BUSINESS-ANALYTICS-INTERNSHIP-PROJECT | /Code.py | 2,669 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## GRIP @ THE SPARKS FOUNDATION¶ DATA SCIENCE AND BUSINESS ANALYTICS INTERNSHIP (SEPT21)
#
# ## Author : Aarohi Mohrir
#
# ## TASK 1 : Prediction using Supervised ML (Level - Beginner)
#
# ## Linear Regression with Python Scikit Learn
# In[18]:
#importing libraries that we... |
e58ce1192919c0758a1cf0f473beeb2a4aec2ef5 | eandtsa/pynet_2019 | /Week_1/week1.py | 305 | 4.125 | 4 | #try to print with Python3 if doesnt work try with Python2 function
try:
ip_addr = raw_input("Enter an IP address (python2): ")
except NameError:
ip_addr = input("Enter an IP address (python3): ")
print(ip_addr)
my_str = "Money"
print(my_str)
print(dir(my_str))
#print(help(my_str.lower))
|
eb78ccc1c393bb7f4826129906ddd11dd0a911a1 | rdharavath-evoke/python-core-concepts2 | /control_structures/conditional-stmts.py | 2,033 | 4.125 | 4 | #Python supports the usual logical conditions from mathematics
#(a==b,a!=b,a<b,a<=b,a>b,a>=b.....)
# 1.if statement (if statement, without indentation (will raise an error))
a=20
b=40
if b>a:
print("b is greater than a")
# o/p : b is greater than a
if b<a:
print("b is less than a")
# o/p : (No output because c... |
9577b00acaac774ee8cb664eedc32830e3c0dc94 | rdharavath-evoke/python-core-concepts2 | /variables-datastructures/variables.py | 1,684 | 4.28125 | 4 | #Think of a variable as a name attached to a particular object
n=300
print(n)
# o/p : 300
#Python also allows chained assignment
#which makes it possible to assign the same value to several variables simultaneously
a=b=c=200
print(a,b,c)
# o/p : 200 200 200
#In many programming languages, variables are statically typed... |
3244fd88a2aa8059d6b4dd7e34d6e7e51b751a4f | rdharavath-evoke/python-core-concepts2 | /variables-datastructures/list.py | 3,081 | 4.3125 | 4 | #Unlike c++ or Java, 'Python' Programming Language doesn't have arrays.
#To hold a sequence of values, then, Python provides the 'list' class.
a=[10,20,30,40,50]
print(a)
# o/p : [10,20,30,40,50]
print(a[0])
#o/p : 10
a=[]
print(a)
#o/p : [] :::empty list
print(type(a))
# o/p : <class 'list'>
a=[10,2.44,"hello"]
pri... |
78c3d1e2efc680b0321b46a5e681403f3eb41902 | rdharavath-evoke/python-core-concepts2 | /python-intro/installation-setup.py | 791 | 4.125 | 4 | ########## Installation on windows #########
'''
Visit the link : https://www.python.org/downloads/ to download the latest release of Python.
In this process, we will install Python 3.8 on our windows operating system.
when we click on the above link, it will bring us the following page.
Step-1 : Select the Python'... |
1daaca77aefd41769dedf93d7fc3a487af229fb2 | Jkimie/final-game | /code.py | 1,037 | 4.15625 | 4 | names = {
'jaden' : "I am awesome",
'marcus' : "I have a slow car",
'jesse' : "I like eating jaden's snacks",
'michael' : "I can easily build and take apart computers"
}
print("Jaden's Code!:")
name = input("Enter name:" )
if name in names.keys():
print("My name is", name, "and", names[name])
else:
print("Sorry... |
1cbaf41f885e433dfbcfc9014daf3661e6e68495 | Jonatan712/Proyecto-1 | /Material.py | 656 | 3.90625 | 4 | print("Elija primero que tipo de material utilizara:")
print("Tipos de Materiales: ")
print("Acero ")
print("Fibra de Vidrio ")
print("Aluminio ")
print("Fibra de Carbono ")
print("Vidrio ")
Acero = 40
Fibra_de_Vidrio = 30
Aluminio = 25
Fibra_de_Carbono = 400
Vidrio = 10
user1 = input()
print("Inserte la cantidad d... |
3f449921ce4338e598dfb0fea633a2ac45207317 | WalaaAbdeltwwab/FAcoders | /Python/week5.py | 330 | 3.59375 | 4 | s1=['Ahmad',18,17,19.5,8,25]
s2=['Sami',20,20,19,9,28]
s3=['Faris',14.5,16,13,7,23]
num=input('Enter Student\'s name: ')
if num==s1[0]:
print(s1[0]+' '+str(sum(s1[1:])))
elif num==s2[0]:
print(s2[0]+' '+str(sum(s2[1:])))
elif num==s3[0]:
print(s3[0]+' '+str(sum(s3[1:])))
else :
print('Student is not rec... |
00e644726c6b255db088970d1180440dec33a3c7 | iamParvezKhan25/Python-Access-Specifier-Practice-OOPS | /multiple2.py | 496 | 3.828125 | 4 | class Base1():
def __init__(self):
self.str1 = "Khan 1"
print("Base 1")
class Base2():
def __init__(self):
self.str2 = "Khan 2"
print ("Base 2")
class Derived(Base1, Base2):
def __init__(self):
# calling Construction of 'Base 1' & 'Base 2'
Bas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.