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 |
|---|---|---|---|---|---|---|
64c615e6222051a6e50b8f8f562c112659ec5e18 | oreo0701/openbigdata | /01_jumptopy/end_of_chap/basic_test_01.py | 439 | 3.8125 | 4 |
print("극장 입장권 판매를 시작합니다.\n")
while True:
try:
age = int(input("현재 나이를 입력하세요: "))
if age < 3:
print("무료 입장입니다.\n")
elif age >= 3 and age <=12:
print("입장료는 10달러 입니다.\n")
elif age >= 13:
print("입장료는 15달러 입니다.\n")
except:
print("다시 입력해주세요... |
5ec608e2a356eb31b0095da2153cedb1e74152d3 | oreo0701/openbigdata | /Review/integer_float.py | 801 | 4.1875 | 4 | num = 3
num1 = 3.14
print(type(num))
print(type(num1))
print(3 / 2) # 1.5
print(3 // 2) # floor division = 1
print(3**2) #exponnet
print(3%2) #modulus - distinguish even and odd
print(2 % 2) #even
print(3 % 2) #odd
print(4 % 2)
print(5 % 2)
print(3 * (2 + 1))
#incrementing values
num = 1
num = num + 1
num1 *= 10 ... |
cd5e5caec4bc113199eb90dae78bc2d7576b02c4 | oreo0701/openbigdata | /03_Data_Science/1.Collection/2. Open API/test_time.py | 205 | 3.5625 | 4 | import datetime
now = datetime.datetime.now()
base_date=str(now.year)+str(now.month)+str(now.day)
base_time=str(now.hour)+str(now.minute)
print(now)
print(base_date)
print(base_time)
#"%Y %m %d %I %M" |
f870ea6fa7baca5bb9c428128313c3a56ac80f4e | oreo0701/openbigdata | /Review/list_tuple_set.py | 1,463 | 4.25 | 4 | #list : sequential data
courses = ['History', 'Math', 'Physic','CompSci']
print(len(courses)) #4 values in list
print(courses[0])
print(courses[3])
print(courses[-1])
print(courses[-4])
print(courses[0:2])
print(courses[:2])
print(courses[2:])
#add values
courses.append('Art')
print(courses)
#choose location to ... |
070da7cc9518ba04e1f70b3eb187835338d8fa42 | oreo0701/openbigdata | /Review/conditionals.py | 748 | 4.03125 | 4 |
# Object Identity : is
language = 'Java'
if language == 'Python':
print('Language is Python')
elif language == 'Java':
print('Language is Java')
elif language == 'JavaScript':
print('Language is JavaScript')
else:
print('No match')
#and, or , not
user = 'Admin'
logged_in = False
if not logged_in:
... |
13714fa8ceca5a8584ab0d08bd44daed58698f97 | meetdaxini/editing-django-models-in-the-frontend | /sample_project/backend/utils.py | 539 | 3.59375 | 4 |
def increment_revision(title):
"""
Increment revision n. at the end of the given title:
"abc" --> "abc (2)"
"abc (2)" --> "abc (3)"
etc ..
Used for cloning objects
"""
new_title = ''
try:
start = title.rfind('(')
if title.endswith(')') and start >= 0:... |
d7d14781ac43fe6853958a55e3d00462dac89f77 | devhid/cse346 | /project2-solution/graph.py | 3,014 | 3.578125 | 4 | from util import to_adjlist
from math import inf
from collections import deque
class Graph:
def __init__(self, matrix):
self.graph = to_adjlist(matrix)
self.vertices = list(self.graph.keys())
def add_edge(self, src, dst, cost):
self.graph[src].append((dst, cost))
self.graph[dst... |
ad9162cd9b5a7811d60ae74317efe14efaade4d8 | schaferpg/My-Hackerrank-Problems | /sparse_Arrays.py | 631 | 3.84375 | 4 | # https://www.hackerrank.com/challenges/sparse-arrays/problem
def matchingStrings(strings, queries):
count_Arr = []
for q in queries:
count = 0
for s in strings:
if q == s:
count += 1
count_Arr.append(count)
return count_Arr
strings_count = int(input())
s... |
0c7add4810a9b77f4769813cf2185f36db34b887 | schaferpg/My-Hackerrank-Problems | /electronic_Shop.py | 708 | 3.953125 | 4 | #!/bin/python3
# https://www.hackerrank.com/challenges/electronics-shop/problem
import sys
def get_Money_Spent(key, usb, s):
cost = total = 0
for k in key:
for u in usb:
total = k + u
if total > cost and total <= s:
cost = total
if cost > 0:
return c... |
6d92887d65e41121e84f44f87ce5f132279d6428 | quinngroup/dr1dl-pyspark | /functions.py | 960 | 3.796875 | 4 | def select_topr(vct_input, r):
"""
Returns the R-th greatest elements indices
in input vector and store them in idxs_n.
Here, we're using this function instead of
a complete sorting one, where it's more efficient
than complete sorting function in real big data application
parameters
----... |
397c3c20106992968f14daa12d689eae5dea1c84 | muskan09/LotsOfCourses | /finallotsofcourses.py | 10,008 | 3.5 | 4 | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from finaldatabase_setup import University, Base, Course, User
engine = create_engine('sqlite:///curriculum.db')
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.... |
b1734acc5ef5488f4a484ea6f353a3e3d28a90b4 | skq576/hangman | /hangman.py | 1,725 | 3.640625 | 4 | #import PyDictionary as pyd
import random
import requests
import json
from os.path import dirname
import filter_words
print(dirname(__file__))
word_length_str = input("what length should the word be (3-10)?")
try:
word_length = int(word_length_str)
if word_length < 3 or word_length > 10:
... |
6881673815932dab0dc44cad69638eace5f4df62 | Somi-Singh/python_dictionary | /resource28.py | 173 | 4.125 | 4 | num = {'n1': [2, 3, 1], 'n2': [5, 1, 2], 'n3': [3, 2, 4]}
res = dict()
for key in sorted(num):
res[key] = sorted(num[key])
print("The sorted dictionary : " +str(res))
|
3a35f9e69043561038a3841993f0316bfc5941c8 | Somi-Singh/python_dictionary | /add_value.py | 65 | 3.546875 | 4 | person= {'1': 'RAM', '2': 17,}
person[3] = 'male'
print(person)
|
5364f9588d8f4d013d77bd6d49564396343d51fe | paperboy0927/PythonWork | /SelectiveCopy.py | 684 | 3.75 | 4 | #! python3
# SelectiveCopy.py : select specific file type (.pdf) and copy to other folder
import os, re, shutil
def selectcopy(folder, target, type):
folder = os.path.abspath(folder)
target = os.path.abspath(target)
print(target)
if not os.path.exists(target):
os.makedirs(target)
for f... |
2c5ce81796a76ac74c88be80b112dae853ebadcc | Akshay184/Machine-Learning | /Projects/naive_bayes/nb_author_id.py | 1,284 | 3.65625 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 1 (Naive Bayes) mini-project.
Use a Naive Bayes Classifier to identify emails by their authors
authors and labels:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from... |
cc5cc6cabff01c5dabf4006a3b8a7847a4425301 | kuksteve/cogs18project | /functions.py | 5,902 | 4.28125 | 4 | """A collection of functions for doing my project."""
def rps(msg_2):
"""Takes the user input between 1 to 4 and translates it to rock, paper, scissors, or exit the program.
Parameters
----------
msg_2 : int
Translate user input to rock, paper, scissors.
Returns
---------
... |
6b6cbd67e07c2dee71b95c03526a06d991102d48 | SazonovPavel/A_byte_of_Python | /11_func_param.py | 465 | 4.1875 | 4 | def printMax(a, b):
if a > b:
print(a, 'максимально')
elif a == b:
print(a, 'равно', b)
else:
print(b, 'максимально')
printMax(3, 4) # Прямая передача значений
x = 5
y = 7
printMax(x, y) # передача переменных в качестве аргументов
x = 5
y = 5
printMax(x, y) # передача переменных... |
a7fa40e53ea8b2ef663a2e21cc7602667b55d691 | NeonNingen/allpythonprojects | /Python Learning/generator2.py | 155 | 3.859375 | 4 | def infinite_sequence():
num = 0
while True:
yield num
num += 1
gen = infinite_sequence()
i = 0
while i < 10:
print(next(gen))
i += 1
print(gen) |
1aca79b9c8751bbbf86d36ab03437048b513a4ea | NeonNingen/allpythonprojects | /test.py | 253 | 3.5 | 4 | import string
from random import *
min_char = 8
max_char = 12
allchar = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(allchar) for x in range(randint(min_char, max_char)))
for i in range(1,81):
print(password)
|
ce94f29545e9e326bd1a6bf502f0e7fba02ff5da | hamiltonianaman/Numerical-Integration-1D | /Monte-carlo.py | 573 | 4.09375 | 4 | from numpy import random as r
# Function which has to be integrated
function = lambda x : x**2
#More the better, but ~10^6 or more would work
iteration = int(input("Iterations : "))
#Input lower limit
lowerlimit = float(input("Lower limit : "))
#Input upper limit
upperlimit = float(input("Upper limit : "))
domain ... |
bcc67225d0ee217ba8d655e5a9e948450d5437b2 | bradloudis/bradloudis.github.io | /coffee_equation.py | 172 | 3.578125 | 4 | # function that returns weight of water for brewing
def kohi(weight):
grams = 60.
liter = 1000.
ratio = liter / grams
return ratio * weight
print(kohi())
|
d8b24559321736accfc2b7d88325a2955f77401a | Abhish3556/Json | /Assignment_1.py | 4,687 | 3.578125 | 4 | import urllib.request
from datetime import *
def getlatestrates():
url=urllib.request.urlopen("https://api.exchangeratesapi.io/latest")
data=url.read()
print(data)
return data
getlatestrates()
def change(amount,currency,desirecurrency,date):
url=urllib.request.urlopen("https://api.exchanger... |
dd042d3cdd8ad7957bd1fd31c94578df2087b93d | helloImProgrammer/Python | /tic_deneme.py | 5,481 | 3.90625 | 4 | def black_board(board):
print(' | | ')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + ' ')
print('-----------')
print(' | | ')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6] + ' ')
print('-----------')
print(' | | ')
print(' ' + b... |
386abd1646f9101f91a7b49215f9d8739acda618 | LanceFiondella/NSF_REU_Summer2019 | /algorithms/PastAlgorithms/GreedyRandomizedAdaptiveSearch/grasp.py | 12,351 | 3.84375 | 4 | # Greedy Randomized Adaptive Search Procedure in the Python Programing Language
# Adapted from:
# The Clever Algorithms Project: http://www.CleverAlgorithms.com
# (c) Copyright 2010 Jason Brownlee. Some Rights Reserved.
# This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 Aus... |
b7440510aad66b666976b8912725e030ddd8d3b4 | LanceFiondella/NSF_REU_Summer2019 | /algorithms/PastAlgorithms/GuidedLocalSearch/guided_local_search.py | 8,058 | 3.859375 | 4 | # Guided Local Search algorithm in python
# adapted from Jason Brownlee's The Clever Algorithms Project: http://www.CleverAlgorithms.com
# by Jacob Aubertine, 23 May 2019
# random library used for generating random numbers, math for sqrt()
import random
import math
# Euclidean (straight-line) distance between two ... |
a0d2f2d6581240c836b21e2d15a6cf4d74f96f53 | shokir85/Python-Essentials | /Ex_Files_Python_Structures_Linked_Lists/Exercise Files/addtwoNumbers.py | 835 | 3.859375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
output = List... |
28e5030d514bba68507f070073ff3e431ab9093e | REGG24/Python-Projects | /Exercises/pruebas.py | 2,687 | 4.03125 | 4 | """
def find_unique_numbers(numbers):
recorridos = set()
unique = set()
for number in numbers:
if number not in recorridos:
recorridos.add(number)
unique.add(number)
else:
if number in unique:
unique.remove(number)
return list(unique)
... |
d189b7d33ed54c71465fab750d21c1669fe26270 | RumanBhuiyan/Encryption-Decryption | /allTogether.py | 1,231 | 3.53125 | 4 | from AES_encryption_decryption import rootAES
from RSA_encryption_decryption import rootRSAEncryption
from RSA_signature import rootRSA
from hashing import rootHash
conductor =input("Enter 'c' to continue or 'q' to quit: ")
while conductor != 'q':
print("\t 1. AES Encryption Decryption ")
print("\t 2. RSA En... |
935e36735e8324a129c35afd471b29b561b21966 | starkbling/schoolsystem | /core/teacher.py | 1,157 | 3.75 | 4 | #-*- coding:utf-8 -*-
"""
__author__ = BlingBling
"""
from members import Member
class Teacher(Member):
def __init__(self,name,age,sex,school):
# Member.__init__(self, name, age,sex) #经典类的继承方式
super(Teacher, self).__init__(name, age, sex) #新式类的继承方式
self.school = school.name
self.__... |
af63ce394403b2e94f3d944c41b3669687dff4a2 | GarryG6/PyProject | /String3_1.py | 727 | 4.28125 | 4 | # Задача 1. Определить, сколько раз в заданной строке встречается некоторый символ.
st = input('Введите строку: ')
sim = input('Введите символ: ')
k = 0 # Переменная-счетчик
for i in st: # Рассматриваем все номера символов строки в памяти компьютера
if i == sim: # Сравниваем соответствующий символ с заданным
... |
63712a1d093a8d1def5e5e3edb697a6ef831d622 | GarryG6/PyProject | /31.py | 794 | 4.1875 | 4 | # Дана последовательность чисел. Определить наибольшую длину монотонно возрастающего фрагмента
# последовательности (то есть такого фрагмента, где все элементы больше предыдущего).
n = int(input('Введите количество элементов '))
count = 1
max_ = 0
second = int(input('Введите элемент '))
for i in range(n - 1):
f... |
0b31e5080af27a8319c649160b02558bfdafa762 | GarryG6/PyProject | /12.py | 498 | 4.0625 | 4 | # «Дано натуральное число. Определить: максимальную нечетную цифру числа №2;
n = int(input('Введите натуральное число: '))
max = 0
posl = 0
while n > 0:
posl = n % 10
if posl % 2 == 1 and posl > max:
max = posl
n = n // 10
if max == 0:
print('Нет максимальной нечетной цифры')
else:
print('М... |
1bef673894fdda8f4671ec036532721bc30831d4 | GarryG6/PyProject | /String13_1.py | 1,072 | 4.25 | 4 | # Задача 11. Дано предложение, в котором слова разделены одним пробелом (начальных и конечных пробелов нет).
# Получить и вывести на экран два его первых слова.
st = input('Введите предложение: ')
# Получаем первое слово
# Определяем позицию первого пробела
pos = st.find(' ') # начиная с начала предложения
# Определя... |
c0d489642df3d964091ca81fb2a256685f92a97a | GarryG6/PyProject | /25.py | 473 | 4.03125 | 4 | # Известна масса в килограммах каждого предмета, загружаемого в автомобиль. Определить общую массу груза.
n = int(input('Введите количество предметов '))
sum = 0
for nom in range(n):
a = int(input('Введите массу очередного предмета '))
sum = sum + a
print('Общая масса всех предметов = ', sum)
|
92385ce38a6965d7f4229cff416c593afcd04167 | GarryG6/PyProject | /28.py | 535 | 4 | 4 | # Дана последовательность чисел. Определить, сколько элементов этой последовательности больше предыдущего элемента.
n = int(input('Введите количество элементов '))
count = 0
nxt = 0
for i in range(n):
a = int(input('Введите элемент '))
prev = nxt
nxt = a
if nxt > prev and i > 0:
count = count... |
02d6f8086c69d0637c9d31cf2cbb62d1391eb56c | GarryG6/PyProject | /String7.py | 297 | 3.734375 | 4 | # Задача 5. Определить количество цифр в заданной строке
st = input('Введите строку: ')
k = 0
for i in range(len(st)):
if st[i].isdigit():
k = k + 1
print('Количество цифр в заданной строке:', k)
|
797d0dfd0bef98ac173538a087509ae45681de3c | valefaraz/lab | /alumnos/58018-Valentin-Faraz/clase01/ejercicio3.py | 659 | 3.921875 | 4 | #Rescriba un programa que cree un histograma de una lista de enteros ingresados por teclado.
class Histograma():
def ingresar_numeros(self):
lista=[]
cantidad=int(input("Ingrese la cantidad de datos del histrograma\n"))
for x in range(cantidad):
a = int(input("ingrese el dato n... |
a6ef8ba4162168b1578b012180924376ea57ec75 | nadiabahrami/c_war_practice | /level_8/mathfundamentals.py | 638 | 3.984375 | 4 | """Make multiple functions that will return the sum, difference, modulus, product, quotient, and the exponent respectively.
Please use the following function names:
addition = add
multiply = multiply
division = divide (both integer and float divisions are accepted)
modulus = mod
exponential = exponent... |
852a1cbe7932d9065b29b6d11f81c3bdc8db6227 | nadiabahrami/c_war_practice | /level_8/evenorodd.py | 272 | 4.4375 | 4 | """Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers."""
def even_or_odd(number):
return "Even" if number % 2 == 0 else "Odd"
def even_or_odd_bp(num):
return 'Odd' if num % 2 else 'Even'
|
5ac3932a7fdda0ef12e30ac69d09ca6d2f2115af | ColinUnity/madlibsgame | /madlibs.py | 498 | 4.09375 | 4 | #mad libs game, link to tutorial https://www.youtube.com/watch?v=rfscVS0vtbw (58:27)
colour = input("Colour: ") #asks player what they want for a spot
plural_noun = input("Plural Noun: ") #asks player what they want for a spot
celebrity = input("Celebrity: ") #asks player what they want for a spot
print("Roses... |
846fed837592a6e579a734c3c76c9f1ad55730ed | errne/Python_text_RPG_practice | /Room.py | 2,344 | 3.84375 | 4 | from Enemy import *
from Battle import *
class Room:
def __init__(self, player):
self.number_of_enemies = self.generate_number_of_enemies()
self.enemies = []
self.player = player
self.treasure_chest = 0
def generate_number_of_enemies(self):
return random.randint(1, 3)... |
2c62a5e57540b8d400ea433308588ae52e2911de | errne/Python_text_RPG_practice | /Battle.py | 3,560 | 3.75 | 4 | import random
from Armour import Armour
from ArmourMaterials import ArmourMaterials
from ArmourTypes import ArmourTypes
class Battle:
def __init__(self, player, enemy):
self.player = player
self.enemy = enemy
self.battle_is_on = True
self.health_potion_drop_chance = 95
se... |
87f91b56e54adfb2d19b5e866a0eecf319acdeb6 | richard912611428iop/leetcode-py | /src/Swap Nodes in Pairs.py | 795 | 3.78125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swap_node(self, n1, n2, n3, n4):
if n3 is None and n4 is None:
return
n1.next = n3
n3.next = n2
n2.next = n4
r... |
25a4e8f1319b458a1d3cca8454126f67c8229589 | richard912611428iop/leetcode-py | /src/Combinations.py | 456 | 3.546875 | 4 | class Solution:
def dfs(self, n, k, start, cur, path, result):
if cur == k:
result.append(path[:])
for i in range(start, n+1):
path.append(i)
self.dfs(n, k, i + 1, cur + 1, path, result)
path.pop()
return
# @return a list of lists of integ... |
0d8833a9ba672daa781c0150442b7252c4fde2c9 | richard912611428iop/leetcode-py | /src/Valid Parentheses.py | 937 | 3.640625 | 4 | class Solution:
# @return a boolean
def isValid(self, s):
stack = collections.deque()
if s is None or len(s) == 0:
return True
stack.append(s[0])
for i in range(1, len(s)):
c = s[i]
if c == '}':
if len(stack) == 0:
... |
58793a445e200a27bac54c49e397696d1ef94c3e | suiup/pythonProject | /python_learning/循环/while_learning.py | 360 | 4.1875 | 4 | print("while 循环演练")
"""
语法:
while 条件(判断 计数器 是否达到 目标次数):
条件满足 xxx
条件满足 xxx
... ...
处理条件(计数器 + 1)
"""
i = 0
while i <= 5:
print("Hello world")
if i == 3:
i = i + 1
continue
i= i + 1 |
dffe13e766c525ce76c78feba50be665075e12cf | suiup/pythonProject | /python_learning/高级变量类型/dic_learning.py | 1,263 | 4.0625 | 4 | print("字典")
"""
字典
可以用来存储多个数据
可以存储无序的数据集合
用 {} 定义
使用键值对存储数据,键值对之间使用 "," 分隔
key value
key 是索引
value 是数据
键和值之间用 : 分隔
key 唯一
value可以为任意的数据类型,但是key只能使用 字符串,数字或元组
应用场景
描述一个物体的相关信息
常用操作:
取值
增加/修改
删除
len()
update()
... |
6d36e9fa445057590df0d005cb5e2cb69df1d9fd | GiannisMavridis2/codility | /3permMissingElement.py | 153 | 3.59375 | 4 | def solution(A):
for i in range(1,len(A)+2):
if i not in A:
return i
A=[2,3,1,5]
lysh=solution(A)
print(lysh)
|
978b25bacf15458f04b14cd4250b80a499553baa | blukatdevelopment/dndutils | /roll72/roll72.py | 1,194 | 3.546875 | 4 | # Roll ability scores for a character
import random
MIN_SCORE = 72
# Returns a dict with accepted rolls, total, and minimum roll
def roll_4d6_drop_lowest():
result = {}
result["rolls"] = []
for i in range(4):
roll = random.randint(1, 6)
result["rolls"].append(roll)
result["minimum"] = min(result["r... |
4464f45eaf50f90ef887757f56d9ecd02ed7330c | imvera/CityUCOM5507_2018A | /test.py | 500 | 4.21875 | 4 | #0917test
#print("i will now count my chickens")
#print ("hens", 25+30/6)
#print("roosters",100-25*3%4)
#print("now count the eggs")
#print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
#print("is it true that 3+2<5-7?")
#print(3+2<5-7)
#print("what is 3+2?",3+2)
#print("what is 5-7?",5-7)
#print("is it greater?",5 > -2)
#print("... |
9ce1782c9f1fba06e9ddce589d33a814b4d95dd6 | tarek1921/python | /Scheduling/tardy_jobs/minizing number of tardy jobs.py | 1,277 | 3.59375 | 4 | #coding = utf-8
def data_input():
"""从txt文本中读取数据"""
jobs = []
jobs_list = []
data = dict()
for job_data in open('data.txt','r'):
print (job_data)
job,processing_time, due_date = job_data.split(',')
processing_time = float(processing_time)
due_date = float(due_date)
jobs_list.append(job)... |
cb4d2a35e124d2528f6058b38c45376d9db6dda4 | EliasLMann/Sorting-Algorithm-Analysis | /DatasetGenerator.py | 2,261 | 3.71875 | 4 | #Created by Elias Mann
#03/19/2021
import random
def create_dataset(size):
sizeList = list()
percent20List = list()
file_base = "/Users/eliasmann/Desktop/Algorithms/21s-pa02-EliasLMann/Sorting_Analysis/Datasets/" + str(size)
#creating list of unique values that is 20% of the dataset size
for x i... |
7ad8bded1d8efb9a70a1c39a01a530716f90ca59 | brslv/code | /python/sum_to_n/sum_to_n.py | 363 | 4.09375 | 4 | # Write a program that asks the user for a number n and prints the sum of the numbers 1 to n
n = int(input("Enter n: "))
sum = 0
nums = []
for num in range(1, n + 1):
nums.append(num)
sum += num
numsStringList = [str(i) for i in nums] # To join a list we use list comprehensions
print("The sum of [{}] is {}... |
84598b88bbcfff140e36decdde6da3278155a39f | brslv/code | /python/occurrence/occurrence.py | 304 | 4.03125 | 4 | # Write a function that checks whether an element occurs in a list.
a_list = [1, 15, "John", "Tim", 8, "Conrad"]
def check(a_list, elem):
for el in a_list:
if el == elem:
return True
return False
print(check(a_list, "Sara")) # False
print(check(a_list, "John")) # True
|
491ffa10c1040c53977dc89573844e6cafadc42f | ranjithjupaka/beginner-python-projects | /3.Hangman/Hangman.py | 1,722 | 4 | 4 | import random
from word import words
import string
import ast
def get_valid_word(words):
valid_word = random.choice(words)
while "-" in words or " " in words:
valid_word = random.choice(words)
valid_word = valid_word.upper()
return valid_word
def hangman():
word = get_valid_word(words... |
ae90b49c66bc6d8af4ba3f106bf8b5ee580e1681 | aindrila2412/Algorithms | /Online_Challenges/ChefFood.py | 430 | 3.546875 | 4 | # source: https://www.codechef.com/LRNDSA02/problems/STFOOD
def ChefFood(N, foods):
stores = [foods[i][0] for i in range(N)]
people = [foods[i][1] for i in range(N)]
prices = [foods[i][2] for i in range(N)]
received_customers = [people[i]//(stores[i] + 1) for i in range(len(people))]
received_profit... |
d155640572e8bebc0329d7a7ab08b6402ef30521 | aindrila2412/Algorithms | /Specific_Algorithms/Permutation.py | 749 | 3.921875 | 4 | def Permutation(permutation, elements, positions):
if len(permutation) == len(elements):
print(permutation)
else:
for i in range(0, len(elements)):
print("this is " + str(elements[i]))
if positions[i]:
print("skip " + str(elements[i]))
cont... |
ee73c6b74b66ae179363d9b2cbef6a794829fdc7 | kerrywong/Basic | /venv/basic_04.py | 2,338 | 4 | 4 | # 函数作为返回值
def lazy_sum(*args):
def sum_list():
sum = 0
for x in args:
sum = sum + x
return sum
return sum_list
f1 = lazy_sum(1, 2, 3)
print(f1) # 返回的是函数整整体(本身,参数,函数值)
print(f1()) # 使用f1函数里面返回值
f2 = lazy_sum([1, 2, 3]) # 每次调用的时候都会返回一个新函数 故不能相比较
print(f1 == f2) # 结果肯定是f... |
7b91eefe4ac4e85eee5589bf8961b6355d64c506 | kerrywong/Basic | /venv/basic_05.py | 1,991 | 3.875 | 4 | # try...except...else...finally
try:
a=input("Please input a number:")
r=10/int(a)
print("The result is %s"%str(r))
except ValueError as e:
print('ValueError:',e)
except ZeroDivisionError as e:
print("ZeroDivisionError:",e)
else:
print("no error")
finally:
print("finally...")
print("END")
#... |
c592cf7442f44cb57d2975ed846a06b1698793e7 | getcontacts/getcontacts | /contact_calc/atom.py | 6,507 | 3.5 | 4 |
import sys
class Atom:
def __init__(self, vmd_index, chain, resname, resid, name, element, icode=''):
"""
Construct a new atom with the values, check the element (potentially infer from name) and set van der Waals
radius based on it.
Parameters
----------
vmd_inde... |
83d9271a9cd495ef4c5fe57309871dd8bb5fe6d8 | youlingsi/AlgorithmPython | /Quick-Union.py | 446 | 3.984375 | 4 | idLst = [0,1,9,4,9,6,6,7,8,9];
i = len(idLst);
"""Find the root of the given number"""
def findRoot(n):
if n == idLst[n]:
return n;
elif n < i :
m = idLst[n];
return findRoot(m);
else:
return "error";
"""Merge the trees of the given number"""
def unionTree(p, q):
rp = f... |
7ef1db4c1a5becf4b0c64187725096ca3d30dbfa | PartnerSlate/mars-air-seating-py | /seating/cli.py | 314 | 3.8125 | 4 | from .assign_seating import assign_seating
def main():
print("WELCOME TO MARS AIR SEATING")
print("")
while True:
input_str = input("How many passengers in your group? ")
seating = assign_seating(input_str)
print(f"Seating assignments: {' '.join(seating)}")
if __name__ == "__main__":
main() |
32cefd6911a585c67e32b818b8506fe8ec87ae9f | slone4ka/secret-santa | /src/secret-santa.py | 2,211 | 3.5 | 4 | #! env python
import sys
import random
import smtplib
SMTP_ADDRESS = ''
SMTP_PASSWORD = ''
EMAIL_MESSAGE = \
'Subject: Secret santa!\n\n' + \
'Hello %s,\n' + \
'You will be giving a gift to %s.'
def send_emails(participants, groups):
smtp = smtplib.SMTP()
smtp.connect('smtp.gmail.com', 587)
s... |
1b56235ac27151555d08f7f78e750600e01ce93e | Okeoma/Codility_python | /perm_missing_elem.py | 411 | 3.5625 | 4 | # This is the solution for Time Complexity > PermMissingElem
#
# This is marked as PAINLESS difficulty
def solution(A):
actual_sum = 0
for number in A:
actual_sum += number
max_number = len(A) + 1
expected_sum = (max_number * (max_number + 1) // 2)
return expected_sum - actual_sum
print(... |
f2a4bed6a06b5bd16091f08ba42fc58977ad44fe | vladvesa/PEP20G06 | /modul5/classes.py | 1,416 | 3.75 | 4 | # classes
class CarFactory:
model = 'VW'
counter = 0
def __init__(self, colour):
print('Building car')
self.colour = colour
def __le__(self, second_car):
print('First object:', self)
print('Second object:', second_car)
return id(self) <= id(second_car)
print(... |
2b726e7eb203a481eb877ade75e690ac67040cbc | bala1144/AdventOfCode2020 | /day4/day4.py | 3,299 | 3.609375 | 4 | import re
def input_parser(input_file):
"""
sample :
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
.
.
.
"""
with open(input_file) as f:
input_list = f.read... |
953912576b2b5c7b6131b368893cfb79bdde270a | Tyler-Carter/100-Days-of-Code | /Day 23 - Turtle Crossing Capstone/car_manager.py | 742 | 3.96875 | 4 | from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager:
def __init__(self):
self.car_list = []
self.move_speed = STARTING_MOVE_DISTANCE
def create_car(self):
new_car = Tur... |
261b6b50f57e8974a123399980f904cb6e6dcc80 | yinzilong/DataStructure | /test/test_strCopy.py | 106 | 3.5625 | 4 | #coding=utf-8
str1 = "hahaha"
str2 = str1
str2 = str2 + "xbb"
print("str1:", str1)
print("str2:", str2)
|
094efb2365d0e528bc8046de8344db8978036bc7 | yinzilong/DataStructure | /InterviewGold/Finder.py | 1,368 | 3.703125 | 4 | # -*- coding:utf-8 -*-
class Finder:
#二分查找法,只是要修改判断条件
#a[mid]>x,本来要在右边找,但是如果x>a[right], 并且a[mid]<a[left],则在左边找
#a[mid]<x,本来要在左边找,但是如果x<a[left],并且a[mid]>a[right],则在右边找
def findElement(self, A, n, x):
left = 0
right = len(A)-1
while left <= right:
mid = (left + right)/... |
ada7588486d6e246134eb53b4769af2daaf5afa4 | yinzilong/DataStructure | /Diagram/diagramTraverse.py | 4,138 | 3.59375 | 4 | #coding=utf-8
class Graph(object):
def __init__(self, *args, **kwargs):
self.node_neightbors={} #用来为每一个结点存邻居结点,键值对 node:[]
self.visited={} #用来记录该结点是否已经被访问过 node:bool
def add_nodes(self, nodelist):
for node in nodelist:
self.add_node(node)
d... |
5643d0ea5b095616abf27db9e901eb23c911c264 | yinzilong/DataStructure | /Sort/myQuickSort.py | 822 | 3.90625 | 4 | #coding=utf-8
#判断异常
#指定枢纽位置
#制定i,j的值
#快排的主要思路
#递归
#一次快排结束的标志的i=j
#整体结束的标志是传入的参数left>right
def quickSort(R, left, right):
if left > right:
return
temp = R[left]
i = left
j = right
while i<j:
while i<j and R[j]>temp:
j -= 1
if(i<j): #此处一定要加判断,不然最... |
93e6b0a687348de10894680c4621ebf7cdfec1d1 | yinzilong/DataStructure | /test/test3_1.py | 646 | 3.96875 | 4 | #coding=utf-8
import sys
import copy
def count_lessZero(list_int):
count=0
for num in list_int:
if num<=0:
count +=1
return count
if __name__ == "__main__":
# 读取第一行的n,表示数组长度
n = int(sys.stdin.readline().strip())
line = sys.stdin.readline().strip()
values = map(int, line... |
7a299e4e46aa665e7424e9e76d20ecfb9707dbdf | Ilnur92/skillfactory-module5-mazhitov | /script.py | 896 | 3.8125 | 4 | field = [[" ", "0", "1", "2"],
["0", "-", "-", "-"],
["1", "-", "-", "-"],
["2", "-", "-", "-"]]
def show_field():
for x in field:
print(x[0], x[1], x[2], x[3])
def ask_field():
i = input("Введите строку: ")
i = int(i)
j = input("Введите столбец: ")
... |
b4c929cb05f63184dc9aa1cd4b9c072c75e40db3 | jeremysong1106/IMIP | /P4 - Deep Learning/code/LayersExercise/reLU.py | 883 | 3.984375 | 4 | import numpy as np
class ReLU:
def __init__(self, input_size, batch_size):
# the current activations have to be stored to be accessible in the back propagation step
self.activations = np.zeros((input_size, batch_size)) # "pre-allocation"
def forward(self, input_tensor):
... |
d1b9a11de6fbcfbf22b58228c87234441f6dd799 | LucasQuintela11-zz/PythonPower | /2.Listas.py | 143 | 3.703125 | 4 | lista1 = ['A', 'B', 'C']
print(type(lista1))
lista1.append('D')
print(lista1)
lista2 = ['A', 1, 1.14, len, [1, 2, 3, 5]]
print(lista2[0])
|
c7868193d3c5f6b7b46fd5078d92f0e42f9df1f8 | amanihamdy/Neural_Task1 | /PerceptronLearning.py | 726 | 3.578125 | 4 | import numpy as np
class Learning :
def sigmoid(self , n):
return 1 / ( 1 + np.exp(-n) )
# input dataset
training_inputs = np.array([[0,0,1],[1,1,1],[1,0,1],[0,1,1]])
# output dataset
training_outputs = np.array([[0,1,1,0]]).T
np.random.seed(1)
random_weights = 2 * np.ran... |
fd7b1bf7844ff538f98d506fe829568a94230174 | arkhn/fhir-river | /django/common/scripts/utils/is_empty.py | 291 | 3.640625 | 4 | def is_empty(value):
"""(Logic) is None, NaN, empty or blank str"""
return (
value is None
or value == "NaN"
or value == "NaT"
or value == "None"
or value == ""
or value in " "
or value == "(null)"
)
|
1a6195375e49cdcf2c06f3fd89f38134bc0ab80e | yukan97/python_essential_mini_tasks | /005_Collections/Task1_3_and_additional.py | 508 | 4.25 | 4 | def avg_multiple(*args):
return sum(args)/len(args)
print(avg_multiple(1, 2, 4, 6))
print(avg_multiple(2, 2))
def sort_str():
s = input("Eneter your text ")
print(' '.join(sorted(s.split(' '))))
sort_str()
def sort_nums():
num_seq_str = input("Please, enter your sequence ").split()
try:
... |
8657e8f07a0abc8be31f453743bde9ebec46bc9b | yukan97/python_essential_mini_tasks | /002_Inheritance/AdditionalTask.py | 1,745 | 3.734375 | 4 | class Vehicle:
def __init__(self, engine, speed):
self.engine = engine
self.speed = speed
def print_attr(self):
print(self.__class__.__name__, self.engine, self.speed)
class LandVehicle(Vehicle):
def __init__(self, engine, speed, trunk_size, max_passangers):
super()... |
939e4245b1e6d47dc64b6866e073130a956c76d8 | murchie85/hackerrank_myway | /mergeTheTools.py | 943 | 3.6875 | 4 | """
Sample Input
STDIN Function
----- --------
AABCAAADA s = 'AABCAAADA'
3 k = 3
Sample Output
AB
CA
AD
Explanation
Split into equal parts of length . Convert each to by removing any subsequent occurrences of non-distinct characters in :
Print each on a new line.
"""
def merge_the_to... |
67dfa55500af7f9c1e0e57bcd96cb01b30d2353c | murchie85/hackerrank_myway | /findaString.py | 1,407 | 4.1875 | 4 | """
https://www.hackerrank.com/challenges/find-a-string/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
Sample Input
ABCDCDC
CDC
Sample Output
2
Concept
Some string processing examples, such as these, might be useful.
There are a couple of new concepts:
In Python, the lengt... |
32a13f43ece653ccac3d56ef10748946a0542cd3 | fadyboy/thinkful_tip_calculator | /exception.py | 1,658 | 4.03125 | 4 | import sys
# import functions from tip_cal_functions
from tip_cal_functions import calculate_meal_costs, calculate_rate
def main():
# assign the value False to the variable done
done = False
try:
# assign the user supplied inputs to the meal, tax_rate and tip_rate variables
meal = float(sy... |
29617b6e12939128a1ef40bfafb12b325a5e9e45 | a582218152/data-analysis | /pandas函数/csv_reader_calue_meets_condition.py | 1,707 | 3.6875 | 4 | import pandas
import pandas as pd
import sys
import csv
#python基础方法实现筛选行中的某数据
input_file = sys.argv[1]
output_file = sys.argv[2]
with open(input_file,'r') as csv_in_file:
with open(output_file,'w') as csv_out_file:
filereader = csv.reader(csv_in_file)
filewriter = csv.writer(csv_out_file)
... |
07d1e43389b4a4d9be991e0714081a810bab0a66 | jabbalaci/fallout3_computer_hack | /next.py | 854 | 3.84375 | 4 | #!/usr/bin/env python3
# encoding: utf-8
"""
I prefer to collect words in files called 01.txt, 02.txt, etc.
This little helper finds the filename with the largest number
in its name and increments it by one, then opens this new file
for editing.
"""
import os
import re
EDITOR = os.getenv('EDITOR')
def main():
... |
bcd4fd3a96701d4dd1ec8e6f1ab296330fa7ed64 | filipedwan/poo_python_aulas_2019_2 | /Cap 02 - Objetos em Python/menu.py | 1,980 | 3.5625 | 4 | import sys
from notebook import Notebook, Note
class Menu:
'''Mostra um menu e aciona as ações apropriadas com base
nas opções escolhidas.'''
def __init__(self):
self.notebook = Notebook()
self.choices = {
"1": self.show_notes,
"2": self.search_notes,
"3... |
504eb713528e0e321d24b6e1f21722ffb903de38 | giulianorosella/Final-Project-Basic-Probability | /LinearRegressing.py | 11,408 | 4.125 | 4 | import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
boston = datasets.load_boston()
class LR(object):
'''An implemententation of a linear regression object, that given features is able to calculate optimal parameters to get the best prediction'''
def __init__(self, predicto... |
a949ff5542b269ac60a8e8c6de555b9354c529c8 | nadiavdleer/connectholland | /code/sortnum.py | 1,020 | 4.125 | 4 | """
Assessment problem 5
Nadia van der Leer for Connect Holland
10 June 2021
"""
from word2number import w2n
from num2words import num2words
def sort_numerically():
# initialise word list
word_list = [
"seventy five",
"two hundred forty one",
"three thousand",
"one million thir... |
fef46579527a8097363d2813496a1aaade7357b3 | Ali5ch/Machine-Learning-Models | /Part 2 - Regression/Section 6 - Polynomial Regression/regression_template.py | 1,399 | 3.53125 | 4 | #Regression_template
"""
Created on Tue Mar 21 19:41:41 2017
@author: ali5c_000
"""
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the dataset
dataset= pd.read_csv('Position_Salaries.csv')
X= dataset.iloc[:,1:2].values
y=dataset.iloc[:,2].values
#splitt... |
a9ac5926ee4759040aecf57986863ef9a324053b | phoophoo187/Privacy_SDN_Edge_IoT | /experiment-mininet-wifi/Cls_topology.py | 2,028 | 3.875 | 4 | """
" The Topology class responed for
" - creating a network topology which specified in a JSON format file
" - adding and removing nodes and edges from a network
" - showing a current network topology
"""
import networkx as nx
from networkx.readwrite import json_graph
import json
import matplotlib.pyplot as plt
c... |
3807abcdef7d07629c2f822a5b4ebc2eab045946 | humatic/foxsi-optics-sim | /src/foxsisim/shell.py | 2,516 | 3.8125 | 4 | '''
Created on Jul 11, 2011
@author: rtaylor
'''
from segment import Segment
from math import tan,pi
class Shell:
'''
A shell consists of two segments, one in the front and one behind. The base location
of the front segment has a smaller z value than that of the back segement. Thus, rays
coming from s... |
55ed9265a2c0b8de0be114d7a51868618d47514e | leticiasimp7/estruturaDeRepeticao | /2B/EstruturaDeRepetiçao/questao11.py | 373 | 3.9375 | 4 | num1=eval(input("Digite o número inicial do intervalo: "))
num2=eval(input("Digite o número final do intervalor:"))
if (num1<num2):
soma=0
auxiliar=num1+1
while (auxiliar<num2):
soma= auxiliar+soma
auxiliar=auxiliar+1
else:
print("Cídiho inválido")
print("O valor inicial é: ", num1)
print("O valor... |
e1e28531c5f26537c94ffcba3d556d6f9999946a | laureleo/epfl | /aa_CS-330/ex1.py | 328 | 3.671875 | 4 | n = input("Quel est votre nom ?\n ")
print("Bonjour ", n)
class Personne:
"""Return the pathname of the KOS root directory."""
def __init__(self, nom, age):
""" Constructeur. """
self.nom = nom
self.age = age
def anniversaire(self):
""" Missing docstring """
self.a... |
878ff34e9362abb623444dc1290815fa60b9eb78 | wateentaleb/Machine-Learning-and-Networking | /MachineLearning.py | 2,129 | 3.734375 | 4 | import pandas
import os
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
import numpy
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
data = pandas.read_csv('data.csv')
#us... |
5e5b597d7b35ba3e7fd9e4f9d9e6a2e3fa0a77ac | mato391/Python | /Log.py | 843 | 3.53125 | 4 | __author__ = 'mato3'
import datetime
class Log:
def __init__(self):
'''
Constructor, opening log.txt file. If file is not exists, file will be created.
:return: None
'''
self.hFile = open("log.txt", "w+")
def __del__(self):
'''
Destructor, closing opened fil... |
a6859dcfc2273c365db9e8639b75e4fbfc3f1671 | tsh/fun_with_code | /basic_math_for_game_developer/vectors_add_and_subs.py | 434 | 3.8125 | 4 | """
One can add two vector to go diagonal:
() ----------------> Horiz
\ \
\ \
\ \
\ \
\ \
\ \
\| \
Vert Diag
If one need Diagonal vector, he could add Horiz + Vert.
"""
from structures import Vector, Point
if __name__ == '__main__':
horizontal = Vector(4,... |
d923154788c2cc16e718df0d791eb5ffaa962bb6 | tsh/fun_with_code | /vectors/simple_movement.py | 1,597 | 3.609375 | 4 | import tkinter
from vector import Vector
# AHTUNG! monkey patching
def _create_circle(self, x, y, r, **kwargs):
return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
tkinter.Canvas.create_circle = _create_circle
class Ball(object):
def __init__(self, position, velocity):
self.position = position
... |
4c4821cb831c898eea416819a966bfc10bf0ab1b | mukund2000/Income-Classification | /Assignments/Assignment-0/Armstrong.py | 398 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 18 22:56:39 2020
@author: Mukund Rastogi
"""
def isArmstrong(n):
temp=n
s=0
while(temp):
rem=temp%10
s=s+rem**3
temp=temp//10
if n==s:
return True
else:
return False
x=int(input("Enter number"))
if(isArmstrong(x... |
f242c0cff98a64a249b1778329694ffb752411cb | HerynJMV/sortAlgorithms | /cocktail.py | 600 | 3.546875 | 4 | def cocktail (A):
n = len(A)
x = 0
while x < n :
print(f'n = {n}, x = {x}\n')
# style to print bars with the number size
for valor in A:
print(f"{'|'*valor}")
# left to right
for i in range(x, n - 1):
if A[i] > A[i + 1] ... |
87e87abc6bcedda29a349fb945fd45541e8a681a | AirborneRON/Python- | /chatbot/chatBot.py | 1,980 | 4.1875 | 4 | file = open("stop_words")
stopList = file.read().split("\n")
file.close()
# how to open up my plain text file, then create a variable to stuff the read file into
#seperating each element of the list by the return key
#then close
# all responses should start with a space before typing
print(" Hello ")
response =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.