blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6cdc8542860c62b17905c103bb06e8a451726d67 | Jashwanth-k/Data-Structures-and-Algorithms | /3.Time Complexity Analysis/print Prime numbers.py | 190 | 3.65625 | 4 | n = int(input('enter :'))
for i in range(1,n+1):
if i > 1:
for j in range(2,i):
if i % j == 0:
break
else:
print(i,end=' ') |
d6f3036f5869236f9bd1a739cb1027c99b0fbfa4 | krishcmd/Random_Python | /pong.py | 1,281 | 3.6875 | 4 | from random import choice, random
from turtle import *
from freegames import vector
def value():
return (3+random()*2)*choice([1,-1])
#randomly generate value between (-5,-3) or (3,5)
ball = vector(0,0)
aim = vector(value(),value())
state = {1:0,2:0}
def move(player,change):
#Move player position by change
state... |
a624f203e908b4fdd16e907e4854d8ddd060fbe4 | AoifeNicAntSaoir/LearningPython | /HelloWorld.py | 3,238 | 4.21875 | 4 | import time
import calendar
#print
print "Hello, Python"
#Continuation Character
item1 = "Bread"
item2 = "milk"
item3 = "eggs"
total = item1 + \
item2 + \
item3
days = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday"]
#String literals
word = 'word'
sentence = """This is a sentence mad... |
9e719189360e4700d9b4d7afceba4de4265418e0 | valeriacavalcanti/APE-2017.2 | /Aulas/03 - 28_11_2017/lista1.py | 202 | 3.84375 | 4 | qtde = 0
lista = [1,2,3,5,5,5,5,5,5,7,8]
numero = int(input("Informe um valor: "))
for i in range(len(lista)):
if (lista[i] == numero):
qtde += 1
print("Quantidade = ", qtde)
|
f39ba6be3471da683a18ad76bc6e161ebbe33c15 | DavidBrionesFF/Curso-Programacion-Python | /capitulos/entrada_salida/capitulo3.py | 1,497 | 4.25 | 4 | # Entradas, salidas de datos, y casting
print("Hola me llamo xd dame tu nombre y tu dinero xd")
nombre = input()
print(f"Me alegro de conocerte {nombre}")
print(f"Ahora por favor {nombre}, dame tu dinero")
dinero = int(input())
print(f"Genial {nombre} que andas {dinero}$")
print(f"Pero te regalare mejor unos 40$ para q... |
c02eda7fe557af84c459d1dcd197e2e32f70dbec | zthxxx/sniputils | /src/conffor/conffor.py | 853 | 3.546875 | 4 | """
Some function for read and write json config file.
"""
import json
from ..snippets import ensure_dir_exist
def load(file: str):
"""
load json file with default options
:param file: file path to load
:return: json data as python object
"""
with open(file, 'r', encoding='utf-8') as jsonfi... |
b48113f8e4294cd1e5e32458ab981a440c27d345 | Abhi5241/Python-Practice-Programs | /primeNumbers.py | 207 | 3.984375 | 4 |
upper=int(input("enter the upper interval:\n"))
for num in range(0,upper+1):
if num>1:
for i in range(2,num):
if(num%i==0):
break
else:
print(num) |
e1481d0d5c51c9bbf2cec41ac223e42ef2fda1a1 | dkramorov/astwobytes | /apps/binary_com/math_operations.py | 6,306 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
class MathOperations:
"""Различные математические операции"""
@staticmethod
def sma(points: list, cur_position: int, diff: int) -> float:
"""SMA: Простое скользящее среднее
Это тоже самое, что и среднее арифметическое
:... |
bcffb84ac4d72de5f535f3032228f3ad574d3363 | WellingtonTorres/PythonExercicios | /ex083.2.py | 305 | 3.859375 | 4 | cont_esq_ = cont_dir_ = 0
expressao_ = str(input('Digite a expressão: '))
for simb in expressao_:
if simb == '(':
cont_esq_ += 1
elif simb == ')':
cont_dir_ += 1
if cont_esq_ == cont_dir_:
print('Sua expressão está correta!')
else:
print('Sua expressão está errada!')
|
a7b3c1e68fe3fa494362b167f49a1354c26bce37 | 13204942/LeetCode_Codeforces_solutions | /342_Power_of_Four.py | 1,407 | 3.796875 | 4 | """
Author: Wang, Fangyijie
Date: Feb 01, 2017
Problem: Power of Four
Difficulty: Easy
Source: https://leetcode.com/problems/power-of-four//
Descriptions:
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Give... |
a530c8e6c75d9b88d152d0fcfa883dfdb0a96990 | hackersploitxxsploitation/Rede-neural-Python3 | /Rede neural simples em Python sem backprophation.py | 212 | 3.71875 | 4 | import math
print("digite os inputs dos neurônios:")
n=float(input())
y=float (input ())#camada de entrada
p1=2
p2=3 #camadas oculta
S=n*p1+n*p2+y*p1+y*p2
n1=1/(1+math.exp (-S))#saida
print(n1)
|
b3e64490d64c77fd50076ae3a9efe60865703c11 | SueAli/cs-problems | /UVA/11906 - Knight in a War Grid.py | 1,564 | 3.578125 | 4 |
from collections import deque
# Time complexity is R * C as each grid will be visited once
while True:
try:
T = int(input())
for t in range(T):
R,C,M,N = map(int,input().split())
W = int(input())
grid = [[0 for c in range(C)] for r in range(R)] #0 means it is unvisited grid
for w ... |
a54c39a0f93db3c997dbd873a8ed309584c4f00c | devinitpy/devinitpy.github.io | /intro/hanna.py | 542 | 4.0625 | 4 | print("what is your name")
name=raw_input("my name is: ")
if name=="derrikk":
print("nice name")
else:
print("oh okk")
print("how old are you")
age=input("my age is: ")
if age>28:
print("you are quite old")
else:
print("wow i see")
print("how tall are you")
height=input("my height is: ")
if height<59:
... |
1d719d5a68b56209199fd80cdc155c35a03b1917 | csvoss/onelinerizer | /tests/12lines.py | 427 | 3.65625 | 4 | ## inspired by https://wiki.python.org/moin/SimplePrograms
class BankAccount(object):
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def overdrawn(self):
... |
0c5e0b20254ca9d2ea71a5599ed6ec2d397bb3c2 | zrowland885/posim | /src/posim/velocities.py | 447 | 3.625 | 4 | # -*- coding: utf-8 -*-
""" Velocity functions to define movement speed and direction """
def random(t, params):
""" Random velocity """
import random
if params == None:
b_min = 0.1
b_max = 1.0
else:
b_min = params['min']
b_max = params['max']
velocity = random.unifo... |
56802451a93926d25d92cc3f0b7ba23254653667 | santhosh-kumar/AlgorithmsAndDataStructures | /python/test/unit/problems/array/test_rearrange_array.py | 641 | 3.546875 | 4 | """
Unit Test for rearrange_array
"""
from unittest import TestCase
from problems.array.rearrange_array import RearrangeArray
class TestRearrangeArray(TestCase):
"""
Unit test for RearrangeArray
"""
def test_solve(self):
"""Test solve
Args:
self: TestRearrangeArray
... |
5837b5a917fb1256e55fca15f2abdd7838017201 | julianofhernandez/ctf | /examples_of_ctf_vs_csv/ctfCityAvgFunding.py | 708 | 4.03125 | 4 | import ctf
# CTF version of a program that reads in a csv file with data on venture capital funding and computes
# the average amount of a funding each american city has then prints it
with Ctf.DictReader("TechCrunchcontinentalUSA.ctf") as reader:
cities = {} #dictionary with key as city and two values as c... |
0df5b5f7ff18b0b00cc0b1b3e279714f682014f2 | hmarcuzzo/distributed-systems-exercises | /Programação com Representação Externa de Dados/client/client.py | 9,500 | 3.71875 | 4 | """Este código é responsavel pela parte do cliente e comunicação com o servidor, ele ira tratar o envio o dos dados
em formato Protocol Buffer ou JSON, via socket TCP.
Protocolo de envio:
1a Mensagem: Tipo de representação dos dados (protobuf ou json).
2a Mensagem: Tipo de requisição (inserção, deletar ou cons... |
706fdf6cc2a07a7dc2d9519ec9f01be8cede5eb2 | juanlozanodbz/Mision-07 | /mison07.py | 1,193 | 4 | 4 | #Autor: Juan Sebastián Lozano Derbez
# Programa que utiliza whiles para ejecutar funciones
def hacerMenu():
print("""Misión 07, Funciones:
1. Calcular divisiones
2. Encontrar el mayor
3. Salir""")
selection = int(input("Selecciona la función que deseas ejecutar: "))
return selection
def calcu... |
1b91218c672c984ea3662b82cdb6f3d068b9a0d4 | atinfosec/Simple-PortScanner | /portScanner.py | 1,486 | 3.671875 | 4 | #!/usr/bin/env python3
import argparse
import socket
def sockConnect(ip,port):
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
try:
s.connect((ip,port))
except:
print('No connection established for {}:{}'.format(ip,port))
try:
s.send(b'testing\r\n')
result = s.recv(1024)
print... |
b6693f72499d93a37f430d9c88a2c1d117f399f8 | artsR/Automate-the-Boring-Stuff-with-Python | /Chapter 14/Chapter 14 - csv.py | 1,131 | 3.96875 | 4 | ############ CHAPTER 14 ############
import csv
csvFile = open('csv_example.csv')
csvReader = csv.reader(csvFile)#(1)'Reader' Object can be looped only once.
data = list(csvReader) # list of lists.
print(data[4][2])
csvFile = open('csv_example.csv')#(1)'Reader' was called before therefore
csvReader = csv.r... |
e2a8580775731521a644f3cd4bb12c2e70323f58 | ReduceKiller/Beginner-bot-python | /chatbot/For loop test.py | 841 | 3.703125 | 4 | __author__ = 'ddpha2'
#x = "cat"
#y = "dog"
#print(x + y)
#words=["cat","dog","fish","sugar glider","frog","rabbit"]
#animals = " "
#combine each item in the list into one string
#for item in words:
# animals = animals + " " + item
#print(animals)
#a = str(open("macvspc.txt").readlines()[0]).lower()
#a = a.re... |
f745af7ec18b1a21f7a3fde9cd3d748234c64d1c | AaronTengDeChuan/leetcode | /leetcode/110.BalancedBinaryTree.py | 1,143 | 3.859375 | 4 | #!usr/bin/env python
#-*-coding:utf-8-*-
import sys
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def getHeight(self, root):
if root == None:
return 0
left = self.getHeight(root.left)
... |
5d5393e37535d381fca55d4029e0f6029d2ebfce | ppbox/leetcode_solutions | /0060_Permutation_Sequence/Solution1.py | 914 | 3.515625 | 4 | class Solution:
def getPermutation(self, n: int, k: int) -> str:
fac = [1] # 阶乘的list,fac[i] = i!
for i in range(1, n + 1):
fac.append(i * fac[i-1])
num_char = ''.join([str(i+1) for i in range(n)]) # num_char 存放字符,如n=4,则num_char = '1234'
res = ''
k -= 1
... |
204327cc7bb9a9a60f89b083a366a4b855eee577 | gissellemm/girlswhocodeprojects | /test.py | 679 | 4.09375 | 4 | from random import *
aRandomNumber = randint(1, 20)
#print(aRandomNumber)
tries = 1
while tries <= 3:
tries += 1
guess = input("Guess a number between 1 and 20 (inclusive): ")
if not guess.isnumeric():
print("That's not a positive whole number, try again!")
else:
gues... |
0dcde5e632af83b89c4631762cf8838197ad521f | jdfrancop/probando | /serial2.py | 1,013 | 3.625 | 4 | import pickle
import os
class Estudiante:
def __init__(self, nombre, edad, curso_inicial):
self.nombre = nombre
self.edad = edad
self.curso_inicial = curso_inicial
self.estado_activo = True
self.cursos = [curso_inicial]
def desactivar(self):
self.estado_acti... |
6826435001b68769d1d5e306dc5deaae39f5e8f9 | ameykasbe/algorithms | /1. searching_algorithms/3. binary_search.py | 1,155 | 4.03125 | 4 | def binary_search(arr, key):
left = 0
right = len(arr) - 1
while(left <= right):
mid = left + (right - left)//2
if arr[mid] == key:
return mid
if key < arr[mid]:
right = mid - 1
else:
left = mid + 1
return -1
def binary_search_rec... |
e0270f90d400ac254e446391b7de1165a71a6edc | korolevevev/repoForUNIX | /korolev.py | 186 | 4.0625 | 4 | print("Hello, World! This is Ilya Korolev's new python program which prints 'Hello, World! This is Ilya Korolev's new python program which prints...'")
for i in range(100):
print(100-i, "left") |
34fa3ca34fb36f36c4f302440668cf73ed1be46a | xikunqu/Python_100_days | /D1-15/Day4/sushu.py | 269 | 3.78125 | 4 | """
输入一个正整数判断它是不是素数
"""
sushu=int(input("请输入一个正整数:"))
if sushu<=2:
print("yes")
else:
for i in range(2,sushu):
if sushu%i==0:
print("no")
else:
continue
print("yes")
|
cc6355b89381d4c40276c77e9f2893cde5c4bb34 | PavanKumar1564/Tcs-Training | /Codes/BFS.py | 1,130 | 4.03125 | 4 | class Node:
def _init_(self,data):
self.data=data
self.left=None
self.right=None
def BFS(root):
queue=[root]
while(queue):
temp=queue.pop(0)
print(temp.data,end=" ")
if temp.left is not None:
queue.append(temp.left)
if tem... |
76bf489a14753d6e577fe5fbd8ab3142b8cbe8f8 | kish0ck/Daily | /2020-12-06.py | 24,840 | 3.640625 | 4 | # # 3강. 숫자 자료형
# print(5)
# print(-10)
# print(3.14)
# print(1000)
# print(5+3)
# print(2*8)
# print(3*(3+1))
# # 4강. 문자열 자료형
# print('풍선')
# print("나비")
# print("ㅋㅋㅋㅋㅋㅋㅋㅋㅋ")
# print("ㅋ"*9)
# # 5강. boolean 자료형
# # 참 / 거짓
# print(5 > 10)
# print(5 < 10)
# print(True)
# print(False)
# print(not True)
# print(not False)... |
eacd33e02b4211570506a20876ec8b4539f47a57 | juny02/university | /2020_ITE1014_2020006208/3-2/3.py | 211 | 3.71875 | 4 | def star(g):
for j in range (1,g+1):
c=0
if c<g+1:
c=c+1
print('*', end='')
a=input()
for i in range(1, int(a)+1):
star(i)
print('')
|
2132f72e0465bac08f6c8cf422f9f68bda47c2f5 | iainmck/bottlecap-mosaic | /server/util.py | 275 | 3.625 | 4 | import math
def distance2d(p1, p2):
(a1,a2) = p1
(b1,b2) = p2
return math.sqrt(math.pow(b1-a1,2) + math.pow(b2-a2,2))
def distance3d(p1, p2):
(a1,a2,a3) = p1
(b1,b2,b3) = p2
return math.sqrt(math.pow(b1-a1,2) + math.pow(b2-a2,2) + math.pow(b3-a3,2)) |
e9af6b4b1e5ac662f516a0efe407e3048357a6e0 | bdjackson/ProjectEuler | /primes.py | 6,890 | 4.34375 | 4 | #!/usr/bin/env python
# ============================================================================
import math
import collections
import operator
# ====================================================
# = Helper functiones for working with prime numbers =
# ====================================================
# ... |
427256121b03d62405fb60240e692b953e299ae9 | Andrewjjj/CMPUT404Lab | /Lab2/client.py | 1,982 | 3.640625 | 4 | #!/usr/bin/env python3
import socket, sys
#create a tcp socket
def create_tcp_socket():
print('Creating socket')
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except (socket.error, msg):
print(f'Failed to create socket. Error code: {str(msg[0])} , Error message : {msg[... |
7f2dfb1fc60d7c2b41a5f02682ec9d2dc41cbc4b | robertjohnsonark/Programming-Paradigms | /Assignment9/assignment9.py | 1,276 | 3.921875 | 4 | # -----------------------------------------------------------
# Assignment 9 CSCE 3193 Programming Paradigms
#
# Robert Johnson
# rcj009@uark.edu
# 010796992
# -----------------------------------------------------------
import sys
import re
import operator
if len(sys.argv) < 3:
if len(sys.argv) < 2:
print('Missing... |
22a2654002bae895191ceeb121d83fc9f8b7a7e8 | hpelletier/WizardsChess | /Main.py | 2,580 | 3.828125 | 4 | import sys
from Model import Board
from View import Mover
from Control import Control
from Speech import Speech
class Game():
def __init__(self):
self.gameState = 1 #State of game: 1 if playing, 0 if game over
self.player = 'white' #Current player: white player always starts
self.board = Board() #The board ... |
69a8ad6db9a80a52559e663a3db10cba3ac5220f | tkscode/pyNormalizeNumExp | /pynormalizenumexp/expression/base.py | 12,068 | 3.625 | 4 | """各種表現パターンクラスの定義モジュール."""
import typing
from enum import Enum
from typing import Any, Dict, List, Optional, Union
# 定数定義
INF = float("inf")
PLACE_HOLDER = "ǂ"
class NotationType(Enum):
"""数値表現の列挙クラス."""
NOT_NUMBER = 0
KANSUJI_09 = 1
KANSUJI_KURAI_SEN = 2
KANSUJI_KURAI_MAN = 4
KANSUJI_KURAI ... |
a844fc180d8f36ded408b7a7cd8f8cceb5791e02 | M4573R/Coursera-Assignments | /Introduction to Recommender Systems/Written Assignment 2/Ass2Q3.py | 1,407 | 4.09375 | 4 | #Title: Python script for computing answer to Question 3 of Written Assignment 2 (Intro to Recommender Systems)
#Author: Karan J. Thakkar
#Question: Count the number of ratings for each movie, order with the most number of ratings first, and submit the top 5.
#Output: Provides the top 5 movie names. You have to strip t... |
2bf022ee3fff9b82196cb898ed4eabff1f46d614 | on1ManArmy/Python | /BarTab.py | 961 | 4 | 4 | # A simple mini project to process the ordered
# items in a restaurants
class Tab:
# Attrubute named menu
menu = {
"beer":5,
"veggie": 12,
"pizza": 139,
"burger": 39,
"Cold_drink":65,
"desert":76
}
# Attrubtes in a class
table ={
"Abh... |
4aa8e664a02ed22db3cf2fd4f4a2e0517e3c3fdf | bomcon123456/DSA_Learning | /Python/Chapter 1/ex24.py | 205 | 3.859375 | 4 | vowels = ["a", "e", "i", "o", "u"]
def countVowels(string):
count = 0
for i in string:
if i in vowels:
count += 1
return count
print(countVowels("Keemochi is my kee"))
|
83803a63afd278267514cb856c7af31e82e43367 | qeedquan/challenges | /codegolf/do-n-and-n^3-have-the-same-set-of-digits.py | 914 | 4.25 | 4 | #!/usr/bin/env python
"""
Given a number n (0 <= n <= 2642245), check if n and n3 have the same set of digits, and output a truthy or falsey value accordingly.
For example, let's check the number 100.
1003 is 1000000.
The set of digits in 100 is {0, 1}.
The set of digits in 1000000 is {0, 1}.
Therefore, 100 shou... |
bfdc1bf9725384da2c6e6a64fbbd5f8d79cbfada | learn-knowlege/leetcode-datastructure | /datastructure/stack.py | 784 | 3.890625 | 4 | class Stack(object):
"""docstring for Stack"""
def __init__(self, *args):
super(Stack, self).__init__()
self.list = []
if args:
self.list = args[0]
def pop(self):
try:
return self.list.pop()
except IndexError as e:
print("Stack is e... |
c451ec7604e17982f9dd00c647f725bb1f7b225c | Lakshmi-Pravallika/PlayFair-Cipher | /pf1.py | 4,554 | 3.875 | 4 | while True:
print("Enter 1 for encryption")
print("Enter 2 for decryption")
print("Other option to exit")
ch=int(input("Enter your choice:"))
if(ch==1):
print("******************************ENCRYPTION*********************************")
Matrix = [[0 for x in range(5)] for y in range(5)]
key=input("En... |
851ad067a6a1447415a84ba38c63afa33fab9098 | aachellis/Spark-Join-Window_Introduction | /window-introduction.py | 1,744 | 4.21875 | 4 | '''
At its core, a window function calculates a return value for every input row of a table based on a group of rows, called the Frame. Every input row can have a unique frame associated with it. This characteristic of window functions makes them more powerful than other functions and allows users to express various d... |
bffa7e06d88473e6c30a5594d61f601f5b1ad1b0 | iamdoublewei/Leetcode | /Python3/2164. Sort Even and Odd Indices Independently.py | 1,842 | 4.3125 | 4 | '''
You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules:
Sort the values at odd indices of nums in non-increasing order.
For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing ... |
0ede6532132897a5ffad43424b31e659e4971a52 | minsu8252/python_test | /arg_sum_nums.py | 316 | 3.546875 | 4 | def sum_num(*args):
print(len(args),'개의 인자',args)
sum = 0
for n in args:
sum += n
averge = sum / len(args)
print('합계 :',sum, '평균 :',averge)
sum_num(10, 20, 30)
sum_num(10, 20, 30, 40, 50)
def min_nums(*args):
print('최솟값은', min(args))
min_nums(10, 2, 9, 3) |
478a083d094c3865c3d89dbab1d8bf303eceb5ec | smarulan613/fundamentos_prog_20211_sebasmc | /SESIONES_CLASE/SESION_20210405/pandas1.py | 1,155 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 4 18:23:46 2021
@author: R005
"""
import pandas as pd
notafundamentos=pd.DataFrame ({'Nombres':['andres','sebastian','laura','camila'],'semestre':[2,3,3,2]}) #notafundamentos es el dataframe
print(notafundamentos)
print()
notafundamentos.insert(2,'ciudad'... |
d64d74aec2528825d32eebf78c9d895fd1177b15 | nareshenoy/base | /src/script/project_euler/55.py | 626 | 3.5 | 4 | def rev(n):
rev_n = 0
while n != 0:
units_place_digit = n % 10
rev_n = rev_n * 10 + units_place_digit
n = n / 10
return rev_n
def ispalindrome(n):
if rev(n) == n:
return True
else:
return False
def islychrel(n):
i = 0
while i < 50:
... |
0d6f04a800afe83e8ad06a5400ed4e2fded9df8a | rakechill/rosalind | /bioinformatics-stronghold/HAMM.py | 195 | 3.609375 | 4 | #Given: Two DNA strings s and t of equal length (not exceeding 1 kbp).
#Return: The Hamming distance dH(s,t).
def hamming_distance(s, t):
return sum([1 for i in zip(s, t) if i[0] != i[1]])
|
828fcd5c8974787277af50302ef8ab5c21c5c428 | mdayunus/dsa-in-py | /binarysearch_recursive.py | 450 | 3.8125 | 4 | def binary_search(data_list, data, start, end):
if start <= end:
num = (start + end) / 2
if data == data_list[num]:
return num
elif data < data_list[num]:
return binary_search(data_list, data, start, end-1)
elif data > data_list[num]:
return binary... |
a68536cac88a84fddc9576d4fb84b67e28daaaa3 | neriunam/spark-training-python | /PythonFunctions.py | 457 | 3.828125 | 4 | # Function
def compare(x, y):
s = ""
if x > y:
s = str(x) + " is great than " + str(y)
elif x < y:
s = str(x) + " is less than " + str(y)
else:
s = str(x) + " is equal than " + str(y)
return s
print(compare(2, 4))
# Function with lambda parameter
def operation(x, y, op):
... |
a87314f1ca785f693d66a705630fefe8b78618c2 | ethanratnofsky/IOU-Calculator | /iou-calculator.py | 5,836 | 3.671875 | 4 | # Program Name: IOU Calculator
# Author: Ethan Ratnofsky
# Program Description: This program calculates the debt of each person in a group based on the contents of receipts,
# assuming the prices are split evenly.
# Date: 11/23/2020
# Create Person class
class Person:
def __init__(self, name):... |
967fb9589e4f9d3918d95df418224e78a0eff54b | fidelis452/day-3-of-5-weeks-of-python-bootcamp | /variable/numeric-var-code-challenge.py | 429 | 4.25 | 4 | # Ask a user to enter a number
# Ask a user to enter a second number
# Calculate the total of the two numbers added together
# Print 'first number + second number = answer'
# For example if someone enters 4 and 6 the output should read
# 4 + 6 = 10
number1 = input('Enter the first number: ')
number2 = input('Enter th... |
2f8de731cc66ad832de8e03b07e72cf36b7ca71e | Vasallius/Python-Journey | /Python For Everybody/Chapter 11/hw11.2.py | 283 | 3.796875 | 4 | import re
regexcommand = input('Enter a regular expression: ')
nolines = 0
fname = ('mbox.txt')
fhand = open(fname)
for line in fhand:
line = line.rstrip()
x = re.findall(regexcommand,line)
if len(x) > 0:
nolines += 1
print(x)
print(nolines)
|
98b5e732bc41bbfceef7a6fb27d3c83dd2ec6cac | Uche-Clare/python-challenge-solutions | /Ekeopara_Praise/Phase 1/Python Basic 1/Day5 Tasks/Task 5.py | 372 | 3.953125 | 4 | '''5. Write a Python program that will return true if the two
given integer values are equal or their sum or difference is 5.'''
def checker(n1, n2):
if n1 == n2:
return "True"
elif n1+n2== 5:
return "True"
elif n1-n2==5:
return "True"
else:
return "False"
print(check... |
5014c1e039f203dca28b319785e10b07e64ec3ad | HaroldBernieGarcia/GARCIA-H.---DATALGO | /gal13binaryTreeClass.py | 3,999 | 3.859375 | 4 | """ HAROLD BERNIE P. GARCIA
DATALOG : Add a New Element to a Binary Search Tree
May 13, 2020
I have neither received nor provided any help on this (lab) activity, nor
have I concealed any violation of the Honor Code.
Defined is a skeleton of a binary search tree structure with a method to cr... |
fd9a0f2c0e0aece0b3d280b0cf16b54e26e15fcc | atharvspathak/CloudCounselageLp3 | /IP_LP3_ Python_Atharv_Pathak_2154/Coding_Quetion2.py | 1,029 | 4.25 | 4 | '''
Problem Statement:
We add a Leap Day on February 29, almost every four years. The leap day is an extra,
or intercalary day and we add it to the shortest month of the year, February.
In the Gregorian calendar three criteria must be taken into account to identify leap
years:
● The year can be evenly divided by 4, is... |
d97178d3baf57caf74b2e0f4da9b7293c4787150 | murali-kotakonda/PythonProgs | /PythonBasics1/functions/functions/oops/Person2.py | 392 | 3.65625 | 4 | class Person:
def __init__(self,id,name,age): #instance varibales
self.id=id
self.name=name
self.age=age
p = Person(1000,"user1",67)
# print obj data
print("************p data************")
print(p.id)
print(p.name)
print(p.age)
p = Person(2000,"user2",69)
# print obj data
print("... |
ef39845cac3d79a26df60af994f3d5bba0cf34d4 | darkyin87/leetcode | /Add_Two_numbers.py | 1,301 | 3.78125 | 4 | # Submission Details
# 1555 / 1555 test cases passed.
# Status: Accepted
# Runtime: 172 ms
# Submitted: 0 minutes ago
# You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a li... |
a10671dad2d7e64608a51e8ff8d12598b728a075 | FabioCostaR/aprendendoPYTHON | /Desafio106.py | 911 | 3.65625 | 4 | #Faça um mini-sistema que utilize o Interactive Help do Python. O usuário vai digitar
#o comando e o manual vai aparecer.
#Quando o usuario digitar a palavra 'FIM' o programa encerrará.
#USE CORES.
def ajuda(msg):
from time import sleep
while True:
tela=str('Sistema de Ajuda do PYTHON')
... |
8a801ef1b154cc0571372c28f4d6ab8be71bd530 | BloonZhang/pygame-practice | /test.py | 753 | 3.78125 | 4 | # First file using pygame!
import pygame
# Initialize pygame
pygame.init()
# Create main display for game. width, height
gameDisplay = pygame.display.set_mode((800, 600))
# Title of the window
pygame.display.set_caption("A bit Racey")
# Create the game clock
clock = pygame.time.Clock()
# Flag to see if there's an e... |
7b31a95fcb1d9a65ddf93dc7cd8f12c19f2fa4d2 | rjtazree/python-pratice | /character find in string.py | 483 | 3.78125 | 4 | def s(input_string,find):
res = None
for i in range(0, len(input_string)):
if input_string[i] == find:
res = i + 1
break
if res == None:
print ("No such charater available in string")
else:
print ("Character {} is present at {}".format(find, st... |
7de51916da5187306580792b0cde8f0114346c5b | Tornike-Skhulukhia/IBSU_Masters_Files | /code_files/__PYTHON__/lecture_1/search/binary_search.py | 653 | 3.921875 | 4 |
def isin(array, element):
# make sure array is sorted, binary search will not work otherwise
assert sorted(array) == array
start_index = 0
end_index = len(array) - 1
while end_index >= start_index:
middle_index = (start_index + end_index) // 2
if element == array[middle_index] ... |
f9eace5ddab8503625b80dec50195aa0bba6ad31 | angelblue05/Exercises | /codeacademy/python/dictionary_key.py | 1,284 | 4.8125 | 5 | # Assigning a dictionary with three key-value pairs to residents:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
print residents['Puffin'] # Prints Puffin's room number
# Your code here!
print residents['Sloth']
print residents['Burmese Python']
# add a new key to a dictionary
dict_name[new_key]... |
18c36d9356f1715501a27ecf2832ad2ef5a70d6e | 101t/python3-tutorial | /codes/002-class/003-multi-inheritance.py | 801 | 3.9375 | 4 | import datetime as dt
class A:
def __init__(self):
print("Hi class A")
def __str__(self):
return "I am Class A"
def __value(self): # This is private method
return "I am Tarek"
@property
def value(self):
return self.__value()
class B:
def __init__(self):
print("Hi class B")
def __str_... |
ab52bc9c3bc57fb83613a8e726032a145f5996fe | somasekharreddy1119/DS-Algo-with-python | /arrays/seperate_0's_and_1's.py | 722 | 3.703125 | 4 | # RBR Interview PREP
# Seperate 0's and 1's in an array
'''
Given a binary array(only 0's and 1's seperate all zero's and ones's in an array
Example: 1001110
Sol: 0001111
Approach 1: (Count sort)
count all 1's and 0's then add all zeros in the front and 1's at the end.
TIME: O(n)
Approach 2:
Take left pointer and rig... |
df7e33c54613b12213706f852725578db656c5aa | poojithayadavalli/Zoho | /sort in specific order.py | 1,184 | 4.21875 | 4 | """
Given an array A of positive integers. Your task is to sort them in such a way that the first part of the array contains odd numbers
sorted in descending order, rest portion contains even numbers sorted in ascending order.
Constraints:
1 <= T <= 103
1 <= N <= 107
0 <= Ai <= 1018
Input:
The first line of input c... |
7d4530264d7ccbe88ea65f3db3642c407b663b45 | Alferdize/Data-Structure-and-Algorithms | /Daily Problem 2/daily_problem_2_3(uber).py | 664 | 3.984375 | 4 | """
daily_problem_2_3(uber).py
Third way to find array data product
"""
import math
EPS = 1e-9
def product(data_pro):
"""Return array Product"""
sum_data = 0
num_data = len(data_pro) # Number of elements
output_data = [] # to store the resultant array
# to hold all sum values
for i in rang... |
85d73fc37042cddd112601a2f4a8f013bf569685 | s-anusha/automatetheboringstuff | /Chapter 13/brute-forcePdfPasswordBreaker.py | 1,721 | 4.5 | 4 | #! python3
# brute-forcePdfPasswordBreaker
'''
Say you have an encrypted PDF that you have forgotten the password to, but you remember it was a single English word. Trying to guess your forgotten password is quite a boring task. Instead you can write a program that will decrypt the PDF by trying every possible English ... |
2289bd89cd9b9e839227088639f83dd7dfd267fb | jaquinterob/curso_python | /for.py | 195 | 3.890625 | 4 | numeros = [1,2,3,4,5,6,7,8,10]
for numero in numeros:
print(numero)
valores = ((10,20),["String", "Otro"],(True, False))
for valor1,valor2 in valores:
print(valor1,valor2)
|
507a9db7ba63ff49275df1eaafc305ca579ac7d4 | jwyx3/practices | /leetcode/math/reach-a-number.py | 877 | 3.734375 | 4 | # https://leetcode.com/problems/reach-a-number/
# https://leetcode.com/problems/reach-a-number/discuss/112986/Concise-Python-with-explanation-and-example
# https://www.youtube.com/watch?v=Bdw2Y9FrqcU
# Time: O(sqrt(N))
# Space: O(1)
class Solution(object):
def reachNumber(self, target):
"""
:type t... |
e1ab1b3663beb582ca0af4a96c8f7f47d7334955 | kyokomi-sandbox/sandbox | /python/helloworld/hello.py | 1,542 | 3.53125 | 4 | __author__ = 'kyokomi'
print('hoge')
import math
print(math.pi)
print(math.sqrt(85))
import random
print(random.random())
print(random.choice([1, 10]))
s = "hogehogeあ"
print(len(s))
print(s, s[1], s[-1]) # インデクシング
print(s[1:8]) # スライシング
print(s + 'hoge') # 連結
print(s * 5) # 繰り返し
print(s.find("ge"))
print(s.... |
3e1a9468fd1db40c5be29206d35278f26c5e5042 | MAZTRO/holberton-system_engineering-devops | /0x16-api_advanced/100-count.py | 1,459 | 3.578125 | 4 | #!/usr/bin/python3
"""
function that queries the Reddit API and prints
the titles of the first 10 hot posts listed for a given subreddit.
"""
from collections import OrderedDict
import requests
def count_words(subreddit, word_list, dict_words={}, after=""):
main_url = 'https://www.reddit.com/'
sub_reddit = 'r... |
16e1d0d51cb08f2fa65cd46e6cd6c305cb7652e4 | nderkach/algorithmic-challenges | /bracket_validator.py | 490 | 3.953125 | 4 | from collections import deque
def bracket_validator(string):
d = deque()
string = string.replace(" ", "")
for i, char in enumerate(string):
if char in ('{', '(', '['):
d.append(char)
elif char in ('}', ')', ']'):
p = d.pop()
if abs(ord(char) - ord(p)) > ... |
be737c0849880010851213a2fd798ffce2baf97d | ojjy/pub_practice | /python/6_twenty_questions.py | 3,157 | 3.765625 | 4 | # Python 3.7.2/win10 64bit/IDE:Pycharm 2018.3.3
# twenty questions game : computer generate number randomly and person need to answer the number
# and save the try_count in the text file for getting score after terminating process
from random import randint
# display top 10 by reading 10 times as one line
def display_... |
27045252fedbf3edce4a283121095334fd181314 | KhairulIzwan/Python-for-Everybody | /Values and Types/Exercise/4/main.py | 416 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit, and print out the converted temperature.
"""
#
celcius = input("Enter Temperature in Celcius: ")
celcius = float(celcius)
# (0°C × 9/5) + 32 = 32°F
fahrenheit = float(celcius * (9/5) ... |
a70f5e71fb9ba52ed633428319b629ef7bc3953c | mljdeveloper/Python_Source_Code | /guppe/min_e_max.py | 2,280 | 4.25 | 4 | """
Min e Max
max() -> retorna o maior valor de um iteravel ou o maior de dois ou mais elemento.
# Exemplos
lista = [1, 2, 3, 8, 99, 34, 129]
print(max(lista))
tupla = (1, 2, 3, 8, 99, 34, 129)
print(max(tupla))
conjunto = {1, 2, 3, 8, 99, 34, 129}
print(max(conjunto))
dicionario = {'a': 1, 'b': 2, 'c': 3, 'd': 8... |
66ad4f78f89269d655b93cf7aad3b21c0d2b8b20 | doctornemesis/Fundamentals_of_Computing | /POC/monte_carlo_TTT.py | 4,823 | 3.890625 | 4 | """
Monte Carlo Tic-Tac-Toe Player
"""
import random
import poc_ttt_gui
import poc_ttt_provided as provided
# Constants for Monte Carlo simulator
# You may change the values of these constants as desired, but
# do not change their names.
NTRIALS = 100 # Number of trials to run
SCORE_CURRENT = 1.0 # Score for s... |
0c9ed9e4453e36dacec390782c3414621160b22d | mhmnederstigt/DataProcessing | /Homework/Week5/helper_scripts/convertCSV2JSON_dl.py | 1,037 | 4.375 | 4 | #!/usr/bin/env python
# Name: Milou Nederstigt
# Student number: 11022914
"""
This script outputs a JSON file with the content of a csv.
Converts a CSV file with three variables to a JSON file containing a dictioniary with three lists (one per variable).
"""
import csv
import json
import sys
if len (sys.argv) != 2 :... |
330c8d9e8a6c3405d53beb2fe24a66f57157e977 | azharcs/Learn-Python-the-Hard-Way | /ex15.py | 521 | 4.125 | 4 | #importing the module
from sys import argv
#providing arguments
script, filename = argv
#open the filename and assign it to a variable
txt = open(filename)
# reading the file using read function and print it.
print "Here's your file %r:" % filename
print txt.read()
#typing the filename again or a new ... |
d4f1fb46c66d6c970caa367497b5ca37609426f7 | Akimov232/big_work | /hommework_2.py | 769 | 4.09375 | 4 | letter_all = 'фывапролджэйцукенгшщзхъячсмитьбю'
def letter_upper(w):
'''
input: string user
output: list of quantity letter capital
'''
letter = 0
for i in w:
for q in letter_all.upper():
if i == q:
letter += 1
return letter
def letter_lo... |
6dfce3f9dd436abc55a113a363b90f1e3c337a8b | ramonvaleriano/python- | /Livros/Livro-Introdução à Programação-Python/Capitulo 6/Exemplos 6/ExemploVideo_7.py | 432 | 3.875 | 4 | # Program: ExemploVideo_7.py
# Author: Ramon R. Valeriano
# Description: Exemplos de uma video aula que eu peguei na internet, sobre Dicionário
# Developed: 24/04/2020 - 23:58
# Updated:
estado = dict()
brasil = list()
for e in range(0, 3):
estado["UF"]= str(input("Unidade Federa: "))
estado["Sigla"]=str(input(... |
4dec42864260f153c71c480a8da4bf31bae3038b | Hemant-1821/AlgoExpert | /Easy/SelectionSort.py | 478 | 3.890625 | 4 | #complexities: Space: O(1) | Time: O(N^2)
def SelectionSort(array):
currentIdx = 0
while currentIdx < len(array)-1:
smallestIdx = currentIdx
for i in range(currentIdx+1, len(array)):
if array[smallestIdx] > array[i]:
smallestIdx = i
swap(currentIdx, smallest... |
0d712d29b934a4cd9457dc921ec7145411a5a330 | w3cp/coding | /python/python-3.5.1/3-intro/6-end-key.py | 197 | 3.71875 | 4 | # The keyword argument end can be used to avoid the newline after
# the output, or end the output with a different string:
a, b = 0, 1
while b < 1000:
print(b, end = ',')
a, b = b, a + b |
17ba50248e46bcd1be2d1842f980f184ad0f532b | damoncheng/Markdown | /Arith/leetcode/Combat/palindrome.py | 1,406 | 4.0625 | 4 | #coding:utf-8
str_content = "abcbabdef"
palindrome_start_index = 0
palindrome_end_index = 0
palindrome_len = 1
def is_palindrome(str_content, start_index, end_index):
while(end_index > start_index):
if str_content[start_index] != str_content[end_index]:
return False
start_index +=... |
a68408ab6ebac515cd6aa588e3ae25bc7fedaec6 | katevnuk/python_challenge | /PyBank/main.py | 2,099 | 4 | 4 | import csv
from statistics import mean
import os
filename = os.path.join('Homework_03-Python_Instructions_PyBank_Resources_budget_data.csv')
with open(filename, 'r', newline='', encoding='latin-1') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
storage = {} # dictionary for keeping data from csv ... |
7a740cf6a0b2a639399ab00bc6b6031c6e198a50 | EdvardCarlsson/Spotify_Song_Discoverer | /song_discoverer.py | 22,767 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 8 16:28:21 2020
@author: edvardcarlsson
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style("whitegrid")
client_id = "spotify_client_id"
client_secret = "spotify_client_secret"
spotify... |
a659fa261150d3297066fdbe2899d3dcc679a58b | VixeruntR/leetcode | /tricks/缓存装饰器.py | 1,047 | 3.625 | 4 | # coding=utf-8
"""
缓存是一种将定量数据加以保存以备迎合后续请求的处理方式, 旨在加快数据的检索速度.
functool模块中的lru_cache装饰器可以实现缓存功能.
lru_cache原型如下:
@functools.lru_cache(maxsize=None, typed=False)
使用functools模块的lur_cache装饰器,可以缓存最多maxsize个此函数的调用结果,从而提高程序执行的效率,特别适合于耗时的函数.
参数maxsize为最多缓存的次数,设置为None表示无限制,否则设置为2^n; 如果typed=True则不同参数类型的调用将分别缓存, 例如f(3)和f(3.0).
被... |
ed62683d7e74f57b44118e77e534c0eac7dd01f0 | sugaigit/mypython_project | /Bob.py | 112 | 3.890625 | 4 | if bob < 1:
print("""No more bottles of beer on the wall.
No more bottles of beer.""")
return
|
a0b8948d066cd36d0abb82c18fe01992e6c7e273 | Aayushsoftinc/Selenium_Python | /Python_SDK/lists.py | 746 | 4.28125 | 4 | list1 = ["Juniper", "Cisco", "Avaya", 10.5, 11, "Pushkar"]
print(len(list1))
print(list1)
print(list1[2])
list1[2] = "HP"
print(list1[2])
list1.append("HAPPY CODING")
print(list1)
del list1[1]
print(list1)
list2 = [-11, 2, 12]
list3 = ["a", "b", "c"]
print(max(list2))
print(max(list3))
list1.insert(1, "CISCO")
prin... |
c51c547a7fe678aa2566e0ffd738376cc8e0c8bf | BonnieThompson/cp1404pracs | /Prac02/get_names.py | 215 | 4 | 4 | outfile = open("name.txt","w")
name = input("what is your name?")
print(name,file=outfile)
outfile.close()
in_file = open("name.txt", "r")
name = in_file.read().strip()
print("Your name is", name)
in_file.close()
|
9e1457335c9b44d9da2f176044e53fc3d1845cde | GiovanaThais/arqPython | /cadastro.py | 497 | 3.5625 | 4 | import os.path
import Agenda as a
while True :
print('-'*40)
print('''Menu :
[1]-Registrar Dados
[2]-Listar Registros
[3]-Sair''')
opc=(int(input('opção desejada: ')))
if opc==3:
break
elif opc==1:
a.registrar()
os.system('cls' if os.name == 'nt' else 'clear')
... |
08c190cada31cf5ece30adb18149a8d92ed494bc | stag152766/gb_ik_python | /Lesson3/task1.py | 3,513 | 3.96875 | 4 | # # 1. Удаление элемента списка во времня его итерирования
# list_1 = [1, 2, 3, 4]
# list_2 = [1, 2, 3, 4]
# list_3 = [1, 2, 3, 4]
# list_4 = [1, 2, 3, 4]
#
# """
# В данном случае на каждой итерации цикла из объекта enumerate извлекается очередной кортеж,
# состоящий из индекса очередного элемента списка и значения эт... |
47cca44a51b4f4819934ff70cf738ed59519f29f | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4151/codes/1585_2905.py | 198 | 3.875 | 4 |
a=float(input("comprimento de A: "))
b=float(input("comprimento de B: "))
c=float(input("comprimento de C: "))
s=(a+b+c)/2
from math import*
area= sqrt(s*(s-a)*(s-b)*(s-c))
print(round(area,5))
|
63c001ffb9d8a688ee5cf75075348603bc3f1a3f | Shiv2157k/leet_code | /goldman_sachs/design_hash_map.py | 2,756 | 3.984375 | 4 | class ListNode:
def __init__(self, key=-1, val=-1, next=None):
self.key = key
self.val = val
self.next = next
class MyHashMap:
"""
1. Need to implement hash function
- map an i/p to fixed size O(1)
2. Insertion
- use hash function to find the block, insert on l... |
1ba0ff9ee8a536184e57711f4c53713813164bac | marcowchan/holberton-system_engineering-devops | /0x16-api_advanced/100-count.py | 1,441 | 3.515625 | 4 | #!/usr/bin/python3
"""Defines count_words()."""
import requests
def count_words(subreddit, word_list, word_count={}, after=None):
"""Counts the number of times a set of words in all hot listings."""
url = 'https://www.reddit.com/r/{}/hot.json'.format(subreddit)
headers = {
'User-Agent': 'Mozilla/5... |
b369859fa5871af374d2118a27eda8d2c3a80611 | karbekk/Python_Data_Structures | /Interview/FInal_Prep/OutCo/Techniques/GCD.py | 148 | 3.65625 | 4 | def GCD(a,b):
if a < 0:
a *= -1
if b < 0:
b *= -1
while b > 0:
a,b = b, a % b
return a
print GCD(18,27)
|
d530fb0bba978bebc542d7ecb181b2ab93545817 | bermec/challenges | /338test.py | 5,184 | 4.25 | 4 | '''
What day of the week did hitler get elected on?
What day of the week did the Normans invade Britain on?
What day of the week did Jesus die on?
What day of the week did MacDonald get founded on?
Today we're gonna find out
For todays challenge you are allowed to use your languages
built in Calender functions/cla... |
0b5361ba090cf61f822f95766484ba00bedb058b | baranitharan2020/PGDDS | /Week 1 - Basics of Python/Average and checks.py | 501 | 4.125 | 4 | #Take input here
#we will take input using ast sys
import ast
input_str = input()
input_list = ast.literal_eval(input_str)
#Remember how we took input in the Alarm clock Question in previous Session?
#Lets see if you can finish taking input on your own
data=input_list[0]
check=input_list[1]
sum=0
#start writing your ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.