blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
983f394c3b370e5b6679b5cdd74505eeb93b72d0 | ian7aylor/Python | /Programiz/Python_Variables_Const_Literals.py | 1,957 | 4.1875 | 4 | import constant
#Python Variables, Constants, and Literals
number = 10
number = 1.1
#Declaring and assigning value to a variable
website = "apple.com"
print(website)
#Assign a new value to website
website = "programiz.com"
print(website)
#Can print multiple variables in a row
a, b, c = 5, 3.2, "Hello"
print (a)... |
a08c8453ce5fb00f3d29dacf45234afaeccfddde | cosmicRover/algoGrind | /intervals/meetingrooms1.py | 632 | 3.71875 | 4 | '''
Time O(n log n) | Space O(1)
'''
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
intervals.sort(key=lambda x:x[0]) #sorting intervals by start time
for i in range(1, len(intervals)):
forward = intervals[i]
backward=intervals[i-1]... |
b7771adea9b8cab545c8121d0854b02dd1710eb4 | liketheflower/CSCI13200 | /homeworks/homework2_solution.py | 1,683 | 4.0625 | 4 | """
Due the following class and we will talk the solution at the beginning of the following class.
Please ONLY submit it to black board.
1. Print 1 to 10 '*' and get output like this(hint: 'a*4 will be 'aaaa', simlar '*'*4 will be '****'.
if you want to output 4 '*', pls use this code "print('*'*4)'":
*
**
***
...
*... |
133ed48b88d569f878e8ee051df085d1196de85c | Zhenye-Na/leetcode | /python/309.best-time-to-buy-and-sell-stock-with-cooldown.py | 1,834 | 3.703125 | 4 | #
# @lc app=leetcode id=309 lang=python3
#
# [309] Best Time to Buy and Sell Stock with Cooldown
#
# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/
#
# algorithms
# Medium (48.06%)
# Likes: 3499
# Dislikes: 112
# Total Accepted: 187.5K
# Total Submissions: 388.6K
# Testca... |
a329931cd82ec692f94079988909c8a021892483 | physikerwelt/DRMF-Seeding-Project | /AlexDanoff/src/math_mode.py | 5,164 | 3.953125 | 4 | math_start = {"\\[": "\\]",
"\\(": "\\)",
"$$": "$$",
"$": "$",
"\\begin{equation}": "\\end{equation}",
"\\begin{equation*}": "\\end{equation*}",
"\\begin{align}": "\\end{align}",
"\\begin{align*}": "\\end{align*}",
... |
1f8e15b81e2ab6686a50af687df9884fc3e079a4 | dsambugaro/Atividades_SD | /06/server/database.py | 3,481 | 3.65625 | 4 | # DB class
import sqlite3
class DB:
def __init__(self):
self.conn = None
self.cursor = None
self.db_name = 'gerenciamento_notas.db'
def _connect(self):
self.conn = sqlite3.connect(self.db_name)
self.cursor = self.conn.cursor()
def _close(self):
self.conn.... |
b076ab089d5a6cd8c48170da89c672d18e140ceb | kraused/maci-code | /meshing/CuboidList.py | 606 | 3.5 | 4 |
from Cuboid import *
# A list of cuboids
class CuboidList(list):
# Create a new instance
# param cubs a list of cuboids
def __init__(self):
list.__init__(self)
# Compute the bounding box of all cuboids in the list
def boundingBox(self):
if 0 == len(self):
return None
lower = self[0].lower
upper = s... |
95eb03e132d0f4094612533fd8358b7098597e30 | Dhrumil1808/deep-learning | /Assignment1/code/numpy/numpy_example5.py | 272 | 3.546875 | 4 | import numpy as np
arr = np.array([0,30,45,60,90,120,135,150,180])
print 'Sine value of the angles'
print np.sin(arr*np.pi/180)
print 'Cosine values of the given angles'
print np.cos(arr*np.pi/180)
print 'Tangent values of given values'
print np.tan(arr*np.pi/180) |
0aa96f02ab9acb56d59e6fabd36431f7594244c8 | BiradaterA/lps_compsci | /class_samples/2-4_operators/square.py | 69 | 3.546875 | 4 | x = 5
y = 2
print('base: ' + str(x))
print('square: ' + str(x ** y))
|
098bbf6c424533f841aeb172c29b2934750cc9d0 | hault69/haule-c4e22 | /LABS/lab3/homework/s7.py | 172 | 3.75 | 4 | # def remove_dollar_sign(s = input("input: ")):
def remove_dollar_sign(s = " "):
new = s.replace("$","")
return new
# new = remove_dollar_sign("100$")
# print(new)
|
fbfc6c65d75492adc925bb4fb47c376cda2b8d2f | xiaohema233/LearnPythonWithZeroFoundation | /06函数/04/checkout.py | 1,398 | 3.75 | 4 | def fun_checkout(money):
"""功能:计算商品合计金额并进行折扣处理
money:保存商品金额的列表
返回商品的合计金额和折扣后的金额
"""
money_old = sum(money) # 计算合计金额
money_new = money_old
if 500 <= money_old < 1000: # 满500可享受9折优惠
money_new = '{:.2f}'.format(money_old * 0.9)
elif 1000 <= money_old <= 2000: # 满1000可享受8折优惠... |
7f9238d1d3ac91543d7fe192bd439607e4d3901d | imsamuel/pcc | /exercises/chapter-3/3.9.py | 256 | 3.828125 | 4 | """
3-9. Dinner Guests:
Working with one of the programs from Exercises 3-4 through 3-7 (page 46), use
len() to print a message indicating the number of people you are inviting to
dinner.
"""
guests = ["Malcolm X", "Lee Kuan Yew", "Lim Bo Seng"]
print(len(guests))
|
e1a0124c7e7a28f8e345a9a3bcf12f75ea8b3fe9 | AlexLymar/itstep | /lesson9/num_len.py | 344 | 3.875 | 4 | #num_len program
def num_len(number):
count = 0
while number: # циклом прохожу количество раз целочисленным делением и считаю количество проходов (count)
count += 1
number //= 10
print('Кількість чисел: ', count)
num_len(5474565) |
a6acadbb8af57f356117a5abf2cc05d02c495a20 | mrhockeymonkey/HappyBattleFactor | /hbf/mob.py | 1,716 | 3.75 | 4 | import pygame
from hbf import enemy
from random import choice, randint
vec = pygame.math.Vector2
class Mob():
"""
Groups of enemy sprites that can be spawned in waves continuously
"""
def __init__(self, game, count, onscreen):
self.game = game
self.count = count
self.onscreen =... |
0473f4b31c083cacc7e9a52870fead348d83175d | anEffingChamp/compSci321 | /chapter5/lab.py | 897 | 3.9375 | 4 | # author Jonathan Smalls
# computer science 321
# Problem Description:
# (Conversion from kilograms to pounds and pounds to kilograms) Write a program
# that displays the following two tables side by side (note that 1 kilogram is
# 2.2 pounds and that 1 pound is .45 kilograms):
# Kilograms Pounds | Pounds ... |
4fc20909474f3e61ae19915e3619e5e0acec030b | Mniharbanu/guvi | /codekata/digitint.py | 66 | 3.640625 | 4 | num=int(input())
a=0
while(num>0):
num=num//10
a=a+1
print(a)
|
ed27c09f2d60230ded01382b11edbcc87f1790e9 | equusprobus/MachineLearning_Coursera | /ex2.py | 3,489 | 4.21875 | 4 | # Exercise 2 of Andrew Ng's Machine Learning class on Coursera:
# Logistic Regression & Regularization
# Only did the first problem. The regulerization is very interesting but it only
# pose minor differences in coding.
# Things learnt:
# 1. How to use minimization routines in SciPy
# 2. "reshape" is a great tool to... |
b4f7d5045ebee86e3c2bd3cbf7a95ddcf7df136e | Everfighting/leetcode-problemset-solutions | /longest-palindromic-substring.py | 789 | 3.5 | 4 | #给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
#
#示例 1:
#
#输入: "babad"
#输出: "bab"
#注意: "aba" 也是一个有效答案。
#示例 2:
#
#输入: "cbbd"
#输出: "bb"
class Solution(object):
def check(self, sub):
return True if sub[::-1] == sub else False
def longestPalindrome(self, s):
"""
:... |
7f9e894d137f1de4231513e37ee19a42c8b20c57 | pahuja-gor/Python-Lectures | /CS 2984/stringCalculator.py | 935 | 4.03125 | 4 | def string_calculator(str):
if (str == ""):
return 0
my_numbers = str.split(',')
sum = 0
for num in my_numbers:
sum += int(num)
return sum
def main():
testSingleNumber()
testEmptyString()
testTwoNumbers()
testAddingZero()
testFiveInputs()
testNegativeNumbers... |
fd0f7e6642f47e2d9556c3410ae8d7ac109de8db | ducanhnguyen/clustering | /src/word_cloud.py | 8,273 | 3.75 | 4 | '''
This file contains these following parts:
- Given a dataset, choose the best number of clusters based on inertia values and silhouette scores
- Given the selected number of clusters, make a word cloud
- Given a word in the word cloud, find the phrases containing this word
'''
import matplotlib.pyplot as plt
impor... |
09849a65cf283ee1a8e08371beabe0d3fd50101b | Xwx100/learnALittleEveryDay | /copy-deepcopy.py | 400 | 3.671875 | 4 | # 赋值:N个对象引用 指向 同一个对象
# 下面两个拷贝:外部对象引用 和 对象 一一对应
# 浅拷贝:内部对象引用 没有拷贝
# 深拷贝:内外部对象引用 都拷贝
import copy
a = [1,2,3,4,[6,7]]
b = a # 引用
c = copy.copy(a) # 浅拷贝
d = copy.deepcopy(a) # 深拷贝
a.append(5)
a[4].append(8)
print(id(a), id(b), id(c), id(d))
print(a, b, c, d) |
3bd52ed31196de9370defe72ed28059acb5e3fd9 | yevpol/DeerLab | /examples/plot_selecting_an_optimal_model.py | 4,171 | 3.53125 | 4 | # %% [markdown]
"""
Selecting an optimal parametric model for fitting a dipolar signal
==================================================================
How to optimally select a parametric model for a given dipolar signal.
"""
import numpy as np
import matplotlib.pyplot as plt
import deerlab as dl
# %%... |
467321555a3d07262df093b238919cc0dbef3bb5 | bartekwojcik/SportBettingRL | /exp/utils/plotting_utils.py | 1,298 | 3.515625 | 4 | from typing import List
import matplotlib.pyplot as plt
from typing import List, Dict, Any
import os
def plot_error_bar(names: List[str], means: List[float], stds: List[float]) -> plt.Axes:
"""
Simple box plot for comparing different algorithms
:param names: list of strings
:param means: list of flo... |
de508de974f3f80c6f0b51c817628ae6dd51ecec | MokoFreedom/LanguageProcessing100 | /20_29/20.py | 615 | 3.703125 | 4 | """
20. JSONデータの読み込み
Wikipedia記事のJSONファイルを読み込み,「イギリス」に関する記事本文を表示せよ.
問題21-29では,ここで抽出した記事本文に対して実行せよ.
"""
import json
def load_country(country):
with open("jawiki-country.json", "r") as f:
data = f.readline()
while data:
d = json.loads(data)
if d["title"] == country:
... |
d12d2749e5f606a78ce393a6fd6efb0356a38324 | FxIvan/FxIvanXX | /calculadora.py | 1,419 | 3.984375 | 4 | def encontrarMultiplos(a,j):
d = 0
multiplo = []
while d <= a:
if d % j == 0:
multiplo.append(d)
d = d + 1
else:
d = d + 1
return multiplo
numero1 = input("Ingrese numero:")
J = input("Ingrese otro numero:")
multiplo = encontrarMultiplos(numero1, J)
... |
3e26516edd79cd7546791180e6fa8ef6947a4674 | engrjislam/uva_python | /uva12157.py | 1,010 | 3.921875 | 4 | def calculate_cost(duration, pulse, cost_per_pulse):
cost = 0
if duration <= 0:
return 0
total_pulse = int((duration / pulse))
return total_pulse * cost_per_pulse + cost_per_pulse;
def main():
test = int(input())
mile_pulse, juice_pulse = 30, 60
mile_cost, juice_cost = 10, 15
ca... |
6b0e8917f1d4dc443893dd8343615bbcec81fdec | kamaradclimber/thereisnorush | /python/track.py | 3,218 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
File : track.py
Description : defines the class "Track"
"""
import lib
import roundabout as __roundabout__
import road as __road__
from constants import *
from os import getcwd
# Bootstrap
if (__name__ == '__main__'):
raise Exception("You should... |
c1d9f613c65acc1e0a3c5646f170f390e386ae37 | hanzhenlei767/leetcode | /74. 搜索二维矩阵.py | 1,298 | 3.796875 | 4 | '''
编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。
示例 1:
输入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
输出: true
示例 2:
输入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
输出: false
'''
class Solution:
... |
82b2b8c98f655e8567f049ccaeecdfa4d9be90ed | mayank888k/Python | /Inheritencee.py | 918 | 4.15625 | 4 | class father(): #Derived class can access all the attributes and
# methods of Base class
age=45 #Constructor is first called of derived class
def __init__(self,name): #so in order to call Base... |
4e1e0d7533a7e0e478cb4e80226a9840a003237e | muondu/python-practise | /Storage/JSON/27.py | 189 | 3.65625 | 4 | import json
x = {
"name": "Nesh",
"age": 11,
"married": False,
"divorced": False,
"pets": None,
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y) |
43dccd829d2cc406d1c578a7b1c7eed2ff679452 | EducatedBernie/HOG-Game | /hog.py | 11,657 | 4.125 | 4 | """The Game of Hog."""
from dice import four_sided, six_sided, make_test_dice
from ucb import main, trace, log_current_line, interact
GOAL_SCORE = 100 # The goal of Hog is to score 100 points.
######################
# Phase 1: Simulator #
######################
# Taking turns
def roll_dice(num_rolls, dice=six_side... |
752c706f891b65a86f27e289b667eb6aee82acf5 | prashantahuja/mongodb_pa | /mongo_pa.py | 551 | 3.671875 | 4 | def insert():
try:
employeeid = raw_input("Enter Employee Id:")
employeename = raw_input("Enter employee Name")
db.employees.insert_one(
{
"id": employeeid,
"name": employeename
}
)
except Exception as ex:
print("exc... |
7dcebe4fcd52824cf5446505d2016f242ddbeef9 | solvedrex223/Final_project_OS | /FileCompSys/Algorithms/InsertionSort/__init__.py | 499 | 3.5625 | 4 | '''
Created on 12 abr. 2020
@author: Zikin
Insertion sort
Avg Case: O(n^2)
worst Case: O(n^2)
Best Case: O(n)
'''
#coded and maintained by zikln - rodrigoor1999@outlook.com
def insertionSort(A):
l = len(A)
i = 1
maxindex = 1
while(i < l):
if A[i].root.freq > A[i-1].root.freq... |
c22a9d00e1cf8c6f9f5aebae4aa95b1792589f57 | adrianotelecom/BlueInicio | /passados/Exercicio1-13-05-21.py | 260 | 4.0625 | 4 | #1. Crie um código em Python que pede qual tabuada o usuário quer ver, em seguida imprima essa tabuada.
tabuada=int(input("Digite um numero para Criar a tabuada: "))
for count in range(10):
print("%d x %d = %d" % (tabuada, count+1, tabuada*(count+1)) ) |
c1e4a3a8745bf31b8dd8a0d64a30f4fa67e7a6eb | tiggers1985/python-learning | /oop_advance/special_funcs.py | 6,517 | 4.0625 | 4 | #!/usr/local/bin python3
# -*- coding: utf-8 -*-
#看到类似__slots__这种形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的。
#__slots__我们已经知道怎么用了,__len__()方法我们也知道是为了能让class作用于len()函数。
#除此之外,Python的class中还有许多这样有特殊用途的函数,可以帮助我们定制类。
#-----------------------------------------------------------------------------------------------------------... |
449cccca9c8eb50c14c1bb65b946546fa964fb10 | TheAwiteb/Challenges | /Challenges19.py | 2,266 | 4.09375 | 4 | #The Primiera
#Primiera (from the french word prime, "prize") is a combination of cards of Scopa, a popular Italian card game.
#For establishing the value of the Primiera, a separate point scale is used for selecting the best cards in the player's deck, in each of the four suits and totaling those four cards point va... |
9672c1dd00b3f3b639aab0c1cbbb481b038d2b01 | Alyssonmach/PythonCrashCourse | /content_b_variables/ex5_string_concatenation.py | 296 | 3.546875 | 4 | first_name = 'alysson'
last_name = "machado"
# programmer format "i like complicated things, love me"
idiot_format = first_name.capitalize().__add__(" " + last_name.capitalize())
# cool programmer format
cool_format = first_name + " " + last_name
print(idiot_format)
print(cool_format.title()) |
e1ea6c0606196f5d0faa1d1128e5347685c6c613 | njpayne/pythagoras | /Archive/Sum_Of_First_N_Positive_Even_Integers.py | 830 | 4.4375 | 4 | # Write a program that asks the user for a positive even integer input n,
# and the outputs the sum 2+4+6+8+...+n, the sum of all the positive even integers up to n.
def main(): # Define the main function
n = int(input("Please enter the positive even integer you would like to end with: "))
if n % 2 != 0: # Check ... |
b7c9b90d5ed1bb78980700eb3e78b2a37809b66d | luchini77/aprendiendo-Poo-python | /caballeros.py | 888 | 3.890625 | 4 | class Caballeros:
cosmos="na"
velocidad_ataque = "lenteja"
def __init__(self):
self.nombre=input("Ingrese nombre del caballero: ")
self.nombre_constelacion=input("Ingrese la armadura: ")
self.ataque = input("Ingrese ataque del caballero: ")
def __str__(self):
return ... |
ee5137d0423dbf43a37fef78ec1f4d32f34687ee | Andchenn/Lshi | /day10/08-线程.py | 602 | 4.15625 | 4 | # 线程:执行代码的分支,默认只有一个线程,(主线程)
# python本质没有多线程(假象)
import threading
import time
def AA(count):
for i in range(count):
print("aa")
time.sleep(1)
def BB(count):
for i in range(count):
print("bb")
if __name__ == '__main__':
sub_thread = threading.Thread(target=AA, args=(10,))
# 启... |
52cf272124cacbaab09ec57ddbadb91fa3d768ef | linwt/nowcoder-leetcode | /2017校招真题编程题汇总_Python/16.小易喜欢的单词.py | 274 | 4 | 4 | # 各条件逐一判断
s = raw_input()
res = 'Likes'
if not s.isupper():
res = 'Dislikes'
for i in range(len(s)-1):
if s[i] == s[i+1]:
res = 'Dislikes'
for i in range(len(s)-3):
if s[i] == s[i+2] and s[i+1] == s[i+3]:
res = 'Dislikes'
print(res) |
a7c7a823f35f718155e3fb2ebe0a0a3e3e613e88 | shikha1997/Interview-Preparation-codes | /Day5/delgivennode.py | 979 | 3.90625 | 4 | class Node:
def __init__(self, data):
self.next = None
self.data = data
class LL:
def __init__(self):
self.head = None
def append(self, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = s... |
3e55400ab1cc8477b355f7dcac691189a7afc5ae | yamada2718/algorithims | /ans/q01_35/q04/q04.py | 421 | 3.734375 | 4 | def cutstick(sticks, length, members): #sticksは棒の数
if sticks >= length:
return 0
elif sticks <= members:
return 1 + cutstick(sticks * 2, length, members) #棒の数 <= 人数 なら棒の数は2倍に
else:
return 1+ cutstick(sticks + members, length, members) #棒の数 > 人数 なら棒の数は人数分だけ増える
print(cutstick(1, 20, 3)... |
a67bc5547b1b6f12dd811092b8b9c829bf415f47 | jclippincott/Competition-Problems | /BattleSimulationSets.py | 509 | 3.5625 | 4 | try:
moves = input()
except EOFError:
exit(0)
mechMoves = ""
moveReplace = {"R":"S", "B":"K", "L":"H"}
RBL = set(["R","B","L"])
i = 0
while i < len(moves):
if(i+2 < len(moves)):
moveset = set(moves[i:i+3])
if(moveset == RBL):
mechMoves += "C"
i += 3
... |
1d083772db79f75e3754dff41957a29f0cdda844 | kerenskybr/math_for_programming | /chapter_06/treating_func_as_vector.py | 556 | 4.15625 | 4 | # plotting utility function for functions in this chapter
import numpy as np
import matplotlib.pyplot as plt
from math import sin
def plot(fs, xmin, xmax):
xs = np.linspace(xmin,xmax,100)
fig, ax = plt.subplots()
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
for f in fs:
ys = [f(x) ... |
7311a159269cf2bc83cc42a6c63cb5afb6592315 | meetashok/projecteuler | /20-30/problem-25.py | 300 | 3.765625 | 4 | ## Problem 25
## Thousand digit Fibonacci
def main():
fibonacci = [1,1]
while True:
fibonacci.append(fibonacci[-1] + fibonacci[-2])
if len(list(str(fibonacci[-1]))) == 1000:
return len(fibonacci)
if __name__ == "__main__":
answer = main()
print(answer)
|
ea1b1b4e34146df18096bd7333c24b442f1e8839 | TechMate/Wipro-PBLApp-Python-TechModule | /Python Control Statement_9637134/Python IO Expression Statement_9637134/readkey3_9637134.py | 172 | 3.78125 | 4 | userlist_ADID = []
for i in range(0,5):
a = input("Enter the user name")
userlist_ADID.append(a)
print(userlist_ADID)
for i in userlist_ADID:
print(i) |
e0dc329bc56b218f808bac1904ca22e5994a69ba | helenamorgan/WhiteStarLine | /IcebergCalculations.py | 4,370 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 7 11:32:58 2021
@author: helena
"""
class IcebergCalc():
"""
Class declaration for the IcebergCalc class.
Provides methods for calculating an iceberg's area, volume and mass.
"""
def __init__(self, lidardata, radardata, seaice_m):
"... |
cbe68c58e3adf4631cb7b692494eb05d9294022e | wangyaochong/learn-python | /_matplotlib/02气温.py | 627 | 3.53125 | 4 | from matplotlib import pyplot as plt
import matplotlib
import random
font = {"weight": "bold", "size": "20", "family": "KaiTi"}
matplotlib.rc("font", **font)
# matplotlib.rc("font", size="20")
# 绘制气温
x = range(0, 120)
y = [random.randint(20, 35) for i in range(120)]
_x = list(x)
_xtick_labels = ["10点{}分".format(i) ... |
e2318c8049a9787102ef69a54545c7388dfd500d | rajveer-py/Day-2-asignment | /DAY2.py | 124 | 4.0625 | 4 | name = 'rajveer'
age = 16
std = 11
st="my name is {},i'm of {} years, i study in {}".format(name, age, std)
print (st)
|
c973117dbf7d0caa1538208ea542e954c7de14c2 | chengtianle1997/algs4_princeton | /2.2 Elementary Sorts/KnuthShuffle.py | 525 | 3.546875 | 4 | from random import randint
def GenerateRandArray(n, min, max):
arr = []
arr = [randint(min, max) for x in range(n)]
return arr
test_arr = GenerateRandArray(20, 0, 10)
# Knuth Shuffle
def KnuthShuffle(nlist):
n = len(nlist)
for i in range(1, n):
rand = randint(0, i-1)
nlist[i], nli... |
157c35e96f562f4871f00bf087cbb5c5706f653a | pablollorca/bases-python | /poo.py | 1,007 | 3.609375 | 4 |
class Auto:
def __init__(self, marca, color, cantidad_ruedas, velocidad_max):
self.marca = marca
self.color = color
self.cantidad_ruedas = cantidad_ruedas
self.velocidad_max = velocidad_max
self.motor = 2.0
self.motores = [2.0, 3.0]
self.marcas_preestablecid... |
d455019a270642917302b10a14432d5667e397e1 | rodrigoc-silva/Python-course | /Lab03_functions/exercise-28.py | 5,488 | 3.921875 | 4 |
#Stock transaction program. It shows profit / loss amount.
def load() -> (str, float, float, float, float):
'''asks for user input about stocks'''
print()
nameStock = input('Enter stock name:')
numberShare = float(input('Enter number of share:'))
stkBuyPrice = float(input('Enter purchase price:')... |
ec3d7cf2c06e5e2d8cd6e148e3fc8357fea236d7 | club-Programacion-UAEM-Ecatepec/Fundamentos-de-Python | /Practicas/5-Strings.py | 1,047 | 4.1875 | 4 | miCadena = "Hola mundo";
miCadena2= 'otra cadena';
otraCadena = """
xD
;D
:(
"""
print(miCadena); # Hola mundo
print(miCadena2); # otra cadena
print(otraCadena); # xD
# ;D
# :(
print(miCadena.upper()); # HOLA MUNDO
print(m... |
dbe38c300e88ae95229d3478245796839018eb0c | Piyushrai558/using-CNN-for-Image-classification- | /8.11 - Building a CNN for Image Classification - CIFAR10.py | 5,496 | 3.65625 | 4 |
# coding: utf-8
# ### The CIFAR-10 Dataset
# * Contains 10 categories of images
# * airplane
# * automobile
# * bird
# * cat
# * deer
# * dog
# * frog
# * horse
# * ship
# * truck
# ### Let's Begin training out model for CIFAR-10 using a deeper CNN
# In[1]:
from __future__ import print_function
import k... |
ea89edbdc7934bdcdbebfa048c12db77f0be605c | JamesAsuraA93/Asymptotic-analysis_BigO | /O(2^N).py | 166 | 3.984375 | 4 | def display_recursive(number):
if number == 0:
return 0
else:
print(2 ** number)
display_recursive(number - 1)
display_recursive(5)
|
28b26e991c0f093746b53858ecfd0cb888bc6be5 | Eunanibus/CipherTool | /src/ciphers/vigenere.py | 4,495 | 3.53125 | 4 | __author__ = "Eunan Camilleri"
__copyright__ = "Copyright 2016, University of Kent"
__version__ = "1.0"
__email__ = "ec368@kent.ac.uk"
__status__ = "Development"
import src.utilities.utility as util
class VigenereCipher():
# Maps the boolean context of whether the Cipher key is known
keyKnown = bool
# S... |
3b2c588395cfe16ac9515a980e26847a76efa0c5 | geog3050/njmitchell | /Quiz1Py5055.py | 323 | 3.5625 | 4 | def thermMovement(climString,tempList):
threshold = 0
if climString=="Tropical":
threshold=30
elif climString=="Contintental":
threshold=25
else:
threshold=18
for i in tempList:
if i<= threshold:
print ("F")
else:
print ("U"... |
2ccd98e61ab31fab2a0b02a68c3c4635f54f052c | hyang012/leetcode-algorithms-questions | /143. Reorder List/Reorder_List.py | 1,856 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Leetcode 143. Reorder List
Given a singly linked list L: L0 -> L1 -> ... -> Ln
reorder it to: L0 -> Ln -> L1 -> Ln-1 -> L2 -> ...
You may not modify the values in the list's nodes, only nodes itself may be changed.
"""
class ListNode(object):
def __init__(self, x... |
5d680f5120ca33b2e0f03acd5fb6c4754d80c773 | RicardoMVA/Connect-Four | /game.py | 5,964 | 4 | 4 | class Game(object):
def __init__ (self):
self.board = [[' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ']]
def... |
2e8796d8b8227526f3e7bd227b33e9b21f7d0227 | signorrayan/linux-commands-Implementation-in-python | /rm.py | 1,540 | 4.09375 | 4 | #the rm command implementation
import os, shutil, sys
currentDirectory = os.getcwd()
def main():
script = sys.argv[0]
switch_path = sys.argv[1:]
if switch_path:
if switch_path[0].startswith('-'): #if we have a switch -r, it means we want to delete a directory reqursively
switch = swit... |
a4566a541d1c794e660580aca5a44204ec13a47e | jsdelivrbot/demos | /python/temp/learning/loopelse.py | 141 | 3.859375 | 4 | #!/usr/bin/python2.6
for number in (1,2,3,4,5,6,7,8,9,0):
# if number > 5:
# None
# break
# else:
print number
else:
"out of the loop"
|
d35de6dfa0e942ac4adec813cf7a1990a1d5f200 | rxxxxxxb/PracticeOnRepeat | /Birth.py | 453 | 3.984375 | 4 | def age_program():
while True:
secondsOrYears = input("Seconds S or Years Y ? ")
if secondsOrYears == "s":
val = input("enter Seconds : ")
print("years {} ".format(int(val)/60/60/24/365))
elif secondsOrYears == "y":
val = input("enter Years : ")
... |
88d0396763ee0fb829adaa2233cf86ded31de9a5 | Alexanderklau/python-project | /100_algorithm/09_chess_project.py | 282 | 3.515625 | 4 | # -*-coding:utf-8 -*-
__author__ = 'Yemilice_lau'
"""
题目:要求输出国际象棋棋盘。
"""
for i in range(1,9):
for j in range(1,9):
if (i + j) % 2 == 0:
print('white')
else:
print('Black')
# if __name__ == '__main__': |
f8fbb8419f3d31aa7bd6ca9179f5493ddb2bd614 | Mauriel20/master-ejercices-python | /exercises/05-hello_harry/app.py | 289 | 4.28125 | 4 | #Complete the function below to print the output per the example.
def hello_name(name):
hello = "Hello, "
exclamacion= "!"
desarrollo= (hello + name + exclamacion)
return desarrollo
#Invoke the function with your name as the function's argument.
print(hello_name("juan"))
|
4e9c2d028810fc41648cbe1e4bb9c6e27eb51cc2 | sulik011/tsts9 | /27.py | 202 | 3.640625 | 4 | # menu = {'Lagman': 120, 'Plov': '120', 'Borsh': 100}
# print(menu)
# menu['Besh barmak'] = 130
# print(menu)
# menu['Lagman'] = 135
# print(menu)
# del menu['Borsh']
# print(menu)
print(list(range(3))[2]) |
a2c235495898d13d8c9f715905eef1d0d1584bb2 | silianpan/Excel_to_Python | /base/Chapter-7/Chapter-7-1/Chapter-7-1.py | 291 | 3.5 | 4 | dic1=dict();print(dic1)#使用dict类创建空字典。
dic2=dict(王五=22,麻子=24);print(dic2)#使用dict类创建字典。
dic3={};print(dic3)#直接使用{}创建空字典。
dic4={'张三':18,'李四':20};print(dic4)#直接使用{}创建字典。
del dic4#删除指定的字典。 |
4121c1e18f505939c7002c10cd77147e3ccaffea | ethanbar11/python_september | /lecture_7/exercise_29.py | 950 | 3.96875 | 4 | def remove_dictionary_spaces(dict_with_spaces):
dict_to_return = {}
for key in dict_with_spaces.keys():
new_key_name = key.replace(' ', '')
dict_to_return[new_key_name] = dict_with_spaces[key]
return dict_to_return
def remove_dictionary_spaces_same(dict_with_spaces):
to_add = {}
to... |
f6541684f91b022a17a10ed8ed582d1b9e496340 | GersonFeDutra/Python-exercises | /Introdução à Ciência da Computação/Aulas/aula 19.py | 1,664 | 4.0625 | 4 | pessoas: dict = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22}
print(f'O {pessoas["nome"]} tem {pessoas["idade"]} anos.')
print(pessoas.keys()) # dict_keys(['nome', 'sexo', 'idade']
print(pessoas.values()) # dict_values(['Gustavo', 'M', 22)
print(pessoas.items()) # dict_items([('nome', 'Gustavo'), ('sexo', 'M'), ('i... |
618c6361554d5205e105e8c1a4564caefc164d95 | AyseErdanisman/PythonProgramlamaKursu | /3.6_uygulama-veri-tipi-donusumleri.py | 325 | 4.21875 | 4 | """
Daire Alanı = πr2
Daire Çeversi = 2πr
Yarıçapı verilen dairenin alanını ve çevresini hesaplayınız
"""
radius = float(input("Yarıçapı giriniz: "))
pi = 3.14
circleArea = pi * (radius ** 2)
circleCir = 2 * pi * radius
print("Daire Alanı: ", circleArea)
print("Daire Çevresi: ", circleCir)
|
102ac1a3dab5deaaca5f6152f822acf985d22ec7 | ilailabs/python | /tutorials/trash/simple_calculator.py | 1,120 | 4.34375 | 4 | while True:
print("Options:")
print("Enter 'add' to add two numbers")
print("Enter 'sub' to subtract two numbers")
print("Enter 'mul' to multiply two numbers")
print("Enter 'div' to divide two numbers")
print("Enter 'qte' to quit the programe")
user_input=input(" ")
if user_input=="qte"... |
81b6010b50e706f96da70d5d4f2b6a1e438e3a7e | vtellez1/Graphs | /projects/social/social.py | 6,166 | 3.90625 | 4 | import random
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
c... |
dd27a2cec719f09b24f6711fa67fc27ac84ad663 | tatev2907/ACA_PYTHON_ | /week5/homework5.py | 2,350 | 3.703125 | 4 | class Roman_Numeral:
def __init__(self, s):
self.num = s
def rom_to_int(self, s):
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
int_val = 0
for i in range(len(s)):
if i > 0 and rom_val[s[i]] > rom_val[s[i - 1]]:
int_val +... |
fa5eb956595433440fef62bc554bc64303db77a0 | akshatmittal1/python | /basic python/akshat.py | 153 | 3.625 | 4 | l=list()
i=0
while(i<5):
n=int(input("enter a no"))
if(n in l ):
print("duplicate")
else:
l.insert(i,n)
i=i+1 |
ab642b7ea9ad301282cc10fb18ae1ffb003b61f8 | Little-Captain/py | /Lean Python/dbcreate.py | 1,209 | 3.5625 | 4 | import os
import sqlite3
db_filename='mydatabase.db'
exists = os.path.exists(db_filename)
if exists:
os.unlink(db_filename)
conn = sqlite3.connect(db_filename)
schema="""create table person (
id integer primary key autoincrement not null,
name text not null,
dob date,
nationality text,
gender text)
""... |
632bac2905d355bbb4f2a9839959b3fdbf69e516 | reggiemccoy/python_code | /numbers/test_score_average.py | 448 | 4.34375 | 4 | # Get three test scores and assign them to the
# test 1, test 2, and test3 variables
test1 = float(input('Enter the first test score: '))
test2 = float(input('Enter the second test score: '))
test3 = float(input('Enter the third test score: '))
# Calcualate the average of the three scores
# and assign the result t... |
778f4d0d47bcb4c3983b1c7ce2de9104b4fcd948 | saurabh-pandey/AlgoAndDS | /myAttempts/arrays/maxSubArrayDivideConquer.py | 1,060 | 3.796875 | 4 | import sys
def subArraySum(arr):
"""A helper function for computing a part of cross-over case"""
maxSum = -sys.maxsize -1
sumSoFar = 0
subArr = []
for i in range(len(arr)):
sumSoFar += arr[i]
if (maxSum < sumSoFar):
maxSum = sumSoFar
subArr = arr[:i+1]
return (maxSum, subArr)
def maxSu... |
606b37e1a4a1f15bd3f0933abd055971b1b18e25 | Amarildop1/Python | /FuncaoCalculaCuboDeUmNumero.py | 242 | 4.0625 | 4 |
def cubo(num):
return num**3
#Teste
num = float(input("Digite um número: "))
cuboDeNum = cubo(num)
print(f"O cubo de {num} é:", cuboDeNum)
#List08 - Quest01
#Funções
# 05.Dez.2019
#Recebe um valor do tipo float e calcula o cubo. |
0f2d37b4b8e86f72477feb67714a136d05895250 | hz336/Algorithm | /LeetCode/DS - Linked List/! E Merge Two Sorted Lists.py | 1,075 | 4.0625 | 4 | """
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
#... |
a4690577762fbd24a003bd714b99819556b95b2a | manhar336/manohar_learning_python_kesav | /Python_basics/Creatingvariables.py | 581 | 4.1875 | 4 | #!/usr/bin/python --- where python is installed
#Creating variables in python
FIRSTNAME = 'GUIDO'
middlename = "van"
LastName = '''Rossum'''
_lang = """python"""
#Accessing or calling variables in python
print (FIRSTNAME) #calling variable
print("calling variable using prefix as string",FIRSTNAME)
print(FIRSTNAM... |
158fb336375c8e6e15f4c886b5c3bb3fe40c2a88 | nsidn98/Machine-Intelligence-and-Brain-Research-ID7123 | /Bandit Algorithms/Bandits.py | 3,631 | 3.703125 | 4 | '''
-----------------------------------------
Bandits Algorithm: Explore then Commit
Upper Confidence Bound
-----------------------------------------
'''
import numpy as np
import matplotlib.pyplot as plt
import random
n = 10000 # horizon
k = 100 # number of experiments
####### Explore then Commit #... |
054627fd3e664a6b09e345ef91efec97c55c88a3 | Malevaje/infa_2019_Malevaje | /lab3/task_hatch.py | 2,045 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 14 14:26:30 2019
@author: 1
"""
from graph import *
def easy_hatch_Y(x1, y1, x2, y2, N):
rectangle(x1, y1, x2, y2)
h = (x2 - x1) / (N + 1)
x = x1 + h
for i in range(N):
line(x, y1, x, y2)
x += h
#easy_hatch_Y(10, 10, 490, 590, 50)
def ea... |
af92ab6ce3f3684cafe1806cf97f90311b22b906 | kisk0419/algorithm_learning | /Binary-Tree/binary_tree.py | 4,472 | 3.6875 | 4 | # coding: utf-8
class Node:
def __init__(self, id):
self.id = id
self.parent = None
self.left = None
self.right = None
def __str__(self):
return 'id={}'.format(self.id)
class BinaryTree:
def __init__(self):
self.root = None
def insert(self,... |
da74a3702dd1254a6b180ecd02f6017e14df3060 | Hegemony/Python-Practice | /NowCoder/算法常考/9.removeNthFromEnd.py | 645 | 3.625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#
#
# @param head ListNode类
# @param n int整型
# @return ListNode类
#
class Solution:
def removeNthFromEnd(self, head, n):
# write code here
p = head
cnt = 0
while p:
... |
2acd1c6df5afe5ee61a8f1f72c7228f393fb2dfb | cjp0116/ML | /randome_forest_example.py | 1,145 | 3.734375 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
"""Step 1: Pick at random K data points from the Training Set.
Step 2: Build the Decision Tree associated with K data points.
Step 3: Choose the number Ntree of trees you want to build and repeat steps 1 & 2.
Step 4: For a new ... |
78b4e2702f4fab22b93ca405c3a77d0f903ba8a8 | qorjiwon/LevelUp-Algorithm | /Template/Trie/trie.py | 1,317 | 3.59375 | 4 | """
@Baek 11426 접두사 찾기
@Prob. https://www.acmicpc.net/problem/14426
@Source. https://www.acmicpc.net/source/22249026
@Algo. Tire
"""
class Node(object):
def __init__(self, key, data=None):
self.key = key
self.data = data
self.children = {}
class Trie(object):
def __in... |
596f516229287f4b6ef6bd443c64a1fe9acbf3dc | praneetha28/repo | /cspp1-practisem3/m4/p1/vowels_counter.py | 156 | 3.921875 | 4 | "'# TAKING THE INPUT'"
S = input()
VOWELS = 0
"'#CHECKING THE THE RANGE'"
for char in S:
if char in'aeiou':
VOWELS = VOWELS + 1
print(VOWELS)
|
3f22bb2eea6081bbc79332cba1c288af82a7f06d | YulyKo/python-learn | /student book with json(lab 4)/StudentBook.py | 4,082 | 3.75 | 4 | # Розробити клас Student, який буде містити
# елементи для зберігання: ім'я, вік, стать, телефон.
# Написати ф-ї члени, які зможуть змінювати їх індивідуально.
# Написати ф-ю, яка буде виводити всю інформацію форматовано..
class Student:
def __init__(self):
pass
def getDataOfStudent(self):
... |
4cf3b3f4e0633c488f26f0715b28eb7ab4758ca9 | PushkinKachroo/computational-physics-class-404-604-Spring-2019 | /Area.py | 609 | 3.59375 | 4 | """ From "COMPUTATIONAL PHYSICS", 3rd Ed, Enlarged Python eTextBook
by RH Landau, MJ Paez, and CC Bordeianu
Copyright Wiley-VCH Verlag GmbH & Co. KGaA, Berlin; Copyright R Landau,
Oregon State Unv, MJ Paez, Univ Antioquia, C Bordeianu, Univ Bucharest, 2015.
Support by National Science Foundation"... |
21fc6fcf522cb0d253237d11bc20000747cf58e4 | nateGeorge/coding-interview-problems | /solutions.py | 7,254 | 3.5625 | 4 | def question1(s, t):
if s is None or t is None or not isinstance(s, str) \
or not isinstance(t, str):
return False
tD = string_dict(t)
sD = string_dict(s)
sL = sD.keys()
# make sure it's even worth going through all the substrings of s first
for l, v in tD.items():
if l ... |
7d8856381efe3dc4ae31487018c14132a803ce75 | gonzaponte/Python | /PyLib/OldFiles/check.py | 2,468 | 3.640625 | 4 | import sys
def wrong( fun ):
''' This function throughs an error for wrong parameters.'''
sys.exit('Error in ' + fun.__name__ + ': wrong parameters.' )
def isint(x):
''' This function checks if the argument is an integer. It returns a boolean'''
return isinstance(x,int)
def islong(x):
'... |
136db4d9c896de9a3ddb9954ae9f01e44ede2dc9 | JPalijado/Assign_3 | /part2.py | 782 | 3.84375 | 4 | def inputNumApple():
numApple = int(input("How many apples you want to buy? "))
return numApple
def inputNumOrange():
numOrange = int(input("How many orange you want to buy? "))
return numOrange
def computePriceApple(numApple):
priceApple = numApple * 20
return priceApple
def computePriceOran... |
7143022b7ae6130be107be69a632cf26d0f0082e | JoamirS/Exercicios-Python | /ex077.py | 599 | 3.875 | 4 | '''
Crie um programa que tenha uma tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para
cada palavra, quais são as suas vogais.
'''
TupleCursoEmVideo = ('APRENDER', 'PROGRAMAR', 'LINGUAGEM', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR',
'TRABALHAR', 'ME... |
ae1da35e2063c0548a7ff774e2f80b94ec127956 | tina0430/Python_examples | /begining/chapter03/ex3_08.py | 606 | 3.8125 | 4 | #클로저(clouser) 연습
#클로저 미사용
def out():
count = 0
def inn():
nonlocal count
count += 1
return count
print(inn())
print('함수 내의 count 값은')
out()
out()
print()
#클로저 사용
def outer():
count = 0
def inner():
nonlocal count
count += 1
... |
018cda2a4ce352c97a947ac8b35e5f5770b15b51 | nidhisha-shetty/Python-programs | /combine-elements.py | 570 | 3.796875 | 4 | #combining elements of two lists with unequal lengths alternatively
def combine_ele(li1, li2):
range_value=[]
range_value+=str(len(li1))
range_value+=str(len(li2))
range_value.sort()
res=[]
for x in range(int(range_value[-1])):
if x in range(len(li1)):
res+=str(li1[x... |
6588a9ed41967db0ff78eff5eb69ffbe7d4538af | giso360/CT6001-formative | /q3.py | 2,766 | 3.5625 | 4 | import pymysql
db = pymysql.connect(host="localhost",
user="root",
passwd="root")
cursor = db.cursor()
cursor.execute("use supplierProduct")
# -- 2. Display the names of the products that are supplied
sql2 = """SELECT distinct name, id FROM supplierproduct.product;"""
ans2... |
fa2d03fd7b2ed2e8d549ad30fa759e0e5451d3da | aashutoshrathi/competitive-programming | /LinkedList/midRem.py | 1,118 | 3.9375 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, val):
temp = self.head
if temp:
while temp.next is not None:
temp = temp.next
temp.next... |
9956956f61e55af9c857956230a15d0b80a3e359 | lujhu/learningtocode | /filesassignment1.py | 165 | 3.8125 | 4 | # Use words.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
textstring = fh.read()
allcaps = textstring.upper()
print allcaps.rstrip()
|
b6b891effa0a89ec02be96ae18f013f279af46a2 | mahaocheng/pythonhardway | /practice/ex1~22.py | 9,682 | 4.625 | 5 | # -*- coding: utf-8 -*-
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print 'Yay! Pringting.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print "... |
5e3b68c3f4f018d7c68dd103a2bc47fc671c89a0 | freesoul84/python_codes | /other_python_codes/binary_search.py | 489 | 3.5 | 4 |
def bin_search(arr,l,r,k):
if r>=l:
mid=l+(r-l)//2
if arr[mid] == k:
return mid
elif arr[mid] > k:
return bin_search(arr,l,mid-1,k)
elif arr[mid]< k:
return bin_search(arr,mid + 1,r,k)
else:
return -1
if __name__=="__main__":
t=in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.