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 |
|---|---|---|---|---|---|---|
1ac909019923ab1c179b73428a8cb574b19991ef | bakunobu/exercise | /1400_basic_tasks/chap_11/ex_11_208.py | 292 | 3.828125 | 4 | def odd_el(nums:list) -> None:
pairs = [1 if not nums[i] % 2 and not nums[i + 1] % 2 else 0 for i in range(len(nums) - 1)]
if 1 in pairs:
i = pairs.index(1)
print(* nums[:i], sep=', ')
else:
print('Таких чисел в массиве нет!')
|
63dabfa515636bd0ef3bcb0020e08883350cbcb0 | marianabsctba/Python_Dev_2 | /Questão05_c_AT.py | 1,656 | 3.625 | 4 | #Questão 05c realizada de modo separado. Favor inserir os arquivos .py da questão 05 com o arquivo assessment_PIB.csv.
import matplotlib.pyplot as plt
import time
def dados_arquivo():
arquivo = open('assessment_PIB.csv', 'r', encoding='utf-8')
arquivo = arquivo.read()
lista_paises = {}
for linha in ar... |
2cfbaf5685d3a36bd65f07467471d29c9482abc2 | sunjilong-tony/exec | /士兵.py | 816 | 3.546875 | 4 | # coding= utf-8
class Gun:
def __init__(self, name):
self.name = name
self.bullet_count = 0
def add_bullet(self, count):
self.bullet_count = count
def shoot(self):
# 判断是否有子弹
if self.bullet_count <= 0:
print("没有子弹了%s" % self.bullet_count)
retu... |
d01f0c7cfb0d150d4fe04c4182b30f142cfcfb41 | sunjilong-tony/exec | /性别的设置.py | 203 | 3.6875 | 4 | # coding= utf-8
import json
def gender(name, sex=None):
if sex is True:
sex = "man"
elif sex is False:
sex = "women"
print("%s is %s" % (name, sex))
gender("tony", True)
|
d080e518dc3c5bd0204bd4c52fb2f85c07710fbd | HOWZ1T/learning-design-patterns | /Builder/interfaces.py | 592 | 3.671875 | 4 | import abc
class Item:
@abc.abstractmethod
def name(self):
raise NotImplementedError("users must implement the method name to use this base class")
@abc.abstractmethod
def packing(self):
raise NotImplementedError("users must implement the method packing to use this base class")
d... |
da6f78143b58a534a7e2c0725b4623612752aeb8 | dma-neves/ProjectEuler | /P4_Largest_Palindrome_Prod/app.py | 248 | 3.515625 | 4 | res = 0
upBound = 1000
for a in range(upBound):
for b in range(upBound):
num = a*b
str_num = str(num)
invert_str_num = str_num[::-1]
if str_num == invert_str_num and num > res:
res = num
print res |
3a5511f8148f60d17457922453d62f73e4b7b2b2 | dma-neves/ProjectEuler | /P12_Divisible_Triangular_Number/app.py | 370 | 3.578125 | 4 | import math
def numDivisors(num):
res = 0
for i in range(1, (int)(math.sqrt(num))):
if (num % i) == 0:
res += 2
return res
triangleNum = 0
counter = 0
found = False
threshold = 500
while not found:
counter += 1
triangleNum += counter
if numDivisors(triangleNum) >= thr... |
48b0b7328d005d99dcbe5e8f2ccede2b0b50b40a | SamZhou33/LPTHW | /EX36/ex36.py | 7,022 | 3.625 | 4 | from sys import argv
from sys import exit
import time
script, name = argv
tools = []
def start():
print """
Hey %s! I have a bad news for you. You are now wanted by police.
I don't know what you did, but I trust you.
The police will come very soon.
You have to escape to a safe place as soon as possible,
and then ... |
a60aab0c0dc270cf03bc9c8385bf30aef27c3a87 | behnazakd/my_practice | /condition/ascii_code.py | 177 | 3.578125 | 4 | columns = 8
rows = 256 // columns
for i in range(rows) :
for j in range(columns):
number =j * rows + i
print(number, chr(number), end = '\t|\t')
print( ) |
66fda70cb15fbe762c0573574979f318c02612eb | misstong/learning_python | /cookbook/DSAlgo/priority_queue.py | 500 | 3.84375 | 4 | import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self,item,priority):
heapq.heappush(self._queue,(-priority,self._index,item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
class Item:
def ... |
6b4a5b7f3c6aa2e690d07735dd2237ee4daac724 | misstong/learning_python | /oop/MultiInheriAndMixin.py | 1,348 | 3.59375 | 4 | class Animal:
def eat(self):
print('Animal can eat')
class Bird(Animal):
def eat(self):
# super().eat()
print('Bird can eat')
super().eat()
class Flyable(Animal):
def eat(self):
# super().eat()
print('Flyable eat')
super().eat()
class FlyingBird(Fly... |
0bcea3fc42bbdf6b0266cccff592a849b0c2d9d3 | alexander857/-FP-_Tareas_00355519 | /factorial.py | 243 | 4.0625 | 4 | print("Factorial de un numero")
n = int(input("Ingrese un numero "))
factorial = 1
if n == 1:
print("El factorial de ",n," es ",factorial)
else:
for i in range(1,n+1):
factorial = factorial*i
print("El factorial de ",n," es ",factorial) |
f8583e9742df9e9fe0b0be756e2ed4bf5cb52e13 | amit9594/Jupyter-Notebooks | /main_package_python/myprogram.py | 223 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 9 15:56:09 2020
@author: user1
"""
def my_func():
print("Hey i am in myprogram.py module")
print("my device ")
def is_even():
print("2,4,6,8,... are even numbers") |
6d9d9177b611ef9e5dc1452c931ebd9e6c05874a | GeraMantecon/HoppierTest | /hoppier_test.py | 1,707 | 3.90625 | 4 | import sys
import json
#Method to transform and clean string with snacks to list of snacks.
def to_SnackList(snack_string):
snacks = [snack.strip() for snack in snack_string.replace(' and ',',').split(',')]
return snacks
def main():
#Load JSONS with snackers data and product data
with open('MOCK_SNACK... |
f84b129fe8999cc966b16db52bdd1ad26a9640eb | kojimakentaro/Python-Scraping | /scr.py | 2,919 | 3.53125 | 4 | #プラグインのインポートを行う
from typing import Text
import requests
from time import sleep
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
options = webdriver.ChromeOptions()
#ヘッドレスモード(使用することにより、実際のサイトの表示はなくなる)
options.add_argument("--headless")
#シークレットモード
#o... |
2d57633cab9e3f4d6f6efbf098f7fcf4a6633f4d | BRaguiarpereira/Aula04Python | /ex15.py | 1,185 | 3.703125 | 4 |
valorS = 0
valor1 = 0
valor2 = 0
valor4 = 0
valor5 = 0
valor9 = 0
codi = 'adas'
cont = 0
scont = -1
while codi!=0:
codi = int(input('Digite o cod :'))
if codi == 1 :
q = float(input('Digite quantidade de produtos:'))
valor1 = 0.50 * q
cont = 1
elif codi == 2 :
... |
783931f0289b1607b5ba54d042f3c213596b6804 | BRaguiarpereira/Aula04Python | /ex18.py | 1,096 | 3.765625 | 4 | v = int(input('Digite valor :'))
con = 0
cont = 0
cont1 = 0
cont2 = 0
cont3 = 0
cont4 = 0
if v==0:
print('Seu retardado não me deu nada e ainda quer troco !!asdhgqw')
else:
while v!=0:
if v>=100:
v = v-100
con = con + 1
elif v>=50:
v = v-... |
645680ff1d2fcfe4da8cadb892a45aabed3cf2b7 | Ahmadkhan12345566/Python-for-beginners | /lecture_002/HellowWorld.py | 663 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 23 03:34:27 2017
@author: Ahmad khan
"""
"""
Python is An interpreted language
there in no conncept of terminotor(;) like in other languages
in python we get rid of these terminators (;) and starting ending baraks ({ })
Python have very easy syntaxt
python verson ... |
1c98e0e4f50a97af79109a1be1688c33f8d8e1b4 | Ahmadkhan12345566/Python-for-beginners | /lecture_013/Opp.py | 920 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#class variable
#method overloding (same name same parameters)
class Person:
'this is a fake class'
a="9"#class variable
def __init__(self ,name):
self.name=name;#datamembers
def xyz(self):
self.name
... |
2bb67da5b3a316ee6a8049daeee646cefa5ac9df | ErnestoSiemba/Python-for-Everybody | /Chapter 8 Exercise 4a.py | 255 | 3.828125 | 4 | words=[]
fhand=open('romeo.txt')
for lines in fhand:
for word in lines.split():
#OK youTube cowboy did it this way, but this isn't taught until Chapter 9!!!!!!!
if word not in words:
words.append(word)
print(sorted(words))
|
a7264cd2838cbe5ae214b15eb6246595ac464c26 | ErnestoSiemba/Python-for-Everybody | /Chapter 11 Exercise 1.py | 280 | 3.78125 | 4 | import re
fname=input('Enter a File to process: ')
fhand=open('mbox.txt')
regex=input('Enter a regular expression: ')
count=0
for line in fhand:
line = line.rstrip()
if re.findall(regex, line):
count=count+1
print(fname, 'had', count, 'lines the matched', regex)
|
211aab051c9fd72261ceff24c64db9a4e16edc23 | ShuguangSun/allocation | /allocation/randomization.py | 19,914 | 4.4375 | 4 | """
Randomization is a module that provides functions to create random group
assignments to be used in clinical trials
"""
import random
import numbers
def cumsum(numbers):
"""Calculates the cumulative sum of a numeric list.
This function operates on the list *in place*.
Args:
numbers: a list o... |
0160c1d040878eb89087177cdf5321fea717e481 | ShuguangSun/allocation | /allocation/adaptive_allocation.py | 4,030 | 4.15625 | 4 | import random
class Minimization(object):
"""Minimization attempts to minimize imbalance within a set of factors between
a group of treatments.
Suppose you are interested in sex and race a prognostic factors in a
clinical trial. So far, you have the following counts:
Prognostic Factor | Level ... |
8b0ba97a00e3dd700beeb2e37ace3e6cdf917756 | wylaris/Monopoly | /properties.py | 1,489 | 3.53125 | 4 | import json
class Property:
name = None
color = None
cost = None
current_rent = None
rent0 = None
rentM = None
rent1 = None
rent2 = None
rent3 = None
rent4 = None
rentH = None
# mortgage = house_cost/2
house_cost = None
owner = 0
space = None
def __ini... |
030f54f486243e31174ef85a5ce890ebb39fbf13 | KrikunovEV/study | /DIP/5/test.py | 121 | 3.5 | 4 |
nodes = [0, 1, 2, 3, 4, 5, 6]
while len(nodes) != 0:
print (len(nodes))
if 0 in nodes:
nodes.remove(0) |
307fa5db59cf3b748e45f8cf80cb9ac4688e4133 | mervealgi/python-tutorials | /day2.py | 1,239 | 4.375 | 4 | #INTRODUCTION TO PYTHON DAY2
###LOGICAL OPERATIONS
a, b = True , False
print(type(a))
print(a or b) #will be True
print(a and b) #will be False
print(not a) #will be False
print (a != b) #will be True,bcs re not equal
print(a == b) #will be False, bcs re not equal
###SLICING
array1 = "PYTHON"
print(array1[0]... |
2b1ab24275d8e24340e4a6ce61c49cda9e7fdd1c | TNEWS01/projets | /prj_02/JEU_MORPION.py | 3,671 | 3.796875 | 4 | # -*-coding:utf-8 -*
#=================
# Jeu du Morpion
#=================
# Import des modules
#===================
import random
from IPython.display import clear_output
# Définition des Fonctions
#=========================
def affiche_tableau(tableau):
clear_output()
print(' | |')
print(' ' + tableau[7] +... |
a0970c0a3e7383e280edbac5a56a18d0df4f9fd5 | TNEWS01/projets | /Formation_Python/Dictionnaires.py | 1,684 | 4 | 4 | # -------------------
# Les dictionnaires
# -------------------
# Création d'un dictionnaire avec {} et : pour spécifier la clef et sa valeur
mon_dict = {'clef1':'valeur1','clef2':'valeur2'}
print(mon_dict)
# {'clef1': 'valeur1', 'clef2': 'valeur2'}
# Retrouver une valeur avec sa clef
print(mon_dict['clef2'])
# vale... |
368e1e44fd55ad8befef5f4eba7a59dae07c35ac | TNEWS01/projets | /Formation_Python/Fonctions.py | 1,360 | 3.9375 | 4 | # -------------------
# Fonctions
# -------------------
# Les fonctions sont une des façons les plus simples de réutilisation de code en Python,
# et elles vont nous permettre de commencer à penser à la conception de programmes
# -------------------
# L' instruction def
#
# def nom_de_fonction(parm1, parm2):
# '''
# ... |
7b3534f75029b8193313f08afaec998f015a71ec | TNEWS01/projets | /Formation_Python/Listes.py | 2,064 | 4.28125 | 4 | # -------------------
# Les listes
# -------------------
# Créer une liste et lui assigner le nom de variable ma_liste
ma_liste = [1,2,3]
print(ma_liste)
# -------------------
ma_liste = ['Une chaine',23,100.232,'o']
print(ma_liste)
# -------------------
# Nombre d'éléments dans la liste
ma_liste = ['un','deux','troi... |
3af0e872f98084ff092b7181c68e96883044841d | naestevez/google-python-exercises | /copyspecial/copyspecial.py | 2,636 | 3.921875 | 4 | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
# import zipfile
"""Copy Specia... |
b53138f201948f2ba48852bc0c01b19a376cac55 | oSoc18/open-parking | /data-processing/cache.py | 1,915 | 3.546875 | 4 | """
Sends a request to every static data link in the index file and stores the
result in a folder, in a file named after the UUID of the facility. It allows
to cache locally the static data, in order not to send requests every time.
It uses a small JSON file to keep track of which files have been cached so far,
which w... |
b6e3692dd74e0baea8f85aec440d2c1831d360a4 | Bobby981229/Python-Learning | /Day 02 - Language Element/String_Type.py | 533 | 4.40625 | 4 | """
字符串运算符
判断是否为小写字母: 'a' <= char <= 'z'
判断是否为大写字母: 'A' <= char <= 'Z'
判断是否为字母: 'a' <= char <= 'z' or 'A' <= char <= 'Z'
判断是否为中文: '\u4e00' <= char <= '\u9fa5'
判断是否为数字: '0' <= char <= '9'
"""
# 统计字符串中小写字母的个数
str1 = "Hello, World !"
count = 0
# 遍历循环查找字符串中的小写字母
for char in str1:
if 'a' <= char <= 'z':
coun... |
0c3a027118d292cce1b372a295e646165e4a2459 | Bobby981229/Python-Learning | /Day 07 - Data Structures_List/Operator.py | 2,372 | 4.25 | 4 | """
运算符
"""
s1 = 'hello ' * 3
print(s1) # hello hello hello
s2 = 'world'
s1 += s2 # 拼接字符串 s1 = s1 + s2
print(s1) # hello hello hello world
print('ll' in s1) # True, ll在hello中
print('good' in s1) # False, good在hello中
str2 = 'abc123456'
# 从字符串中取出指定位置的字符(下标运算)
print(str2[2]) # c, 从零开始
# 字符串切片(从指定的开始索引到指定的结束索引)
p... |
d25f779f4fa8fcedf26a99c36a95fd08ddfb1fff | Bobby981229/Python-Learning | /Day 04 - Loop Structure/While.py | 370 | 3.71875 | 4 | import random
result = random.randint(1, 100)
count = 0
while True:
count += 1
answer = int(input('请输入数字: '))
if answer > result:
print("小一点")
elif answer < result:
print("大一点")
else:
print("猜对了")
break # 终止循环
print("\n您一共猜了%d次, 最终答案为%d" % (count, result))
|
8b26c3afa7882019664ed7c783ee7d25fb8bdb69 | Bobby981229/Python-Learning | /Day 18 - Regular Expressions/Python_RegularExpression.py | 1,382 | 3.875 | 4 | """
Python对正则表达式的支持
Python提供了re模块来支持正则表达式相关操作,下面是re模块中的核心函数
"""
# compile(pattern, flags=0) 编译正则表达式返回正则表达式对象
# match(pattern, string, flags=0) 用正则表达式匹配字符串 成功返回匹配对象 否则返回None
# search(pattern, string, flags=0) 搜索字符串中第一次出现正则表达式的模式 成功返回匹配对象 否则返回None
# split(pattern, string, maxs... |
c439e861dcd14dedd32cc102897376998c0bca2e | Bobby981229/Python-Learning | /Day 08 - Data Structures_Tuple/Tuple_Definition.py | 1,135 | 3.828125 | 4 | """
定义和使用元组
元组是不可变类型,这就意味着元组类型的变量一旦定义,
其中的元素不能再添加或删除,而且元素的值也不能进行修改
"""
# 定义一个三元组
t1 = (30, 10, 55)
# 定义一个四元组
t2 = ('刘尚远', 21, True, '陕西西安')
# 查看变量的类型
print('t1的类型: ', type(t1))
print('t2的类型: ', type(t2))
print()
# 查看元组中元素的数量
print('t1中元素的数量: ', len(t1))
print('t1中元素的数量: ', len(t2))
print()
# 通过索引运算获取元组中的元素
print(... |
974397c2a0980ada4e92b3e13b38483b803dbee9 | Bobby981229/Python-Learning | /Day 11 - Introduction to OOP/Print_Obj.py | 767 | 4.21875 | 4 | """
打印对象
在类中放置__repr__魔术方法
该方法返回的字符串就是用print函数打印对象的时候会显示的内容
"""
class Student:
"""学生"""
def __init__(self, name, age):
"""初始化方法"""
self.name = name
self.age = age
def study(self, course_name):
"""学习"""
print(f'{self.name}正在学习{course_name}.')
def play(self):
... |
d454ebd9ac9aa27762486b102a8c18bed8be5c89 | Bobby981229/Python-Learning | /Day 06 - Functions and Modules/Math_Number.py | 741 | 3.875 | 4 | """
实现计算求最大公约数和最小公倍数的函数
"""
def gcd(x, y): # 计算最大公约数
# if x > y:
# (x, y) = (y, x)
# else:
# (x, y)
(x, y) = (y, x) if x > y else (x, y)
for i in range(x, 0, -1): # 从两个数中较大的数开始做递减的循环
if x % i == 0 and y % i == 0:
return i
def lcm(x, y): # 计算最小公倍数
return x ... |
5c3e9eca8a134aa837b3a06ac22fb4acc2c8973f | Bobby981229/Python-Learning | /Day 10 - Data Structures_Dictionary/Dictionary_Calculation.py | 1,030 | 4.15625 | 4 | """
字典的运算
"""
person = {'name': '刘尚远', 'age': 21, 'weight': 68, 'home': '西影路46号'}
# 检查name和tel两个键在不在person字典中
print('name & tel in person:', 'name' in person, 'tel' in person) # True False
print()
# 通过age修将person字典中对应的值修改为22
if 'age' in person: # 如果age存在person中, 则修改age的值
person['age'] = 22
print('修改后的age:... |
39856c8048dfc5065c7dcb8518c3eb1aaaa92a0f | Bobby981229/Python-Learning | /Day 06 - Functions and Modules/Parameter_Function.py | 1,149 | 4.03125 | 4 | from random import randint
def roll_dice(n=2): # 默认两个骰子
"""摇色子"""
total = 0
for _ in range(n): # 循环两次
total += randint(1, 6) # 从1~6中随机选取一位,相加计算得出total
return total # 返回total
def add(a=0, b=0, c=0): # 定义a, b, c三个参数
# 三个数相加
return a + b + c
print('默认两颗骰子: %d' % roll_dice()) # 如... |
8aa5fbf8d58db8094e0dab793af65cab51b378e8 | aakinlalu/Mini-Python-Projects | /dow_csv/dow_csv_solution.py | 1,713 | 4.125 | 4 | """
Dow CSV
-------
The table in the file 'dow2008.csv' has records holding the
daily performance of the Dow Jones Industrial Average from the
beginning of 2008. The table has the following columns (separated by
commas).
DATE OPEN HIGH LOW CLOSE VOLUME ADJ_CLOSE
2008-01-02 13261.82 ... |
c9309c348e40d160950dd3f54e4d25ae842ea9ff | aakinlalu/Mini-Python-Projects | /calc_integral_1408529802/calc_integral.py | 794 | 3.9375 | 4 | """
Calculate Integral
------------------
Topics: NumPy array indexing and array math.
Use array slicing and math operations to calculate the
numerical integral for ``sin`` from 0 to `x`, for every value
in the `x` array below (0 to ``2*pi``) using Riemann sums or
the trapezoidal rule. There is no need to use a 'fo... |
65eb96c96759e5d9907fb3b12a33836daeaebb9d | aakinlalu/Mini-Python-Projects | /file_management/file_management.py | 3,281 | 4.625 | 5 | """
File management
---------------
The goal of this exercise is to practice manipulating your file system:
creating folders and files, moving them around, and erasing them.
One piece of information to know about is that each python script contains its
own namespace. Such that, when in a script you define a = 1, a get... |
281108088625a352ead48165f4ca9e1c57a60b6f | chmosquera/101-Fundamentals-of-Computer-Science | /lab5/poly/map.py | 276 | 3.734375 | 4 | # Name: Chanelle Mosquera
# Section: 101-16
# Description of program: List Indexing
# Instructor: S. Einakian
# Due date: 02/02/16
list1 = [1, 2, 3, 4]
def square_all(list1):
list1
finalList =
return finalList
def add_n_all(x, y):
finalList = x
return finalList
print len(list1)
|
699325a4a13b70e15e875b1b218202d60394bbbc | chmosquera/101-Fundamentals-of-Computer-Science | /project2_submission/landerFuncs.py | 3,098 | 3.65625 | 4 | # Project 2 - Moonlander
# Author:
# Version:
def showWelcome():
print "\n Welcome aboard the Lunar Module Flight Simulator \n \n \t To begin you must specify the LM's initial altitude \n \t and fuel level. To simulate the actual LM use \n \t values of 1300 meters and 500 liters, respectively. \n \n \t Good ... |
134c3e562636880c5b5226250fe82c7823c7b908 | chmosquera/101-Fundamentals-of-Computer-Science | /labQuiz1/quizFuncs.py | 736 | 3.78125 | 4 | #Name: Chanelle Mosquera
#Section: CPE 101 - 016
def multiply_List(l_int, num):
mult_l = []
for i in range(len(l_int)):
if i == 1:
sub_l = []
for n in range(len(l_int[i])):
sub_l.append(l_int[i][n] * num)
mult_l.append(sub_l)
else:
mult_l.append(l_int[i] * num)
return mult_l
def average_Lis... |
37e8217d9dff9c6553a5a69453207683c9b67907 | ScottSko/Python---Pearson---Third-Edition---Chapter-11 | /Chapter 11 - PE - #1 Employee and ProductionWorker Classes.py | 1,452 | 3.953125 | 4 | class Employee:
def __init__(self, name, number):
self.__name = name
self.__number = number
def get_name(self):
return self.__name
def get_number(self):
return self.__number
def set_name(self, name):
self.__name = name
def set_number(self, nu... |
70289edcd1d671f61663a316966fe86cd860c88d | jhoover4/algorithms | /cracking_the_coding/chapter_1-Arrays/1_is_unique.py | 1,483 | 4.0625 | 4 | import unittest
def is_unique(string: str) -> bool:
"""
Problem: Determine if a string has all unique characters.
Answer: Use a hash table (a set uses this for lookups) to check if char gets repeated.
This is trivial to implement in Python.
Time complexity: O(n)
"""
existing_chars = set... |
0ef3108559c9684fd490f5a7ffa5bfe2dc112cec | jhoover4/algorithms | /cracking_the_coding/chapter_2-LinkedLists/7_intersection.py | 781 | 3.53125 | 4 | import unittest
from collections import deque
from .LinkedList import SinglyLinkedList
# Problem 2.7
def intersection(lis):
"""
Problem: Find where two nodes intersect in a malformed linked list.
Answer:
Time complexity:
:param LinkedList lis:
:return bool:
"""
# TODO
class Tes... |
99728de2ec99c6e60ff42a3a7811f5268028031d | jhoover4/algorithms | /cracking_the_coding/chapter_1-Arrays/7_rotate_matrix.py | 2,120 | 4.40625 | 4 | import unittest
from typing import List
def rotate_matrix(matrix: List[List[int]]) -> List[List[int]]:
"""
Problem: Rotate an M x N matrix 90 degrees.
Answer:
Time complexity: O(MxN)
"""
if not matrix or not matrix[0]:
raise ValueError("Must supply valid M x N matrix.")
col_len... |
afd546b2bebe8c950668184ae0a806e04b68d65c | mjunaidharis/py4e | /Getting Started With Python/3.1.py | 474 | 4.09375 | 4 | # Input both values
hrs = input("Enter Hours:")
rate_per_hour = input("Enter Pay:")
gross_pay = 0
# convert them to float
hrs = float(hrs)
rate_per_hour = float(rate_per_hour)
# if gross pay is less than equal 40hrs compute directly
if hrs <= 40:
gross_pay = hrs * rate_per_hour
else:
# same for f... |
a0909167df71ff56d79b4f59e3fa22a9aea8d5b4 | jifrivly/Python | /calculator.py | 775 | 4.125 | 4 | num1 = float(input("Enter a number : "))
num2 = float(input("Enter a number : "))
def add(x, y):
return x+y
def sub(x, y):
return x-y
def mul(x, y):
return x*y
def div(x, y):
if y == 0:
return "0 division not accepted"
else:
return x/y
print("Choose an option : \n1 : Additi... |
9db90c8ea62e0c8b2729f2dae9635742d2967290 | jifrivly/Python | /string.py | 1,231 | 3.921875 | 4 | # index
a = "HELLO"
print a[0], a[-5]
print a[5], a[-1]
print a[:]
print a[::-1]
print a[1:]
print a[2::-1]
print a[:-1]
print a[-1:]
# palindrome checking
a = raw_input("Enter the string : ").upper()
def check_palindrom(b):
if b == b[::-1]:
print "String is palindrome "
else:
print "String i... |
0b5e9512b94ca45add5163dd65290193b14d41be | SnowySailor/Checkout-Order-Total-Kata | /src/models/specials/geteolforaoff.py | 2,290 | 3.53125 | 4 | # Buy cheese, get any other item of equal or lesser value for 25% off"
from src.helpers import get_value
class GetEOLforAoff:
def __init__(self, off):
self.off = off
def to_dict(self):
d = dict()
d['type'] = 'getEOLforAoff'
d['off'] = self.off
return d
def calcula... |
de6794ac2a7bde0a5a0c771638d2fb2d103d8c0a | korchalovsky/python-learn | /Graph/Dijkstra's.py | 1,274 | 3.640625 | 4 | graph_weight = {'A': {'B': 4, 'C': 2},
'B': {'C': 5, 'D': 10},
'C': {'E': 3},
'D': {'F': 11},
'E': {'D': 4},
'F': {}}
infinity = float("inf")
weights = {'B': 4,
'C': 2,
'D': infinity,
'E': infinity,
... |
23551c2df837c3a4d5ca2afda408f4371ff560d1 | sdeleon28/musicmath | /midi.py | 1,898 | 3.515625 | 4 | class MidiNote(object):
def __init__(self, note_name, octave):
self.note_name = note_name
self.octave = octave
def __str__(self):
return '{} - {}'.format(self.note_name, octave)
# note (note_name, octave)
MIDI_NUMBERS_TO_NOTES = [
[21, MidiNote('A', 0)],
[22, MidiNote('A#', 0)]... |
3bd7b25494f64e3ee6fad1af4354166069b0f3fe | TomNguyen-0/school | /cs530/a3/old/a3 old2.py | 7,040 | 3.5 | 4 | import sys
#function definitions and implementations
def checkFirst(item):
if item == '_':
return True
else:
return item.isalpha()
def digitOrChar(item):
if item.isdigit():
return True
elif item == '_':
return True
else:
return item.isalpha()
def isId(string):
for index in range (len(string)):
if... |
699c10b8c3fabab88bbc5c3c19890d4973e68d04 | natewagner10/Distributed-Computing-Facebook-Ads | /classify_ads.py | 13,668 | 3.515625 | 4 | from nltk.corpus import stopwords
import nltk
#nltk.download('stopwords')
stop_words = stopwords.words("english")
def removeStopWords(line):
clean = []
try:
for word in line[4].split():
word = word.lower()
word = word.replace('.', '')
word = word.replace('-', '')
... |
50313eb4b12c2e0320d71d2bc3e888348df9bf2b | rm-hull/luma.examples | /examples/starfield.py | 2,386 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014-18 Richard Hull and contributors
# See LICENSE.rst for details.
# PYTHON_ARGCOMPLETE_OK
"""
3D starfield simulation.
Adapted from:
http://codentronix.com/2011/05/28/3d-starfield-made-using-python-and-pygame/
"""
from random import randrange
from demo... |
c4779105cbd438ac417af99d6f9478ba7b45a4fc | BorisVV/cellphonesUnittest_Capstone | /test_phone_manager.py | 7,034 | 3.859375 | 4 | import unittest
from phone_manager import Phone, Employee, PhoneAssignments, PhoneError
import traceback
class TestPhoneManager(unittest.TestCase):
def test_create_and_add_new_phone(self):
testPhone1 = Phone(1, 'Apple', 'iPhone 6')
testPhone2 = Phone(2, 'Apple', 'iPhone 5')
testPhones ... |
8c67bfa2b52f8d4856a300604d0cca02616e07ea | Keilan/advent-of-code-2018 | /8/license.py | 1,877 | 3.8125 | 4 | import sys
class Node:
def __init__(self, children, metadata):
self.children = children
self.metadata = metadata
def __str__(self):
return 'Node with {} children and metadata {}'.format(len(self.children), self.metadata)
def build_tree(tree, info):
"""
Recursiv... |
183f2e4a3b8b35bcfbb53cadf905a886afc68b5f | Keilan/advent-of-code-2018 | /13/cart.py | 5,207 | 3.578125 | 4 | import sys
from enum import Enum
import numpy as np
class Direction(Enum):
UP = '^'
DOWN = 'v'
LEFT = '<'
RIGHT = '>'
class Turn(Enum):
LEFT = 0
STRAIGHT = 1
RIGHT = 2
class Cart:
def __init__(self, x, y, direction):
self.x = x
self.y = y
... |
cf73803e189c1e93759cb6999fd07b43ca554feb | Samfan01/News-App | /app/tests/source_test.py | 639 | 3.515625 | 4 | import unittest
from models import source
class SourceTest(unittest.TestCase):
'''
Test Class to test the behaviour of the Source class
'''
def setUp(self):
'''
Set up method to run before each test
'''
self.new_source = Source('abc-news','ABC NEWS',"Australia's mo... |
a47c4ec10c8b328d086e178553844df0f5f64ebd | damianlukawski/Weather_API | /Finding_capital_of_perfect_weather.py | 2,067 | 3.53125 | 4 | import requests
import json
from API_functions import format_response_2
#the main app for weather analysis
def get_weather(city):
weather_key = 'ce5aac7c1aacbd6070822b7c504a0ef9'
url = 'https://api.openweathermap.org/data/2.5/weather'
parameters = {'APPID': weather_key, 'q': city, 'units':'Metric'}
re... |
87f26f94315fa4fef114db617a578f2c357b6dff | gvling/paper | /utils/errorMsg.py | 998 | 3.640625 | 4 | def assertLengthError(target, length, method='exactly'):
'''
Assert an error of length over range of a list or a tuple
method: 'exactly' or 'range'
'''
methods = ['exactly', 'range']
methods.index(method)
if(method == 'exactly'):
assert len(target) == length, 'Required a list or a ... |
9e9cceebf6e4e3069cdea58a3fe13d85d583344d | xu-robert/Leetcode | /Jump Game IV.py | 3,519 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 27 10:09:13 2020
Jump Game IV
Given an array of integers arr, you are initially positioned at the first index of the array.
In one step you can jump from index i to index:
i + 1 where: i + 1 < arr.length.
i - 1 where: i - 1 >= 0.
j where: arr[i] == arr[j] and i != j.
R... |
b579825b65cfbebde0fb97fdcd985774c8ae9c79 | xu-robert/Leetcode | /Check If Two String Arrays are Equivalent.py | 1,913 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 8 10:02:05 2021
Check If Two String Arrays are Equivalent
Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.
A string is represented by an array if the array elements concatenated in order forms the str... |
b5d0e95aed015e33024477d48fccd4071cd94e9e | xu-robert/Leetcode | /Kth Largest Element in an Array.py | 1,121 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 16 08:42:43 2021
Classic heap problem: lots of better explanations online.
The key is that even though we want the kth LARGEST number, we maintain a heap with the SMALLEST number at the top
of the heap ( a min heap). When the heap reaches size k (or length k), this means... |
7de1029584254c86070f996b8033b3082b60b323 | xu-robert/Leetcode | /Remove Duplicates from Sorted Array II.py | 2,788 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 11 09:34:06 2020
Remove Duplicates from Sorted Array II
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array; you must do this by modifying the input... |
80b974b6c31ffaceefd40b29c4417938c1b9963a | xu-robert/Leetcode | /Smallest Range II.py | 3,421 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 21 09:56:53 2020
Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K,
and add x to A[i] (only once).
After this process, we have some array B.
Return the smallest possible difference between the maximum value of B
and the minimu... |
60a48f393540ceed1199716ac5489a9498d74883 | xu-robert/Leetcode | /Shortest Common Supersequence.py | 5,205 | 4.125 | 4 | '''
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If multiple answers exist, you may return any of them.
(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results ... |
222f36759eabbd54ee5cf9c6da93d2a665d7d588 | felipebarino/Tutorial-Basico-OpenCV | /2_getting_and_setting.py | 1,551 | 3.546875 | 4 | # Importa as bibliotecas
from __future__ import print_function
import cv2
# Nome do arquivo de imagem a ler e caminho dele, a partir do atual
fileName = "trex.png"
path = "Images/" + fileName
# Carrega a imagem
image = cv2.imread(path)
# Imagens são importadas como arrays NumPy
# A origem (0, 0) é o canto superior e... |
f443dafb6a8a87ca0ba00a7fc1f6f13ae0247e95 | suinautant/learnCode | /python/old/code6-7.py | 274 | 3.703125 | 4 | i, i, guguLine = 0, 0, ""
for i in range(2, 10):
guguLine = guguLine + (" # %d단 #" % i)
print(guguLine)
for i in range(1, 10):
guguLine = ""
for k in range(2, 10):
guguLine = guguLine + str(" %2d x %2d = %2d" % (k, i, k*i))
print(guguLine)
|
97ced7db8276963e95dccf042449353e007efee1 | suinautant/learnCode | /python/code9-13.py | 392 | 3.6875 | 4 | import random
def getNumber():
return random.randrange(1, 46)
lotto = []
num = 0
print("** 로또 추첨을 시작합니다. ** \n")
while True:
num = getNumber()
if lotto.count(num) == 0:
lotto.append(num)
if len(lotto) >= 6:
break
print("추첨 된 로또 번호 ==> ", end='')
lotto.sort()
for i in range(0, 6)... |
5cbbd3bd410041e47b619b53511e6a04b389c7ad | suinautant/learnCode | /python/old/p132.py | 247 | 3.578125 | 4 | num = int(input("*** 숫자를 입력하세요 : "))
tagV = True
for i in range(2, num):
if num % i == 0:
tagV = False
if tagV == True:
print("%d는 소수입니다." % num)
else:
print("%d는 소수가 아닙니다." % num)
|
065b63b088ee2d041254c8b38be7d52987f791be | suinautant/learnCode | /python/old/code4-1.py | 336 | 3.609375 | 4 | money, c500, c100, c50, c10 = 0, 0, 0, 0, 0
money = int(input("교환할 돈은 얼마? : "))
c500 = money // 500
money %= 500
c100 = money // 100
money %= 100
c50 = money // 50
money %= 50
c10 = money // 10
money %= 10
print("\n500 * ", c500)
print("100 * ", c100)
print("50 * ", c50)
print("10 * ", c10)
print("remainder * ", money... |
ea82a64f6463127ace0211e9fb322ef41b4b33eb | suinautant/learnCode | /python/ex9-9.py | 211 | 3.703125 | 4 | def myRange(start, end, hop=1):
retVal = start
while retVal <= end:
yield retVal
retVal += hop
hap = 0
for i in myRange(1, 5, 2):
print("i : ", i)
hap += i
print("hap : ", hap)
|
c5ba139cbce24ee694f04c2b1dc0438115ca5803 | eshevelevee/ozonpyth1 | /dict_example.py | 181 | 3.671875 | 4 | family = dict(dad=60, mom=50, aunt=12)
print(family['dad'])
family['uncle'] = 55
print(family)
for key, value in family.items():
print ("\nKey: " + key + " Value:" + str(value)) |
64cabb119e5afe63c6be42a59f8a3d547fb9ad4d | Nimisha-V-Arun/Interview-Prep | /Arrays/Python/countLetter.py | 500 | 4.0625 | 4 | def countLetter(string):
count = list()
cnt = 1
for x in range(len(string)):
# if you reach the last char of the string or if the adj char are different
if(x+1 == len(string) or string[x] != string[x+1]):
count.append(string[x])
count.append(str(cnt))
cnt... |
af3980d343fe683b8a3477ab0e25b8444b5c1422 | lofajob/PyLes | /lessons/younglinux/les2_2.py | 1,106 | 3.796875 | 4 | # -*- coding: utf-8 -*-
# lesson 2.2
class Guitar:
body = "mahogany"
strings = "6"
pickups = "EMG"
def changebody(self, newbody):
self.body = newbody
print "Guitar has upgraded to %s wood body" % self.body
def changestrings(self, newstr):
self.strings = newstr... |
31b15085fa9411fb18e684b4de113a5336d12fe9 | lofajob/PyLes | /lessons/Podoba/ls4/3or4.py | 343 | 4.3125 | 4 | i = 10
while i > 0:
print i
if i>5:
print "Bigger than 5!"
elif i%2 !=0:
print "this is ODD number"
print "and i <= 5"
else:
print "i <= 5"
print "this is EVEN nember, not ODD"
print "special number! :)"
i=i-1
print "we are after 'while' l... |
e19a7a4e908a4866173b7f12ab9b973741af5301 | lofajob/PyLes | /lessons/Podoba/ls7_for/Game_of_Key.py | 1,070 | 4.0625 | 4 | # Game of Key
#function of menu
def menu(list, question):
for entry in list:
print 1 + list.index(entry),
print ") " + entry
return input(question) - 1
#initialize list of items in the room
# u -
items = [u"", u"", u"", u"", u"", u""]
#initialize variables for loops
keyloca... |
d3cae3f2cd307a21ad129459c7f964c3e4623e9b | lofajob/PyLes | /lessons/Podoba/ls7_for/Game_of_Key_2.py | 2,059 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# Game of Key
import random
#function of menu
def menu(list, question):
for entry in list:
print 1 + list.index(entry),
print ") " + entry
return input(question) - 1
# function check of choice
def check(choice, location):
if choice == location:
... |
8f55d2c03861b37c0facb46ad8619d248410c3ca | lofajob/PyLes | /examples/class_Animal.py | 369 | 3.78125 | 4 | # -*- coding: utf-8 -*-
class Animal(object):
def __init__(self, name):
self.name = name
self.legs = 4
def getName(self):
return self.name
def repr(self):
print "Animal has %s name, and has %s legs" % self.name, self.legs
class Dog(Animal):
def gav(self):
p... |
ed08466a6bf2c0588b9bf39bcab661d4817f3cdf | lofajob/PyLes | /examples/Tkinter/Tkinter.py | 329 | 3.890625 | 4 | from Tkinter import *
tk = Tk()
tk.title("delete words!")
tk.geometry('300x400')
def button_clicked():
text1.delete('1.0',END)
print 'tlala'
button = Button(tk, text="Other words", command=button_clicked)
button.pack(fill =BOTH)
text1=Text(height=7,width=7,font='Arial 14')
text1.pack()
tk.mai... |
9cc7eb4216e184c507b4b3b10a9c7b2014554cf1 | iara1998/atividades | /q15 moduralização.py | 438 | 4.03125 | 4 | #15. Recebe um número no formato CDU e imprima na forma UDC. Exemplo: 123, sairá 321. O número deve ser armazenado em
#outra variável antes de ser impresso.
def veri(n):
num = str(n)
if len(num) == 3:
return num
else:
return 0
n = int(input("Forneça um número de três algarismos: "))
if ver... |
597dbeae85b1c202aedf33b0ec37a0435242ff67 | iara1998/atividades | /atividade condicional-q5.py | 277 | 3.84375 | 4 | #5. Crie uma função que recebe um número por parâmetro e retorna o valor booleano verdadeiro se o número
#for par.
def num(x):
return x % 2 == 0
try:
x = int(input("Forneça um número inteiro: "))
print(num(x))
except:
print("Numero invalido.")
|
caa32798a71ac51dc51e0576669e17cb72a7fd0a | iara1998/atividades | /Q 3 - repetição.py | 133 | 3.75 | 4 | #03. Imprimir os múltiplos de 5, no intervalo de 1 até
#500.
for a in range(0,499,5):
print(a, end = ", ")
print("500.")
|
e34f1431870b07bc8661791d7520d6354bccb461 | iara1998/atividades | /atividade condicional-q4.py | 449 | 3.890625 | 4 | #4. Faça uma função que recebe três números por parâmetro e imprime na tela em ordem crescente.
def rece(x, y, z):
numeros = [x, y, z]
numeros.sort()
print("Em ordem crescente: %f, %f, %f." % (numeros[0], numeros[1], numeros[2])).rstrip('.').rstrip('0')
try:
x, y, z = float(input("Forneça três númer... |
3b913ebde7e7614dd0220a5884766acd72c48de7 | iara1998/atividades | /q5 moduralização1.py | 229 | 4.03125 | 4 | #Recebe uma velocidade em m/s, retorne esta velocidade em km/h. (Vkm/h = Vm/s * 3.6)0
def velocidade(x):
return (x * 3.6)
b = float(input("Digite a velocidade em m/s"))
b = velocidade(b)
print("valor em km/h e:",b)
|
6835fbe492e675847f84f0e9597dd7e748521f7f | iara1998/atividades | /Q 7 - repetição.py | 642 | 3.78125 | 4 | #07. Criar um algoritmo que calcule e imprima o valor
#de bn
#. O valor de n deverá ser maior que 1 e inteiro
#e o valor de b maior ou igual a 2 e inteiro.
try:
b = int(input("Escreva dois valores inteiros para 'b' e 'n', respectivamente (com b >= 2 e n > 1): "))
n = int(input())
while b < 2 or n <= 1:
... |
ea6996d330642ea76455603c4e88089a38473d58 | toddschultz/DegreesOfClimateChange | /DegreesOfClimateChange/plot_functions.py | 16,067 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""plot_functions various functions to create graphs of temperature data
This python module contains a multiple Python functions to create different
visualizations of the average global temperature data from the various grab
functions in this project. The are designed to have a consistent input... |
7dc6513a29e40574d0fa43cd92993825dc8853f0 | luismasuelli/mistra | /mistra/core/timelapses.py | 2,876 | 3.5 | 4 | from datetime import timedelta, date, datetime
from .growing_arrays import GrowingArray
class Timelapse:
"""
Timelapse is an abstract class allowing us to handle common utilities regarding
datetimes in frames, digests, and indicators. They will also give yp the data,
in the end, but will not handl... |
2e0b50b34d75c822cde65e9bb57e9b70fa5c7e4f | luismasuelli/mistra | /mistra/core/growing_arrays/types.py | 5,765 | 3.515625 | 4 | from numpy import zeros, full
from .support import chunked_slicing, fix_slicing, fix_input
class GrowingArray:
"""
A growing array can grow, but never shrink. Every time new data needs to be added, the array will
perhaps grow to cover the required indices. Several chunks (all of the same size) will be c... |
35c5aa99ff56e8812460c0679a6d52d05af89758 | takikawa0524/100pon | /09.py | 437 | 3.734375 | 4 | # 入力された文の一定以上の文字数の単語を並び変えるやつ
import random
def shuffle(str):
result = []
for word in str.split():
if len(word) > 4: # 長さが4超であればシャッフル
word = word[:1] + ''.join(random.sample(word[1:-1], len(word) - 2)) + word[-1:]
result.append(word)
return ' '.join(result)
str = input('文章を入力: ')
str... |
2f7e552a7c6cee1b51845751501788dd2eb976aa | mikehendersonofbk/post-parser | /main.py | 5,158 | 3.515625 | 4 | import json
import re
import pandas as pd
"""
containsField
Inputs:
df: DataFrame
field_name: Name of text field to evaluate
value: Word to check existence of in the field provided
Determines which records in the dataframe contain the specified word
"""
def containsField(df, field_name... |
8bbf131a37fa50e19b858583574c964380be4897 | ChaitDevOps/Scripts | /PythonScripts/variable.py | 878 | 3.75 | 4 | #!/usr/bin/python
# Value that seperates a Variable with plain text in a print command is ,
# using same variable twice in the code, overrides previous value of the variable.
# Variable Rules:
# Names cannot start with a number, best practice is to be all lowercase.
# There can be no spaces on the name, use "underscore... |
3708eda29bf47b6a2ab23eb56e8f95b9f88e4a5e | ChaitDevOps/Scripts | /PythonScripts/ad-lists.py | 1,018 | 4.5 | 4 | #!/usr/bin/python
# ad-lists.py
# Diving a little deeper into Lists.
#.append() Appends an element to the 'END' of the exisitng list.
from __future__ import print_function
l = [1,2,3]
l.append([4])
print(l)
#.extend() extends list by appending elements from the iterable
l = [4,5,6]
l.extend([7,8,9])
print(l)
# .in... |
85769cf60c277a432a21b44b95e3814d23511666 | ChaitDevOps/Scripts | /PythonScripts/lambda.py | 556 | 4.15625 | 4 | #!/usr/bin/python
# Lambda Expressions
# lambda.py
# Chaitanya Bingu
# Lamba expressions is basically a one line condensed version of a function.
# Writing a Square Function, we will break it down into a Lambda Expression.
def square(num):
result = num**2
print result
square(2)
def square(num):
print num... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.