blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
08305e35fa7ccd7c1815f64d60be88a89e2e9276 | JTQueena/work | /831order.py | 183 | 3.578125 | 4 | import pandas as pd
df=pd.read_csv("831.csv", encoding="utf-8")
condition=df['need'] >= 1
#print(condition)
filteredData=df[condition]
print(filteredData[['name', 'need']])
n=input()
|
7c5bc65b394dcae0eac54da53d18a61c5724034b | suryasr007/algorithms | /Algorithms/BFS.py | 763 | 4.25 | 4 | import queue
class Vertex(object):
"""
Vertex object has data, visited and neighbour list
"""
def __init__(self, data):
self.data = data
self.visited = False
self.neighbour_list = list()
def __str__(self):
return str(self.data)
def bfs(root):
"""
Functional... |
14fc5f44675333205e2c7e12b58807949e065495 | aganpython/laopo3.5 | /matplot/Matplot_Contours.py | 795 | 3.765625 | 4 | # -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
import numpy as np
#Contours 等高线图
def f(x,y):
# the height function
return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y) #把x,y绑定成网格的输入值。
# use plt.contourf to filling contours
# X,Y and value... |
0790b98e408e966e4d674d3b9d3f501c1b8060fd | alexforcode/leetcode | /200-299/204.py | 748 | 4.0625 | 4 | """
Count the number of prime numbers less than a non-negative number, n.
Constraints:
0 <= n <= 5 * 10**6
"""
import math
from typing import List
def count_primes(n: int) -> int:
if n <= 2:
return 0
sieve: List[bool] = [True] * n
sieve[0] = sieve[1] = False
for idx in range(4, n, 2):
... |
ce5aabff75a11e5a98ae3f4ec0f8e679548a968e | SJeliazkova/SoftUni | /Python-Fundamentals/Exams/mid_exam_preparation/02_array_modifier.py | 596 | 3.640625 | 4 | array = list(map(int, input().split()))
data = input()
while not data == "end":
if data == "decrease":
for i in range(len(array)):
array[i] -= 1
else:
command = data.split()[0]
index_1 = int(data.split()[1])
index_2 = int(data.split()[2])
if command == "sw... |
56c4199a532f272c62b05d40f4edc058418c311b | alexfoss8/si_206_final_project | /visualizeData.py | 3,629 | 3.53125 | 4 | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
def make_minority_pie_chart(data, output_folder, state):
# make lists of all the data
total_white = data[-2].split()[-1]
total_minority = data[-1].split()[-1]
labels = ["white", "minority"]
populations = [total_white, total_minori... |
5535d8ce36d5150b4ed8b2020874c630a89d6cf3 | tobymyers/codingthematrix | /chapter0/chapter0_lab.py | 5,798 | 3.65625 | 4 | # #0.5.1 find num of mins in week
# hour = 60
# day = 24
# week = 7
# mins_in_week = hour * day * week
# print(mins_in_week, 'num mins in week')
#
# #0.5.2 find remainder w/out %
# num_div = 2304811//43
# remainder = 2304811 - (43 * num_div)
# print(remainder, 'remainder')
#
# #0.5.3 eval boolean expression
# print(((6... |
e5e98429d28bde1d780605084726c78ab21b2f46 | ASIMER/Logika | /pupil_turtle_game.py | 1,353 | 3.859375 | 4 | from turtle import*
class Sprite(Turtle):
def __init__(self,x,y,color,shape,speed):
super().__init__()
self.shape(shape)
self.color(color)
self.penup()
self.goto(x,y)
self.speed = speed
def move_up(self):
self.goto(self.xcor(),self.ycor() + self.speed)
... |
1672d21da4674058a55a81ee5d7ff8aaf5061446 | ArtemiyShilin/Python-GB | /main6.py | 133 | 3.578125 | 4 | person_name = 'Кеша'
age = 32
print('Меня зовут', person_name, 'мне', age, 'года')
print(person_name, age, age + 2, sep='/')
|
be5ea37c1b983ba32eb395e84eef2528b06397dc | pauloalwis/python3 | /leia.preco.de.produto.aplique.desconto.5%.py | 279 | 3.59375 | 4 | # Leia o preço de um produto e mostre seu novo preço, com 5% de desconto
produtoPreco = float(input('Digite o preço do produto, para aplicar o desconto de 5%.'))
print('Novo preço do produto com desconto de 5% será {:.2f}'.format(produtoPreco - ((produtoPreco * 5) / 100))) |
bc459938c8889e80f128ad13bd51cced9a4a502f | kidult00/NatureOfCode-Examples-Python | /chp04_systems/NOC_4_09_AdditiveBlending/NOC_4_09_AdditiveBlending.pyde | 667 | 3.6875 | 4 | # The Nature of Code - Python Version
# [kidult00](https://github.com/kidult00)
# Smoke Particle System
# This example demonstrates a "glow" like effect using
# additive blending with a Particle system. By playing
# with colors, textures, etc. you can achieve a variety of looks.
from ParticleSystem import ParticleS... |
161ba559bcb612424ef00dbb56da7548df9cc522 | KhachatryanGor86/Intro-to-Python | /week2/Practical/problem10.py | 216 | 3.515625 | 4 | import datetime
import time
import calendar
tod = datetime.datetime.today()
days5 = datetime.timedelta(days=5)
print(tod)
print(tod.year)
print(tod.month)
print(tod.weekday())
print(tod - days5)
print(tod + days5) |
058c36b6de08695a863062f4568c9b75df72ebf4 | bkoh1782291/bkoh1782291 | /2021/s1/ai/py2/tictt.py | 7,764 | 4.03125 | 4 | # Brian Koh
# a1782291
# Artificial Intelligence Assignment 1
# usage : $ python tictactoe.py [state] [path]
import sys
import copy
import math
# defines which player's turn at the current game board
def curr_player(board):
X_count = 0
O_count = 0
for i in range(3):
for j in range(3):
... |
fcc08b3c83eaa453a0cb049ed8e37a639c34e82e | arima0714/AtCoder | /ABS/PracticeC.py | 140 | 3.8125 | 4 | # 入力は1行の文字列
input_str = input()
result = 0
for index in input_str:
if index == "1":
result += 1
print(result) |
7fa9696dc5b6e9685ac55fb4967b040b284eeb8c | demetriuspine/pythonPracticing2020 | /URIonlineAndFatec/ADS_ALP_001.py | 382 | 3.609375 | 4 | soma = 5 + 2
subtrai = 5 - 2
multiplica = 5 * 2
divide = 5 / 2
x,y = divmod(5, 2)
w = pow (5,2)
print("Soma 5 e 2 = %04i " % (soma))
print("Subtrai 2 de 5 = %i " % subtrai)
print("Multiplica 5 por 2 = %i " % multiplica)
print("Divide 5 por 2 = %06.2f " % divide)
print("5 dividido por 2 = %i e Resto da divisão... |
043657304f48dc92ef742c980e63af3bb2aba63d | chxj1992/leetcode-exercise | /subject_lcci/10_01_sorted_merge_lcci/_1.py | 754 | 3.9375 | 4 | import unittest
from typing import List
class Solution:
def merge(self, A: List[int], m: int, B: List[int], n: int) -> None:
i = 0
while B:
if i >= m or B[0] < A[i]:
A.insert(i, B.pop(0))
m += 1
A.pop()
i += 1
class Test(uni... |
3c7a1fe1e6273220c4036816e16408bdc9fc1646 | biao111/learn_python | /list/demo2-7.py | 250 | 3.84375 | 4 | #已知一个列表,存储1到10的元素遍历循环列表中的所有偶数
list = [1, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10]
i = 0
for list1 in list:
if list1 % 2 == 0:
i += 1
print("第{}个偶数{}".format(i , list1) )
|
7fa5ff7d7333ddc6e41feac4cb642bc04bb5e8da | Muhammad-Salman-Hassan/Python_Basic | /BubbleSort.py | 355 | 3.84375 | 4 | def bsort(arr):
for i in range(0,len(arr)-1):
for j in range(1,len(arr)-i):
if arr[j]<arr[j-1]:
swap(arr,j,j-1)
def swap(arr,index_1,index_2):
temp=arr[index_1]
arr[index_1]=arr[index_2]
arr[index_2]=temp
arr=[25,1,3,4,5]
bsort(arr)
for i in range(len(arr... |
04a69666d587d182d4f6fdbcbeaf170904884181 | yeldred/Pratique | /test1.py | 1,886 | 3.9375 | 4 | """nomTexte = "Hello world \n thats good"
print(nomTexte)
for val1 in range(20):
val1 += 1
print(val1)
valeur1 = "Bonjour"
var1 = (valeur1[1:3])
var2 = (valeur1[3:5])
print(var1 + var2)
valeur2 = input("entrer le premier valeur")
valeur2 = int(valeur2)
valeur3 = input("entrer la dexieme valeur")
valeur3 = i... |
4eb58072a702a58c4f80737f3738197f3b815d50 | gilsonaureliano/Python-aulas | /python_aulas/desaf079_lista_lacarvalorsemlimite.py | 505 | 4 | 4 | lista = list()
while True:
n = (int(input("Digite um numero: ")))
if n in lista:
print('Valor duplicado! Não adicionado...')
else:
lista.append(n)
print('Valor adicionado com sucesso!!!')
while True:
s = str(input('Quer continuar [S/N]')).upper().strip()
if s not... |
f5aa7fd35b945ec642ea5856b857cf8b77d0c011 | MrJustPeachy/CodingChallenges | /Kattis/Difficulty - 1/Difficulty - 1.2/stones.py | 92 | 3.578125 | 4 | stones = input().strip()
if int(stones) % 2 == 0:
print("Bob")
else:
print("Alice") |
85d218ee599843c4c20b28188b324a1b22e5732a | NoJhonnie/Github | /learnpython/practice/ex41.py | 4,137 | 3.5 | 4 | #coding=utf-8
from sys import exit
from random import randint
def death():
quips = ["You died. Youkinda suck at this.",
"Nice job, you died ...jackass.",
"Such a luser.",
"I have a small puppy that's better at this."]
print quips(randint(0, len(quips)-1)) #在quips随机选出一个死亡表... |
0c8815a5b6435a36547f2501a2fe7893978f4f2c | Ryan-Nguyen-7/ICS3U-Unit5-04-Python | /cylinder.py | 984 | 4.4375 | 4 | #!/usr/bin/env python3
# Created by Ryan Nguyen
# Created on January 2021
# This program uses a function to calculate
# the volume of a cylinder
import math
def calculate_volume(radius, height):
# This function calculates volume of a cylinder
# process
volume = math.pi * (radius ** 2) * height
#... |
77e36da487ddbb6c3094f98668df5c7a6bb15e80 | byui-cse/cse210-student-solo-checkpoints-complete | /07-snake/snake/game/food.py | 1,804 | 3.984375 | 4 | import random
from game import constants
from game.actor import Actor
from game.point import Point
class Food(Actor):
"""A nutritious substance that snake's like. The responsibility of
Food is to keep track of its appearance and position. A Food can move
around randomly if asked to do so.
Stereot... |
555a9808a257c00a18ac0b8cd5b5d4535c4a37f0 | farrukhkhalid1/100Days | /Day20+21/scoreboard.py | 985 | 3.703125 | 4 | from turtle import Turtle
ALIGNMENT = "center"
FONT = ('courier',24,'normal')
class ScoreBoard(Turtle):
def __init__(self):
super().__init__()
self.score = 0
self.high_score = 0
with open("highscore.txt",'r') as file:
self.high_score = int(file.read())
self.penu... |
846b7850a0b095c0dd96398bc31526e876b5ded3 | gandrew313/Python | /bitwise.py | 104 | 3.734375 | 4 | a = 10
b = 5
print('a =', a, '\tb = ', b)
a = a ^ b
b = a ^ b
a = a ^ b
print('a =', a, '\tb =', b)
|
f55bc767736aa207fbd1f37e65b8c6dcc6f97a04 | SumalathaGorla/dsp_lab | /lab4_accumulator.py | 256 | 3.65625 | 4 | import numpy as np
n=int(input("enter number number of samples:"))
x=[]
for i in range(n):
y=int(input("enter samples:"))
x=np.append(x,y)
print("entered samples:",x)
y=[]
s=0
for i in range(n):
s=s+x[i]
y=np.append(y,s)
print("accumulator result:",y)
|
6763b76de69aac9314e3bfe3d7d3dd9d9654a854 | MUSE-UIUC/SpellingCorrection | /candidates/closest_words/closest_words.py | 896 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 20, 2017
This program
(1) for each given input word, find a list of closest words
"""
import difflib
from nltk.corpus import words
'''
Helper Functions
'''
'''
Find a list of closest words for each input word
input:
word - input word
n0 - (optional, defaul... |
4f01a133405a752e9344d66da8eb60775663ce53 | saiharsha8461/machine-learning-assignment | /Pro5.py | 185 | 3.765625 | 4 | s = input("Enter the string: ").lower()
d = dict()
for l in s:
d[l] = d.get(l, 0)+1
print("Occurance of characters in a string")
for k, v in d.items():
print(f'{k}-{v}')
|
3f9f117f8df28787dc35a2af0a21bb6a6f206a99 | StraightDraw/stats | /_build/jupyter_execute/sb/1.py | 1,512 | 3.84375 | 4 | # 1.1 Narcissism
from datascience import *
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plots
plots.style.use('fivethirtyeight')
I keep some data frames in CSV format accessible from my website. One of them is called `personality.csv` and has, as you might imagine, personality variables. In this... |
335e5dd25faa149115654b6f51943413e73ef814 | AtheeshRathnaweera/Cryptography_with_python | /symmetric/streamCiphers/stream.py | 718 | 3.765625 | 4 | #Those algorithms work on a byte-by-byte basis. The block size is always one byte.
#Two algorithms are supported by pycrypto: ARC4 and XOR.
#Only one mode is available: ECB. (Electronic code book)
from Crypto.Cipher import ARC4
def encryptionMethod(textToEncrypt):
key = "myKeY" # can use any size of key
obj... |
088740ecc9e635ec8fc217556107ba12b442a52d | Mozartt/Mozartt | /STT_Providres/Google_STT_File.py | 3,155 | 3.515625 | 4 | """Streams transcription of the given audio file."""
import io
import time
# beta library. supports more configurations that are still being tested.
from google.cloud import speech_v1p1beta1 as speech
from google.oauth2 import service_account
import time
class STTFromStreamGoogle:
def __init__(self):
self... |
5ddf38be54730a76316a9f38cc9a31a445c880e3 | SohanJadhav/python_assignments | /Assignment13/Advertisement_Casestudy.py | 715 | 3.546875 | 4 | import pandas as pd
from sklearn.linear_model import LinearRegression
def main():
data = pd.read_csv("Advertising.csv")
# print(data)
TV= data.TV
Radio= data.radio
Newspaper= data.newspaper
# TV = TV.reshape((-1,1))
# Radio = Radio.reshape((-1,1))
# Newspaper = Newspaper.reshape((-1,... |
9eab7ab05d1a5d4db9740dd0b39b0b89024f1080 | Suryamadhan/9thGradeProgramming | /CPLab_18/DigitCounterRunner.py | 611 | 4.25 | 4 | """
Lab 17.1 Digit Counter
---------
This lab counts the digits on the input number. You will
be using while loops
"""
from DigitCounter import *
def main():
"""Test Case"""
numDigits = DigitCounter(34567)
#print("There are ", numDigits.countDigits(), " digits in ", 34567)
number = int(input("W... |
99e1e6ad75f4beea73cca9080d8b4e8c8434a2ce | ak-b/Problem-Solving | /two_pointers/two_pointers01.py | 1,905 | 4.21875 | 4 | '''
Given an array of sorted numbers and a target sum, find a pair in the array whose sum is equal to the given target.
Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target.
Example 1:
Input: [1, 2, 3, 4, 6], target=6
Output: [1, 3]
Explanation: The number... |
aa7e023a80453574d6332e51087709505908e368 | bridgecrew-perf7/StreamLit_Test | /streamlit.py | 3,991 | 3.703125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/markinvd/StreamLit_Test/main/water_potability.csv')
df.sample(5)
# In[3]:
df.fillna(df.mean(), inplace=True)
# In[5]:
#separando em treino e teste
X = df.drop('Potability',axis='columns')
y... |
ebb7f16d9159536790758b83869666f80c25db08 | sersavn/practice-codesignal | /Arcade/Intro/SortByHeight.py | 386 | 3.859375 | 4 | #For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be
#sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190].
def sortByHeight(a):
b = sorted([elements for elements in a if elements != -1])
c = []
counter = 0
for h in a:
if h == -1:
c.append(h)
else:
... |
d444bd3a78bc10397700fc4ddb187862f0cc1c2a | Deepanshu4712/firstProject | /fhandle.py | 3,285 | 3.96875 | 4 | import pickle
class Employee():
def __init__(self, name, designation, noHours, payRate):
self.name = name
self.designation = designation
self.noHours = noHours
self.payRate = payRate
def __str__(self):
return """\n\nName : %s\nDesignation : %s \nNo. of hours w... |
520358b7d9b80e3151d57854e5b19712d9dec756 | Moncefmd/lettermastercheat | /Trie.py | 774 | 3.796875 | 4 | from Node import Node
class Trie:
def __init__(self):
self.root = Node("*")
def add_string(self, word):
curnode = self.root
for letter in word:
temp = curnode.get_child(letter)
if temp is not None:
curnode = temp
else:
... |
29707743551e3d23a5ed722d22c752b3eabfbd25 | srinivasdasu24/Programming | /GUI Programming/controlling_mouse.py | 1,442 | 3.796875 | 4 | """
Documentation :pyautogui.readthedocs.org
Installation : pip install pyautogui
This program explains how to control the mouse using python
If you want to stop the program move the mouse to the top left corner as mouse control we are giving to program to make it stop
Raises FAILSAFE error when it encounters issue
... |
6ddc3ad68044f8458286a950f018ba594a079e6f | OrdinaryCoder00/CODE-WARS-PROBLEMS-SOLUTIONS | /7Kyu - Product of Array Items.py | 338 | 3.9375 | 4 | def product(numbers):
# Implement me! :)
# sure darling ;-)
result = 1
#checking whether list of numbers are NONE or EMPTY
if(numbers==None or numbers==[]):
return None
else:
#looping through the numbers.
for num in numbers:
result = result * num
return... |
6753ff59653ce19c624f93b95626569690432e45 | CarlosAmorim94/Python | /Exercícios Python/ex061_Progressão aritmetica V2.py | 432 | 3.828125 | 4 | """
EXERCÍCIO 061: Progressão Aritmética v2.0
Refaça o EXERCÍCIO 051, lendo o primeiro termo e a razão de uma PA, mostrando
os 10 primeiros termos da progressão usando a estrutura while.
"""
primeiroTermo = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razão: '))
termo = primeiroTermo
cont = 1
w... |
62c04cccafb2e46d3f1fae6b135111ef09939030 | wakkpu/algorithm-study | /20 Summer Study/greedy/activity_selection.py | 322 | 3.5625 | 4 | def activity_selection(S, F):
L = [0]
k = 0
for i in range(1, len(S)):
if S[i] >= F[k]:
L.append(i)
k = i
return L
if __name__ == "__main__":
S = [1, 3, 0, 5, 3, 5, 6, 8, 8, 2, 12]
F = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
print(activity_selection(S, F... |
e1c1ade765742f2a794a4a3beeee49fe667da10d | nitish24t/DataStructures-Python | /Algorithms/Sorting/SelectionSort.py | 1,166 | 3.9375 | 4 | def selectionSort(arr):
"""
Selects the maximum element and swaps it with the iteration index
"""
n = len(arr)
for i in range(n):
max = (arr[i],i)
for j in range(i,n):
if arr[j] > max[0]:
max = (arr[j],j)
#swap the max index with iteration index
... |
486e4b5afb512ae1f9164e6b6e79d9d155a3ab98 | brellin/game | /src/util.py | 972 | 3.65625 | 4 | from sys import stdout
from time import sleep
class Stack():
def __init__(self):
self.storage = []
self.size = 0
def insert(self, value):
self.storage.append(value)
self.size += 1
def pop(self):
if self.size:
self.size -= 1
return self.stor... |
ceb013a89bebdbcbb8f1941791e0046b7e74035d | changyue-fps/meanshift | /mean_shift/cluster.py | 529 | 3.515625 | 4 | import numpy as np
class Cluster:
"""
Class represents a set of points that belong to the same cluster.
Cluster contains data points and centroid.
"""
def __init__(self, centroid):
self._centroid = centroid
self._points = []
def add_point(self, point):
"""
Add... |
fa67680c009dea050c1e2c07990a518e0228493d | AnnieKL/CS-Basics-in-Python- | /Problem Sets/strings_ak.py | 1,688 | 4.1875 | 4 | # Assume s is a string of lower case characters.
# Write a program that counts up the number of vowels contained in the string s.
# Valid vowels are: 'a', 'e', 'i', 'o', and 'u'.
# For example, if s = 'azcbobobegghakl', your program should print:
# Number of vowels: 5
count=0
for letter in s:
if letter=="a" or ... |
d2beef70e8def3f2061b454a2bd582fa96ed1e7f | JYlsc/leetcode | /code/medium/12.py | 1,042 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/30 10:38
# @Author : Leishichi
# @File : 12.py
# @Software: PyCharm
# @Tag:
class Solution:
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
symbols = {1: "I", 5: "V", 10: "X", 50: "L", 100: "... |
4006399857a18850c01440e3a14c25013c41bb98 | julianascimentosantos/cursoemvideo-python3 | /Desafios/Desafio074.py | 244 | 3.59375 | 4 | from random import randint
sorteio = randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9), randint(0, 9)
print(f'Os valores sorteados foram: {sorteio}')
print(f'O maior valor foi {max(sorteio)}')
print(f'O menor valor foi {min(sorteio)}') |
1e9a45aa699d5e7012360ba507b5a66c44fc3a05 | sam1208318697/Leetcode | /Leetcode_env/2019/7_19/Min_Stack.py | 1,659 | 4.0625 | 4 | # 155. 最小栈
# 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
# push(x) -- 将元素 x 推入栈中。
# pop() -- 删除栈顶的元素。
# top() -- 获取栈顶元素。
# getMin() -- 检索栈中的最小元素。
# 示例:
# MinStack minStack = new MinStack();
# minStack.push(-2);
# minStack.push(0);
# minStack.push(-3);
# minStack.getMin(); --> 返回 -3.
# minStack.pop();
# minStack.top()... |
e52ba6990264a20a36c8fbd257ef98375cf1961b | shahhyash/SearchAndDestroy | /environment.py | 4,119 | 3.75 | 4 | import matplotlib.pyplot as plt
import numpy as np
import random
CELL_FLAT=3 # represented by the color WHITE
CELL_HILLY=2 # represented by the color LIGHT GREEN
CELL_FORESTED=1 # represented by the color DARK GREEN
CELL_CAVES=0 # represented by the color BLACK
# Probabilities of existence; ... |
26007cde384224008b7af40e43af5703a5bc56d1 | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/sldcar001/boxes.py | 775 | 3.875 | 4 | def print_square():
print("*"*5)
print("*","*",sep=" ")
print("*","*",sep=" ")
print("*","*",sep=" ")
print("*"*5)
def print_rectangle(w,h):
#w=eval(width)
#h=eval(height)
print("*"*w)
while h>2:
print("*","*",sep=" "*(w-2))
h-=1
print("*"*w... |
eed85c25517ed4a83a5521310b6d7e39e2260fe5 | glennmatlin/data_structures_and_algorithms | /Arrays & Strings/Two Sum.py | 1,422 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
https://leetcode.com/explore/interview/card/uber/289/array-and-string/1682/
Created on Mon Oct 5 16:17:38 2020
@author: Glenn
"""
# =============================================================================
# nums = [2,7,11,15], target = 9
# Output: [0,1]
# Output: Becau... |
a6ad1c521f0b663931662d5685e20aa4bccbea4a | b08442806/270201068 | /lab1/example6.py | 72 | 3.5 | 4 | x= float(input("a="))
y= float(input("b="))
z= (x**2+y**2)**0.5
print(z) |
d0f3db513b4027273122b3ac8c6531a3b24c10d0 | 418003839/TallerDeHerramientasComputacionales | /Clases/Programas/Tarea4/Problema2S.py | 299 | 3.5625 | 4 | #!/usr/bin/python3.6.7
# _*_ coding utf-8 _*_
""""
Jorge S Martínez Villafan, 418003839
Taller de herraientas computacionales
Dado dos tiempos el programa nos devuelve el valor de su posición y
"""
from Problema2 import y
t= int(input("tiempo 1: "))
t1= int(input("termpo 2: "))
y = v0*t - 1.0/2*g*t1**2
print(y)
|
4a9c533ca8e5e7ed37b2c4b18753fa55ccb07671 | Sranciato/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/101-remove_char_at.py | 143 | 3.75 | 4 | #!/usr/bin/python3
def remove_char_at(str, n):
if n < 0:
return str
start = str[:n]
end = str[n+1:]
return start + end
|
9da54194420772a5e7812b56dc8c190bc3236c36 | fpoposki/Basic-Code-Examples | /Basic Bank Account Class.py | 754 | 3.5 | 4 | class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, dep_amt):
self.balance = self.balance + dep_amt
print(f"Added {dep_amt} to the balance")
def withdrawal(self, wd_amt):
if self.balance >= wd_am... |
6330474d6dcc0bbe9844ec87c5ebff9fad4c4508 | RADHIKA7770/Campus_Recruitment | /Salary_Prediction_Model.py | 6,082 | 3.578125 | 4 | ## Import necessary library for analysis
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
## Load data in pandas df
df = pd.read_csv(r"C:\Users\lenovo\Downloads\DS_Practice\Campus_Recuritment_Model\Placement_Data.csv", index_col=0)
df.head(3)
## Check detail... |
649d362ea70da9f9c9b0eba12b5d2a56f6da8bc3 | milansanders/AdventOfCode2020 | /18/18A.py | 1,663 | 3.90625 | 4 | def pop_elem(line) -> (str, str):
if len(line) == 0:
return None, ""
first = line[0]
if first == "+" or first == "*" or first == "(" or first == ")":
return first, line[1:]
else:
for i in range(len(line)):
if not line[i].isdigit():
return int(line[:i])... |
c46841460774a06444e0fd8453e279163a6a04b4 | polatbilek/python-101 | /5_problem_10_2.py | 307 | 3.828125 | 4 | numbers = [1, 2, 6, 5, 8, 4, 11, -1]
for i in range(len(numbers)):
min_val = numbers[i]
min_index = i
for j in range(i, len(numbers)):
if min_val > numbers[j]:
min_val = numbers[j]
min_index = j
temp = numbers[i]
numbers[i] = min_val
numbers[min_index] = temp
print(numbers) |
70465512f32385a8da83c3baaefbe37df74af015 | vivian-my/LeetCode | /intersection_Linkedlist.py | 820 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
#两个链表 输出相交的node 值
#又是环的思路 快慢指针 一定会相遇 把最后的tail指向头 形成环
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
... |
e89101906ab047d0b57a34bff154d173dd636c51 | cphsiung/Python_Learning | /extractJSON.py | 424 | 3.640625 | 4 | # parse and extract the comment counts from the JSON data, compute the
# sum of the numbers in the file
# http://py4e-data.dr-chuck.net/comments_863165.json
import urllib.request, urllib.parse, urllib.error
import json
url = input('Enter - ')
source = urllib.request.urlopen(url).read()
info = json.loads(source)
sum =... |
7bb6217a0883e60710cb9f63238c03fcc92e1858 | Chandler-Song/sample | /python/io/do_stringio.py | 593 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'StringIO'
# StringIO顾名思义就是在内存中读写str。
# 要把str写入StringIO,我们需要先创建一个StringIO,然后,像文件一样写入即可:
from io import StringIO
f=StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
# getvalue()方法用于获得写入后的str。
print('01.',f.getvalue())
# 要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取:... |
60a9fefdbfb511f8d64bfaef3c7c7cb3085aff75 | joonxz/learnpythonthehardway | /ex33.py | 1,203 | 4.625 | 5 | # EX 33
numbers = []
def printNumbers(number, increment):
i = 0
incrementBy = increment
while i < number:
print(f"At the top i is {i}")
numbers.append(i)
i = i + incrementBy
print("Numbers now: ", numbers)
print(f"At the bottom i is {i}")
"""
for i in range(number):
print(f"At the top of i is... |
10121f8b7b5aeb7a9db197c25b12fa5302ba0c78 | morgan-lang/python | /week06/classes-methods.py | 454 | 3.6875 | 4 | # initialize the class
class Customer(object):
Id = None
Name = None
def ToString(self):
return str(self.Id) + ", " + str(self.Name)
objCustomer1 = Customer() # copy 1 of customer class. using it like a template
objCustomer1.Id = 1
objCustomer1.Name = "Bob Smith"
objCustomer2 = Customer() #... |
661bb517e842150d2b19cc3fb4c397082167cd3b | migcam/demo | /_test_/app_main_test.py | 441 | 3.515625 | 4 | import unittest
from fibonacci import dynamic_fibbo
def test_fibbo__low(self):
expected = 144
value = 12
result = dynamic_fibbo(value)
self.assertEqual(expected, result, "Fibbo pequeño no es igual")
def test_fibbo__big(self):
expected = 2222322446294204455297398934619099672066669390964997649909796... |
d2730942b68614267b46b2e69ca5c3b0f9c54d50 | huine/automatos | /AutomataGenerator.py | 3,688 | 3.5 | 4 | # -*- coding: utf-8 -*-
from Automata import AutomataFunction, AutomataGoTo
import os
class AutomataGenerator(object):
"""."""
def __init__(self):
"""."""
self.qty_symbols = 0
self.symbols = []
self.qty_est = 0
self.states = {}
self.initial = 0
self.qty... |
cd34faf38e62f669c811e39d38d02ca6a2bd20c4 | rafaelperazzo/programacao-web | /moodledata/vpl_data/380/usersdata/346/95115/submittedfiles/principal.py | 1,169 | 3.515625 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
'''
n= int(input('Digite uma quantidade de notas: '))
if n>1:
print(n)
else:
print(int(input('Quantidade inválida, digite novamente: ')))
notas=[]
for i in range (0,n,1):
notas.append(float(input('Digite a nota%d: ' % (i+1))))
media=0
for i in range(0... |
2f9094c15a7e8399d7325e4ee0877a1d839075db | Firestormant/Alguns-projetos-que-eu-gostei | /BibliotecadaFunçãoFinal.py | 2,341 | 3.640625 | 4 | def leia(texto):
import colorama
from colorama import Fore, Back, Style
from time import sleep
colorama.init()
valido = False
while not valido:
entrada = str(input(texto))
animal()
if entrada.isalpha() or entrada.strip()=="":
print(Fore.RED+"ERRO!"+Fore.RESET... |
beeb2c0bdf09af2d53547504507e4f06073daa72 | xingyguy/Data_Homework | /Python Homework/PyBank/main.py | 1,956 | 3.59375 | 4 | import os
import csv
csvpath = os.path.join("Resources", "budget_data.csv")
total = 0
length = 0
difference = 0
previousrow = 0
cumulative_difference = 0
greatestprofit_month = "blank"
greatestprofit_value = 0
greatestdecrease_month = "blank"
greatestdecrease_value = 0
with open(csvpath, newline='') as csvfile:
c... |
d9dd79a6244824b7d71aa3246cf6d64fb001da1b | Evelyn-agv/Ejercicio | /Clase 2/Ejercicio 2.py | 1,373 | 3.984375 | 4 | class Datos():
c=0 # variables de clases
def __init__(self, informar="Inicio"):
self.info=informar #variables de instancia
def datoPersonal(self):
#Númericos
edad, peso= 20, 70.5
#Strings
nombres= 'Evelyn García'
ciudad= "Milagro... |
dd145bce3301f9f8efe1959326507bc42695ad78 | gauravowlcity/GeeksForGeeks | /firstSumPair.py | 641 | 3.578125 | 4 | '''
You have an array of integers. Find the first pair of integers whose sum is equal to k.
'''
def checkpair(arr,k):
arr.sort()
n = len(arr)
l = 0
r = n-1
while l < r:
if arr[l] + arr[r] == k:
return arr[l],arr[r]
elif arr[l] + arr[r] > k:
r -= 1
els... |
530b9f6e7dd31756bda466ab6ae2007e94acff97 | vothin/code | /game/DFW.py | 3,976 | 3.9375 | 4 | import random
list_player = ["狗略略", "狗子月", "狗子霸", "白菜", "狗伊娃", "小水银", "华日酱", "啊兔兔"]
player2 = 0
list2 = []
list3 = ["扣除", "增加", "翻倍", "缩减", "清空", "不变"]
print("欢迎来到文字大富翁游戏!!!")
print("游戏角色分别有:狗略略、狗子月、狗子霸、白菜、狗伊娃、小水银、华日酱、啊兔兔")
# 是否开始游戏
# 选择人物
# 查看人物属性+技能
# 角色特有技能
# 角色不同属性:力量,耐力,智力,精神,舒服,幸运
#... |
cba8b71dbe741cf817119ac0b00d2d943d4bd96a | RelaxedDong/python_base | /面向对象/私有属性.py | 726 | 3.9375 | 4 | #encoding:utf-8
# __author__ = 'donghao'
# __time__ = 2019/1/12 15:59
class Woman(object):
def __init__(self,name):
self.name = name
self.__age = 18
def secret(self):
print('%s的年龄是%s'%(self.name,self.__age))
self.__ask_age()
def __ask_age(self):
print('... |
86df621f501b13d15e2a8c1fb629d5185e6c2f13 | dinnu814/Python | /IIEC/duplicates.py | 222 | 3.546875 | 4 | input = [1,2,3,4,4,6,6,7,8,9]
output = []
uniqItems = {}
for x in input:
if x not in uniqItems:
uniqItems[x] = 1
else:
if uniqItems[x] == 1:
output.append(x)
uniqItems[x] += 1
print(output) |
2c01bc9186c9bbda57678e8e46d18ad56fb0d077 | summershaaa/Data_Structures-and-Algorithms | /剑指Offer/剑指28_对称的二叉树.py | 1,075 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 2 10:43:14 2019
@author: WinJX
"""
#剑指28:对称的二叉树
class TreeNode:
def __init__(self, x,left = None,right = None):
self.val = x
self.left = left
self.right = right
class Solution:
def isSymmetrical(self,root):
... |
3ae02997774bd19626965989a85ea8bbf525a926 | deepiml/lpthw | /exercise15.py | 222 | 3.71875 | 4 | from sys import argv
script,filename=argv
txt=open(filename)
print "the filename is %r"%filename
txt.read()
print "am typing it again"
file_again=raw_input('>')
txt_again=open(file_again)
print 'txt_again.read()'
|
1018b5721ecfc37f4f73dff7476a15686411f3ce | AidenSmith09/Python | /Day19_Test_Code/shopping_cat_0.py | 2,106 | 3.703125 | 4 | # /bin/etc/env Python
# coding: utf-8
"""
功能要求:
要求用户输入总资产,例如:2000
显示商品列表,让用户根据序号选择商品,加入购物车
购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
附加:可充值、某商品移除购物车
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
"""
"""
money = input一个总的资产,用于存储。
""... |
259237f79efc1b4cbc38431206697afa849b218f | jesset685/temperature_converter | /03_f_to_c_v1.py | 464 | 4.1875 | 4 | # quick component to convert degrees C to F.
# Function takes in value, does conversion and puts answer into a list.
def to_celsius(from_fahrenheit):
celsius = (from_fahrenheit -32) * 5/9
return celsius
# Main routine
temperatures = [0, 32, 100]
converted = []
for item in temperatures:
answer = to_celsi... |
c48d2016a2ae6d9d88b8449cf8830226e9279732 | nsmertiya/iplstats-visulaization-app | /batsmen_app_page.py | 2,641 | 3.609375 | 4 | '''
Script for Visualising and Dislaying Batsmen's Stats IPL
'''
import base64
import streamlit as st
import altair as alt
from get_stats import batsmen_stats_dataframe
from config_file import feature_plot_mapping
from config_file import batting_stats_features
def app(timeline):
'''
Function: to re... |
21535927f162c5a204bda4434c0733458a4ce802 | Prashant-Mohania/PracticePython | /before/dict_ex1 cube_finder.py | 154 | 3.734375 | 4 | def cube_finder(n):
num = {}
for i in range(1,user+1):
num[i] = i**3
return num
user = int(input("enter:- "))
print(cube_finder(user)) |
36e7ba329c59e0136d4dbb47c2e04a9e17c13f51 | faft37/Python-Projects | /cdTime.py | 2,649 | 4.25 | 4 | # Name: J. Carter Haley
# cdTime.py
#Problem: This program aims to help your friend, Jimmy, by creating a
#program that can output the total time for each cd in his shop both
#individually and as a whole.
#Certification of Authority:
#I certify that this lab is entirely my own work.
#The input that the user... |
b1773d448758815ba95021f8cd771b658c29a04d | gabriellaec/desoft-analise-exercicios | /backup/user_143/ch20_2020_03_04_19_16_35_894948.py | 200 | 3.703125 | 4 | # Pergunta quantos km
qts_km= float(input('quantos km:'))
def P(qts_km):
if qts_km <= 200:
P=qts_km*0,5
return P
else:
P=qts_km*0,45
return P
print (P)
|
70898fe8e2f6cf6953477c55f7960b7bda7879fd | greenfox-zerda-lasers/gygabor | /week-06/refactoring/model_tkwanderer.py | 4,774 | 3.609375 | 4 | import csv
from random import randint, choice
class Area:
def __init__(self):
self.game_area = []
self.read_area()
# read Area map from area.csv
def read_area(self):
with open('../area.csv', 'r', newline='') as csvfile:
reader = csv.reader(csvfile)
for i in... |
7aa6f6d7ea6986a3bae0b4d104c29259e837aad3 | taitujing123/my_leetcode | /013_roman2Int.py | 1,255 | 3.578125 | 4 | """
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
C 可以放在 D (500) 和 M... |
fa593d18b7777ef528a103fe9f605e7ca4c089f8 | dunaldo/checkio-solutions | /checkio.org/Elementary/FizzBuzz.py | 307 | 3.859375 | 4 | """FizzBuzz on checkio.org."""
def checkio(x):
"""Checking things."""
if x % 3 == 0 and x % 5 == 0:
return "Fizz Buzz"
elif x % 3 == 0:
return "Fizz"
elif x % 5 == 0:
return "Buzz"
else:
return str(x)
l = int(input())
print(checkio(l))
|
e6232d82b31d22982999b6d6a356969223148ec6 | MartaJJ/zajecia_schedule_misp | /phoneNumber.py | 1,018 | 3.765625 | 4 |
class Numery():
def __init__(self,numer):
numer= str(numer)
self.numer=numer
self.slownik_cyfr = {"0":'zero', "1":'jeden', "2":'dwa', "3":'trzy', "4":'cztery',
"5":'pięć', "6":'sześć', "7":'siedem', "8":'osiem', "9":'dziewięć'}
self.... |
0838efd03c44daa0e57a87341bf3a0ff3ee8d6a5 | DoctorSad/_Course | /Lesson_10/_0_argparser.py | 1,777 | 4 | 4 | """
Применение argparser на примере генератора паролей
"""
import argparse
import random
from string import ascii_lowercase, ascii_letters, digits, punctuation
def gen_password(chars, length=8):
"""Базовая функция для генерации пароля"""
password = ""
for _ in range(length):
password += rando... |
112b5e25de87cac2926d6247278df17256309d26 | JDKdevStudio/Taller30Abril | /33.AñoBisiestoOrNot.py | 181 | 4 | 4 | año = int(input("Escriba el año que desea analizar"))
if año % 4 == 0 and (año % 100 != 0 or año % 400 == 0):
print("Es bisiesto")
else:
print("No es bisiesto")
|
5d5f240c6957e43ce5157fa9a3507a362c47cbd5 | way2arun/datastructures_algorithms | /src/arrays/unique_chars_solution_3.py | 480 | 4.03125 | 4 | # Time complexity :- O(n)
# We are using only 1 loop and python string count function
def unique_char_count(input_string):
# Initialize the total
total = 0
for i in input_string:
count = input_string.count(i)
if count > 1:
# If count is more increment the total
tota... |
4c319691461441c6480fc1eb8f77e533acb70162 | BigWillieN/PoliTO-Schoolwork | /Labs/Lab03/ex02.py | 740 | 4.1875 | 4 | "Exercise 3.2"
def ex2():
#This function translates letter grade into numerical grade
#Input
grade = input("Enter your letter grade:")
#Processing
if grade.upper() == "F":
number = 0.0
elif grade.upper() == "D-":
number = 0.7
elif grade.upper() == "D+":
number = 1.... |
1624b31007f901f402bbb32f794109219803647b | Gabe-flomo/Linked-lists | /linked_list.py | 4,554 | 4.0625 | 4 | from box import Box
class LinkedList:
def __init__(self,node = None):
self.node = node
self.length = 0 if node is None else 1
def _len(self):
return self.length
def insert(self,data):
'''
Inserts a new node starting from the head.
Once the head is initi... |
81fa204d1a5a6528378a6f6f6572d94747da80f2 | Anton1579/Python-2 | /lesson2.py | 7,369 | 4.09375 | 4 | # 1. Создать список и заполнить его элементами различных типов данных.
# Реализовать скрипт проверки типа данных каждого элемента.
# Использовать функцию type() для проверки типа.
# Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
a = ['4', 45.6, None, 'Name', 34, 2.4]
for i in a:
... |
7822c127a756a309d393195758129d208d01b533 | donaldjnavarro/game_dungeon | /roster.py | 2,712 | 3.84375 | 4 | import json
from prompt import prompt
def get_roster():
# Set a roster variable based on a local json of characters
with open('roster.json') as json_file:
return json.load(json_file)
def display_roster():
# Display the roster
# 1. Grab the roster from a local json file
# 2. Loop through th... |
7ca58124b4d0724dc88eeaecf85ab77d64bb5e98 | wwwenguo/Python_Projects | /Basics/Day3.py | 2,509 | 4.09375 | 4 | # Odd or Even
num = input("Please enter an int number: ")
num = int(num)
if num % 2 == 1:
print("This is an odd number.")
else:
print("This is an even number.")
# Leap year
year_num = input("Please enter the year: ")
year_num = int(year_num)
if year_num % 4 == 0:
if year_num % 100 == 0:
if year_num... |
8e5fb1cdf935b11415df5d8d2057ddf1ecf036ce | Tim-mhn/dominant_set | /submission/dominant_glouton.py | 2,007 | 3.5 | 4 | import sys, os, time
import networkx as nx
def dominant_glouton(g):
"""
A Faire:
- Ecrire une fonction qui retourne le dominant du graphe non dirigé g passé en parametre.
- cette fonction doit retourner la liste des noeuds d'un petit dominant de g
:param g: le gra... |
406c6ba62cf54c075f43e752f990fc8d4981384b | leksiam/PythonCourse | /Practice/S.Mikheev/exam/task_9.py | 851 | 3.703125 | 4 | class User:
name = None
age = None
def setName(self, name):
self.name = name
def getName(self):
return self.name
def setAge(self, age):
self.age = age
def getAge(self):
return self.age
class Worker(User):
salary = None
def setSalary(self, salary):
... |
2698613876d07c268d9520ee8b0ece7ecdfc90a1 | tayyabmalik4/python_GUI | /26_More_functionality_GUI.py | 547 | 3.890625 | 4 | # (26)**********************More funtions in GUI*******************************
from tkinter import *
root = Tk()
root.geometry("1000x780")
root.title("CodeWithTayyab - Title of My GUI")
root.wm_iconbitmap("Excercises/img/2.ico")
root.configure(background='grey')
# ----when we retrive the width and height we use this... |
e7c7033c4139dc4c9b305b61f3a31114ecc1f939 | Pauloa90/Python | /ex076.py | 264 | 3.578125 | 4 | tabela = ('Impressora', 350,'Tv', 1250, 'carro', 25000)
print('-'*40)
print(f'{"Listagem de Precos":^40}')
print('-'*40)
for x in range(0, len(tabela)):
if x % 2 == 0:
print(f'{tabela[x]:.<30}', end='')
else:
print(f'R${tabela[x]:>7.2f}') |
5510de167c7489a64578c458377f5d2ef45f8fbb | KimaniBobby/Lecture8 | /assignment_2_2.py | 345 | 3.96875 | 4 | #Profit and total revenue
#assignment_2_2.py
def main():
print("This program helps calculate the profit of Company X")
#profit = 23% of total revenue
total_revenue = int(input("Please enter the total revenue:"))
profit = 0.23 * total_revenue
print("The profit for Company X is:",profit)
main(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.