blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c631c0cfb2a18645a422092a706393cdb7b1e535 | alvarov0907/python-scientific | /hellotensorflow.py | 5,857 | 3.59375 | 4 | '''
Basic Tensorflow2 walkthrough and snippet cookbook.
You can start here adding whatever you want to have a functional running code.
Run this code with ann3 environment.
Tensorflow is fast, and allows automatic differentiation.
# OpemMP sometimes raises coredumps, try export KMP_DUPLICATE_LIB_OK=TRUE
Sources: ... |
e938bb5eb9e742f8a97b04003c7806d476902162 | RennanFelipe7/algoritmos20192 | /Lista 3/lista03ex17.py | 623 | 3.921875 | 4 | QuantidadeDeTurmas = int(input("Qual a quantidade de turmas? "))
cont = 0
SomaDeAlunos = 0
while cont < QuantidadeDeTurmas:
QuantidadeDeAlunos = int(input("Qual a quantidade de alunos dessa turma? "))
while QuantidadeDeAlunos > 40:
print("O maximo de alunos por tuma é 40, por favor digite novamente a qu... |
447fe79bdc451ce7a0810187ca9d7319f10f61de | canwe/python3-course-advanced | /29_multiprocessing/multiprocessing_demo.py | 1,765 | 4.09375 | 4 | """
The multiprocessing module allows to spawn processes the same way the threading module allows to
spawn threads. The advantage on multiprocessing module is that we can avoid the
GIL (Global Interpreter Lock) and use in a real way multiple processors on a machine.
"""
import os
from multiprocessing import Process, ... |
26b280a437aafe8ef6cf66d6b649180869f7df89 | lastosellie/algorithm | /Programmers/12914.py | 440 | 4 | 4 | '''
멀리 뛰기
https://programmers.co.kr/learn/courses/30/lessons/12914
'''
def dfs(a, n):
s = sum(a)
if s == n:
print(a)
a.pop()
return 1
elif s > n:
a.pop()
return 0
a.append(1)
sum1 = dfs(a, n)
a.pop()
a.append(2)
sum2 = dfs(a, n)
def solution(n):
... |
27dbe29c01c2ded00473f8a86e79a574bd6583f3 | SongJXin/ARTS | /leetcode/1-two-sum/two-sum.py | 907 | 3.671875 | 4 | # Runtime: 1160 ms, faster than 31.89% of Python3 online submissions for Two Sum.
# Memory Usage: 13.8 MB, less than 27.63% of Python3 online submissions for Two Sum.
class Solution1:
def twoSum(self, nums, target):
for num in nums:
if target - num in nums[nums.index(num)-len(nums)+1:]:
... |
307a927f5994b65a5d1a4587a845236ea81af730 | edu-athensoft/stem1401python_student | /sj190912_python2/py1003/review_if3.py | 349 | 3.828125 | 4 | # flow control - if statement
level = int(input("Enter your current level: "))
# 0 - 19.99, 20 - 49.99, 50 +
if level>=50 :
print("buy my sword of lvl 50")
print("collecting mineral")
elif level>=20 :
print("buy a stick of lvl 20")
print("farming")
else:
print("My current level is {}".format(l... |
7db633ba0f68fe8c10af5c45655b1924d4d36723 | MarianaDrozd/cursor_my_homeworks | /HW8_Advanced_classes.py | 4,621 | 3.953125 | 4 | from __future__ import annotations
from typing import Dict, Any
from abc import ABC, abstractmethod
import uuid
import random
import time
class Animal(ABC):
def __init__(self, power: int, speed: int):
self.id = None
self.max_power = power
self.current_power = power
self.speed = sp... |
bf44e5f9f0985059c574875d9f303d77210338f5 | Erivaldojelson/Calculadora | /day6.py | 440 | 3.84375 | 4 | x = int (1) # x will be 1
y = int (2.8) # y will be 2
z = int ("3") # z will be 3
w = float("4.2") # w will be 4.2
print(x)
print(y)
print(z)
print(w)
x = float(1) # x will be 1
y = float (2.8) # y will be 2
z = float("3") # z will be 3
w = float("4.2") # w will be 4.2
print(x)
print(y)
print(z)
print(w)... |
99defb0a781227421b12b4a315bba50f843d6929 | Mosiv/Python-lissons | /game.py | 596 | 3.875 | 4 | '''Game: Guess the number'''
import random
random_number = random.randint(1,50)
attempt_counter = 0
print('Игра, угадай число от 1 до 50')
while attempt_counter < 6:
number = int(input('Введите число: '))
attempt_counter+=1
if number == random_number:
print('Угадал')
break
if number > r... |
f79ae4edfa85555f6e93ff8a792160865278cdb9 | carolynfischer/various_python_scripts | /is_unique.py | 357 | 4 | 4 | """
Determine if all characters in the sting are unique
"""
def is_unique(s):
split_string = []
for i in s:
split_string.append(i)
unique_set = set(split_string)
if len(s) == len(unique_set):
return True
else:
return False
if __name__ == "__main__":
print is_unique("ka... |
defcc1face872ed1e02adcd9d8fedd5e9a63595d | nareshenoy/base | /src/script/project_euler/47.py | 1,443 | 3.625 | 4 | import math
def get_num_factors(n):
factors = set()
sq = n / 2 + 1
for i in range(2, sq + 1):
if n == 1: break
while n % i == 0:
factors.add(i)
n = n / i
#print i
return len(factors)
def main():
n_1 = get_num_factors(1)
n_2... |
bc741497e4a8d4f012b7e11550ad1ed5a3fac44f | anlaganlag/Funcs | /有序流.py | 1,669 | 3.625 | 4 | def __init__(self, n: int):
self.pointer = 1
self.stream = (n+1)*[""]
def insert(self, id: int, value: str) -> List[str]:
self.stream[id] = value
//每次插入初始化都爲[],類似每次先做清理工作...
ans = []
//如果id和指針匹配..有點類似擊中了g點..沒擊中就return []
if self.pointer == id:
//將id選一個分身即i...
... |
aa04005069b22096f9676a94144309831d044972 | iMikeT/MathProject2 | /Postcode Task/Postcode.py | 4,934 | 4.0625 | 4 | import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv(r'F:\Documents\University\Math Project\Project Year 4\Machine Learning\Job Example\Task Sheet\Postcode_Estimates_Table_1.csv') # Create dataframe
print('Original Data')
print()
print(df.head())
print()
clist = list(df['Postcode'])
clist = ... |
7091eb0e3645669c18d0080c2ac9445d6423916d | ElvinKim/201803_ita_python | /20180325_2_practice_1.py | 357 | 3.875 | 4 | def average(a, b):
return (a + b) / 2
print(average(10, 20))
def average_lst(lst):
total = 0
cnt = 0
for num in lst:
total += num
cnt += 1
return total / cnt
a = [1, 2, 3, 4, 5]
print(average_lst(a))
print(average_lst((1, 2, 3)))
def average_lst_v2(lst):
... |
966a9200a9cff8f58c7bf341d59cbbcd6a7be814 | liyanhang/liyh-footmark | /python-footmark/code/if.py | 283 | 3.828125 | 4 | #!/usr/bin/python
# Filename: if.py
number=23
guess=int(raw_input('Enter an integer:'))
if guess==number:
print'woaini'
elif guess<number:
print'niaiwo'
# do whatever you want
else:
print'no, it is ugly'
print'DDDD'
# jieshaoyixia
if False:
print 'haobuhao'
|
534f77ddf5d2706619925527a05cc48e28fd45fe | FelicianoSachilombo/psr_21-22 | /Parte03/T/Ex2/class_example.py | 653 | 3.890625 | 4 | #!/usr/bin/python3
import colorama
class Person:
def __init__(self, name, address, phone):
self.name = name
self.address = address
self.phone = phone
def __str__(self):
return 'Name: ' + self.name + ' address: ' + self.address + ' phone: ' + str(self.phone)
def main():
jo... |
2ad59aa36eb769291e2670902af4653be5e6352a | vladvlad23/UBBComputerScienceBachelor | /FundamentalsOfProgramming/Assignment 03-04/complexOperations.py | 1,218 | 4.0625 | 4 | def getReal(complexNumber):
return complexNumber.real
def getImaginary(complexNumber):
return complexNumber.imag
def turnStringToComplexNumber(number):
'''
Function will receive a string which will be turned into a complex Number
The String is guaranteed to be a complex number
'''
# new ... |
4f4994ff203923341ba6eac13727f4a4b2acfd03 | green-fox-academy/florimaros | /week-3/friday/gyak/gyak21b.py | 213 | 3.984375 | 4 | u = 13
#if u is between 10 and 20 print Sweet if less than 10 print More if more than 20 print less.
out = ""
if u > 10 and u <=20:
out="Sweet"
elif u <= 10:
out="More"
else:
out="Less"
print(out)
|
ecb2cb457a26bbfa0804fbb689345585aaf76053 | DeisherJohn/DailyCodingSolutions | /PythonSolutions/p021.py | 3,096 | 3.796875 | 4 | #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Program: Room scheduler
# Daily Problem #: 21
# Author: John Deisher
# Date Started: 5/9/2019
# Date Finished: 5/9/2019
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
This problem was asked by Snapchat.
Given an a... |
cc3cd55c42307d9fbffa1472432e2ce475dd9e8a | doct0rX/PythonMIT1x | /week2/ProblemSet/pset2.py | 547 | 3.765625 | 4 | """
Author: Mustafa Jamal
Uncomment the code out to run it on your machine.
"""
# balance = 3329
changableBalance = balance
# annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12.0
lowestPayment = 0
while changableBalance > 0:
changableBalance = balance
lowestPayment += 10
for i in rang... |
21d1983aaa1599f59fefa2de8a4a38f27d884c4d | wilsonmakchina/small_scripts | /text_processing/regEx_usage.py | 319 | 3.53125 | 4 | # substitute ',' for '/' for my file
import re
import sys
file_name = sys.argv[1]
file = open(file_name) # read file
file2 = open(file_name + '_result.txt', 'w') # write file
for line in file.readlines():
line = line.rstrip()
line = re.sub('/', ',', line, count=0)
print(line,file=file2)
file.close()
file2.close()
|
071cc0fe9debfbc187f6939e8e82657ec648433e | Horeb294/hub | /mypython.py | 161 | 3.515625 | 4 |
myname ="Esther Nyamekye"
mynumber = 100
mybool = True
def full_name(first, last):
return first + " " + last
full_name("Esther", "Nyamekye")
#comments in python
|
d65ba7c053d31a081a2bb0f1f7ce2abda1b091b5 | AK-1121/code_extraction | /python/python_24738.py | 140 | 3.71875 | 4 | # Delete list of elements from a list
listBig = [1,2,3,4,5,6,7,8,4,7]
listSmall = [4,7]
for item in listSmall: listBig.remove(item)
|
16a3e2766d05baa04c4dfb6cfd4475a6bbd26d35 | URTK/Lab-2-2 | /Main.py | 268 | 3.890625 | 4 | x,y = float(input('x = ')),float(input('y = '))
if (x>=1 and x<=7 and y>=1 and y<=7): # Входит в квадрат ?
if (x+y>=5 and x+y<=11 and x-y>=-3 and x-y<=3): # Входит в ромб?
print('True')
else:
print('False')
else:
print('False')
|
2e99a52dd8789b22ed35ddb288e354b1b4f2f6ff | ZanataMahatma/Python-Exercicios | /ex112/utilidadescev/moeda/__init__.py | 1,826 | 4.3125 | 4 | '''Exercício Python 112: Dentro do pacote utilidadesCeV que criamos no desafio 111, temos um módulo chamado dado.
Crie uma função chamada leiaDinheiro() que seja capaz de funcionar como a função imputa(),
mas com uma validação de dados para aceitar apenas valores que seja monetários.'''
def aumentar(preço=0, taxa=0, ... |
0133774a0c3ec40cfe359f73aa1b0e0fa690b7eb | dcarlyle/udacity_dlnd_image_classification_p2 | /dlnd_image_classification.py | 40,833 | 3.703125 | 4 |
# coding: utf-8
# # Image Classification
# In this project, you'll classify images from the [CIFAR-10 dataset](https://www.cs.toronto.edu/~kriz/cifar.html). The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. Th... |
2a4aae8f42361dd0c1ae73ec7a7834b9cc9c11e2 | ascurlock/Scurlock-Math361B | /Number Theory/N5_Divisors_Scurlock.py | 573 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 12:02:25 2019
@author: Ashley
"""
#%%
def divisor(n):
div = []
for i in range(1, int(n/2) + 1):
if n%i == 0:
div.append(i)
print('The proper divisors of', n ,'are',div)
divisor(220)
#%%
def divisor_mod(n):
... |
e262832a22b015a681d69fa141654333ffc59c10 | prashantchanne12/Leetcode | /unique number of occurence.py | 1,136 | 3.90625 | 4 | '''
Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences... |
b2c2e1fbc1d3b6806daf2afb800b636889023dd5 | jcohen66/python-sorting | /questions/medium/keypad_string.py | 2,985 | 4.21875 | 4 | import string
def get_key_to_letters():
'''
Create a map
'''
possible_letters = string.ascii_lowercase
possible_keys = string.digits
key_to_letters = {}
start_index = 0
for key in possible_keys:
if key == '0':
key_to_letters[key] = " "
elif key == '1':
... |
acce6bc75b30f05b4d9e765f413c61b022d1ef76 | PulkitSingh2008/Calculator-that-you-need | /Clacu.py | 839 | 4.34375 | 4 | #defining function (calculation)
def calculation(number1,number2):
# if statements to perform calculations
if operator =="+":
total=number1+number2
return (total)
elif operator =="*":
total=number1*number2
return (total)
elif operator =="^":
total=number1**number2
return (total)
elif o... |
41310e7d2cb40d3fbc1c5a8ae59ba0be7e08b34a | pixelblacksmith/megacode | /polynomial.py | 1,888 | 3.828125 | 4 | def eval(x, poly):
'''Evaluate at x the polynomial with coefficients given in poly.
The value p(x) is returned.'''
sum = 0
while 1:
sum = sum + poly[0] # Add the next coef.
poly = poly[1:] # Done with that one.
if not poly: break # If no more, done entirely.
... |
210c220a65b37348e504e208e97b63665635b964 | friedlich/python | /19年7月/7.25/np.reshape.py | 447 | 4.3125 | 4 | # 在numpy模块中,我们经常会使用resize 和 reshape,在具体使用中,通常是使用resize改变数组的尺寸大小,
# 使用reshape用来增加数组的维度。
# 给数组一个新的形状而不改变其数据
import numpy as np
X=np.array([1,2,3,4,5,6,7,8])
X_2=X.reshape((2,4)) #return a 2*4 2-dim array
X_3=X.reshape((2,2,2)) # return a 2*2*2 3-dim array
print("X:\n",X)
print("X_2:\n",X_2)
print("X_3:\n",X_3)... |
6459d257467ca13b66072a2e33831224780a9115 | KONASANI-0143/Dev | /requirements/venky_task/AI/pyplot.py | 270 | 3.546875 | 4 | import matplotlib.pyplot as plt
x=[1,2,3]
y=[4,5,8]
x1=[7,8,9]
y2=[4,5,6]
plt.plot(x,y,label="First line")
plt.plot(x1,y2,label="second label")
plt.xlabel("Plot Number")
plt.ylabel("Important var")
plt.title(" Interesting graph and check it")
plt.legend()
plt.show()
|
6c75b48db65713fe753428334e42dacef1c9a964 | plasticroad/DataCamp | /Python/07.Cleaning-Data-in-Python/01.Exploring-your-data/05.Visualizing-multiple-variables-with-boxplots.py | 823 | 4.25 | 4 | '''
Visualizing multiple variables with boxplots
Histograms are great ways of visualizing single variables. To visualize multiple
variables, boxplots are useful, especially when one of the variables is
categorical.
In this exercise, your job is to use a boxplot to compare the 'initial_cost' across
the different va... |
ebc756af54b04e24ea197aa227b64bf74af34e6d | why1679158278/python-stu | /python资料/day8.4/day04/exercise06.py | 143 | 3.640625 | 4 | """
在终端中录入一个内容,循环打印每个文字的编码值。
"""
for chr in input("请输入文字:"):
print(ord(chr))
|
bc77036f6b96d947ee1f794a37cf45986d3f2f91 | Davidxswang/leetcode | /easy/840-Magic Squares In Grid.py | 1,730 | 4.0625 | 4 | """
https://leetcode.com/problems/magic-squares-in-grid/
A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given an grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
Exa... |
21c49bf72688125502f89b747e439b5fa85e445d | claukako/intermediate-python-course | /dice_roller.py | 501 | 4.09375 | 4 | import random
def main():
dicerolls = int(input('How many dice would you like to roll? '))
dice_size = int(input('How many sides are the dice? '))
dicesum = 0
for i in range(0, dicerolls):
roll = random.randint(1, 6)
dicesum += roll
if roll == 1:
print(f'you rolled a {roll}! Critical fail!')
elif roll ==... |
1680dc420a819b35814a90848677a99846010662 | DamienMolina/watermark | /watermark.py | 786 | 3.5625 | 4 | from PIL import Image
import os
import glob
mask = Image.open('mask.png')
area = (50, 50)
name_folder_in = "photos_in"
name_folder_in = input("What's the name of the folder of the photos you want to watermark?")
name_folder_out = "watermarked_photos"
if not os.path.exists(name_folder_out):
os.makedirs(name_fold... |
8060e4e27bbdee7fe96a4fc0168fd69084732875 | wise200/AdventOfCode | /2019/day01.py | 234 | 3.71875 | 4 |
def fuel(n):
return max(0, n // 3 - 2)
sum = 0
with open('day01.dat', 'r') as file:
for line in file:
num = int(line)
while fuel(num) > 0:
sum += fuel(num)
num = fuel(num)
print(sum)
|
53897c8c65d83255fa67af3c7f07343b767879fc | Harish1901/Deeplearning | /Linearregression.py | 1,606 | 4 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import sklearn
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
#data imported in csv format
data=pd.read_csv("/Users/Santhosh/Downloads/50_Startups.csv")
# separating dependent and independent variabl... |
7ee1619205f470af76e65d39fa0bd020390990f5 | bagwanbulbul/pythonBasicQuestions | /if_else_Q8.py | 189 | 4.03125 | 4 | #input by user
user_input = int(raw_input("enter the number"))
if(user_input%5 == 0 and user_input%15 == 0):
print ("dono se divisible hai")
else:
print ("dono se divisible nhi hai")
|
ed23d1feee1682f6b42706401908f5e78f701a18 | jsjimenez51/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 389 | 4.09375 | 4 | #!/usr/bin/python3
"""
Module that defines save_to_json_file.
"""
import json
def save_to_json_file(my_obj, filename):
"""
Writes an object to a text file using JSON representation
Args:
my_obj: the object that is written to the file
filename: the file to write the object to
"""
with ope... |
d3c8ac718e9d26362c259fad9ca0de903eaa0638 | stefanosc/algorithms | /graph/clustering_large.py | 1,832 | 3.53125 | 4 | """Simple implementation of clustering algorithm using
bit hamming to determine verticies distance
"""
import os
import sys
misc_path = os.path.abspath(os.path.join('..', 'misc'))
sys.path.append(misc_path)
from bitmasks import bitmasks
from union_find_clustering import UnionFind
import numpy as np
import itertools... |
7aaaefa5a5332f0948dcd906fd6b9b1be407c52a | noveljava/study_leetcode | /completed/146. LRU Cache.py | 1,596 | 3.671875 | 4 | class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.lru_info = []
self.memory = {}
def get(self, key: int) -> int:
if key not in self.lru_info:
return -1
self.lru_info.remove(key)
self.lru_info.insert(0, key)
re... |
2cbf1d1a71bb05bd124905effc05e5255ecca781 | crystal30/DataStructure | /PycharmProjects/BST/BinarySearch.py | 4,201 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#在有序的数组中,查找目标元素target,若target在数组中,返回target的下标,若不在该数组中,返回-1
class BinarySearch():
#1. 用递归的方式实现 二分查找法
@classmethod
def bS1(cls,arr,target):
n = len(arr)
#递归结束的条件
return cls.__bs(arr, 0, n-1, target)
#搜索范围 arr[l,r],前闭后闭。
@class... |
116e24f632d6f60cd0c54b2e09021e55c370eee4 | lmjamily/Git-Out | /notaesquecida.py | 128 | 3.859375 | 4 | A = int(input("Digite a nota1: "))
M = int(input("Digite a média: "))
print("Essa é a sua nota da seguda prova: " , 2*M - A)
|
353d2f751abc0ce5173dac9cd0faad55328cef25 | blueleen2/ML_Projects | /Navive_Bayes.py | 2,286 | 3.9375 | 4 | # Assigning features and label variables
weather=['Sunny','Sunny','Overcast','Rainy','Rainy','Rainy','Overcast','Sunny','Sunny','Rainy','Sunny','Overcast','Overcast','Rainy']
temp=['Hot','Hot','Hot','Mild','Cool','Cool','Cool','Mild','Cool','Mild','Mild','Mild','Hot','Mild']
play=['No','No','Yes','Yes','Yes','No','Yes'... |
fd4875b14e04df99341144fcb4f31de09ecd68c9 | tannyboi/induction | /DataStructures, Modules, Exceptions,Classes/tuple_dict.py | 410 | 3.5 | 4 | d1 = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
for (x,y) in d1.items():
print(x,y)
a=(0,1,2)
b='b'
d2 = dict.fromkeys(a,b)
for (x,y) in d2.items():
print(x,y)
d2.update({3:'g'})
print(d2)
print(d2.setdefault(1,'f'))
#new entry with same key not allowed, will retur alloted... |
36378eb673f26b653fe8a5d43bc012e5e063f7e4 | cocoon333/lintcode | /68_solution.py | 443 | 3.5 | 4 | class Solution:
"""
@param root: A Tree
@return: Postorder in ArrayList which contains node values.
"""
def postorderTraversal(self, root):
res = []
self.postorderTraversa(root, res)
return res
def postorderTraversa(self, node, res):
if (node):
s... |
310e9f04dcbd51e6373e3e350470afe9b16d8ecb | A-Dragon-Bot/ReadingNotes | /myDeque.py | 2,659 | 3.765625 | 4 | class myDeque:
#构造方法,默认队列大小为10
def __init__(self, iterable=None,maxlen = 10):
if iterable==None:
self._content = []
self._current = 0
else:
self._content = list(iterable)
self._current = len(iterable)
self._size = maxlen
if self._si... |
22283e3e1b1dbfa69471fd46141c11766bbcf52f | akashmmcode/python | /singlefuctionareas.py | 758 | 3.859375 | 4 | a = int(input("select an input : 1-circle , 2-triangle , 3-rectangle , 4-square \nselect one : "))
def geometry(shapes):
if shapes == 1:
r = int(input("input radius :"))
area_of_circle = 3.14*r**2
return(area_of_circle)
elif shapes == 2:
h = int(input(" input height :"))
... |
01c9cc19ec2062259bc69df24f839cd9d4d59d38 | coderZsq/coderZsq.practice.data | /study-notes/py-collection/11_列表/02_in_练习.py | 267 | 3.640625 | 4 | month = int(input('请输入月份:'))
if month in [3, 4, 5]:
print('春季')
elif month in [6, 7, 8]:
print('夏季')
elif month in [9, 10, 11]:
print('秋季')
elif month in [12, 1, 2]:
print('冬季')
else:
print('非法输入')
|
b068e9c22e7d930f4380f81917c9c42af8ebe9d8 | kongyitian/coding_interviews | /LeetCode/Easy/Longest_Common_Prefix.py | 800 | 3.640625 | 4 | '''
Write a function to find the longest common prefix string amongst an array of strings.
'''
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if(len(strs)==0):
return ""
shortest = len(strs[0])
... |
fa72208f7fafec5304bdb4f3296f868279e0eeb0 | hariniv22/Election_Analysis | /Python_practice.py | 2,763 | 4.3125 | 4 | print("Hello World")
counties = ["Arapahoe", "Denver", "Jefferson"]
if counties[1] == "Denver":
print(counties[1])
if "El Paso" in counties:
print("El Paso is in the list of counties")
else:
print("El Paso is not in the list of counties")
if "Araphoe" and "El Paso" in counties:
print("Arapahoe and El P... |
1cc723dc2e4c4bd1cf29dd32f635af0dccdc123b | SpenserHardin/vending-machine | /src/vending_machine.py | 884 | 3.5 | 4 | from src.model.penny import Penny
class VendingMachine(object):
DISPLAY = 'Insert Coins'
PAYMENT = 0.0
def __init__(self, item, validator, price=None):
self.item = item
self.price = price
self.validator = validator
def insert_coins(self, coin):
identified_coin = self... |
12782ddc994c8914541733e1c8f9dd39e38777fb | bagaspandu154/tugaaas-big-data-menggunakan-python | /hello.py | 392 | 3.5 | 4 | print ("======================================")
print (" Biodata Sederhana Dengan Python ")
print ("======================================")
nama = input("Masukkan nama: Bagas Pandu Annursyah")
kelas = input("Masukkan kelas: Teknik Informatika A")
kampus = input("Inputkan kampus: Universitas Narotama")
... |
f9795fd1f5ef75f2a05785acfe1dac5167b8a339 | Filin3/python | /2for6_2.py | 203 | 3.640625 | 4 | s = ""
k = 0
for i in range(3):
for j in range(4):
x = input("Введите элемент {} строкой и {} столбцом: ".format(i+1, j+1))
s += x
s += "\n"
print(s) |
fa800bb30c9b08e419f88db3e9ec41a0529f8ad2 | kiransy015/Python-Frameworks | /venvScripts1/venvScripts/Pgm52.py | 462 | 3.90625 | 4 | #Set is unordered DataStructure and it doesnot allow duplicate elements
b={20,40,10,50,90,10,60,10}
print(b)
#Adding elements into a set
b.add(200)
print(b)
#Merging elements of 2 different sets
b={20,40,10,50,90}
c={10,30,40}
b.update(c)
print("After merge :",b)
print(c)
#Removing elements from a set
b.remove(40)
... |
c9df7600784325c1a468c405d473d3fe4970b94b | jghafa/archive | /CouncilSQL.py | 2,597 | 3.6875 | 4 | #!/usr/bin/python3
""" Create a SQLite database of items uploaded to Internet Archive
This replaces a three pickle files and will add the abilty for update programs to run together
"""
print('Council SQL insertion')
import pickle
import sqlite3
from internetarchive import *
#Define the database. The database is comp... |
d3a1828226389c29f5d539885a2f2316441a1367 | gretasimba/movieTrailerWebsite | /entertainment_center.py | 4,724 | 3.75 | 4 | import media # class Movie initates in media.py
import fresh_tomatoes # class generates fresh_tomatoes.html
""" creates 6 instances of class Movies to create "my favore movies" website.
Each instance pass 4 attributes to class Movie: movie_title as string,
movie_storyline as string, poster_url as string, youtub... |
53605d3cebf52412744af54ce3cfaa9bec8da4de | passlonis/SUMMER_BOOTCAMP_2018_Python | /lesson4/task3/list_items.py | 684 | 4.0625 | 4 |
print("::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
animals = ['elephant', 'lion', 'tiger', "giraffe", "monkey", 'dog']
print(animals)
animals[1:3] = ['cat']
print(animals)
animals[1:3] = []
print(animals)
animals = []
print(animals)
print("----------------------------------------------------")
... |
69f544673ba8d292af4fac97658bbcb8bdbb60cb | Quving/telegram-alfred | /alfred/material/user.py | 1,346 | 3.6875 | 4 | #!/usr/bin/env python3
class User:
def __init__(self, user_dict=None):
self.user_dict = user_dict
self.id = self.__get_user_dict_attribute(key="id", default="")
self.username = self.__get_user_dict_attribute(key="username", default="")
self.first_name = self.__get_user_dict_attribu... |
97a60f0a45eaadcf7a2b5328f9be10b83d4abab3 | DevKheder/PythonCrashCourse | /introducing-lists/3-5 changing-guest-list.py | 573 | 4.28125 | 4 | # creating a list of guests
guests = ["modar", "sara", "samer", "ahmed", "mouhammed"]
# storing the name of the guest who can't make it to dinner
popped_guest = guests.pop(0)
# print a message and inform the name who can't make it
print("I am afraid " + popped_guest.title() + " can't make it to the dinner")
# repla... |
6c026d6d3fc9088c3e567780d5bf9f0018948688 | yinlinzh/dive-into-python | /skipper.py | 733 | 3.71875 | 4 | class SkipIterator:
def __init__(self, wrapper):
self.wrapper = wrapper
self.offset = 0
def __next__(self):
if self.offset >= len(self.wrapper):
raise StopIteration()
else:
res = self.wrapper[self.offset]
self.offset += 2
return re... |
d631d18f19831293d875556d0e3bc078eca2aa3e | jasongorman/codecraft_nov_2020 | /source/propertybased_py/test/square_root_test.py | 413 | 3.53125 | 4 | import unittest
from maths import sqrt
from parameterized import parameterized
class SquareRootTest(unittest.TestCase):
@parameterized.expand(
[(0,),
(1,),
(4,),
(9,),
(16,),
(0.25,),
(25,)]
)
def test_square_root(self, input):
self.as... |
176e51029490030a1850a61d55626c3f41bf90a7 | dcpatti/Basic-Python | /py-bank/main.py | 2,146 | 3.90625 | 4 | #Load the CSV reader and the OS path interpreter
import os
import csv
#Open and read the file. The first row is a header
with open('budget_data.csv', 'r') as csvfile:
next(csvfile)
readCSV = csv.reader(csvfile, delimiter=',')
num_lines = 0
total = 0
PLAverage = 0
PLHighest = 0
PLLowest = ... |
cf902a3752b4faf8cdb37ca3c81b6b10ba38af66 | ethanfuller/python | /2014 tax bracket.py | 1,935 | 3.65625 | 4 | #!/usr/bin/python2.2 -tt
# Copyright 2014 Point_Four. All Rights Reserved.
import os
def main():
os.system('clear')
print ''
# Chart variables
personal_exemption = 3950
std_deduction_single = 6200
std_deduction_marriedj = 12400
std_deduction_marrieds = 6200
# Start/Filing status
print 'Fi... |
69c513a362f3a7fbe286b6a456b7f5348b872b6c | YongHoonJJo/Python | /Lang_J2P/if.py | 777 | 4.1875 | 4 | ### if ... else ... ###
money = 1
if money:
print("by taxi")
else:
print('by walk')
# 'by taxi'
money = 2000
if money >=3000:
print("by taxi")
else:
print('by walk')
# 'by walk'
### and, or, not ###
money = 2000
card = 1
if money >=3000 or card:
print("by taxi")
else:
print('by walk')
# 'by taxi'
### x in... |
c3db86107413657fcbd4775839f5eaef9ec8af37 | Single430/pyecharts | /pyecharts/charts/parallel.py | 2,425 | 3.546875 | 4 | #!/usr/bin/env python
# coding=utf-8
from pyecharts.base import Base
class Parallel(Base):
"""
<<< Parallel chart >>>
Parallel Coordinates is a common way of visualizing high-dimensional geometry and
analyzing multivariate data.
"""
def __init__(self, title="", subtitle="", **kwargs):
... |
e5f7614216ac5d429678010f7aa34fa0c5f908be | Israelmath/jobs | /scicrop-api-test-python.py | 7,842 | 3.5 | 4 | # Python 3.6.9
import json
import datetime
from typing import Dict
import requests
class Degrees:
"""
Classe responsável por organizar as informações dos cursos e graduações
Obs: Algumas implementações de métodos serviram como testes
"""
def __init__(self, instituicao: str, nome_curso: str, data... |
b00efe87b508e6da7e5968bdaaab2f88e2e77b4d | wanjinzhong/python_study | /venv/My_Script/SSM.py | 8,034 | 3.6875 | 4 | class Student:
id = 0
name = ''
score = 0
grade = ''
def __init__(self):
pass
def __init__(self, id, name, score):
self.id = id
self.name = name
self.score = score
def calc_grade(self):
if self.score < 0:
return "CHEAT"
elif self... |
33f988ac5a9515a7e63a2663e253a0dcd47b70c4 | minskeyguo/mylib | /python-edu/17-pygame-basic/02-geometry.py | 1,223 | 3.796875 | 4 | #!/usr/bin/python3
import sys, pygame
from pygame.locals import *
black = (0, 0, 0)
white = (255,255,255)
red = (255,0,0)
green = (0, 255, 0)
blue = (0, 0, 255)
pygame.init()
pygame.display.set_caption("drawing") # set the title of the window
surface = pygame.display.set_mode((400, 300)) # return pygame.Surface
su... |
f9d1e890f8ee8b178841fc8533b580baa62209db | dustinboswell/daily-coding-problem | /prob45.py | 397 | 3.984375 | 4 | '''
Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a function rand7() that returns an integer from 1 to 7 (inclusive).
'''
import random
def rand5():
return random.randint(1, 5)
def rand7():
while True:
rand25 = 5 * (rand5() - 1) + (rand5()... |
445669ad33d8221a605da97516acd333a1fd483b | stdai1016/NUEiP_Interview_Test_2021_11 | /test_3.py | 1,029 | 4.46875 | 4 | #!/usr/bin/env python3
"""
題目三、資料處理 - 陣列
"""
def minus_sum_of_array(nums1, nums2):
""" 返回將陣列總和減去另一陣列總和之值
@param `nums1`
@param `nums2`
@return
"""
return sum(nums1) - sum(nums2)
def separate_numbers_by_parity(numbers):
""" 將數字陣列分割成偶數和奇數陣列並返回
@param `list` `numbers`
@return `... |
eb4367cb1dddd2f1467068f0737d888fb4492a7c | sqho/python-projects | /assignments/disemvoweler.py | 424 | 3.90625 | 4 | def removeVowels(input_string):
letters = []
for x in input_string:
letters.append(x)
for letter in letters:
if letter == "a" or letter == "e":
letters.remove(letter)
elif letter == "i" or letter == "o":
letters.remove(letter)
elif letter == "u":
letters.remove(letter)
final_string = ""
for left... |
c755282673eb73b92edc1cb3d5c29d8c1699af96 | ivenpoker/Python-Projects | /Projects/Online Workouts/w3resource/Basic - Part-I/program-87.py | 908 | 4.1875 | 4 | # !/usr/bin/env python3
#######################################################################################
# #
# Program purpose: Get the size of a file. #
# Program Author : Happi... |
5e86e45678379767821f91ea7e764ddc2f0ebf34 | dalaAM/month-01 | /day16_all/day16/exercise04.py | 596 | 4.21875 | 4 | """
写出for元组的原理
写出for字典的原理(不使用for,获取字典键值对)
"""
tuple01 = (3, 54, 5, 56, 6, 7, 8)
# for item in tuple01:
# print(item)
iterator = tuple01.__iter__()
while True:
try:
item = iterator.__next__()
print(item)
except StopIteration:
break
dict01 = {"a": "A", "b": "B", "c": "C"}
# for ... |
feeac25008c5fcffa0eb42e9eec779c4ca226ee2 | MrTamas/PCAP | /Module 4/Introduction to Functions/bmi_with_unit_conversion.py | 574 | 3.734375 | 4 | def feet_m(feet, inches):
m_per_feet = 0.3048
m_per_inches = m_per_feet / 12
meters_from_feet = feet * m_per_feet
meters_from_inches = inches * m_per_inches
return meters_from_feet + meters_from_inches
def lb_kg(lbs):
kg_per_lb = 0.4536
return lbs * kg_per_lb
def bmi(height1, hei... |
5affe1906df6bda3bddac594dd1fa054bb5231a4 | LanghuaYang/origin | /pythoncode/operation.py | 255 | 3.578125 | 4 | i = 2 * 5
print(i)
i = 2 ** 4
print(i)
j = 5/2
print(j)
j = 5//2
print(j)
j = 5%2
print(j)
k = ~5
print(k)#按位翻转 ~x = -(x+1)
k = True
k = not k
k = not 1==2#逻辑非 !
print(k)
m = True
print(k and m) #逻辑与 &&
print(k or m) #逻辑或 ||
|
28e8c0babce3c87300e36cab093c628dbf2d323d | aobakwemmokwa/ampackage | /ampackage/sorting.py | 2,649 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 18 20:37:06 2019
@author: Aobakwe Mmokwa
"""
from random import randint
def bubble_sort(items):
"""
sort items of a list using bubble sort.
bubble sort runs through a list checking items and swapping them if
required:
example
... |
5abbd95b986a25737ded0b5868177f67fb6046ed | rsreevishal/A-December-of-Algorithms-2019 | /December-13/d13.py | 256 | 3.59375 | 4 | n = int(input('Enter no of switches:'))
res = [False for _ in range(n+1)]
for i in range(1,n+1):
for j in range(1,n+1):
if(j%i == 0):
res[j] = not res[j]
print('No of switches in the \'on\' state at the end:',res[1:n+1].count(True)) |
9b88c85c7ef7f484effa5b5dd0d1d41082025a27 | Rim-El-Ballouli/Python-Crash-Course | /solutions/chapter10/ex_10_4.py | 250 | 3.859375 | 4 | while True:
print('enter q to quit qny time ')
name = input('Enter your name ')
if name == 'q':
break
else:
print('Hello ' + name)
with open('guest_book.txt', 'a') as file:
file.write(name + '\n') |
2fdd1c8256d6d9564cbc3c8e2c3cdaa47c7bb411 | NJonas184/CS_portfolio | /CSC 356 Machine Learning/Exercise 4.py | 788 | 3.734375 | 4 | import pandas as pd
import numpy as np
def main():
print("Hello World!")
nanExercise = np.random.randint(30, size = (10, 3))
preGen = np.array([
[12, 15, 15],
[23, np.nan, 25],
[14, 17, 21],
[np.nan, np.nan, np.nan],
[np.nan, 25, 1],
[17, 29, 26],
[ 5,... |
960de1b5d12a7400556d49c408b40a81aa7a3d4f | balloman/lpthw | /examples/EX43/ex43_classes.py | 6,437 | 3.890625 | 4 | from sys import exit
from random import randint
from time import sleep
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
d... |
f412518d42cc6fd4245ad78a17f10761156bb5db | fabriciocovalesci/ListOfBrazilPythonExercises | /SequentialStructure/number_9.py | 528 | 4.40625 | 4 | """
[PT]
9. Faça um Programa que peça a temperatura em graus Farenheit, transforme e mostre a
temperatura em graus Celsius. Fórmula matemática: C = (5 * (F-32) / 9).
[EN]
9. Make a Program that asks for the temperature in Farenheit degrees, transform and show the
temperature in degrees Celsius. Mathematical formula: ... |
de51803803160ac07c2ee85d967f2fd644e25b39 | mauricioZelaya/QETraining_BDT_python | /DennisGamboa/Inheritance_test.py | 761 | 3.875 | 4 | class Person:
def __init__(self, first, last, age, ci):
self.first_name = first
self.last_name = last
self.ages = age
self.cis = ci
def Name(self):
return self.first_name + " " + self.last_name + " " + self.ages + " " + self.cis
class Employee(Person):
def __init_... |
4a24f36df7f69a2ab50c5ba6f12dd9ff45cc2f93 | NiklasMM/podcast_stats | /podcast_stats/__init__.py | 1,830 | 3.65625 | 4 | """podcast_stats - A script to pull the rss feed for a podcast and run some analysis on it."""
import feedparser
from datetime import datetime, timedelta
from time import mktime
__version__ = '0.1.0'
__author__ = 'Niklas Meinzer <github@niklas-meinzer.de>'
__all__ = []
def get_parsed_feed(feed_url):
"""
... |
a9d206d586cc88581e3e74f04612e90a1db3748b | saraducks/Python_interview_prep | /LPHW/exercise_3.py | 1,115 | 3.984375 | 4 | def test_math_func(x,y):
addition = x + y; #This is to test '+' addition
print "This is addition", addition
if x > y: # check which number is great and then perform '-' subraction
subraction = x - y
print "This is subraction", subraction
else:
subr... |
242635e6f7ded26f4ed0fbad9ff8da7fc9fc1c24 | maxmahe1/python-eval | /Huffman/huffman.py | 3,724 | 3.734375 | 4 | # La classe Node va servir pour initialiser les choses. Le but de l'algorithme est de construire l'arbre
# et d'ensuite le remonter, finalement un petit peu comme le programme précèdent.
# Les notations dg et dd correspondent à feuille droite et feuille gauche.
class Node:
def __init__(self,valeur, dg, dd=None)... |
945f3769cb26025f4af271267704f722b3b0cec3 | felipemaion/studying_python | /bmr.py | 1,360 | 4.15625 | 4 | '''This is a BMR (Basic Metabolism Rate) calculator from Mifflin St Jeor'''
#''' coded by Screw '''
def get_info():
try:
mass = float(input('What\'s your weight in kg?: '))
height = float(input('What\'s your height in cm?: '))
age = int(input('How old are you?: '))
... |
19672d3b46c559218813a64dbd1ec686b7055f75 | mhiyer/sampling_methods_with_pandas | /bootstrapping_pandas_dataframe.py | 4,079 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 22 14:01:21 2019
@author: mh iyer
Description: Bootstrapping or 'sampling with replacement'
Given a labelled dataset, generate multiple samples by sampling with replacement randomly
Equivalent to picking marbles out of a jar- pick the first one, put it back, p... |
f4ebf3d3aee06c92786121cd2fa22efa0e35d18c | czer01ne/Tensor_practice | /simple_linear_regression_gd_tf_test.py | 715 | 3.5625 | 4 | import tensorflow as tf
## 데이터 수집
x_data = [1, 2, 3]
y_data = [1, 2, 3]
## 예측 모델 정의
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
y = W * x_data + b
## 비용 함수, 최적화 함수 정의
cost = tf.reduce_mean(tf.square(y - y_data))
a = tf.Variable(0.1) # learn... |
420a3c2ae09c59434975712320c0b34113291b28 | ZhuYun97/product-classification | /utils/stopwordslist.py | 808 | 3.59375 | 4 | def stopwordslist(filepath):
stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]
stopwords.append("★")
stopwords.append("[")
stopwords.append("]")
stopwords.append("【")
stopwords.append("】")
stopwords.append("(")
stopwords.append(")")
stopwords.ap... |
45aadfde687414e060052b08f9578c201c31493c | tharunnayak14/python | /ch13.py | 1,687 | 3.5 | 4 | # data on the web
# xml
# json
# eXtensible markup language(XML)
# <people>
# <person>
# <name> tharun </name>
# <phone> 231823 </phone>
# </person>
# <person>
# <name> nayak </name>
# <phone type = "intl"> 234342 </phone>
# <email />
# </person>
# </people>
# ... |
641eb82a7eabe47971297b22a86e878649cf538b | zhilyaev/ArchPC-SUAI | /src/1.py | 2,322 | 3.5625 | 4 |
def toHex(v, bits):
return hex((v + (1 << bits)) % (1 << bits))
def bin_add(*args):
return bin(sum(int(x, 2) for x in args))[2:]
def toFloat(x):
z = '0'
print('X := ' + str(x))
if x < 0:
z = '1'
x = (-1) * x
if x > 8388607: # int(111 1111 1111 1111 1111 1111, 2) => 8388607
... |
e3e3947589e9f212b228636dd385b242703b85b1 | sakshi13-cmd/tathastu_week_of_code | /tathastuproject2/pattern3.py | 170 | 3.796875 | 4 | n=int(input("enter a value:"))
for i in range(n):
print((str(n-i) + "*") * (n-1-i) + str(n-i))
for j in range(2,n+1):
print((str(j) + "*") * (j-1) + str(j))
|
6d68492a2cf15a2524fdcc7e028df27a86cbc871 | Anshul1196/leetcode | /challenges/2020/07/W2/D4.py | 576 | 3.765625 | 4 | """
Solution for July LeetCoding Challenges Week 2 Day 4: Subsets
"""
class Solution:
"""
Double the set iteratively
- Number of nodes: N
- Space Complexity: O(N 2^N)
- Time Complexity: O(N 2^N)
Runtime: 32 ms / 86.44%
Memory Usage: 14 MB / 60.80%
"""
def subsets(self, nums: List[i... |
bbf0d1a5b0b488e8e8a2c6b7b4fcf60d53a03c5e | udayom/PyPractice | /subclass_example.py | 673 | 3.90625 | 4 | class Student():
def __init__(self,name):
self.name = name
a = Student("Sam")
print a.name
b = Student("UDAY")
print b.name
print "New Example"
class Rectangle():
def __init__(self,l,b):
self.length = l
self.breadth = b
def getArea(self):
return self.length*self.breadth
def getPerimeter(self):
return ... |
4eb8e9a7668244a894bb00e7f55a08e41000924e | OZ-T/leetcode | /0/merge_two_lists.py | 1,345 | 3.9375 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 is Non... |
2b60f356fca203039c88b201316359c3c6181f28 | allenchng/Bit-O-Code | /IQ/240.py | 1,618 | 3.765625 | 4 | # Suppose you are given two datasets as shown below:
# Data on the Gini coefficient (proxy for income inequality).
# This is a number between 0 and 1, where 0 corresponds to perfect equality (e.g. everyone has the same income) and 1 corresponds to perfect inequality (where one person has all the income—and everyone e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.