blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
082b03fc887f3cf806c335df90a15c8b4252d491 | heikoschmidt1187/DailyCodingChallenges | /day05.py | 1,095 | 4.53125 | 5 | #!/bin/python3
"""
cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and
last element of that pair. For example, car(cons(3, 4)) returns 3, and
cdr(cons(3, 4)) returns 4.
Given this implementation of cons:
def cons(a, b):
def pair(f):
return f(a, b)
return pair
Implement c... |
0d2eb22e96d280be6ebb47a615a4802696fe8fed | Peter-John88/ConquerPython | /009dict_and_set.py | 1,371 | 4.15625 | 4 | # -*- coding:utf-8 -*-
####dict
d={'Michael':95, 'Bob':75, 'Tracy':85}
print d
print d['Michael']
d['Adam']=67
print d['Adam']
d['Jack']=90
print d['Jack']
d['Jack']=88
print d['Jack']
print d
#d['Thomas'] KeyError
print 'Thomas' in d
print d.get('Thomas')
print d.get('Thomas',-1)
print d
d.pop('Bob')
print... |
2155b71fbd35533810ae60c268b30368d518bd29 | Peter-John88/ConquerPython | /013recursion_function.py | 1,261 | 4.09375 | 4 | # -*- coding:utf-8 -*-
#一个函数在内部调用自身本身,这个函数就是递归函数
def fact(n):
if n==1:
return 1
return n * fact(n-1)
print fact(1)
print fact(5)
print fact(100)
print fact(500)
#print fact(1000) #RuntimeError: maximum recursion depth exceeded
#
#使用递归函数需要注意防止栈溢出。在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,... |
bf1a3ff2739da1243df79390fa067cf86e3e55ef | Peter-John88/ConquerPython | /032inheritance_and_polymorphism.py | 6,248 | 4.75 | 5 | # -*- coding:utf-8 -*-
#在OOP程序设计中,当我们定义一个class的时候,可以从某个现有的class继承,新的class称为子类(Subclass),而被继承的class称为基类、父类或超类(Base class、Super class)。
#比如,我们已经编写了一个名为Animal的class,有一个run()方法可以直接打印:
class Animal(object):
def run(self):
print 'Animal is running...'
#当我们需要编写Dog和Cat类时,就可以直接从Animal类继承:
class Dog(A... |
5600021c6eba77730e17a1f229633c511853a51f | Peter-John88/ConquerPython | /033get_object_info.py | 5,172 | 4.0625 | 4 | # -*- coding:utf-8 -*-
#当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?
###使用type()
#首先,我们来判断对象类型,使用type()函数. 基本类型都可以用type()判断:
print type(123)
print type('str')
print type(None)
#如果一个变量指向函数或者类,也可以用type()判断:
print type(abs)
class Animal(object):
pass
a = Animal()
print type(a)
#但是type()函数返回的是什么类型呢?它返... |
3666c2e7decfaa73e0a10daa76cdd23a1aa89379 | Achew-glitch/python_homework | /hw01_normal_02.py | 817 | 4.40625 | 4 | # Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значения на экран.
# Решите задачу, используя только две переменные.
# Подсказки:
# * постарайтесь сделать решение через действия над числами;
# * при желании и понимании воспользуйтесь синтакси... |
01f3ebdf63f79101d7b730c8edad56e620de79b3 | jonghyunlee1993/DailyAlgorithms | /Python/progrmmers/다리를지나는트럭.py | 582 | 3.71875 | 4 | def solution(bridge_length, weight, truck_weights):
queue = [0] * bridge_length
sec = 0
while True:
try:
queue.pop(0)
if truck_weights:
if sum(queue) + truck_weights[0] <= weight:
queue.append(truck_weights.pop(0))
else:
... |
f96b528f3aa6c35bff1686b9ed8ac0de6f12a079 | jonghyunlee1993/DailyAlgorithms | /Python/progrmmers/시저암호.py | 385 | 3.65625 | 4 | import string
def solution(s, n):
answer = ""
lower = string.ascii_lowercase * 2
upper = string.ascii_uppercase * 2
for letter in s:
if letter.isspace():
answer += " "
elif letter.isupper():
answer += upper[upper.index(letter) + n]
elif letter.islower():
answer += lower[lower.index(letter) + n]
... |
e9f0a62b9d52fb2e5117b6677726ca84e5b9f9e3 | jonghyunlee1993/DailyAlgorithms | /Python/samsung/홀수더하기.py | 257 | 3.765625 | 4 | num_lines = int(input())
for iteration in range(1, num_lines + 1):
answer = 0
line = list(map(int, input().strip().split()))
for number in line:
if number % 2 == 1:
answer += number
print(f"#{iteration} {answer}") |
4ce6e7caadfa9adde0252363d8c1493cb57c7de0 | jonghyunlee1993/DailyAlgorithms | /Python/goorm/앵무새꼬꼬.py | 492 | 3.703125 | 4 | # -*- coding: utf-8 -*-
# UTF-8 encoding when using korean
length = int(input())
for i in range(length):
res = str()
sent = str(input())
for char in sent:
if char.count("A") or char.count("a"):
res += char
elif char.count("E") or char.count("e"):
res += char
elif char.count("I") or char.count("i"):
... |
a14d0b1ac41ee8d11985e66840d81c7e5c6ae0e3 | TechnionYearlyProject/TheDoors | /models/Schedule.py | 17,867 | 3.59375 | 4 | """
This class represent the weekly schedule for user.
if a user want to order room,
first we check if on this time the user already have a meeting .
the schedule is a dictionary that looks ike that:
{'date': 12/11/23 , 'email': user@email.com, 'room_id': taub1, 'begin_meeting': 8 , 'end_meeting': 10 , 'order_id': ... |
ae2588a71653932e9fed3d6104286796ac56b656 | yogeshrakate/Methods_of_Different_DS | /Methods_of_List.py | 1,943 | 4.09375 | 4 | #Methods of list
#append(object)
L=[1,2,3]
L.append(4)
print('1',L)
L.append('Hi')
print('2',L)
L.append(3.14)
print('3',L)
L.append((5,8))#tuple can be added to list
print('4',L)
#L.append(7,8)
#print(L)this will give TypeError as 2 arguments can't be given
#clear()
L.clear()
print('5',L)
L.append([14,'yog',(4,),3.... |
9841c9fd33c70f5b97183772f8fcc2395334c189 | Mahler7/udemy-python-bootcamp | /milestone-projects/blackjack.py | 2,795 | 4.03125 | 4 | #Milestone Project 2 - Blackjack Game In this milestone project you will be creating a Complete BlackJack Card Game in Python.
# Here are the requirements:
# You need to create a simple text-based BlackJack game
# The game needs to have one player versus an automated dealer.
#Deck
# 2-10 are face value
# Face cards ... |
06751a10f3c8ba14a497b82c3fecefb1182b6cda | Mahler7/udemy-python-bootcamp | /milestone-projects/tic-tac-toe.py | 10,002 | 4.0625 | 4 |
def game_board():
print('Welcome to the Tic-Tac-Toe game')
print("Enter a number that's available on the board when it's your turn.")
board = [[1],[2],[3],[4],[5],[6],[7],[8],[9]]
print(board[0], board[1], board[2])
print(board[3], board[4], board[5])
print(board[6], board[7], board[8])
... |
c401e5a8cde94a8accd7480f97d201b8a7e01f8c | Mahler7/udemy-python-bootcamp | /errors-and-exceptions/errors-and-exceptions-test.py | 965 | 4.1875 | 4 | ###Problem 1 Handle the exception thrown by the code below by using try and except blocks.
try:
for i in ['a','b','c']:
print(i**2)
except TypeError:
print('The data type is not correct.')
###Problem 2 Handle the exception thrown by the code below by using **try** and **except** blocks. Then use a **f... |
d283bd5e0433d3c7ff28e3ff5ac8bd63982d930f | Mahler7/udemy-python-bootcamp | /python-statements/while-loops.py | 523 | 4 | 4 | x = 0
while x < 10:
print('x is currently:', x)
x += 1
else:
print("All Done")
y = 0
while y < 10:
print('y is currently:', y)
print('y is still less than 10, adding 1 to y')
y += 1
if y == 3:
print("y = 3")
else:
print('continuing ...')
continue
z = 0
while z ... |
83668edce1011fa81343180832fa0a6994e9de68 | Mahler7/udemy-python-bootcamp | /built-in-functions/enumerate.py | 369 | 3.828125 | 4 | def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1
l = ['a','b','c']
count = 0
for item in l:
print(count)
print(item)
count += 1
for count, item in enumerate(l):
print(count)
print(item)
for count, item in enumerate(l):
if count >= ... |
6d50180b655ec5f7ff2ce09b6848da5bdf5419c2 | dchoyle/deepKernelGeneralization | /KernelFunctionUtilities.py | 8,210 | 3.53125 | 4 | import numpy as np
import math
def getLinearKernel():
"""
Function to return a linear kernel function
:return: Returns linear kernel function
"""
def linearKernel( x ):
return( x )
return( linearKernel )
def getBaseKernel_q0( antiSymmetric=False ):
"""
... |
1ce1d163a4edda202089fe5108a5665c62746e12 | Accerator/python | /object/object01.py | 914 | 3.84375 | 4 | '''
class 类名[(父类)]:
属性:特征
方法:动作
'''
'''
普通方法格式:
def 方法名(self[,参数,参数]
pass
'''
class Phone:
brand = '华为'
price = 4999
type = 'mate 80'
# 普通方法
def call(self):
print(self)
print('正在打电话...')
print('正在访问通信录:')
for person in self... |
f4c465238b1b0ec12fafc8c7ee2e9566426f4fba | Accerator/python | /object/object02.py | 774 | 3.796875 | 4 | class Phone:
#魔术方法之一:称为魔术方法 __名字__()
def __init__(self):
self.brand = 'xiaomi'
self.price = 4999
def call(self):
print('------------>call')
print('价格',self.price) #不能保证每个self中都存在
p1 = Phone()
p1.price = 5999
p1.call()
print(p1.price)
class Person:
... |
5c0681c0ba6dbf152ee035f16a617d3629854e87 | Accerator/python | /list_new/list_new01.py | 1,106 | 3.9375 | 4 | #列表推导式
#旧的列表———》新的列表
#1.列表推导式 格式:[表达式 for 变量 in 旧列表] 或者 [表达式 for 变量 in 旧列表 if 条件]
names = ['tom', 'lily', 'abc', 'jack', 'bob']
result = [name for name in names if len(name) > 3]
print(result) # ['lily', 'jack']
result = [name.capitalize() for name in names if len(name) > 3]
print(result) # ['Lily', 'Jac... |
c65390a6306670227d9cb585116f622a83d64a0b | Accerator/python | /error/error01.py | 1,693 | 3.90625 | 4 | #异常:程序运行的时候报出来的
'''
def chu(a,b):
return a/b
#ZeroDivisionError: division by zero
chu(1,0)
'''
#异常处理
'''
情况一:
try:
可能出现异常的代码
except:输入的异常类型
如果有异常执行的代码
except:输入的异常类型
如果有异常执行的代码
except Exception:
如果有异常执行的代码
finally:
无论是否异常都会被执行的代码
情况二: ... |
1f48c6f4f083dfd221d8c6742cc5a46026ee930d | pankti09/Python | /10_prac.py | 2,489 | 4 | 4 | #Title : Program that Prepare grade sheet. For each of following subjects the marks should be given by user and grades should be calculated according to the given table and grade should be displayed for each subject.
#Name : Shah Pankti S.
#Roll No.: 17EC078
#Date : 26/12/2019
#Time : 19:45
Subject=... |
e56c12fd4825e42cd77c0fb25f9313b0fd09e7ed | pankti09/Python | /test1.py | 204 | 3.875 | 4 | #Title : WAP to convert temp from celsius to farhernhint
Temp=int(input("Enter temperature value in celsius:"))
Ftemp= ((9/5)*Temp) + 32
print("Temperature in Fahernhint is {}".format(Ftemp))
|
d8b55be1e5058572dedc86845a7ef8f31193e04b | pankti09/Python | /21_prac.py | 426 | 3.78125 | 4 | #Title : Program to print following using for loop
'''
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
'''
#Name : Shah Pankti S.
#Roll No.: 17EC078
#Date : 26/12/2019
#Time : 22:15
for i in range(0,6):
for j in range(i):
print('*',end=' ... |
6b3acef0360ebd20103a1c8bf651258b7fd5ab44 | Muhfa12/PROTEK-8 | /PP11.py | 2,662 | 3.84375 | 4 | # 11
buah = {"apel" : 5000, "jeruk" : 8500, "mangga" : 7800, "duku" : 6500}
def jumlahBuah(namaBuah):
jumlah = int(input("Berapa Kg : "))
harga = buah.get(namaBuah, 0) * jumlah
return harga
def beliBuah(buahDict):
print("Daftar Buah : ")
for x,y in buahDict.items():
print("- ", x, ... |
9473d3621a84a413d8b703c8880ff9c6b82c87e7 | AKumanov/tic-tac-toe | /tic-tack-toe/src/checker.py | 1,104 | 4.03125 | 4 | def check_horizontally(matrix):
for row in range(len(matrix)):
if matrix[row].count("X") == 3 or matrix[row].count("O") == 3:
return True
continue
return False
def check_vertically(matrix):
if [matrix[0][0], matrix[1][0], matrix[2][0]].count("X") == 3 or [matrix[0][0], matrix[1... |
5acbcdc262bf5e6a07f4b938dc4cb17599c45df4 | Michael37/Programming1-2 | /Lesson 9/Exercises/9.3.1.py | 683 | 4.34375 | 4 | # Michael McCullough
# Period 4
# 12/7/15
# 9.3.1
# Grade calculator; gets input of grade in numbers and converts info to a letter value
grade = float(input("what is a grade in one of your classes? "))
if grade > 0.0 and grade < 0.76:
print ("You have an F")
elif grade > 0.75 and grade < 1.51:
print ("You h... |
b5923c10755bafea992cd2cc35c273f467a87aec | Michael37/Programming1-2 | /Lesson 9/Labs/9.2 Lab.py | 1,194 | 3.859375 | 4 | # Michael McCullough
# Period 4
# 12/2/15
# Lab 9.2
# This program creates a magic 8 "ball"
import random
compNum = random.randint(1, 21)
user = input("Ask me a question. ")
if compNum == 1:
print ("It's certain!")
elif compNum == 2:
print ("It is decidedly so.")
elif compNum == 3:
print ("Without a do... |
b8073e5019b0abf478fe904b959c78b7b946d463 | Enzo-ltz/BachelorDIM-Lectures-Algorithms-2020 | /S1_algotools.py | 4,747 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Éditeur de Spyder
Ceci est un script temporaire.
"""
import numpy as np
import cv2
from random import *
def average(tab):
'''
This funtion calculates the average of a list
Args :
tab: The list of number
Returns the mean of the list
... |
7f7605fd1152109e4e1eff7e714f3123768d61e9 | AbrahamS0/Ciphered-messages-test | /basic_server1.py | 954 | 3.640625 | 4 | #server
# TCP Server Code
from socket import *
host="127.0.0.1" #Direccion ip a conectarse
port=4448 # Puerto a conectarse
# Imports socket module
s=socket(AF_INET, SOCK_STREAM)
s.bind((host,port)) # Binds the socket. Note that the input to
... |
e6b630f78e99dbc85a8501e8b3abe138d2b27b8d | HUSS41N/HackerEarth | /two_strings.py | 189 | 3.640625 | 4 | t = int(input())
for i in range(t):
s1,s2 = input().split()
s1 = ''.join(sorted(s1))
s2 = ''.join(sorted(s2))
if s1 == s2:
print('YES')
else:
print('NO') |
7dd153ac7ca5fd2fc2eb08f78de276be9818f065 | priyesh16/algo2 | /knapsack2.py | 1,845 | 3.734375 | 4 | #! /usr/bin/env python
import sys
import itertools
kslist = []
dynarr = []
def readfile(filename):
global dynarr
str = [" ", "\n"]
replacestr = [""]
""" read file into a list """
with open(filename) as f:
everyline = f.readlines()
""" get the first line and compute no of lines and bits """
firstline = ... |
32481f381fb1515bf17b869844a053db260235e9 | johnconnor77/ubidots-dialogflow_sarahdots | /Phase0x01/0x04-Retrieve_all_devices.py | 1,298 | 3.609375 | 4 | #!/usr/bin/env python
"""
Second Example for retrieving all devices
"""
import requests
import time
import json
ENDPOINT = "industrial.api.ubidots.com"
TOKEN = "BBFF-o9Wgd3hZokBMNd7d4vyzH9ZfLa5qj8"
def get_all_devices(url=ENDPOINT, token=TOKEN):
"""
Function that retrieves a list of devices from a si... |
c53b5c13adb30e712769f9662e1877bd9e64825a | billowkiller/algorithms | /permute.py | 267 | 3.625 | 4 | A = [1,2,3,4,5]
def heapPermute(n):
if n == 1:
print A
else:
for i in range(n):
heapPermute(n-1)
if n%2 == 1:
temp = A[0]
A[0] = A[n-1]
A[n-1] = temp
else:
temp = A[i]
A[i] = A[n-1]
A[n-1] = temp
heapPermute(5)
|
449a95907c0c66f0d46e695bc158cab4ee363c3d | gengho/Car2know | /Car2know/analysis/QueryData.py | 2,402 | 3.609375 | 4 | from urllib2 import Request, urlopen, URLError
from datetime import time
from datetime import date
import datetime
import time
import sys
import os
# Using request and urlopen to get data from car2go's API
# We need the city name and consumer_key
def querydata():
request = Request("http://www.car2go... |
b528a7a0524b5a8c401629da2c0d9a777fe49d50 | myConsciousness/metis | /metis/sql.py | 14,143 | 3.75 | 4 | # -*- coding: utf-8 -*-
'''
SQLite is a relational database management system contained in a C programming library.
In contrast to many other database management systems, SQLite is not a client–server database engine.
Rather, it is embedded into the end program.
SQLite is ACID-compliant and implements most of the SQ... |
a262e549b58f342aa613f379a9196ed94162d240 | maslah25/Pyrimid | /main.py | 179 | 3.515625 | 4 |
pyrimid = 10
for i in range(0,pyrimid):
for k in range(0,pyrimid-i):
print(" ",end="")
for j in range(0, 2*i+1):
print("*", end="")
print("Somalia")
|
b816d18b98ca3abe53ec949e64e4584a3df95084 | vikasrtr/pyLinearRegression | /demos/linear_regression.py | 804 | 3.671875 | 4 | """
Demo of linear regression (OLS)
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model
import sys
sys.path.append('../models')
# include the OLS class
from LinearRegression import LinearRegression
data = pd.read_csv('data/machine.data.txt', header=None)
# l... |
e646a897db85abcb328642dfce6d02b8a5b69fc5 | FRAZ5094/Pokemon-Emerald | /test.py | 117 | 3.578125 | 4 | bruh=[(1,2,"bruh"),(3,2,"ex")]
coordList=list(coord[:2]for coord in bruh)
if (1,2) in coordList:
print("True") |
418628f6f69e6c52d277468977ffcd8acc46028a | murilosleite/PycharmProjects | /pythonExercicios/ex018.py | 400 | 3.96875 | 4 | from math import sin, cos, tan, radians
angulo = float(input('Digite o angulo que você deseja: '))
seno = sin(radians(angulo))
coseno = cos(radians(angulo))
tangente = tan(radians(angulo))
print('O angulo de {} tem o SENO de {:.2f}'.format(angulo, seno))
print('O angulo de {} tem o COSENO de {:.2f}'.format(angulo, cose... |
5a4157149a1fe905774f0a51cf6ae637fbdf8f5c | murilosleite/PycharmProjects | /pythonExercicios/ex015.py | 220 | 3.5625 | 4 | dias = int(input('Quantos dias de carro alugado: '))
Km = int(input('Quantos Km rodado: '))
totaldiaria = dias * 60
totalkm = Km * 0.15
total = totalkm + totaldiaria
print('O total a pagar é de: R${:.2f}'.format(total)) |
d15526a594a6593a328f8200607616c128eb4296 | bozy15/mongodb-test | /test.py | 1,245 | 4.21875 | 4 | def welcome_function():
"""
This function is the welcome function, it is called
first in the main_program_call function. The function
prints a welcome message and instructions to the user.
"""
print("WELCOME TO LEARNPULSE")
print(
"Through this program you can submit and search for \... |
5f8fbe43e04ff046b53a7701851b60910778e8a2 | MadhumithaS2001/SR_DailyChallenge | /Triangle Pattern with Integer Series.py | 1,567 | 3.5625 | 4 | '''
Triangle Pattern with Integer Series
The program must accept an integer N as the input.
The program must form a string S by concatenating the positive integers from 1.
Then the program must print the N lines of the pattern based on the following conditions.
- In the 1st line, N-1 asterisks and the first charac... |
3e628ae24afa40165546a5ece7ed0078b620a2e3 | mattjhann/Powershell | /001 Multiples of 3 and 5.py | 342 | 4.21875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
numbers = []
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
numbers.append(i)
j = 0
for i in numbers:
... |
82208c3d15f8824bf5cd31176faeaa0bc8c40dc2 | lz-tangerine/coursera | /while_soma.py | 128 | 3.59375 | 4 | valor = int(input())
soma = n = 0
while valor != 0:
n = valor % 10
valor = valor // 10
soma += n
print(soma)
|
f2b6398b7887d94abb1eca5c5154eba9a5e209ef | JustynaGacek/dotsAndCrossesClientServer | /DotsAndCrosses/gamelogic.py | 5,373 | 3.546875 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
import math
from TCP import myEnum
import time
class GameLogic:
""" class representing the game of a dots and crosses """
rows = [0, 0, 0]
columns = [0, 0, 0]
diagonals = [0, 0]
winning_flag = 0
BUFFER_SIZE = 32
connection = 0
board = [... |
ce06222a257dc8c71f78807d43068c09da218248 | hsy0601/Test | /pythonexm/test.py | 584 | 3.921875 | 4 | from turtle import *
def draw(radius,color1,color2):
width(3)
color("black",color1)
begin_fill()
circle(radius/2,180)
circle(radius,180)
left(180)
circle(-radius/2,180)
end_fill()
left(90)
penup()
forward(radius*0.35)
right(90)
pendown()
color(color1,color2)
... |
e2b2c9b2c24413046ea0a66011ac651c68736a7e | EmilyJRoj/emoji27 | /anothernewproj/anothernewproj.py | 607 | 4.1875 | 4 | # starting off
print(22 / 7)
print(355 / 113)
import math
print(9801 / (2206 * math.sqrt(2)))
def archimedes(numsides, numSides):
innerAngleB = 360.0 / numSides
halfAngleA = innerAngleB / 2
oneHalfSides = math.sin(math.radians(halfAngleA))
sideS = oneHalfSideS * 2
polygoncircumference = numSides ... |
5c2a025d34af3629afcda380fd534d58261ae8f9 | 6bstkc1/PythonForAbsoluteBeginners | /word_jumble.py | 607 | 4 | 4 | """
word_jumble.py
has the user guess a word from a random list of words
first prints number of char
gives player 5 times to guess character
have player guess word
"""
import random
WORDS = ("abacus","catering","through","traveling","greatest","threating")
word = random.choice(WORDS)
print("The length... |
2bfb623891353f45fa590323432bc096b378a25e | rishabhzn200/PubMedDataAnalysis | /FileOperations.py | 975 | 3.84375 | 4 | import pickle
import os
# Class to define all the File Operations
class FileOperations:
def __init__(self):
pass
# Function to save the file using pickle
def SaveFile(self, filepath, obj, mode='wb'):
with open(filepath, mode) as picklefile:
if mode == 'w':
for ... |
1aec9168f36e40c2d51251fb939e5e14273e7016 | jaiminpan/awesome-memo | /python/code/zip_unzip.py | 772 | 3.546875 | 4 | import zipfile
#解压zip文件
def unzip(package_path, dest):
myzip=zipfile.ZipFile(package_path, 'r')
for name in myzip.namelist():
myzip.extract(name, dest)
f_handle=open(dest+name,"wb")
f_handle.write(myzip.read(name))
f_handle.close()
myzip.close()
#添加文件到已有的zip包中
def ... |
ec177630b37db033dac7ac09f012843045d79221 | Nikita9456/dictionary | /question9.py | 127 | 3.90625 | 4 | my_dict={
"a":50,
"b":58,
"c":65,
"d":65,
"y":98,
"w":32
}
n=sorted(my_dict.values())
k=n[-3:]
print(k) |
73259ac4e682d7f54c2b30c501b05cffe0b2f905 | KyleRosenberg/SkyscraperProblem | /sky.py | 1,733 | 3.65625 | 4 | from graphics import *
win = GraphWin("SkyScraper", 300, 300)
#win.yUp()
buildings = [[2, 9, 10], [3, 7, 15], [5, 12, 12], [15, 20, 10], [19, 24, 8]]
min = buildings[0][0]
max = buildings[len(buildings)-1][1] + 1
yVals = []
xVals = []
def sort():
for index in range(1,len(xVals)):
currentvalueX = xVals[index]
... |
4716341d78fd04ba068736c481d026eb1c81d50c | amitkaneria/myexperimentswithpython | /learn/basics/controlStructures/randomNumber.py | 639 | 4.03125 | 4 | import random
if __name__ == "__main__":
while True:
ins = int(input("Enter your number (-1 to exit):"))
testNum = random.randint(0,10)
if ins == -1:
exit()
while True:
if ins < testNum:
ins = int(input("Your number is too LOW, please enter... |
7d9b77b9791d6f48c8e2ea5bf7c93ac4e572ae53 | starxfighter/Python | /pythonoop/hospital.py | 1,964 | 3.515625 | 4 | import random
import math
# Create Patient class
class Patient():
def __init__(self, pid, name, allergies):
self.allergies = []
self.pid = pid
self.name = name
self.allergies = allergies
self.bedNum = None
# print(self)
def displayPat(self):
print("pid"... |
005820e4723485bd8150dcd66d0c7114e73643fa | starxfighter/Python | /pythonfundamentals/makingTuples.py | 197 | 3.84375 | 4 | def makeTuple(myDict):
items = list(myDict.items())
print(items)
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
makeTuple(my_dict) |
909f6711ace82c40da9af049d37f090f7e73ef2f | starxfighter/Python | /pythonfundamentals/filterByType.py | 1,420 | 4.03125 | 4 | # print a specific message based on type and criteria
def filter_type(value):
typechk = type(value).__name__
if typechk == "int":
if value <= 100:
print("That's a small number")
else:
print("Thats a big number")
elif typechk == "str":
if len(value) <= 50:
... |
acdb0ee0f25254591fac1875be103230231f2acd | starxfighter/Python | /pythonoop/animalOOP.py | 1,594 | 4.34375 | 4 | # Set definition of the parent animal class
class Animal():
def __init__(self, name, health):
self.name = name
self.health = health
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def display_health(self):
... |
25521e139c7e6739ad5278fdb323096f1227b96d | boheldo/Aniket | /sum of digits.py | 137 | 3.9375 | 4 | n=int(input("Enter a number:"))
total=0
while(n>0):
dig=n%10
total=total+dig
n=n//10
print("Sum of digits is:",total)
|
1c9c8321f2dcb5d162a95a318ffd56b512497d8c | Sasha1152/Training | /decorators/update_dict_decor.py | 537 | 3.65625 | 4 | # https://hackernoon.com/the-goodies-of-python-decorators-66r3tsy
def dict_from_func(func):
return {func.__name__: func}
operations = {}
@operations.update
@dict_from_func
def mul(a, b):
return a * b
@operations.update
@dict_from_func
def add(a, b):
return a + b
# equals this: add = operations.update(d... |
e6f814a58986b77532373c23d5d183771cd6f033 | Sasha1152/Training | /test_task/whats_get_printed.py | 216 | 3.5 | 4 | x = 4.5
y = 2
print(x // y)
x = True
y = False
z = False
if x or y and z:
print('yes')
else:
print('no')
one = chr(104) # h
two = chr(105) # i
print(one + two)
d = {}
d[1] = 1
d[1.0] = 2
d['1'] = 1
print(d) |
054c7869b58db2f55e9a83827396f34dc1bc7fc7 | Sasha1152/Training | /CheckiO/Scientific Expedition/TheMostWantedLetter.py | 1,163 | 4.03125 | 4 | # https://py.checkio.org/uk/mission/most-wanted-letter/
def checkio(text: str) -> str:
letters_counter = {}
text = text.lower()
for letter in text:
if letter.isalpha():
if letter in letters_counter:
letters_counter[letter] += 1
else:
letters_... |
2dc3c1c156d891aa9a13c74c89212b5991a58738 | Sasha1152/Training | /classes/@classmethod.py | 637 | 3.515625 | 4 | class MyClass:
@classmethod
def method(cls, arg):
print('%s classmethod. %d' % (cls.__name__, arg))
@classmethod
def call_original_method(cls):
cls.method(5)
def call_class_method(self):
self.method(10)
class MySubclass(MyClass):
@classmethod
def call_original_method(cls):
cls.method(6)
MyClass.metho... |
a806dad256f648f42532c9cf866a3c0e9caf48e7 | Sasha1152/Training | /def_value_by_default.py | 1,360 | 4.25 | 4 | def foo(x, l=[]):
l.append(x)
print(x, l)
foo(1) # 1 [1]
foo(2) # 2 [1, 2]
foo(3) # 3 [1, 2, 3]
print('------'*3)
def foo(x, l):
l.append(x)
print(x, l)
l = []
foo(1, l) # 1 [1]
foo(2, l) # 2 [1, 2]
foo(3, l) # 3 [1, 2, 3]
print('------'*3)
def f(a = 0):
a += 1 # Операція присвоєння по ... |
e8d24fec55c875729cbd28c35ebe0ad7a8adb0e6 | Sasha1152/Training | /classes/super-2.py | 424 | 3.734375 | 4 | class A(object):
mind = 'yes'
def __init__(self, name, surname):
self.name = name
self.surname = surname
class B(A):
def __init__(self, name, surname, age, gender):
super(B, self).__init__(name, surname)
self.age = 36
self.gender = gender
obj_a = A('Kate', 'Rozd')... |
4bece578004f785b9b3ca4338d017c1fcc25c30e | Sasha1152/Training | /classes/super-3.py | 654 | 3.859375 | 4 | # https://www.journaldev.com/15911/python-super
class A:
def __init__(self):
print('Initializing: class A')
def sub_method(self, n):
print('Printing from class A :', n)
class B(A):
def __init__(self):
print('Initializing: class B')
super().__init__()
def sub_method(s... |
81d3261cb03e8b7dbea6af9ad6902a66a1ddba3e | Sasha1152/Training | /CheckiO/Home/sun_angle.py | 660 | 3.671875 | 4 | # https://py.checkio.org/ru/mission/sun-angle/
from time import strptime
def sun_angle(time):
strptime(time, '%H:%M')
hours, minutes = (int(i) for i in time.split(':'))
if strptime(time, '%H:%M') < strptime('6:00', '%H:%M')\
or strptime(time, '%H:%M') > strptime('18:00', '%H:%M'):
return "I don't see the sun... |
ad7d56f80307b9d52fbe5bb7a0323b8cbe51d0eb | Sasha1152/Training | /test_task/odd_even_numbers.py | 486 | 3.78125 | 4 | def purse_number(num):
"""
>>> print(purse_number(34567))
{'odd': 3, 'even': 2}
>>> print(purse_number(100))
{'odd': 1, 'even': 2}
>>> print(purse_number('word'))
False
"""
if type(num) is str:
return False
counter = {'odd': 0, 'even': 0}
num_str = str(num)
for i... |
d51606bc7069fe22fa422e4b08269ec16daca276 | Sasha1152/Training | /CheckiO/Ice Base/MoveZeros.py | 275 | 3.703125 | 4 | # https://py.checkio.org/uk/mission/move-zeros/
def move_zeros(items: list) -> list:
return [i for i in items if i] + [i for i in items if not i]
print(list(move_zeros([0, 1, 0, 3, 12])))
print(list(move_zeros([0])))
print(list(move_zeros([0, 1, 0, 2, 1, 0, 3, 12]))) |
e538287b39d59ce578719995a3b5c944efe73ed7 | Sasha1152/Training | /classes/@classmethod_2.py | 567 | 3.75 | 4 | class A():
count = 0
def __init__(self):
A.count += 1
def exclaim(self):
print('I am a class "A"!')
@classmethod
def kids(cls):
print('class "A" has', cls.count, 'objects') # or (A.count) - the same
obj1 = A()
obj2 = A()
obj3 = A()
A.kids() # 3 - attribute of class
ob... |
69220b2fbfebcba4f4db4af6e34cc104d814f220 | Sasha1152/Training | /strings/replace_word+doctest-2.py | 1,026 | 3.703125 | 4 | def replace(s, old, new):
"""
>>> replace('Ukraine', 'i', 'I')
'UkraIne'
>>> s = 'I love summer! summer is my favorite time of year!'
>>> replace(s, 'summer', 'winter')
'I love winter! winter is my favorite time of year!'
>>> replace(s, 'o', 'a')
'I lave summer! summer is my favarite tim... |
74e609e227e2eb5ddf3ed318a50424b68258ea65 | Sasha1152/Training | /task.py | 1,583 | 3.828125 | 4 | testing_list = [1, 2, 3, 4, 0, -1, 4, 5, 6, 7, 8, 9]
print(testing_list[0])
print(testing_list[1])
# 1. Find minimal element of list using `for` loop.
number_min = testing_list[0]
for number in testing_list:
if number < number_min:
number_min = number
print(number_min)
# 2. Find minimal element of ... |
4fe99da9a59cc213e6a1f1e2d4cc83064118852e | Sasha1152/Training | /classes/circle_Raymond.py | 2,119 | 4.125 | 4 | # https://www.youtube.com/watch?v=tfaFMfulY1M&feature=youtu.be
import math
class Circle:
"""An advanced circle analitic toolkit"""
__slots__ = ['diameter'] # flyweight design pattern suppresses the instance dictionary
version = '0.1' # class variable
def __init__(self, radius):
self.radius ... |
6010d7d73d05156605824f305b2024a1b8f16a84 | Sasha1152/Training | /classes/self.py | 287 | 3.796875 | 4 | class A:
def __init__(self, name):
self.name = name
def say(self):
return 'Hello!'
husband = A('Sasha')
print(husband.name) # Sasha
husband.name2 = 'Alex'
print(husband.name2) # Alex
print(husband.say()) # Hello!
# the same:
print(A.say(husband)) # Hello!
|
70e8918f7da010ed382af76bdac24f586d66743a | Sasha1152/Training | /decorators/box_decorator.py | 294 | 3.59375 | 4 | def decorator(f):
def wrapper(a, b, c):
print('Begin')
print('a=' + str(a), 'b=' + str(b), 'c=' + str(c))
print('V =', f(a, b, c))
print('End')
print('---' * 6)
return wrapper
@decorator # or box = decorator(box)
def box(a, b, c):
return a * b * c
box(2, 3, 4)
box(10, 10, 20)
|
c117de71c3f7e51f8ab4e05e0d16da2311a9da10 | veroon-eng/x-o | /x-o(human vs human).py | 3,597 | 3.90625 | 4 | board={"0":" ","1":" ","2":" ",
"3":" ","4":" ","5":" ",
"6":" ","7":" ","8":" "}
player=1
total_moves=0
end_check=0
def check():
#####checking for player one(X)#####
#check for rows
if board["0"]=="X" and board["1"]=="X" and board["2"]=="X":
print("player one won!!!!!!... |
04fcd980b7c380c31df51c6fb906ce4a4a2fbd3f | matthewgilbert/mapping | /mapping/util.py | 29,764 | 3.71875 | 4 | import pandas as pd
import numpy as np
import os
def read_price_data(files, name_func=None):
"""
Convenience function for reading in pricing data from csv files
Parameters
----------
files: list
List of strings refering to csv files to read data in from, first
column should be dat... |
62d5a976d67014b71d07566498a14758068915d2 | emielver/MonzoScraper | /Author.py | 1,262 | 3.671875 | 4 | class Author:
def __init__(self, name, position):
self.name = name
self.positions = [position]
self.gender = ''
self.blogs = []
def add_blog(self, blog):
self.blogs.append(blog)
def add_position(self, position):
self.positions.append(position)
def set... |
80633ad4f9c490c87f5c3f1487666750cee182f5 | jbpeters/pyfractal | /mandelcolors.py | 330 | 3.5625 | 4 | import math as M
PI=M.pi
def Make_color(Max_iter,frequency,count):
w=[]
d=[]
value=[]
for hue in range(3):
w.append(frequency[hue]*PI/Max_iter)
d.append(w[hue]*Max_iter+PI)
value.append(int(255/2.0*(1+M.cos(w[hue]*count-d[hue]))))
return(value)
#print Make_color(1024,(3,7,... |
a5a57b64d94b05d9d17fb70835b7957caa2eff62 | cihangirkoral/python-rewiew | /homework_02.py | 1,834 | 4.71875 | 5 | # ################ HOMEWORK 02 ######################
# 4-1. Pizzas: Think of at least three kinds of your favorite pizza Store these
# pizza names in a list, and then use a for loop to print the name of each pizza
# • Modify your for loop to print a sentence using the name of the pizza
# instead of... |
4c585fc81235aee9bfb86f5adbbc0e46dd2bc86d | maryrosecook/recursion | /flatten.py | 167 | 3.671875 | 4 | def flatten(l):
f = []
for item in l:
if type(item) == list:
f.extend(flatten(item))
else:
f.append(item)
return f
|
f104db302deb0898e2627a408280aee54d7f76d8 | HelpSlipFrank/practice | /rock_paper_scissors.py | 3,249 | 3.9375 | 4 | """
Make a two-player Rock-Paper-Scissors game.
(Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner,
and ask if the players want to start a new game)
Remember the rules:
Rock beats scissors
Scissors beats paper
Paper beats rock
"""
def rock_paper... |
efe029dfb58aa46842ed74b76c21914d988a802e | SyedAltamash/AltamashProgramming | /Fibonacci_Sequence.py | 393 | 4.15625 | 4 | #from math import e
#result = input('How many decimal places do you want to print for e: ')
#print('{:.{}f}'.format(e, result))
def fibonacci_sequence(number):
list = []
a =1
b = 1
for i in range(number):
list.append(a)
a,b = b,a+b
print(list)
result = int(input('Hey e... |
8506c3f7419674331e96f48eebe37d4953034446 | Almuafa/covid19 | /covid.py | 2,741 | 3.578125 | 4 | import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
def pull_states():
"""
name: pull_states
desc: this function pulls all the states which will be used by other modules
input: None
output: list (list of all states)
example invocation:
states = pull_states... |
539949c601098bf6ee18857023a80eb440d06426 | 6reg/data_visualization | /visualize.py | 1,899 | 4.1875 | 4 | """
Image Visualization Project.
This program creates visualizations of data sets that
change over time. For example, 'child-mortality.txt'
is loaded in and the output is a vsualization of the
change in child mortality around the world from 1960
until 2017. Red means high and green means low.
"""
from simpleimag... |
3e34cf723f0f3a1ba5478f4c4affd2ce6342edab | a93-git/codingame-solutions | /clash/fastest/fast-clash13.py | 326 | 3.71875 | 4 | """ Good teeth - 1, rotten teeth - 0, pulled out teeth - -
Pull out the rotten tooth
"""
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
n = int(input())
for i in range(n):
row = input()
res = row.replace('0', '-')
prin... |
bd0d76a828767321fa84ea23a8059672048998a3 | a93-git/codingame-solutions | /puzzles/easy/horse_racing_duals.py | 637 | 3.671875 | 4 | """ Find the min differences between two numbers for the given number set"""
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
n = int(input())
_min = 0
p = []
for i in range(n):
pi = int(input())
p.append(pi)
p.sort()
curr_v... |
bc593c5a3b29513bab27e6c01e950491bf427636 | a93-git/codingame-solutions | /clash/reverse/rev-clash6.py | 325 | 3.859375 | 4 | """ Print a triangle of n with n-rows
n = 3
3
33
333
n = 4
4
44
444
4444
"""
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
n = int(input())
for i in range(1,n+1):
s = ''
for j in range(i):
s = s + str(n)
pri... |
73a2c511e242f01da0cfd04c045628a4e2660b24 | a93-git/codingame-solutions | /clash/fastest/fast-clash17.py | 281 | 3.84375 | 4 | """ Remove digits from a string"""
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
s = input()
a = ['0','1','2','3','4','5','6','7','8','9']
for i in a:
s = s.replace(i, '')
print(s) |
bf57ef8ab0f2651f42a5c11269c0ea6d04f94380 | a93-git/codingame-solutions | /clash/fastest/fast-clash3.py | 330 | 3.734375 | 4 | """ Get the sum of alphabet values of a string of non-zero length"""
import sys
import math
s = input()
l = list(s)
res = 0
for i in l:
if ord(i) <= 122 and ord(i) >= 97:
res = res + (ord(i) - 96)
elif ord(i) <= 90 and ord(i) >= 65:
res = res + (ord(i) - 64)
else:
res = res + 0
... |
dc014e1c583d95bde2155a4cdb499b6ede613b9d | a93-git/codingame-solutions | /clash/fastest/fast-clash15.py | 258 | 4.03125 | 4 | """ Print the average ASCII value of a string"""
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
s = input()
t = 0
for i in s:
t = t + ord(i)
print(t//len(s)) |
7732d8a64f90e4466b5765b7280254fb90bb6816 | myatthukyaw-edu/activelearning | /plot_function.py | 1,231 | 3.671875 | 4 | import matplotlib.pyplot as plt
import numpy as np
def plot_fun(X, y):
#X_train, X_test = X_train.astype('int32')*255. , X_test.astype('int8')*255.
# Define the labels of the dataset
labels = ['airplane', 'automobile', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck']
# Let's view ... |
c1c6d1fa75d2b31f699df0e5f8ac77cca1161928 | frisomeijer/ProjectEuler100 | /Problem_002/Solution_002.py | 734 | 4.0625 | 4 | '''
Problem 2:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-v... |
b98da74f144dc5cb6a3f6e691f9a0f2e41a8cb03 | frisomeijer/ProjectEuler100 | /Problem_020/Solution_020.py | 660 | 4.15625 | 4 | '''
Problem 20:
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
'''
import time
start_time = time.time()
def factorial_digit_sum(n):
fac... |
eb165f82166326f83d339974a7579db49ed047d7 | GLAU-TND/python-programming-assignment2-jaish-chimnani | /largest_number.py | 236 | 3.640625 | 4 | from itertools import permutations
a=list(map(int,input().split()))
def largest(l):
lst = []
for i in permutations(l, len(l)):
lst.append("".join(map(str,i)))
return max(lst)
print(largest(a))
|
a82368543cd9c132cf1b7be409942c718b2e6d54 | luissalgueiro/curso_iot | /codigos_py/dog.py | 1,267 | 4.15625 | 4 | ## AUTHOR= Luis Salgueiro
## DATE= 21/10/2019
## DESCRIPTION = CODE FOR ACTIVITY 2 OF PLA3
class Dog:
species="caniche"
def __init__(self, name, age):
self.name = name
self.age = age
bambi = Dog("Bambi", 5)
mikey = Dog("Rufus", 6)
boby = Dog("Boby",15)
rino = Dog("Rino", 5)
oli = Dog("Oli",... |
75a85e7905c31de3fbd3ac4e082c57de088b49a1 | carxly/Small-Python-projects | /Games/3_rps.py | 551 | 3.5625 | 4 | # ROCK PAPER SCISSCORS
from tkinter import *
from tkinter.ttk import *
window = Tk()
window.title('Rock! Paper! Scissors!')
window.geometry('600x400')
greeting = Label(window, text='Rock, paper or scissors..??')
greeting.grid(column=1, row=0)
button1 = Button(window, text='ROCK')
button1.grid(column=0, row=2)
button... |
aa130ce8eaf46f609e8b47ddb3db71daa277a499 | natgeosociety/Transmogrify | /transmogrify/filesystem/__init__.py | 1,051 | 4 | 4 | """
Slight abstraction of the filesystem calls to allow for other types of storage
"""
import os
def makedirs(dirname):
if dirname.startswith("s3://"):
# S3 will make the directories when we submit the file
return
else:
assert dirname.startswith("/"), "dirname must be absolute"
bi... |
cf39769061e619e9a3edf87688327e97f96ccf26 | prasanna1695/python-code | /1-2.py | 474 | 4.34375 | 4 | #Write code to reverse a C-Style String.
#(C-String means that abcd is represented as five characters
# including the null character.)
def reverseCStyleString(s):
reversed_string = ""
for char in s:
reversed_string = char + reversed_string
return reversed_string
print "Test1: hello"
print reverseCStyleString("he... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.