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 |
|---|---|---|---|---|---|---|
583e0240ea29239e19dff725257fddd772d802b4 | bjmay3/Supervised-Learning-Algorithms | /DecisionTrees_Car.py | 6,635 | 3.59375 | 4 | # Decision Tree classification (Car Evaluation)
# Part A - Data Preparation
# Import the necessary libraries
import numpy as np
import pandas as pd
import os
import graphviz
import matplotlib.pyplot as plt
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier... |
7e885a9d995a88509f2b11c403bad91fa771331e | jhagstrom/aoc | /2018/day_2.1.py | 438 | 3.65625 | 4 | from collections import Counter
indata_file = open("./2018/input_day2.txt", "r")
indata_txt = indata_file.readlines()
number_of_threes = 0
number_of_twos = 0
for line in indata_txt:
line = line.strip('\n')
characters = list(line)
counts = list(Counter(characters).values())
if(3 in counts):
numbe... |
63756dbda9070dd378118718383a7dbebcc469d9 | haaks1998/Python-Simple | /07. function.py | 1,011 | 4.1875 | 4 | # A function is a set of statements that take inputs, do some specific computation and returns output.
# We can call function any number of times through its name. The inputs of the function are known as parameters or arguments.
# First we have to define function. Then we call it using its name.
# format:
# def ... |
de812af47c00f567c7ad8771d8e182d31f83b2dc | haaks1998/Python-Simple | /08. lambda.py | 3,025 | 4.375 | 4 | # lambda function are single line and single use functions
# often called as throw away functions
# format function_name = lambda arguments: function_expression
print("Square Lambda function\n")
squared = lambda x: x*x
print(squared(int(input("Enter number: "))))
#............................................. |
3dd22a089fd49714b6cd36abbd3e5a6a3c6a4d2b | rakipov/py-base-home-work | /py-home-work/tasks/horoscope.py | 1,961 | 4.1875 | 4 | # Простая задача из первых лекий для определения знака зодиака
day = int(input('Введите день: '))
month = (input('Введите месяц: ')).lower()
if day <= 31:
if (21 <= day <= 31 and month == 'март') or (1 <= day <= 20 and month == 'апрель'):
zodiac = 'Овен'
elif (21 <= day <= 30 and month == 'апрель') or ... |
de0d0d3feca3ee5a4ea7858973c5f9f1e1fb3ebe | anthonypitts2022/Tree_Node_Finder | /Tree_Node_Finder.py | 2,007 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 19:18:03 2019
@author: Anthony Pitts, anthony.pitts@columbia.edu
Description: Searches a tree for a specfified node name
"""
class Node:
#name of Node
Name = None
#list of all child nodes
Children = []
def __... |
2af0d553a0bc30b0a9ef14b2c5c1232c6fbdf4cd | niaragnorak/python_encryption | /Niaragnorak_Encryption.py | 5,306 | 3.5625 | 4 | import tkinter as tk
import try1
from tkinter import *
from tkinter.filedialog import askopenfilename
root=tk.Tk()
root.configure(background='black')
root.title("Python_Encryption")
root.geometry('1920x1080')
dummy=Label(root,text="",bg='black')
welcome=Label(root,text="WELCOME TO PYTHON ENCRYPTION",bg='black',fg='whit... |
2d95625294be5907d014ea1c2c0a5c7c30640d34 | feixuanwo/py_bulidinfunc | /myreverse_reversed.py | 241 | 4.15625 | 4 | #!:coding:utf-8
#reversed与reverse不同。前者是内置函数,后者是列表、字典的方法。前者返回一个新列表。
i = [x for x in range(-5,6)]
for x in reversed(i):
print x,
print
print i
print i.reverse()
print i
|
f9271bc44ac5da31d176e3186a88220ee0c284e3 | cat-box/2019PythonAssignments | /assignment2/abstract_player.py | 4,969 | 4.03125 | 4 | class AbstractPlayer:
"""AbstractPlayer class
"""
def __init__(self, fname, lname, height, weight, jersey_num, date_birth, year_joined, player_type):
"""Constructor method for AbstractPlayer
Args:
fname (string): First name
lname (string): Last name
... |
f4c701f570edd33932bae1c6de032f9608891afc | ibhuiyan17/matplotlib-runtime | /csvTest.py | 872 | 3.609375 | 4 | #csvTest.py
import csv
import time
path = raw_input("enter path of csv file: ")
startTime = time.time()
with open(path, 'rb') as csvfile:
contents = []
file_reader = csv.reader(csvfile, delimiter = ',')
'''
row_num = 1
for row in file_reader:
print 'Row #%d:' % row_num, #Prints Contents in easy to re... |
da085485695bac92fc29df22fe5326f3763050c8 | soulcardz/python | /TestFiles/test.4.py | 231 | 3.71875 | 4 | str = 'python quiz practice code'
def opstr (a):
lis = ""
c = a.split()
b = len(c) - 1
lis = lis + c[b]
while b > 0:
lis = lis + " " + c[b - 1]
b = b - 1
return lis
print (opstr(str))
|
6d0313542bed3a787a8f10b1b840b6534a4818a1 | soulcardz/python | /TestFiles/test.2.py | 338 | 3.578125 | 4 | correctlis = [5,7,12,50]
wronglis = [5,2,3,1,5000]
def orglist (a):
length = len(a)
i = 0
b = 1
flag = True
while i < (length - 1) :
b = i + 1
if a[i] > a[b]:
flag = False
break
i = i+1
return flag
g = orglist(correctlis)
f = orglist(wronglis)
p... |
1520b9faa5b957da64ea48e158adacc0e5987adf | pixeltk623/python | /Core Python/Datatypes/string.py | 478 | 4.28125 | 4 | # Strings
# Strings in python are surrounded by either single quotation marks, or double quotation marks.
# 'hello' is the same as "hello".
# You can display a string literal with the print() function:
# print("Hello")
# print('Hello')
# a = "hello"
# print(a)
# a = """cdsa
# asdasdas
# asdasdassdasd
# asdasdsa""... |
47452085ef55b59dbc810e986300362cfbe80a36 | pixeltk623/python | /Core Python/List/lecture.py | 6,190 | 4.46875 | 4 | # List
# Lists are used to store multiple items in a single variable.
# List Items
# List items are ordered, changeable, and allow duplicate values.
# List items are indexed, the first item has index [0], the second item has index [1] etc.
# thislist = ["apple", "banana", "cherry"]
# print(thislist[2])
#Allow Duplic... |
4ee16d790677be1eaeb377db035bbdda72309791 | pixeltk623/python | /MYSQL & Mongo Database/mysqli.py | 5,476 | 4.375 | 4 | # Install MySQL Driver
#python -m pip install mysql-connector-python
import mysql.connector
# Database Connection
# mydb = mysql.connector.connect(
# host="localhost",
# user="root",
# password="",
# database="core_python"
# )
mydb = mysql.connector.connect(
host="localhost",
user="root",
password=""
)... |
87c9b606584258cebac198989bf60683fde8bfeb | faruqii/Tugas-Alpro | /statistic2.py | 516 | 3.640625 | 4 | # list = [100,80,55,70,25,40,100,20,90,50]
import statistics
import numpy as np
list = []
n = int(input("masukan jumlah data :"))
for i in range(0, n):
nilai = int(input())
list.append(nilai)
list.sort()
average = statistics.mean(list)
median = statistics.median(list)
modus = statistics.mode(list)
prin... |
66cb206d674005d1177b4bfa5de23c2b92722a27 | daviduarte/deepSearch | /profundidade.py | 2,034 | 3.9375 | 4 | """
Implementation of deep search in a binary tree. In this search approch, we use a stack to organize the elements to be covered.
Therefore, we did not use a explicit stack, instead we use the implict function call stack.
"""
import numpy as np
# When the element is find, this var is set to 1, blocking new iterat... |
e32d5812d6eec3eac843f0824caa54547e68df55 | KastyaLimoneSS/Gnom | /discriminant.py | 861 | 3.953125 | 4 | import time
import math
a=0
b=0
c=0
d=0
x1=0
x2=0
def equation():
a = int(input("Введите коэфициент a:"))
b = int(input("Введите коэфициент b:"))
c = int(input("Введите число c:"))
print(a)
d = b**2 - 4*a*c
x1 = (-b + math.sqrt(d))/(a*2)
x2 = (-b - math.sqrt(d))/(a*2)
... |
aefdd7e77b1d657b246c119f7cceabfea2dfd5f7 | S3FA/super-street-fire | /ssf-python/glovetests/src/gestures/client_datatypes.py | 5,667 | 3.515625 | 4 | '''
client_datatypes.py
This file contains the basic data types that hold the various
expected inputs from the Super Street Fire game sensors
@author: Callum Hay
'''
import operator
PLAYER_ONE = 1
PLAYER_TWO = 2
# The GloveData class defines the data type the holds
# the various inputs expected from... |
1a47812edf03576d3f91bae631942827f6dab948 | Parya1112009/mytest | /cisco1.py | 212 | 3.90625 | 4 | import string
str ='hello world!'
print str
print str*2
list = ["priy",20.3,12,45,"eva"]
list1 = ("priy",20.3,12,45,"eva")
print list[2:5]
print list*3
print "tuple is\n",list1
print list1[1:2]
print list1*3
|
f79758f5f58bc781f32e43333ff7772a0374b8fc | Parya1112009/mytest | /split_join.py | 145 | 3.796875 | 4 | import string
string = " my: name: is: priya:"
#for i in str.split(":"):
result =string.split(":")
result1 = "::".join(result)
print result1
|
2b41ee2fb6ceab1a314c683c689d63e0f0e005da | Parya1112009/mytest | /prime_number.py | 211 | 4.0625 | 4 | n1 =int(raw_input("enter the number"))
is_prime(n1)
def is_prime(n):
for i in range(2,9):
if n % i == 0:
print "is not a prime number",n
break
else:
print "is a prime number",n
|
c731f628ffd7c2367bc6c477e95c22e231b91c60 | Parya1112009/mytest | /lookbehind11.py | 140 | 3.5 | 4 | import re
stri = "priyafooqb"
# the below re matches any b not precedded by foo"
match = re.search(r'(?<!foo)b',stri)
print match.group()
|
de83aa76537a736564caa321640cf244211db0f2 | Parya1112009/mytest | /listoperations2.py | 428 | 4 | 4 | list = [1,2,3,4,5,6,7,7,8]
list1 = [1,2,3,4,5,6,7,8]
x = int(raw_input("enter the number to be searched"))
if x in list1:
print "yes it is present in the list"
else:
print "no it is not present in the list"
min = min(list)
print "minimum number is",min
max = max(list)
print "maximum number is",max
occurence = lis... |
e6fa41545d0d1c84b0cf0bca3bdfe1804813e88b | Parya1112009/mytest | /palindrom.py | 272 | 3.90625 | 4 | import string
str = raw_input("entr the number")
k = len(str)/2 -1
print k
count = 0
i=0
while i<=k:
if str[i] ==str[-i-1]:
count = count +1
i= i+1
print count
if count>k:
print "%s string is palindrom"%str
else:
print "%s string is not palindrom"%str
|
4da845a17ab03f16469b3c1f92bcbb65077e8c77 | Parya1112009/mytest | /duplicate.py | 226 | 3.65625 | 4 | list1 = []
l = []
count = 0
with open("dupli.txt","r") as f:
for i in f.read().split():
list1.append(i)
list2 = list(set(list1))
print list1
print list2
for j in list1:
if j not in list2:
l.append(j)
print l
|
f886849532196b81f6ebde575210419ce866b905 | Parya1112009/mytest | /re_cisco.py | 98 | 3.6875 | 4 | import re
str = "abb"
match = re.search(r'(.*)?',str)
print match.group()
#print match.group(2)
|
e50bdc5bc028172772c9b313483905cdcec139d7 | Parya1112009/mytest | /deepshallow.py | 129 | 3.609375 | 4 | import copy
dict1 ={"name":"eva","age":"7","grade":"1"}
dict3 =dict1.copy()
dict1["grade"] = "23"
print dict1
print dict3
|
2dd4276a51e630ab97bd2270ac4f4d1e9a7fa9c5 | Parya1112009/mytest | /ciscowebsite.py | 268 | 3.6875 | 4 | list = [1,2,3,4,5]
list1 = []
number =6
def func():
for i in range(len(list)):
for j in range(len(list)):
sum = list[i] + list[j]
if sum == number:
return (list[i],list[j])
continue
list11 = func()
list1.append(list11)
print list1
|
78cefa8e88b86f3259c7d3725df8e9ca6de4ab53 | Parya1112009/mytest | /flatlist_real.py | 413 | 3.703125 | 4 | list_flattened = []
def flatten_list(list1):
print list1
for i in list1:
print i
if isinstance(i,list):
flatten_list(i)
else:
list_flattened.append(i)
return list_flattened
list1 = [[18,[25,34,48],77],44,45,66,[5,65,17,8],2,4,5,[19,10,11,12]]
for i in list1:
if isinsta... |
2a4ce3d7eeb8b6a405afa25f565f04b48e973c51 | Parya1112009/mytest | /string.join.py | 122 | 3.6875 | 4 | import string
str = "i am a gud girl"
str = str.split(" ")
print "-".join(str)
str2 = string.join(str,"$")
print str2
|
ec2148fdc7a10a881f01c13f8216f66d131e60ba | bejohi/TDAForITD | /morphdetect/visualisation.py | 1,062 | 3.640625 | 4 | import matplotlib.pyplot as plt
import morphdetect.loging as log
def visualize_2D_binary_matrix(binary_matrix: list):
"""Visualizes a given 2D Matrix which stores only binary values"""
log.log_info(
str(visualize_2D_binary_matrix.__name__) + ": visualize matrix with height: " + str(len(binary_matrix))... |
876fe60eba8c9760a153d0b10984db32a6214378 | lhleonardo/ufla-atividades-grafos | /exercicios/lista-3/main.py | 2,449 | 3.578125 | 4 | from grafo import Grafo
from vertice import Vertice
def main():
caminho = input("Digite o caminho do arquivo: ")
arquivo = open(caminho, "r")
computadores = {}
tarefas = {}
# cria o grafo
grafo = Grafo()
# adiciona os 10 computadores, de 0 a 9
for i in range(10):
vertice ... |
62b895bd0d0c58485460b4ee6520fb88e4342214 | a-konyaev/python-tests | /descriptor.py | 1,663 | 3.5625 | 4 | # дескриптор переопределяет поведение при обращении к атрибуту
# получается, это те же гетеры и сетеры
from abc import ABCMeta, abstractclassmethod
class Descriptor:
# instance - сюда будет передан obj
# owner - сюда будет передан Class
def __get__(self, instance, owner):
print(f'get: instance={t... |
be7d3dd435ac23ac4295a1ebd2b727706be5e801 | a-konyaev/python-tests | /errors.py | 553 | 3.5625 | 4 | import traceback
while True:
print("...")
try:
s = input(">")
i = int(s)
if i == 0:
raise ValueError("i don't be zero")
assert i > 0, f"{i} less by zero"
except ValueError as err:
print(f"error: {str(err)}: " + err.args[0])
except KeyboardInterrup... |
ab6e7b63b8ca141e8e709e205b4ae8659a224bc4 | aslima/Data-Science-course | /fibonacci.py | 487 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 22:42:20 2017
@author: Alexandre Sales Lima
Cursos de Big Data & Data Science
Trabalho 1 Questão 2
"""
import numpy as np
def fibonacci(n):
if n == 0:
return print( 0)
elif n == 1:
return print( 1 )
f = np.zeros(... |
e0b42313ea9348684c43d1d8295d3ebf6213f7ca | ashutoshsinha25/Python-Leetcode-Solution | /55.Jump Game.py | 664 | 3.578125 | 4 | class Solution(object):
def canJump(self, nums):
nums_len = len(nums)
result_arr = [False] * nums_len
result_arr[0] = True
current_true_i = 0
for i in range(nums_len):
# print(result_arr)
if nums[i] >= 1 and result_arr[i]:
if... |
c2e5a338bc3aa4cf398d4053385b96bf8bb81e78 | undergraver/PythonPresentation | /05_financial/credit.py | 2,254 | 3.9375 | 4 | #!/usr/bin/env python
import math
# user input
moneyAmount=90000
monthsOfCredit=24
# credit details offered by bank
interestRate=8.52 # that is in percent
interestRateIncreaseInMonth=0 # that is in percent - because ROBOR/LIBOR/EURIBOR
monthlyAdministrativeInterestRate=0.04 # that is in percent ( 0.04% )
def GetI... |
86ecc1824f7ede762ddc15743ace1b5457fffc52 | undergraver/PythonPresentation | /07_problem_generators/regula_falsi.py | 3,305 | 3.6875 | 4 | #!/usr/bin/env python
import gettext
import random
import sys
def tr(text):
return gettext.gettext(text)
def pl(text, textpl,count):
return gettext.ngettext(text,textpl,count)
class Animal:
def __init__(self,name, name_plural,number_of_legs):
self.name = name
self.name_plural = name_plur... |
4b3f9e149707817aefa696ce2d336453cd93f34a | undergraver/PythonPresentation | /05_financial/increase.py | 766 | 4.125 | 4 | #!/usr/bin/env python
import sys
# raise in percent
raise_applied=6
raise_desired=40
# we compute:
#
# NOTE: the raise is computed annually
#
# 1. the number of years to reach the desired raise with the applied raise
# 2. money lost if the desired raise is applied instantly and no other raise is done
salary_now=100... |
ad75ffb88e550905b4d167706ab5491768400878 | undergraver/PythonPresentation | /02_typical/xmlBasic.py | 824 | 3.609375 | 4 | #!/usr/bin/env python
# This code is under BSD 2-clause license
from xml.dom.minidom import parse, parseString
def handleDOM(document):
examples = document.getElementsByTagName("example")
for example in examples:
handleExample(example)
def handleExample(example):
name = example.getAttribute('na... |
6a293c64aabc496cc4e1669935d1659dc1042c39 | Kjartanl/TestingPython | /TestingPython/Logic/basic_logic.py | 368 | 4.21875 | 4 |
stmt = True
contradiction = False
if(stmt):
print("Indeed!")
if(contradiction):
print("Still true, but shouldn't be! Wtf?")
else:
print("I'm afraid I'm obliged to protest!")
print("------- WHILE LOOP ---------")
number = 0
while(number < 5):
print("Nr is %s" %number)
number = num... |
fba16cc04bcbe45e3d26247dbfef3ea9fe61dcd0 | matejpiro/Sibenice | /sibenice.py | 2,184 | 3.875 | 4 | def oddelovnik():
print("-"*20)
# získej písmeno a vrať ho kapitálkama
def ziskej_pismeno():
user_guess = input("Hádej po jednom písmenu. Zadej písmeno:")
return user_guess.upper()
# funkce která vezme písmeno, projede list a pokud najde shodu, vloží ono písmeno do "view_listu" na správné místo (dle index... |
b774d1f5782804f6e7eafc6acbcecf73db687fea | zwwangoo/tkfordrowseal | /test.py | 5,170 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import Tkinter as tk
# from Tkinter import TracebackType
win = tk.Tk()
win.title("Python GUI") # 添加标题
# 创建一个容器,
monty = tk.LabelFrame(win, text=" Monty Python ") # 创建一个容器,其父容器为win
monty.grid(column=0, row=0, padx=10, pady=10) # padx pady 该容器外围需... |
92fd438e6f2abbca8a70deb8ec717762dbf31ddc | T7galaxy/ArcadeMachine | /controller_test/main.py | 2,368 | 3.5625 | 4 | import sys
# April was here
import pygame
from pygame.locals import *
# initializes pygame
pygame.init()
# sets window text (top left corner text)
pygame.display.set_caption('game base')
# creates screen of size 500 pixels by 500 pixels
screen = pygame.display.set_mode((500, 500), 0, 32)
# creates clock for the game ... |
87749b59b4d77a0a04eb5d8d3b65332c48e4a7b1 | Gusstr/Uppgifter | /uppgift3.py | 129 | 3.671875 | 4 |
T = int(input("tal: "))
def delfem(a):
if a % 5 == 0:
return True
else:
return False
print(delfem(T))
|
f4f9ba1982577f908487115093736c315f4a2c8c | aanantt/Sorting-Algorithms | /InsertionSort.py | 253 | 4.21875 | 4 | def insertionSort(array):
for i in range(len(array)):
j=i-1
while array[j] > array[j+1] and j >=0:
array[j], array[j+1] = array[j+1], array[j]
j -= 1
return array
print(insertionSort([1,5,8,2,9,0])) |
ddc51a5a16177413cef993ea77fb604f7dace875 | Amfeat/Python_learning | /lesson_003/00_bubbles.py | 1,677 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import random
import simple_draw as sd
sd.resolution = (1200, 600)
sd.background_color = (21, 23, 60)
detalization = 5
bubble_width = 2
# Нарисовать пузырек - три вложенных окружностей с шагом 5 пикселей
# Написать функцию рисования пузырька, принммающую 2 (или более) параметра: точка рисов... |
92b441f501d7fe687efd1a5f839bb5fb3fee60f0 | Amfeat/Python_learning | /lesson_003/07_wall.py | 622 | 3.625 | 4 | # -*- coding: utf-8 -*-
# (цикл for)
import simple_draw as sd
sd.resolution = (1200, 600)
# Нарисовать стену из кирпичей. Размер кирпича - 100х50
# Использовать вложенные циклы for
def brick(x, y):
# def rectangle(left_bottom, right_top, color=COLOR_YELLOW, width=0):
left_bottom = sd.get_point(x, y)
ri... |
d026e223e892d33512d51b4e212360b234601a61 | Logirdus/py_lessons | /restore_countofsymbols.py | 502 | 3.609375 | 4 | numbers = ['0','1','2','3','4','5','6','7','8','9']
with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file:
for line in input_file:
count = ''
symbol = line[0]
for i in range(1, len(line)):
if line[i] not in numbers:
output_file.write(s... |
7383d76e3be7a0b1982e4e0b12736185f5bebd22 | rameshnataru1224/bookproject12 | /book_rental_program.py | 5,093 | 3.6875 | 4 | """
Author: Ramesh
Task: Book rental system
"""
from tkinter import Label, Entry, W, E, Button, END, Tk
class BookSystem(object):
"""Renting the books"""
def __init__(self, book):
self.book_charges = {"regular": 1.5, "fiction": 3, "novels": 1.5}
self.min_book_charges = {"regular": 2, "fiction... |
67ee3a01622adecc944da7b9a4f4269ac9d3f94d | RodrigoSperandio/LearnPython | /AulaPython/exercicio1.py | 261 | 3.96875 | 4 | print("Calcule a area de um retangulo")
base = input("Qual o tamanho da base do seu retangulo? ")
altura = input("Qual o tamanho da altura do seu retangulo? ")
area = float(base) * float(altura)
print(f'O seu retangulo possui area: {area} unidades de metida') |
7863e76546d81e46b2bd86a376bc85c03ec81b11 | q2044757581/leetcode | /19. 删除链表的倒数第N个节点/code.py | 886 | 3.59375 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
length = 0
p = head
# 先用一次遍历求长度
while p:
length += 1
p = p.next
del_index = lengt... |
7b61ba45e3abb3e9c760e4ea603a5d9309b20815 | q2044757581/leetcode | /2、两数相加/code.py | 998 | 3.546875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
sum_val = l1.val + l2.val
p = l3 = ListNode(int(sum_val % 10))
left = int(sum_val / 10)
l1 = l1.next
l2 = l2.next
while l1 and l... |
f5abc15c235f93e461187b1c5b4373cf3c7b18d8 | Cary19900111/G7Cary | /Learn/crclosure/main.py | 984 | 3.984375 | 4 | '''
闭包的作用:1.保存上次的运行结果。2.类似配置的作用
'''
def add_step1(number1):
'''如果在一个内部函数里,对在外部作用域(但不是在全局作用域)
的变量进行引用,那么内部函数就被认为是闭包(closure)'''
def add_step2(number2):
result = number1+number2
return result
return add_step2
def nonlocal_cr():
'''不能修改外部作用域的局部变量的'''
foo = 10
def add(number2):
... |
db4b2589fced75a64c6b55331dd7bbec12836441 | Cary19900111/G7Cary | /Learn/crdataStrcuture/Array/dict/copycr.py | 1,696 | 4.15625 | 4 | from copy import copy,deepcopy
def copy_tutorial():
'''
第一层的id不一样,但是第二层的id是一样的,指向的是同一块地址
修改copy1,就会修改copy2
'''
dict_in = {"name":"Cary","favor":["tabletennis","basketball"]}
dict_copy1 = copy(dict_in)
dict_copy2 = copy(dict_in)
print("Before copy1:{}".format(dict_copy1))
print("Befor... |
8e14c5e23cccdd6b3db117ab9c4322efc57c700d | arul2810/Facebook-Hacker-Cup | /Airport_Problem.py | 932 | 3.6875 | 4 | test_cases=int(input("Enter Number of Test Cases:"))
def split(word):
return [char for char in word]
for i in range (0,test_cases,1):
N = int(input())
if N%2 == 0:
print("Input is incorrect")
in_string_temp = str(input())
in_string = split(in_string_temp)
a_value = 0
b_value = 0
... |
bb1404efadc58c6568c109d0cad0f763c2742d57 | yxs314159/demo-code | /pylearn/assignment/calculator/01.py | 857 | 4 | 4 | #! /user/bin/env python
# _*_ coding: utf-8 _*_
# __author__ = "王顶"
# Email: 408542507@qq.com
"""
四则运算
"""
def show_nenu():
cmd_menu = ("\n"
"[1] Add\n"
"[2] Subtract\n"
"[3] Multiply\n"
"[4] Divide\n")
print(cmd_menu)
return
def calc(nu... |
ff8d49216bb5d554a9ab67380b356b5609343498 | Grayidea-bit/Arrow-keys | /main.py | 609 | 3.765625 | 4 | ##需要先安裝pygame (pip install pygame)
import pygame,sys
from pygame.locals import *
pygame.init();
windows_surface = pygame.display.set_mode((10,10), pygame.NOFRAME);
x,y =0,0;
while True:
for event in pygame.event.get():
if event.type==KEYDOWN:
if event.key==K_LEFT:
x-=1
... |
a2f754044b5a3d626bbbd0db61ae411e39f143fe | aike-s/holbertonschool-higher_level_programming | /0x03-python-data_structures/4-new_in_list.py | 254 | 3.53125 | 4 | #!/usr/bin/python3
def new_in_list(my_list, idx, element):
new_list = my_list.copy()
if idx < 0:
return new_list
i = 0
for x in new_list:
if i == idx:
new_list[idx] = element
i += 1
return new_list
|
cf5c40538ab942b02626a95277dd65778eb5a5f4 | aike-s/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-add_item.py | 581 | 3.734375 | 4 | #!/usr/bin/python3
"""
In this file a main for add arguments to a Python list and save them in a file
"""
from sys import argv
load_from_json_file = __import__('6-load_from_json_file').load_from_json_file
save_to_json_file = __import__('5-save_to_json_file').save_to_json_file
if __name__ == "__main__":
filename =... |
bfcc8ffcbcdacb92815ae184f7c42e196fd9c23d | kjklug/class-work | /temperature-conversion.py | 155 | 4.09375 | 4 | celsius=input('Enter a temperature in degrees Celsius: ')
fahrenheit=9/5*(float(celsius))+32
print('The temperature in degrees Fahrenheit is ', fahrenheit) |
65c57c302b3d1a34c6da45b8b0f3a2f1f348917e | kjklug/class-work | /traversal.py | 118 | 3.71875 | 4 | inp=input('Enter a string:\n')
index=len(inp)-1
while index >=0:
letter=inp[index]
print(letter)
index=index-1 |
5d9f29e7940ba04a1b0e152c54571d1bb01cfaff | kjklug/class-work | /spam-confidence.py | 352 | 3.6875 | 4 | fname=input('Enter the file name: ')
try:
fhand=open(fname)
except:
print('File cannot be opened:', fname)
exit()
count=0
total=0
for line in fhand:
if line.startswith('X-DSPAM-Confidence:'):
count=count+1
atpos=line.find(':')
num=float(line[atpos+1:-1])
total=total+num
average=total/count
print('Ave... |
0544ffecb22c776cff16a0024d8f7c7f9caac870 | Aluriak/GBI | /workingfile_correction.py | 4,647 | 3.671875 | 4 | """
This file is dedicated to the practical session.
Functions and routines have to be completed, according to the subject provided by
the standing guys.
By default, useful functions defined in local library (libtp) are imported,
as many __future__ features that allows user to code in Python 3 style,
even if dinopy... |
fc2e497f6a4df5ed6002bb92dbcf4c5b3af8b393 | 2292527883/Learn-python-3-to-hard-way | /ex39/ex39.py | 1,962 | 4.1875 | 4 | # 字典
# create a mapping of state to abbreviation
statse = { # 定义字典
'Oregon': 'OR',
'Floida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some citise in them
cites = {
'CA': 'san Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
... |
134bf3bc84a1f0b67781d6f27656f24b81eef683 | simonvantulder/Python_OOP | /python_Fundamentals/numberTwo.py | 979 | 4.28125 | 4 |
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'},
{'first_name': 'Mark', 'last_name': 'Guillen'},
{'first_name': 'KB', 'last_name': 'Tonel'}
]
#iterateDictionary(students)
# should output: (it's okay if each key-value p... |
b7e9b5cc9b462dcafffe8d8640878ee025453a0a | PramodSuthar/pythonSnippets | /passByArgs.py | 531 | 4.09375 | 4 |
### pass by Value: all immutable obj are passed by value
def changeVal(x):
x += 100
n = 10
print(n)
changeVal(n)
print(n)
### Pass by reference: all mutable obj are passed by reference
print("Example 1")
def changeList_1(l):
l.append(50)
myList_1 = [10,20,30,40]
print(myList_1)
chan... |
f6cc9110831cf63cbcac77d35988cf8e2bf76ceb | PramodSuthar/pythonSnippets | /listComprehension.py | 649 | 4.0625 | 4 |
### first Example
print("******** first Example")
grades = [95.5, 98.5, 86, 79, 65]
modifiedGrades = []
for grade in grades:
modifiedGrades.append(grade + 1.5)
print(grades)
print(modifiedGrades)
modifyGrades = [grade + 2.5 for grade in grades]
print(modifyGrades)
### second Exam... |
dd9dca4f015cb790227af5eb427850a1c8823202 | PramodSuthar/pythonSnippets | /generator.py | 670 | 4.15625 | 4 | """
def squence_num(nums):
result = []
for i in nums:
result.append(i*i)
return result
squared_list = squence_num([1,2,3,4,5])
print(squared_list)
"""
def squence_num(nums):
for i in nums:
yield(i*i)
##squared_list = squence_num([1,2,3,4,5])
"""
print(squa... |
baf8ea1ca723cf6de19571e649c605ced72a8e2a | JanusGeiri/MathStuff | /ttt.py | 1,805 | 3.703125 | 4 | class TicTacToe:
def __init__(self, inp_board=[[0, 0, 0], [0, 0, 0], [0, 0, 0]]):
self.board = inp_board
def getDiag(self):
board = self.board
diag1 = []
diag2 = []
for i in range(3):
for j in range(3):
diag1.append(board[i][j])
... |
c5ec0674bf289a0386f7bbba1198643fff3eb1b7 | EECS388-F19/lab-ryanlieu | /helloworld.py | 249 | 3.515625 | 4 | import random
name = 'Ryan'
rand_one = random.randint(0,100)
rand_two = random.randint(0,100)
rand_sum = rand_one + rand_two
print(name)
print(rand_one)
print(rand_two)
print('Sum = {}'.format(rand_sum))
print('Average = {}'.format(rand_sum / 2.0)) |
1347eee1bcf53e10949bf3af41e175d14064780a | thiter/python-work | /bytecode.py | 401 | 3.59375 | 4 | #! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "thiter"
def testcode():
a = 'hello,中国'
b = u'Hello,中国'
print type(a), len(a), a
print type(b), len(b), b
def testcode1():
str1 = u"你好"
print type(str1), str1
str2 = str1.encode("utf-8")
print type(str2), str2
if __name... |
97f2231fc25288bc899f36a645b097ca78c24390 | kth4540/Script_Language | /Regular_expression/Reg_quiz.py | 297 | 3.828125 | 4 | import re
numberRegex=re.compile(r'''((\d\d)(\d)*)* #AREA CODE
(-)?( )? #SEPARATOR
(\d\d\d)(\d)? # 3 OR 4 DIGITS
(-)?( )? #SEPARATOR
(\d\d\d\d) # 4 DIGITS
''',re.VERBOSE)
phoneNum=numberRegex.search('010-2622-4540')
if phoneNum==None:
print('wrong number')
else:
print(phoneNum.group()) |
32a67c8b343cf010143c393baedb7e203928027b | kth4540/Script_Language | /control_flow/control_flow.py | 754 | 3.65625 | 4 | import random
#spam=0
#while spam<5:
# print('hello world')
# spam=spam+1
#input()
#while(True):
# print('please type your name')
# name=input()
# if name=='your name':
# break
#print('thank you')
#while True:
# print('who are you?')
# name=input()
# if name!='joe':
# continue
#... |
41d588b31626842bf048b64f7cbe60e51783917e | berbusatto/algoritmos_facul | /lista_for.py | 12,591 | 3.9375 | 4 | # EXERCÍCIO 1
# Escreva um algoritmo para calcular e escrever o valor da soma S:
# S = (1/1) + (2/4) + (3/9) + (4/16) + (5/25) + (6/36) + .... (10/100)
# soma = 0
# for x in range(11):
# if x > 0:
# soma = soma + (x / (x * x))
#
# print(soma)
# EXERCÍCIO 2
# Escreva um algoritmo que leia o código e o salá... |
2a748a692f254f0f24f7dc98f9d65bccb3f10278 | berbusatto/algoritmos_facul | /trabalho for.py | 2,372 | 3.765625 | 4 | # SENAC PORTÃO
# ADS PRIMEIRO PERÍODO
# BERNARDO SAAD GEBRAN BUSATTO
# TRABALHO COMANDO PARA
# Calcule o imposto de renda a ser pago por cada um dos 10 contribuintes informados
# pelo cliente, considerando que os dados de cada contribuinte são: número do CPF e renda mensal.
# Faça o cálculo do imposto ... |
24f9a18fb45c897194fda0e73b82e9cb9fb842e1 | sravanrekandar/akademize-grofers-python | /33_printing_lines.py | 232 | 3.515625 | 4 | def print_line():
for i in range(10):
print("_", end="")
print()
for i in range(10):
print_line()
"""
\n - new line character
\t - tab
https://www.w3schools.com/python/gloss_python_escape_characters.asp
"""
|
7b7281c6e932fc4eeee3fcf3579fcf9a09555892 | sravanrekandar/akademize-grofers-python | /05_strings_vs_integers.py | 77 | 3.6875 | 4 | first = "10"
second = "10"
print(first + second)
a = 10
b = 10
print(a + b) |
edea772079188bf3a4d9cf7f13dd14f11c843d19 | sravanrekandar/akademize-grofers-python | /84_sorting.py | 296 | 3.984375 | 4 | numbers = [33, 55, 6, 77, 8, 9]
print(numbers)
numbers.sort()
print(numbers)
cities = ["Hyderabad", "Chennai", "Bengaluru", "Mumbai"]
cities.sort()
print(cities)
"""
Sorting Techniques, suggested reads
bubble sort
selection sort
insertion sort
merge sort
quick sort
radix sort
....
......
"""
|
e6ef7ccc9523abe2c6994aa48af2d977fa378526 | sravanrekandar/akademize-grofers-python | /37_sum_of_naturals.py | 179 | 4.03125 | 4 | def print_sum(num):
sum = (num * (num+1)) / 2
print(f"Sum of first {num} Natural numbers = {sum}")
def main():
n = int(input("Enter n: "))
print_sum(n)
main()
|
0ab1f3e6911d61e7973a202bd544251b18470359 | ringoshogo/study_python4 | /pos-system.py | 5,313 | 3.609375 | 4 | import pandas as pd
from datetime import datetime as dt
### 商品クラス
class Item:
def __init__(self,item_code,item_name,price):
self.item_code=item_code
self.item_name=item_name
self.price=price
def get_price(self):
return self.price
### オーダークラス
class Order:
def __init__(s... |
a8eb495f0fea08409ac73a3279bb07b537216dd5 | jeffyoon/python_tutorial | /formatted_output.py | 4,415 | 4.0625 | 4 | # The easiest way, but not the most elagant one
q = 459
p = 0.098
print(q, p, p * q)
print(q, p, p * q, sep=",")
print(q, p, p * q, sep=":")
# Alternatively, we can construe out of the values a new string by using the string concatenation operator:
print(str(q) + " " + str(p) + " " + str(p * q))
# The second method ... |
d8a8c491a550a578fb54b463fe8ed2de1f6b67ec | LeitengH/CSCIB351 | /test.py | 616 | 3.8125 | 4 | HEIGHT = 15
WIDTH = 15
board = [[[] for y in range(HEIGHT)] for x in range(WIDTH)]
for i in range (0, HEIGHT):
for j in range (0, WIDTH):
board[i][j] = 0 # fill 0 in it
def printBoard(WIDTH,HEIGHT):
print("")
print("+" + "---+" * WIDTH)
for rowNum in range(HEIGHT - 1, -1, -1):
... |
e732f667ac9b2639556756b625ba3649fbcc70a5 | FreVanBuynderKDGIoT/Make1.2.1 | /Les/Demo7_23112020.py | 558 | 4.0625 | 4 | #!/usr/bin/env python
"""
info about our project
"""
# import
__author__ = "Fre Van Buynder"
__email__ = "fre.vanbuynder@student.kdg.be"
__status__ = "Development"
def main():
list_of_words = ["hi", "I", "am", "Fre", "how", "are", "You"]
searching_word = input("Which word do you want to find?: ")
i ... |
ea9586937f73cfb408e1d632cfbc2106409d8f60 | FreVanBuynderKDGIoT/Make1.2.1 | /oefening5.py | 325 | 3.640625 | 4 | #!/usr/bin/env python
"""
info about project
"""
# imports
__author__ = "Fre Van Buynder"
__email__ = "fre.vanbuynder@student.kdg.be"
__status__ = "Development"
# functions
def main():
word = input("Give me a random word (the more random the better): ")
print("the word exist of", len(word), "letters")
if... |
5608fcc34a45df22a95d7a7e2b4e0ff3b67adfcd | ggg05158/Baekjoon_py | /10808.py | 179 | 3.546875 | 4 | word=input()
w_len=len(word)
list=[]
for j in range(26):
list.append(0)
for i in range(w_len):
list[ord(word[i])-97]+=1
for k in range(26):
print(f"{list[k]} ",end='') |
ddcc13f5c8162130af1532c156686f967e1e94cc | ggg05158/Baekjoon_py | /2609.py | 385 | 3.640625 | 4 | def max(n1,n2):
div=0
for i in range(1,(n2 if n1>n2 else n1)+1):
if(n1%i==0 and n2%i==0):
div=i
return div
def min(n1,n2):
n1d=n1/max(n1,n2)
n2d=n2/max(n1,n2)
return max(n1,n2)*n1d*n2d
def main():
num1, num2=input().split( )
num1=eval(num1)
num2=eval(num2)
pri... |
eb458a86ddee9aa197d3c57650dc4a8d625782c6 | cojok/trainings_fun | /multiplication_table.py | 365 | 3.515625 | 4 | # https://www.codewars.com/kata/5432fd1c913a65b28f000342
def multiplication_table(row,col):
results = []
for i in range(1, row + 1):
tmp = []
for j in range(1, col + 1):
if i != 1:
tmp.append((results[0][j - 1] * i ))
else:
tmp.append(j)
... |
0e07914cfa997c6ee2bef28123972e089f49b454 | montaro/algorithms-course | /P0/Task4.py | 1,234 | 4.125 | 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 4:
The telephone company want to i... |
ef2a8723dfb2eb6dfc8946e80a9fc8ab49798b86 | LA200/HW1_ADM | /code.py | 17,496 | 4.25 | 4 | # ===== PROBLEM1 =====
# Exercise 1 - Introduction - Say "Hello, World!" With Python
print("Hello, World!")
# Exercise 2 - Introduction - Python If-Else
def isOdd(n):
if n%2!=0:
print('Weird')
else:
if 2<=n and n<=5:
print('Not Weird')
else:
if 6... |
6bcf83defad22296e598716ea5799563eb42598b | gh102003/CipherChallenge2020 | /transposition_row_row.py | 247 | 3.734375 | 4 | # Fill in rows, reorder columns then read off rows
ciphertext = input("Enter ciphertext: ")
# key = RDF
plaintext = ""
for a, b, c in zip(ciphertext[0::3], ciphertext[1::3], ciphertext[2::3]):
plaintext += c + a + b
print()
print(plaintext) |
7bbacbc333866ca9e4c6d23d0bba4793808dda4b | webfun-sept2017/BradWalasek-webfun-sept2017 | /Python/ScoresandGrades/ScoresandGrades.py | 401 | 3.875 | 4 | import random
def grade(score):
if score >=60 and score < 70:
grade = "D"
if score >=70 and score < 80:
grade = "C"
if score >=80 and score < 90:
grade = "B"
if score >=90 and score <= 100:
grade = "A"
ret = "Score: "+ str(score) + "; Your grade is " + grade
ret... |
0499369101509985cd9144cd28f0d1392c5944fb | Lepajewski/PythonStudia | /Medium/01.py | 141 | 3.75 | 4 | text = list(input().split())
for i in range(len(text)):
text[i] = int(text[i], 2)
text[i] = chr(text[i])
print(text[i], end='')
|
d473354b602dfb92f1a3ce03459bbf9a500b6a1c | Lepajewski/PythonStudia | /Medium/properbracketing.py | 1,078 | 3.796875 | 4 | brackets = input()
opening = '([{'
closing = ')]}'
flag = True
if brackets[0] == closing[0] or brackets[0] == closing[1] or brackets[0] == closing[2] or brackets[-1] == opening[0] or brackets[-1] == opening[1] or brackets[-1] == opening[2]:
flag = False
elif len(brackets) % 2 != 0:
flag = False
else:
op, c... |
7dd04fd5f61b9823ad79c762ef14c2b91e618a17 | merzme/My-Python-EXperiments | /positve.py | 250 | 4.03125 | 4 |
def main():
num = float(input('enter a number:'))
if num > 0:
print('the num is positive')
elif num == 0:
print('the num is zero')
else:
print('the num is negative')
if __name__ == "__main__":
main()
|
3cd5ee91b3fad659fa09ea70a2cc4f920aee3275 | wangbqian/python_work | /pay3.py | 241 | 3.609375 | 4 | def computepay(h,r):
if (h<=40):
return h*10.5
else:
return (40*10.5+(h-40)*10.5*1.5)
hrs = raw_input("Enter Hours: ")
hrs = float(hrs)
rts = raw_input("Enter Rate: ")
rts = float(rts)
p = computepay(hrs,rts)
print p |
7b9e11f648348c3d1ad4cd69a916a942e8778839 | wangbqian/python_work | /5.2.py | 382 | 3.96875 | 4 | largest = None
smallest = 10000
while True:
num = raw_input("Enter a integer number: ")
if num == "done" :
break
else:
try:
num = int(num)
except:
print "Invalid input"
continue
smallest = min(num,smallest)
largest = max(num,larges... |
3a54379dd20a03bd361e6a63bf2cb5426ef62ea2 | avihebbar/learning | /test.py | 528 | 3.625 | 4 | class node(object):
"""docstring for node"""
def __init__(self, value):
super(node, self).__init__()
self.value = value
self.next = None
t = node(3)
s = node(4)
t.next = s
r = node(5)
curr = t
nextNode = t.next
while nextNode is not None:
print "Node value",curr.value
curr = curr.next
nextNode ... |
c75cdba527683ebdfb26a8419d467cd06b618b51 | sunjiyun26/pythonstep | /Advancedfeatures/section.py | 472 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'sunjiyun'
print '切片'
_list = range(0,100,1)
r = []
n = 3
for i in range(n):
r.append(_list[i])
print r
print('1:3',_list[1:3])
print(_list[-9:])
print 'range(0,100):',range(1,99,2)
print _list[:2]
print _list[:10]
print _list[-20:-10]
print(_list[10:20... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.