blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6185918a83634c596f81f0ec2879ddd39ebcb790 | stavernatalia95/Lesson-5.1-Assignment | /rocket.py | 790 | 4.1875 | 4 |
# A simulator for a rocket ship in a game.
class Rocket:
# The __init__() method doesn't take any arguments but sets the x and y positions to zero.
def __init__(self):
self.x=0
self.y=0
# Move_up() - will increment y position by 1
def move_up(self):
self.y+=1
# Move_righ... |
cdcb808d39a7691ea9dd9038bd8fbb30135c1db5 | PrashantThakurNitP/python-december-code | /calliing_base_static _method_inside_derived_class.py | 453 | 3.8125 | 4 | class base:
x=11#STATIC METHOD
@staticmethod
def basefunction():
print("inside base function")
class derived(base):
@staticmethod
def derivedfunction():
print("inside derived class static method")
base.basefunction()
derived.basefunction()
print("using base.x ... |
dcf1b16b585b11d80f2d81c869ea5e05290e90fc | masamasa42/test | /abc154b.py | 159 | 3.625 | 4 | # -*- coding: utf-8 -*-
#https://atcoder.jp/contests/abc141/tasks/abc154_b
import sys
import math
u=input()
a=""
for i in range(len(u)):
a+="x"
print(a)
|
1e17635ea617ca3730911efbe428e0505f0eda4c | predora005/weather-forecasting | /07.gsm_random_forest/wfile/name_handle.py | 2,927 | 3.546875 | 4 | # coding: utf-8
import re
##################################################
# ファイル名から要素を取得する(地上気象データ用)
##################################################
def elements_from_filename_ground(filename):
""" ファイル名から要素を取得する(地上気象データ用)
Args:
filename(string) : ファイル名
Returns:
list[string] : 要素のリ... |
0938852821ee34fe5dde661a8131917a77a13a47 | ianloic/Steph | /typesystem.py | 2,917 | 3.640625 | 4 | """A simple type-system for Steph."""
import typing
from enum import Enum
__all__ = ['type_union', 'Type', 'UNKNOWN', 'Number', 'STRING', 'BOOLEAN', 'Function']
class TypeException(Exception):
pass
class Operator(Enum):
# arithmetic
add = ('+', 2)
subtract = ('-', 2)
multiply = ('*', 2)
di... |
3070f1d536d32d368fab0adbb800b068ae319bfa | madhulika9293/cspp1-assignments | /m11/p4/assignment4.py | 883 | 3.71875 | 4 | '''
Exercise: Assignment-4
We are now ready to begin writing the code that interacts
with the player. We'll be implementing the playHand function.
This function allows the user to play out a single hand.
First, though, you'll need to implement the helper calculateHandlen function,
which can be done in under five lines ... |
11631f5418c3fa0d52dcc40d5307a7d59e73acc4 | Christopher-Caswell/holbertonschool-higher_level_programming | /0x03-python-data_structures/4-new_in_list.py | 288 | 3.734375 | 4 | #!/usr/bin/python3
def new_in_list(my_list, idx, element):
if idx < 0 or idx > len(my_list):
return my_list
tmp = list()
for x in range(len(my_list)):
if x == idx:
tmp.append(element)
else:
tmp.append(my_list[x])
return tmp
|
91c93f60046efb049315fb5bb439f0629e079325 | dwightr/ud036_StarterCode | /media.py | 1,186 | 3.609375 | 4 | import webbrowser
class Video():
"""
Video Class provides a way to store
video related information
"""
def __init__(self, trailer_youtube_url):
# Initialize Video Class Instance Variables
self.trailer_youtube_url = trailer_youtube_url
class Movie(Video):
"""
M... |
25a82e30d4867e34f06101b50e9208a9181737f2 | AntonioFacundo/Phyton | /Python/Practicas con Python/busquedas.py | 549 | 4.1875 | 4 | course = "Curso"
my_string = "Codigo facilito"
result = "{a} de {b}".format(a = course, b = my_string)
result = result.lower()
"""Busqueda"""
#regresa el valor de la cadena donde está
#localizado el resultado de busqueda
pos = result.find("codigo")
print(pos)
print(result[9])
#contador de letras
count = result.coun... |
cae39dc26cb406ade5fc9cc3f39c54be4dd28831 | viniciusgerardi/Python-Misc | /Exercicios/98.py | 649 | 4.09375 | 4 | # Faça um programa que tenha uma função chamada contador(), que receba três parâmetros:
# início, fim e passo. Seu programa tem que realizar três contagens através da função criada:
# a) de 1 até 10, de 1 em 1
# b) de 10 até 0, de 2 em 2
# c) uma contagem personalizada
def contador(início, fim, passo):
print(f'Co... |
b35593b60d7600dc309f37810a835aaa2610f190 | peter-de-boer/ponzischeme_webapp | /backend/games/fundCard.py | 847 | 3.6875 | 4 | class FundCard(object):
def __init__(self, value, time, interest, fundtype):
self.value = value
self.time = time
self.interest = interest
self.fundtype = fundtype
self.averageInterestPerc = self.averageInterest()
def averageInterest(self):
return 100*(((self.inte... |
785aa490eddc3aa2a7c50fb32969a6659ca1daa8 | jxjjdj/Python | /arithmetic_analysis/二分法.py | 586 | 3.84375 | 4 | import math
def bisection(function, a, b):#找方程在[a,b]中的解
start = a
end = b
if function(a) == 0:
return a
else function(b) == 0:
return b
elif function(a) * function(b) > 0;
print("couldn't find the root in [a, b")
return
else:
mid = (start + end) / 2.0
while abs(start - mid) > 10**-7:... |
9f36c5270d2ba37c48d3a1c1824297977e94b69e | az-ahmad/python | /projects/BlackJackv2/newblackjack.py | 613 | 3.703125 | 4 | import random
playerList = []
def greeting():
print('Welcome to BlackJack 2 player v.02')
while True:
try:
numPlayers = int(input('How many players will there be? '))
except:
print('Enter a valid number between 1 and 10')
continue
if numPlayers>0 and... |
da07132350ec4941a0d9dc8edc9fb8811c91a315 | kavin2606/Interview_prep | /question10.py | 503 | 4.03125 | 4 | def is_palindrome(str):
return (str == str[::-1])
def make_palindrome(string):
if(is_palindrome(string)):
return string
if string[0] == string[-1]:
return string[0] + make_palindrome(string[1:-1]) + string[-1]
else:
one = string[0] + make_palindrome(string[1:]) + string[0]
two = string[-1] + make_palin... |
f2d982cfa5e546a5435ce8bceabc46f114592ed0 | venkateshraizaday/ArtificialIntelligence | /a3/ZacateAutoPlayer.py | 8,095 | 3.9375 | 4 | # Automatic Zacate game player
# B551 Fall 2015
# PUT YOUR NAME AND USER ID HERE!
#
# Based on skeleton code by D. Crandall
#
# PUT YOUR REPORT HERE!
'''
As in the codebase provided, i implemented the first roll and second roll function to return a subset of the rolled dice.
The third roll sends the category that produ... |
0d8e5d1a56bf221a3a01ac43f76c8b33e8720244 | Aasthaengg/IBMdataset | /Python_codes/p03080/s537304676.py | 112 | 3.578125 | 4 | N = int(input())
s = input()
nR = s.count("R")
nB = s.count("B")
if nR > nB:
print("Yes")
else:
print("No")
|
8684c6c9be9f0e2977b24aad3bea6978d376d00f | DrinkMagma/viztracer | /src/viztracer/counter.py | 864 | 3.515625 | 4 | class Counter:
def __init__(self, callback, name, value={}):
self._name = name
self._callback = callback
def _update(self, d):
if self._callback:
self._callback(self._name, d)
def update(self, *args):
if len(args) == 1:
if type(args[0]) is dict:
... |
09f2e9db9496343d399e27e255c397f44e355b88 | sam-coleman/Presidential_Analysis | /analyze_tweets.py | 2,745 | 3.640625 | 4 | """
Analyze the Tweets
MP 3: Text Mining
@author: Sam Coleman
"""
from get_tweets import pull_all_tweets
from PIL import Image
from wordcloud import WordCloud
from matplotlib import pyplot as plt
def get_freq_dict(user_list):
"""
Get dictionry of top words with words as keys and their respective frequencies ... |
381a700504cf76f44f7620af5e764de29cbd63a9 | christopherdoan/face-maskid | /face_detect/face-detect.py | 960 | 3.609375 | 4 | import cv2
from cv2 import imread
from cv2 import imshow
from cv2 import waitKey
from cv2 import destroyAllWindows
from cv2 import CascadeClassifier
from cv2 import rectangle
""" Implementation of tutorial provided by MachineLearningMastery article written by Jason Brownlee:
https://machinelearningmastery.com/how-to... |
d19405297aec6d65cda25b8ef29e1b1d4dc7712b | j2k2020/basic_git | /python/sec04/05_while2.py | 363 | 3.984375 | 4 | # 7을 입력할 때까지 계속 입력하는 프로그램
# 7을 입력하면 프로그램 종료 (while문 사용)
#
# 숫자 입력: 3
# 다시 입력: 9
# 다시 입력: 1
# 다시 입력: 7
# 7 입력했습니다. 종료
num = int(input("숫자 입력: "))
while num != 7:
num = int(input("다시 입력: "))
print(num, "입력했습니다. 종료~") |
bc5f84721649a490403427ab132f8ccacd9a32b1 | martingaston/advent-of-code-2019 | /aoc2019/06.py | 2,922 | 3.921875 | 4 | import unittest
import collections
def steps_to_root(node, nodes):
root = "COM"
count = 1
while nodes[node] != root:
count += 1
node = nodes[node]
return count
def parse_orbit_map(orbit_map):
orbit_nodes = {}
for orbit_node in orbit_map:
orbiter, orbits = orbit_nod... |
0340214111976466f4df44d468d65a5dd011e12b | Yasaman1997/My_Python_Training | /Test/function/cube.py | 160 | 3.796875 | 4 | def cube(number):
print "%d" % (number ** 3)
def by_three(number):
if number % 3 == 0:
cube(number)
else:
return False
|
1a4db77cfc78c35bcef304d19b5b28730f4f89e8 | RombosK/GB_1824 | /Kopanev_Roman_DZ_11/dz_11_2.py | 1,031 | 3.90625 | 4 | # Создайте собственный класс-исключение, обрабатывающий ситуацию деления на ноль. Проверьте его работу на данных, вводимых
# пользователем. При вводе нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой.
class MyZeroDivision(Exception):
def __init__(self, text):
... |
80388097a3f7a682b5fe65c3472dd5e954af5555 | choroba/perlweeklychallenge-club | /challenge-207/lubos-kolouch/python/ch-1.py | 1,731 | 4.1875 | 4 | #!/usr/bin/env python3
import unittest
from typing import List
def is_single_row_word(word: str) -> bool:
"""Check if a word can be typed using only one row of the keyboard.
Args:
word (str): The word to check.
Returns:
bool: True if the word can be typed using only one row of the keybo... |
7b7960e139e1025bc0d903b38d2d3bbf4e4a7eeb | Ice-Sniper/pygame_mcpi_LCD_7seg | /lcdfontdisp.py | 4,092 | 3.84375 | 4 | # Display LCD font in 5x7 dot matrix for Pygame or Minecraft
# LCD フォントの表示、5x7ドットマトリクス、Pygameやマイクラ用
# self.BLOCK_SIZE などの定数は全て変数にする。途中で変化することもある。
import lcdfont
GRAY = (80, 80, 80)
GREEN = (10, 250, 10)
WHITE = (250, 250, 250)
class LcdFontDisplay():
"""Display line by LCD font
LCDフォントで描くディスプレイライン
""... |
92ae1b8ce66ea6ab7f79ed85a671215074b888bc | jintangli/PythonProject | /Algorithm/Array/ArraySum_ContinuousSubArray.py | 1,012 | 3.828125 | 4 | ##
# given an array and a number,
# find all the combination of two indices such that the sum of their element value equals to this given number
class Solution(object):
def findSubArray(self, array, sum):
i, j, k = (0, 0, len(array))
temp = array[i]
while i<=j<k:
if(temp == sum... |
c74772fabd2043f650db15a739dabc6bc5751c0f | Humbertotl/FundamentosPython | /aula2/programa11.py | 307 | 4 | 4 | lista1 = ['e','c','a','b','d']
lista_ordenada = sorted(lista1, reverse=True)
lista_d = reversed(lista1)
lista_rev_da_ord = reversed(lista_ordenada)
print(lista1,'lista original')
print(list(lista_d))
print(lista_ordenada)
print(list(lista_rev_da_ord))
#list.sort() #executando o metodo
#print(list)
|
f9dc6f7ca615edbaa1664c0e7be57db274032615 | 132sonalipatil/132sonalipatil-132sonalipatil-Prediction-using-Supervised-ML | /Prediction-using-Supervised-ML.py | 2,916 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # SONALI PATIL
# # Task 1 - Prediction using Supervised ML (Level - Beginner)
#
# In[25]:
# import all reuired libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[26]:
# Reading the ... |
81d71f981fa67a586176705be5fc17f5ac3ce8bf | apalabh/Portfolio- | /password.py | 583 | 3.9375 | 4 | def takePass():
p=input("Enter a password : ")
if checkPass(p)== True :
pn = input("Enter password again : ")
else :
p = input("Enter new password : ")
if p == pn :
pass
else :
p=input("Enter a password : ")
return p
def c... |
6c900d9c6f54b8d16c71ee96775c04004800b048 | MrHamdulay/csc3-capstone | /examples/data/Assignment_7/ostada001/util.py | 3,763 | 3.65625 | 4 | '''Question 2 Assignment 7
Utility functions which manipulate a 2 dimensional, 4*4 array
Adam Oosthuizen
27 April 2014'''
def create_grid(grid):
'''creates a 4x4 grid'''
grid=[]
for i in range(4):
grid.append(['']*4)
return grid
def print_grid(grid):
'''Print out a 4x4 grid in... |
dfd64c6d2867e8c310c3518e32401b046fc2eadf | Julian-Chu/leetcode_python | /lintcode/lintcode49.py | 467 | 3.546875 | 4 | class Solution:
"""
@param: chars: The letter array you should sort by Case
@return: nothing
"""
def sortLetters(self, chars):
l, r = 0, len(chars) - 1
while l <= r:
while l <= r and chars[l] >= 'a':
l += 1
while l <= r and chars[r] < 'a':
... |
e49b58c27398ff86aca74c86ffd096f3b9ce670c | munsangu/20190615python | /python_basic/def_test.py | 334 | 3.6875 | 4 | def add(a,b):
result = a+b
print("a=",a,"b=",b)
return result
def add_many(*args):
result = 0
for i in args:
result = result + i
return result
def print_kwargs(**args):
print(args)
print_kwargs(name="kang",age=70,city="Daegu")
a = 1
def test_1():
global a
a = a+1
tes... |
a36b090fa6fa05e1b98953a0a90afdbbcafaba53 | krishdb38/Python_Free_Coding | /tkinter_free/radio_button.py | 520 | 3.640625 | 4 | import tkinter as tk
window = tk.Tk()
v = tk.StringVar()
def show_choice():
print(v.get())
tk.Label(window,text="Choose a Metrix for blastp",padx=20).pack()
tk.Radiobutton(window,text = "BLOSUM45",variable=v,value = "BLOSUM45",command = show_choice).pack(side = "left")
tk.Radiobutton(window,text = "BLOSUM62",vari... |
1b36acc766282b623811d3b20669229c402751c1 | AdvaithD/Paradise | /CTCI-Solutions/CH1-ArraysStrings/palindrome.py | 417 | 3.90625 | 4 | def isPermutationOfAPalindrome(string):
let count = {}
for letter in string.replace(' ', ''):
if letter in count:
count[letter] += 1
else:
count[letter] = 1
for x in coun.values():
oddcount += x % 2
if oddcount > 1:
return False
return ... |
fcd8a540da5dd1addfed17d877b1c05323b5cac4 | abhi1362/HackerRank | /Python/Sets/Introduction to Sets.py | 298 | 3.96875 | 4 | def average(array):
set_=set(array)
average = 0
for item in set_:
average = average + item
average = average / len(set_)
return average
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result) |
8a5c10b6f722c9e3dcf30f5882afadfefe6d130c | AzizHarrington/command-line-games | /blackjack.py | 5,771 | 3.75 | 4 | import random
import os
class Deck(object):
def __init__(self):
self.cards = ['%s%s' % (num, suit)
for num in 'A23456789TJQK'
for suit in '♠♥♦♣']
random.shuffle(self.cards)
def drawone(self):
if len(self.cards) == 0:
print("ever... |
445a90d225600ceb3e8f55ff8e27dd787a10de85 | findango/wooords-solver | /wooords.py | 1,354 | 3.515625 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
wooords.py - solve a Wooords puzzle
"""
import sys
from collections import defaultdict
ANAGRAMS = defaultdict(list)
MIN_WORD_LENGTH = 3
def load_dictionary(fname):
f = open(fname)
for word in f.readlines():
word = word.rstrip("\n")
key = "".join(sor... |
0ac19ac8e8b3a8285739b2b144b4a1c9ddf8a0f5 | 7kjmol/PythonTestProject | /Exeicise/1-20/example14.py | 1,018 | 3.9375 | 4 | '''
题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
(2)如果n<>k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为新的正整数你n,重复执行第一步。
(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。
'''
import math
def isSushu(num):
flag = True
for i in range(2,int(math.sqrt(num))):
if((num % ... |
bd5e05cf4af6e4df377e351165cb55db44ea8eb6 | Artem-Vorobiov/Physics_In_Games_T | /9_om.py | 1,931 | 3.890625 | 4 | import turtle
import math
import random
# Set up screen
wn = turtle.Screen()
wn.bgcolor('blue')
wn.title('Simple Object Motion with Physics and NO Friction Player in the center')
class Player(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.color('white')
self.shape('triangle')
self.pen... |
869a4b6ea96a20fffc4e333ddc263530cee7f142 | ht-dep/Algorithms-by-Python | /Python Offer/06.The Sixth Chapter/64.Sum_1_n.py | 443 | 3.640625 | 4 | # coding:utf-8
'''
求1+2+3+...+n的和
要求不能使用乘除法,for,while,if,else,switch,case等关键字以及条件判断语句
'''
class Solution(object):
def sum0(self, n):
return 0
def sum(self, n):
fun = {False: self.sum0, True: self.sum} # fun为字典,key值为bool类型,value为函数
return n + fun[not not n](n - 1) #
if __name__ ==... |
568d7a0c7522158b85cef9fc6cbb9de2305c868b | rliu054/machine-learning-from-scratch | /DecisionTree/decision_tree.py | 3,764 | 3.75 | 4 | """
Decision tree module.
"""
import math
import operator
def create_data_set():
"""Generate a simple test data set."""
data_set = [
[1, 1, 'yes'],
[1, 1, 'yes'],
[1, 0, 'no'],
[0, 1, 'no'],
[0, 1, 'no'],
]
labels = ['no surfacing', 'flippers']
return data... |
76c810b2f3da012c9c352d9747e6c2ec07c93d97 | ecly/kattis | /watchdog/watchdog.py | 765 | 3.625 | 4 | def dist(x1, y1, x2, y2):
return (abs(x1 - x2) ** 2 + abs(y1 - y2) ** 2) ** 0.5
def find_shortest(s, h):
hatches = {tuple(map(int, input().split())) for _ in range(h)}
for x in range(s):
for y in range(s):
if (x, y) in hatches:
continue
max_leash_length = m... |
c2d8fe69d77582f58b0017236e798fd6f6859a11 | travbrown/CS-0 | /Intro_classes.py | 2,908 | 3.984375 | 4 | class Person:
# This function is called whenever a new Person object is created. The
# self parameter refers to the object itself, i.e. the instance of the
# class that is being created.
def __init__(self, first, last):
self.first = first
self.middle = None
self.last = las... |
fc34d04e5ead1c23e982c992dcc95ebb49652300 | eightnoteight/compro | /spoj/ec_conb.py | 187 | 3.640625 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
for _ in xrange(int(raw_input())):
t = int(raw_input())
if t % 2:
print t
else:
print int(bin(t)[-1:1:-1], 2)
|
efd46f1ea8fb824d75aabede0d5a49e9fe2be15f | jcruz63/python_college_assignments | /journal4.py | 1,327 | 4.15625 | 4 | import math
# create function stub
def hyp_step1(a, b):
return 0
# first second step square a and b print results to test
def hyp_step2(a, b):
print("inside step 2") # this is just to make the console read clearer
a_sqr = a**2
b_sqr = b**2
print('a squared is', a_sqr)
print('b squared is', b_... |
fa2dcb3832fd28ca58fe280c0636481703050dc6 | tarunjoseph94/Python-Lab | /hand7_1.py | 530 | 3.96875 | 4 | class Rectangle:
def __init__(self,height,width):
self.height=height
self.width=width
def area(self):
a=self.height*self.width
return a
def peri(self):
p=2+(self.height+self.width)
return p
def heightReturn(self):
return self.height
def widthReturn(self):
return self.width
def isSqaure(self):
i... |
84e4a57279bf1764679d997f5d5595d82e331526 | shouliang/Development | /Python/LeetCode/300_length_of_LIS.py | 2,268 | 3.84375 | 4 | '''
最长上升子序列
300. Longest Increasing Subsequence:https://leetcode.com/problems/longest-increasing-subsequence/
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefo... |
5fcbcb5745eef5f1b3bc843e759f9cbbfb75c96f | BrettParker97/CodingProblems | /2021-08-02/sol.py | 1,770 | 3.90625 | 4 |
class LRUCache:
def __init__(self, listSize):
self.listSize = listSize
self.FIFO = []
self.cache = {}
def addToFIFO(self, value):
res = None
#if value is in list, then delete it
#and bring it to the front
if value in self.FIFO:
self.F... |
69743ad6e437de27b044b345ebea695aea78895a | murffious/pythonclass-cornell | /coursework/programming-with-objects/exercise1/script.py | 649 | 4.25 | 4 | """
A script to show off the creation and use of objects.
Author: Paul Murff
Date: Feb 6 2020
"""
import introcs
import funcs
# Step 1: Create a green RGB object, assign it to variable green, and then print it
green = introcs.RGB(0,255,0,255)
print(green)
# Step 2: Create a 50% transparent red RGB object, assign it... |
f4f549bce6bac2398f6ad5d6b357fb6e38ab7815 | Wbec/Personal-projects | /Small-Projects/roman.py | 1,117 | 3.75 | 4 | done=False
while done==False:
goodnum=False
while goodnum==False:
try:
inp=input("input a number or type quit:")
if inp=='quit':
done=True
num=0
break
num=int(inp)
except ValueError:
goodn... |
6db4db007552705943d007b56c5212b0655a872a | luana-ribeiro2/mergeSort | /mergeSort.py | 1,178 | 3.65625 | 4 | def mergeSort(listaOrdenar):
if len(listaOrdenar) > 1:
meio = len(listaOrdenar)//2
dire = listaOrdenar[meio:]
esq = listaOrdenar[:meio]
mergeSort(dire)
mergeSort(esq)
i = j = l = 0
while j < len(dire) and i < len(esq):
if esq[i] > dire[j]:
... |
2a19e4aad097ae938467fffaae38d3d2451d32ba | dixit5sharma/Learn-Basic-Python | /Ch3_List_SubString.py | 611 | 3.78125 | 4 | a=[0,1,2,3,4,5,6,7,8,9]
b="This is a sentence"
p=a[2:6] # a[start:end] start index is inclusive, end index is exclusive.
q=b[3:15]
print(p) # [2, 3, 4, 5]
print(q) # s is a sente
# Increasing the Jump value
c=a[2:7:2]
d=b[3:15:3]
print(c) # [2, 4, 6]
print(d) # ss n
# Start index not required if ... |
2f7d1856b353b557bec1ac230af0079d6711a53f | EruDev/Python-Practice | /第2章/2-3.py | 801 | 4.46875 | 4 | # 如何进行反向迭代?
"""
案例:实现一个连续浮点数发生器,根据给定的范围(start,end)和步进值(step)产生
一些连续的浮点数,如迭代FloatRange(3.0, 4.0, 0.2)可生产序列:
正向:3.0->3.2->3.4->3.6->3.8->4.0
反向:4.0->3.8->3.6->3.4->3.2->3.0
"""
class FloatRange:
def __init__(self, start,end, step=0.1):
self.start = start
self.end = end
self.step = step
def __iter__(self):
... |
28ee08af5f431bb7196fa4670db3242c8408c422 | colinknebl/MS_SWDV | /SWDV600_Intro_To_Programming/Modules/module2/ball_filler.py | 867 | 4.1875 | 4 | # ball_filler.py
#
# Program to calculate the amount of filler required
# for the user specified amount of balls
import math
def main():
# get the number of balls
numberOfBalls = int(input('How many bowling balls will be manufactured? '))
# get the ball diameter
ballDiameter = float(input('What is ... |
226afc2cfc5714762629070ab3f2129d25940c59 | franciscocamellon/Francisco_Camello_DR2_TP3 | /questao_02.py | 1,430 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
/************************ TESTE DE PERFORMANCE 03 **************************
* Questao 02 *
* Aluno : Francisco Alves Camello Neto *
* Disciplina : Fundamentos do Desenvolvimento Pyt... |
76fe0158c173a40783cdb28f8908ec3e6e23a2e1 | henrique17h/Aprendizado_Python | /desafio27.py | 231 | 3.859375 | 4 | velocidade= float(input('Qual a velocidade atual do carro? '))
if velocidade > 80:
print('Você foi multado!')
multa= (velocidade-80) *7
print ('Você excedeu o limite de 80km e pagará {:.2f}R$ de multa'.format(multa)) |
580fc0f8958d3da82ab63f8d79342f629eb4e39a | vozille/Algorithms | /datastructures/Basics/priority_queue.py | 334 | 3.640625 | 4 | import heapq
class priority_queue:
def __init__(self):
self.queue = []
self.index = 0
def push(self,item,priority):
heapq.heappush(self.queue,(-priority,self.index,item))
def pop(self):
return heapq.heappop(self.queue)[-1]
q = priority_queue()
q.push('aa',1)
q.push('fgff',2)
... |
c07dfeb7ced7af023d2feba73c039a652e48bc2f | jtrieudang/CodingDojo-Algorithm | /Morning Algo03.py | 1,836 | 4.375 | 4 | # Introduce concept of inheritance
# Show how objects can interact
# Three classes: Person, Vehicle, Car
# Allow people to buy and sell cars
class Car:
def __init__(self, make, model, year, mileage = 0):
self.make = make
self.model = model
self.year = year
self.mileage = m... |
dce73a91cfee9a1dd9d33d58a547acc1ae4ef944 | FrancisJen/pythonic | /14pythonic/iterator_140501.py | 1,270 | 4.15625 | 4 | # 14-5: iterator, Generator
# 可迭代对象,iterable: list, tuple, set
# for i in iterable
# 可迭代对象不一定是迭代器:list
# iterator: 是对象也就是class, 也是可迭代对象
# 如何将普通的对象变为可迭代对象呢
# 包含 def __iter__(self) & def __next__(self)
# 迭代器是一次性,遍历之后就不能再此遍历了
# 如何遍历两次呢:
# 遍历之前先copy这个对象
# diff:
# 迭代器是可迭代对象,但... |
881fe19ccc18fb6878bd011108403afdd4ec3685 | EricksonSiqueira/curso-em-video-python-3 | /Mundo 1 fundamentos basicos/Aula 10 (condições 1)/Desafio 033.py | 692 | 3.90625 | 4 | # Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
co = {'li': '\033[m',
'vd': '\033[32m',
'vm': '\033[31m',
'az': '\033[34m'}
n1 =int(input(f"{co['az']}Digite um número{co['li']}: "))
n2 =int(input(f"{co['az']}Digite um número{co['li']}: "))
n3 =int(input(f"{co['az']}... |
0b1c2a195178a5e74a305bd36880e3c4f4830d08 | knutsvk/sandbox | /euler/p21.py | 387 | 3.6875 | 4 | def sum_proper_divisors(n):
ans = 1
for x in range(2,n):
if n % x == 0:
ans += x
return ans
def is_amicable(a):
b = sum_proper_divisors(a)
return sum_proper_divisors(b) == a and a != b
if __name__ == "__main__":
amicable_sum = 0
for n in range(2,10000):
if is_... |
02d61c919e1fc2270c7f591ece11cb0eb28ce1f3 | aleksiheikkila/HackerRank_Python_Problems | /Piling_Up.py | 719 | 3.859375 | 4 | '''
HackerRank problem
Domain : Python
Author : Aleksi Heikkilä
Created : Jun 2020
Problem : https://www.hackerrank.com/challenges/piling-up/problem
'''
from collections import deque
num_testcases = int(input())
for case_nbr in range(num_testcases):
num_cubes = int(input())
cubes = deque(int(side) f... |
907d67626367c26c335cd311c788c18290150cc1 | djmar33/python_work | /ex/ex8/8-3.py | 259 | 3.5625 | 4 | #8-3 T_shirt
def make_shirt(size, prompt):
print("即将制作一件大小为 " + size.upper() + ",标语为 " + prompt.title() + " 的T-shirt.")
#位置实参
make_shirt('xl', 'i love you')
#关键字实参
make_shirt(size='xl', prompt='i love you')
|
72ca76ff5d65a7722c42ca53d31ee6c59a8e3528 | 777acauleytosi/python | /fortnite.py | 2,064 | 3.90625 | 4 | #fortnite.py
#the game fortnite
# by Macauley Tosi
def main():
print("welcome to Fortnite Battle royal!")
print("The last one to survive gets the victory royal!")
username = input("whats your username you would like? ")
print(username,"has entered the Battle bus, and you decide where to land")
... |
fbf6769c605677264f4e804130e56fb3a170eb35 | indiarosefriswell/TaxiFareModel | /TaxiFareModel/data.py | 1,357 | 3.640625 | 4 | import pandas as pd
from TaxiFareModel.params import BUCKET_NAME, BUCKET_TRAIN_DATA_PATH
def get_data(nrows=10_000):
'''returns a DataFrame with nrows from s3 bucket'''
df = pd.read_csv(f"gs://{BUCKET_NAME}/{BUCKET_TRAIN_DATA_PATH}", nrows=nrows)
return df
def clean_data(df, test=False):
'''
... |
2a5346be632931d12295e15e0dcc62522933f198 | endlessmeal/data_science_learning | /probability_theory/central_limit_theorem.py | 2,364 | 3.875 | 4 | import random
from collections import Counter
import matplotlib.pyplot as plt
import math
# независимое испытание Бернулли
# в котором имеется всего два исхода (1 или 0)
def bernoulli_trial(p):
return 1 if random.random() < p else 0
# биномиальное распределение
def binomial(n, p):
return sum(bernoulli_trial(... |
e57a58fbddecf4582aec87401ea41575b0f5825a | vshypko/coding_challenges | /problems/misc/people.py | 4,446 | 3.625 | 4 | # Name | Favorite Color | Birthday
# Theo | Green | October 10, 2000
# Sherwin | Blue | May 3, 2003
# Daniel | Orange | December 2, 2003
# Sunny | Orange | January 4, 1999
# Aubrianna| Green | August 5, 1999
# 1-1) How would you represe... |
2d7ad4347ed17ac1389950a6f538580dfba1f012 | HyderYang/python_common | /7.函数/04.py | 776 | 3.734375 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# 构造一个可以返回多个值得函数
# 为了返回多个值 函数直接 return 一元组即可
def my_fun():
return 1, 2, 3
a, b, c = my_fun()
print(a)
print(b)
print(c)
# 尽管 my_fun() 看上去返回多个值 实际上是创建了一个元祖然后返回的 这个语法看上去比较奇怪
# 实际上我们使用的是逗号来生成一个元祖 而不是括号
a = (1, 2)
print(a)
b = 1, 2
print(b)
# 当我们调用返回一个元祖的函数的时候 通常... |
f4aa3433734e3b5b502259a590f0f6b165649bae | sky-dream/LeetCodeProblemsStudy | /[1143][Medium][Longest_Common_Subsequence]/Longest_Common_Subsequence.py | 769 | 3.609375 | 4 | # leetcode time cost : 64 ms
# leetcode memory cost : 13.8 MB
# solution 1, DP
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
last_memory=[0]*(len(text1)+1)
memory=[0]*(len(text1)+1)
for i,t2 in enumerate(text2):
memory=[0]*(len(text1)+1... |
d91a2646808ceaaaff03925b2249d3697edbf8c8 | Hidenver2016/Leetcode | /Python3.6/369-Py3-M-Plus One Linked List.py | 3,624 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 15 22:51:53 2019
@author: hjiang
"""
"""
Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are st... |
cd314e584e7ba509064647484dccca86c03161e5 | arafe102/Arafe102 | /Main.py | 4,622 | 3.859375 | 4 | import sqlite3
from Student import Student
conn = sqlite3.connect('StudentDB.db')
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS Student(StudentId INTEGER PRIMARY KEY AUTOINCREMENT, FirstName varchar(25),"
"LastName varchar(25), GPA NUMERIC, Major varchar(20), FacultyAdvisor varchar(25));")
'''stu... |
38e4a094c2c02cc09017a854bcef5c3f2e3eef2d | Abhyudaya100/my-projects-2 | /sumofcubeoffirstNnumbers.py | 184 | 3.65625 | 4 | '''
N = int(input())
total = 0
for n in range(1,N + 1,1):
total += n*n*n
print(total)
'''
print(4194303)
25 8.33
30 10
28.33 9.44
33.33 11.11 |
b1bac867cba63f7510e1a68216104943f250e791 | LucasMayer02/UFCG_Exercicios | /atividades/e_dobro/questao.py | 148 | 3.703125 | 4 | # 2021-03-22, lucas.mayer.almeida@ccc.ufcg.edu.br
#
num1 = int(input())
num2 = int(input())
if num1 * 2 == num2 or num2 * 2 == num1 :
print("SIM")
else:
print("NAO")
|
bc998bbd6fc02f13ac4df8c44366e3be042379cc | Hornet004/alx-higher_level_programming | /0x03-python-data_structures/0-print_list_integer.py | 113 | 4 | 4 | #!/usr/bin/python3
def print_list_integer(my_list=[]):
for int in my_list:
print("{:d}".format(int))
|
fb691c0faff3b74a9eeb1113c3aa0f1d7de7c570 | Developer122018/learn-python-code-practice-and-tdd | /Day4 _1.py | 448 | 4.46875 | 4 | # # Write a Python program to count the number of characters (character frequency) in a string
#
# def count_num_of_characters_in_a_string(p_string=''):
# #return len(p_string)
# #way 2
# num_count = 0
# for i in p_string:
# num_count += 1
# return num_count
#
#
# if __name__ == '__main__':
... |
2efade694bec92640047693191d2f6a2c8acf07a | EdiTV2021/Python_2021 | /funcion.py | 549 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 2 19:41:40 2021
@author: Edison
"""
# print("Ingrese el siguiente valor: ")
# a=input()
# print("Ingrese el siguiente valor: ")
# b=input()
# print("Ingrese el siguiente valor: ")
# c=input()
# print("Ingrese el siguiente valor: ")
# d=input()
#funcion ... |
b9d06ff2710b1d4fd95bf2e11572d848779ef34b | Sushmi-pal/pythonassignment | /Qn39.py | 67 | 3.515625 | 4 | tup=13,14,15
a,b,c=tup
print('The sum of elements of tuple',a+b+c)
|
027b5974c2d69a349c75787a8f5ce6a157008b16 | VladBaryliuk/my_start_tasks | /new/src/25.01.2020/while task 4.py | 148 | 3.515625 | 4 | a = 0
sstr = 0
while True:
c = float (input())
sstr += 1
if c > 22.0:
break
elif sstr == 7:
a = sstr // 7
print (a)
|
a81aca1e56ec5a5cac17775316090631358666c3 | faisal-git/Data_Structure | /Graphs/print_cycle.py | 1,667 | 3.828125 | 4 | # color algorithm can be used
# no self loop and parallel edges
# state 0: not visited ,state 1: currently in visiting loop ,state 2: completely visited
import collections
def dfs(v,visited,g,parent,cycle):
visited[v]=1
print(v)
for n in g[v]:
if visited[n]==0:
parent[n]=v
... |
6a7428cac9b447bbaa86b5725fb98b2868454601 | BruceYi119/python | /io2.py | 2,862 | 3.59375 | 4 | # def f1(n):
# return n * 10
# print(f1(10))
# 람다함수 : 메모리절약, 가독성 향상, 코드 간결
# b = lambda n:n * 10
#
# print(b(22))
#
# def f2(x, y, f):
# print(x * y * f(x + y))
#
# f2(10, 100, lambda x:x + 1)
# a = [1,2,3,5,6]
# result = [];
#
# def f(list):
# result = [(v * 3) for v in list]
# print(result)
#
# f(a... |
d35cfe84caeb444b52be33520e8a6b4a9608447b | Blossomyyh/leetcode | /VMware/TaskScheduler.py | 1,604 | 3.8125 | 4 | """
621. Task Scheduler
# asynchronous processing
"""
## RC ##
## APPROACH : HASHMAP ##
## LOGIC : TAKE THE MAXIMUM FREQUENCY ELEMENT AND MAKE THOSE MANY NUMBER OF SLOTS ##
## Slot size = (n+1) if n= 2 => slotsize = 3 Example: {A:5, B:1} => ABxAxxAxxAxxAxx => indices of A = 0,2 and middle there should be n elements, s... |
cc72fa3082be06314b5de1ae8ce7ec9d682a3e6d | Its-Haze/pvt21_programmering | /quiz2/quiz.py | 1,417 | 3.609375 | 4 | from quiz2.api import QuizAPI, BaseAPI
from random import randint
QUIZ_URL = "https://bjornkjellgren.se/quiz/v2/questions"
class Player:
def ask_num(self, n):
raise NotImplementedError
class ConsolePlayer(Player):
def ask_num(self, n):
while True:
res = int(input(">"))
... |
93e233a5e16fc877fb9ab6efcab46296986638e1 | superyang713/Hacker_Rank | /nested_list.py | 410 | 3.8125 | 4 | # dict could be used, but the point of this challenge is to use nested list.
def main():
n = int(input()) # useless but required by the challenge
data = []
for _ in range(n):
name = input()
score = float(input())
record = [name, score]
data.append(record)
data = sor... |
0cd23944a5e7ce288380e3a05a074cccf5de499b | Harshit090/Python-Problems | /functions/ans9.py | 153 | 3.59375 | 4 | def add(a):
def add1(b):
c = 1 + b
return c
x = add1(a)
return x
a = int(input("Enter a no\n"))
q = add(a)
print(q)
|
82090cac0408c4b069c23a04214276c9d9407658 | KivenCkl/DataStructures_Python | /Common_Algorithms/permutations.py | 346 | 3.53125 | 4 | """
全排列算法
"""
def permute(arr):
"""
时间复杂度: O(n!)
"""
if len(arr) == 0:
return []
if len(arr) == 1:
yield arr
for i in range(len(arr)):
x = arr[i]
xs = arr[:i] + arr[i + 1:]
for j in permute(xs):
yield [x] + j
print(list(permute(list(range(4... |
0ccd95d779aa34894187db92f0e47df09fc3ee18 | Harishkumar18/data_structures | /cracking_the_coding_interview/Arrays_and_Strings/zero_matrix.py | 1,132 | 4.1875 | 4 | """
Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
"""
def set_zeros(mat):
m, n = len(mat), len(mat[0])
if m < 1:
return mat
if n < 1:
... |
e6a115fd820e2b3cbf511bccce6f5a25eb722866 | myamullaciencia/Bayesian-statistics | /_build/jupyter_execute/12_binomial_soln.py | 14,528 | 3.84375 | 4 | # Bite Size Bayes
Copyright 2020 Allen B. Downey
License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
## The Euro problem
In [a previous notebook](https://colab.... |
8289b99c6a2b73c53219c2a6cd0e8eee04e1b9fe | aidanohora/Python-Practicals | /p7p2.py | 247 | 4.09375 | 4 | year = int(input("Enter a year: "))
if year%4 != 0:
print("This is a common year.")
elif year%100 != 0:
print("This is a leap year.")
elif year%400 != 0:
print("This is a common year.")
else:
print("This is a leap year.")
|
8287bb193b9bdcfef42b341c6a7f839be668ce98 | bethanymbaker/arch | /scripts/tetris.py | 2,547 | 4.09375 | 4 | import numpy as np
from time import sleep
class Tetris:
def __init__(self, num_rows, num_cols):
self.num_rows = num_rows
self.num_cols = num_cols
self.board = [[-1] * num_cols for _ in range(num_rows)]
self.is_complete = False
def display_board(self):
for row in range... |
2b1e9aab7696ea85c4626ecf4d4b8c3f02ce1fe3 | bappi2097/hackerrank-python | /hackerrank/String Validators.py | 602 | 3.65625 | 4 | if __name__ == '__main__':
s = input()
validations = {
'alnum': False,
'alpha': False,
'digit': False,
'lower': False,
'upper': False
}
for i in s:
if i.isalnum():
validations['alnum'] = True
if i.isalpha():
val... |
b1a22342b68941ca9491fcabf1bfbfde71281006 | dineshbalachandran/mypython | /src/daily/daily221.py | 462 | 4.21875 | 4 | """ Let's define a "sevenish" number to be one which is either a power of 7, or the sum of unique powers of 7.
The first few sevenish numbers are 1, 7, 8, 49, and so on. Create an algorithm to find the nth sevenish number. """
import math, sys
def sevenish(n):
if n == 0:
return 0
x = math.floor... |
8dae63d4b3ae94459b4759febbb40601e47b8719 | deysonali/CSC190 | /190lab1/stackLib.py | 284 | 3.703125 | 4 | class stack:
def __init__(self):
self.store=[]
def push(self, x):
self.store=self.store+[x]
return True
def pop(self):
if (len(self.store)==0):
return False
else:
rval=self.store[len(self.store)-1]
self.store=self.store[0:len(self.store)-1]
return rval
|
a9f5e26c202ec7e5cbf4e601f8f84613e84889b9 | miro-lp/SoftUni | /Fundamentals/Functions/CenterPoint.py | 389 | 3.9375 | 4 | def nearest_point(x_1, y_1, x_2, y_2):
hypo_1 = x_1 ** 2 + y_1 ** 2
hypo_2 = x_2 ** 2 + y_2 ** 2
if hypo_1 <= hypo_2:
print("(" + str(int(x_1)) + ", " + str(int(y_1)) + ")")
else:
print("(" + str(int(x_2)) + ", " + str(int(y_2)) + ")")
x_1 = float(input())
y_1 = float(input())
x_2 = fl... |
0c1a87ed8e5cc1b3acfb9be1ae5fb5690a17590d | naren-m/programming_practice | /general/divide_and_conquer/binary_search.py | 728 | 3.953125 | 4 | # Problem Grokking algorithms book. Exercise 4.4
def binary_search(arr, element, start=0, end=0):
print(arr, element, start, end)
if start >= end:
return -1
mid = (start + end) // 2
if element == arr[mid]:
return mid
elif element < arr[mid]:
# element to find is less than... |
ef5ad615a839853719d8cae7071b3371f9a0199a | RikuX43/School_projects | /Intro/employeepay.py | 268 | 3.921875 | 4 | # Put your code here
wage = float(input('Enter the wage: '))
reg_hours = int(input('Enter the regular hours: '))
ot_hours = int(input('Enter the overtime hours: '))
weekly_pay = wage * reg_hours + ot_hours * wage * 1.5
print("The total weekly pay is $", weekly_pay)
|
b73ba06e055ea3e1d682ea78e9f59aa25145930f | faustoandrade/TALLER-1-PD | /12sumacuadrados.py | 212 | 3.5625 | 4 | def cuadros(n):
sum = 0
if n < 100:
for i in range(1,n):
if i % 4 == 0:
t = i ** 2
sum = sum + t
print sum(
t = input("ingrese numero: ")
cuadros(t) |
eaac9612f152d37b0c51bac1a43e604364243485 | Sapan-Ravidas/Data-Stucture-And-Algorithms | /Dynamic Programming/knapsack.py | 1,103 | 3.6875 | 4 |
class Item:
def __init__(self, name, weight, profit):
self.name = name
self.weight = weight
self.profit = profit
def __repr__(self):
return f"Item({self.name}, w='{self.weight}', p='{self.profit}')"
def knapsack(items, capacity):
n = len(items)
if n == 0:
... |
fe5c07f94552fff371bd55267e75c1acff213a4e | topdcw/Leetcode | /601-700/Solution_665.py | 989 | 3.84375 | 4 | """
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.
We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).
"""
class Solution:
def checkPossibility(self, nums):
count=0
i=1
whi... |
953c598989bef5c14e2d1d4bb8c804a4e4f91766 | ATField2501/G-S_Python-Exercices | /Swinnen_exercice10.py | 966 | 3.515625 | 4 | #!/usr/bin/python2
# -*- coding: utf8
# auteur:<atfield2501@gmail.com>
# Exercice page 52
"""
5.15. Écrivez un programme qui analyse un par un tous les éléments d'une liste de mots (par
exemple : ['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra'] pour générer deux
nouvelles listes. L'un... |
aeaac14f67ed7ac59114679e79c788e919d053b7 | ChristianTsoungui/sells_management | /sells_management.py | 4,372 | 3.546875 | 4 |
# coding: utf-8
# In[1]:
# Importing the libraries
import pandas as pd
import numpy as np
import re
# ## Data cleaning and Item_Price conversion in float
# In[2]:
# function that will remove the dollar sign from the item_price and convert it in float
def remov(x):
L = list(x)
del L[0]
S = ''.join(L)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.