blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
227830e710c39afc391898227688007985273ab9 | Iam-El/Random-Problems-Solved | /Linked list/createLinkedlist.py | 5,471 | 4.125 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
# Inserting at the End of the Linked List
def insertatEnd(self, newdata): # self.head should be node not none for this function
# newnode=Nod... |
d1366371ab09e23e16a6a551307a75f1f90e842c | GregorySkir/GG | /py/6read_zip.py | 1,765 | 3.53125 | 4 | import datetime
import zipfile
import csv
def print_info(archive_name):
if not zipfile.is_zipfile(archive_name):
return ('not a zipfile')
zf = zipfile.ZipFile(archive_name, 'r')
for info in zf.infolist():
print (info.filename)
print ('\tComment:\t', info.comment)
print ('\tM... |
7348458d8900ab64ea6ce0774b1045a8a57cd5d8 | jiaxiaochu/spider | /00-Knowledge-review/04-闭包/05-修改闭包全局变量.py | 816 | 3.765625 | 4 | # coding = utf-8
def add_b():
global b
b = 42
print("This id add_b's", b)
def do_global():
global b
b = b + 10
print("This is do_global's", b)
do_global()
print(b)
add_b()
# global 定义的变量,表明其作用域在局部以外,
# 即局部函数执行完之后,不销毁 函数内部以global定义的变量
# def add_... |
277c360773f3f7c048e518e76b58134744c3ee9e | gibum1228/Python_Study | /201814066_14.py | 7,372 | 3.65625 | 4 | """
201814066 김기범
과제 14번
"""
class Fraction:
def __init__(self, n, d):
"""
초기 값 정의해주는 메쏘드(자동 메쏘드)
:param n: 분자
:param d: 분모
"""
self.numer = n
self.denom = d
if n > 0 and d < 0: # 분자가 양수고 분모가 음수면 - 부호를 분자로 이동
self.denom = -d
se... |
515b34337df87e07e04b205836c281ad2baa1634 | Ena-Sharma/Meraki_Solution | /Python_Programing_Excercise/Day_2/string_concatination2.py | 490 | 4.15625 | 4 | '''
Apko ek string di jayegi jiske akhir me agar 'ing' hogi toh ushe aage apko 'ly' add karni hai aur agar 'ing' nhi hai toh 'ing' add karna hai.
Lekin agar uske akhir meh 'ly' hai toh ushme app kuch bi add ni karoge
Eg:
Input: 'abc'
Output: 'abcing'
Input: 'string'
Output: 'stringly'
'''
string=raw_input('E... |
55ceafa3e30e997bac0c6219141943391d4ae53e | HarishK501/100-days-of-coding | /longest-balanced-parenthesis.py | 983 | 3.75 | 4 | from stackADT import Stack
def getLBPlength(S): # Longest Balanced Parenthesis(LBP)
stk = Stack(len(S)+1)
stk.push(-1)
popCount = maxLen = 0
for i in range(len(S)):
if S[i] == '(':
stk.push(i)
else:
if not stk.isEmpty():
stk.pop()
... |
9c559527aeb31f6f96b4db8a8a94248336c33306 | anku255/Interviewbit | /Programming/String/reverse_the_string.py | 578 | 3.578125 | 4 | class Solution:
def reverseWords(self, inputStr):
inputStr = inputStr.strip()
reversedStr = ''
words = []
word = ''
for char in inputStr:
if char != ' ':
word += char
else:
words.append(word)
word = ''
words.append(word)
for i in range(len(words) - 1,... |
d536ad106a052cef9d1a2fcffddfa3b357d2c225 | harishbharatham/Python_Programming_Skills | /Prob12_3.py | 661 | 3.71875 | 4 | from account import account, atm
for i in range (10):
accountlist = []
accountlist.append(account(id1 = i))
def main1():
print(atmSim.mainMenu())
choiceInput = eval(input("Enter a choice:" ))
if choiceInput == 1:
print(atmSim.GetBalance())
main1()
elif choiceInput =... |
893be65167ff35ae6e6482cc758666c7bc523622 | krisjanis-gross/remote-pi | /custom_configuration/b_griezeejs/input_functions/test1.py | 420 | 3.703125 | 4 | import os
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
buttonPin = 17
GPIO.setup(buttonPin,GPIO.IN)
#initialise a previous input variable to 0 (assume button not pressed last)
prev_input = 1
start_time = 0
current_time = 0
while True:
#take a reading
input = GPIO.input(buttonPin)
# input = 0 ... |
15b888c88dcfb0a81fba91aaa38af83b276118da | kapilparab/HackerRank-Solutions-Python | /Algorithms/Utopian-Tree.py | 326 | 3.5625 | 4 | def utopianTree(n):
init_height = 1
if n == 0:
return init_height
else:
for i in range(1,n+1):
if i%2==0:
init_height += 1
else:
init_height *= 2
return init_height
cycles = [0,1,4]
for i in cycles:
utopianT... |
9184a9d9059a8b4c6fabfdfa6cdbcb647958dd68 | k43lgeorge666/Python_Scripting | /basic code/lista2.py | 233 | 3.53125 | 4 | #!/usr/bin/python
lista = [10,5,3,43,50,7]
nro_elementos = 0
x = 0
while x<len(lista):
if lista[x] >=7:
nro_elementos = nro_elementos + 1
x = x+1
print("La cantidad de elementos mayores a 7 es: " + str(nro_elementos))
print("")
|
d3d18aebda9b9a1057fadc0d9f916e659f220518 | plusuncold/word_bingo | /create_mode.py | 2,519 | 3.765625 | 4 | import game_data
from typing import List, Dict
ROUNDS = 5
DEFAULT_SAVE_PATH = 'game_state.json'
def get_player_count() -> int:
player_count = input('How many people are playing? ')
return int(player_count)
def get_players(player_count: int) -> List[str]:
player_list = input('Who is playing? (Ente... |
af8aaa57c8c55c9e8136aa49b08ba393bb6c0803 | patricknyu/random_stuff | /fizzbuzz.py | 744 | 3.984375 | 4 | def fib(n):
if(n == 1):
return [0]
elif(n==2):
return [0,1]
else:
fib_list = [0,1]
for i in range(2,n+1):
fib_list.append(fib_list[-1]+fib_list[-2])
return fib_list
def sieve(n):
sieve = [True]*n
sieve[0] = False
sieve[1] = False
for i in range(2,n):
if sieve[i]:
for j in range(i*i,n,i):
... |
c6f358bb9755e681c69b66c750b7da2d64885c71 | mazyvan/Python-Threads | /Hilos1.py | 2,386 | 3.890625 | 4 | import threading
import sys
import time
from random import randint
print('SUPER THREADING GAME v0.1 By Iván Sánchez')
print()
# Declaramos nuestras variables globales para guardar los numeros aleatorios
number1 = 0
number2 = 0
ejecutarHilo_1 = True
ejecutarHilo_2 = True
# Declaramos la función que genera un nuevo ... |
49b7aa41cf70b2b1eb17778299f147447a2d0adb | django-group/python-itvdn | /домашка/advanced/lesson 1/Alex Osmolowski/HW_01_02/udp_client.py | 915 | 3.515625 | 4 | # Задание 2
# Создайте UDP клиента, который будет отправлять уникальный идентификатор устройства на сервер,
# уведомляя о своем присутствии.
# UDP client socket
import socket
def main():
# создаем UDP socket (IP)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# цикл ввода и отправки сообщений ... |
7a33a88dc7478f886bccfc1e509c365b89b7781d | piloulac/leetcode | /9.palindrome_number.py | 292 | 3.90625 | 4 | # Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
class Solution:
def isPalindrome(self, x: int) -> bool:
xStr = str(x)
return xStr == xStr[::-1]
# Next challenges:
# do it without converting to string |
23fec1961a1efccd7415be1376c7003253288370 | andrezzadede/Curso_Guanabara_Python_Mundo_3 | /Mundo 3 - Exercícios/87Exercicio.py | 727 | 4.15625 | 4 | #Aprimore o desafio anterior, mostrando no final:
#A) A soma de todos os valores pares digitados
#B) A soma dos valores da tecerceira coluna
#C) O maior dos valores da segunda linha
matriz = [[0,0,0], [0,0,0], [0,0,0]]
maior = scol = pares = 0
for l in range(0,3):
for c in range(0,3):
matriz[l][c] = int(input(f'D... |
2c0b2aa89478c4d7bde199e479f963f644aafa81 | Clockwick/DataStructureP2 | /Practice/Recursion/SUBHAM.py | 189 | 3.5 | 4 | def fun(x):
if(x > 0):
x -= 1
fun(x)
print(x, end=" ")
x -= 1
fun(x)
# Driver code
a = 5
fun(a)
# This code is contributed by SHUBHAMSINGH10
|
a0477f46064c87b8d5fa6f495e921ae1c5105181 | Lazaraaus/python-card-games | /card_player.py | 2,988 | 3.875 | 4 | #Python class for a Player of our Card game
#Global TODO: Add error catching blocks (built-in and self-defined) to all critical functions
#Global TODO: Add unit tests for all classes and functions
from card_suite import Deck
class CardPlayer:
"""A simple class for modeling a player to play cards"""
de... |
48b25508ccd4b3882247542cb86008d66003327d | xexugarcia95/LearningPython | /CodigoJesus/Excepciones/Ejercicio1.py | 495 | 3.890625 | 4 | def division(a, b):
try:
return a/b
except ZeroDivisionError:
print("No se puede dividir entre cero")
return "Operación errónea"
while True:
try:
op1 = int(input("introduce un operador: "))
op2 = int(input("Introduce otro operador: "))
break
except Value... |
fa6d6ca9198350b6282be28a65d8fb3a3f62f24c | KamilGrodzki97/Scripts | /Lab6/1.txt.txt | 112 | 3.75 | 4 | znaki = input("Podaj znaki: ")
print("Znaki, które podałeś: " + znaki)
for pozycja in znaki:
print(pozycja) |
99d71c5dffeb0cf85180b1b734eea0abc600dfa2 | bugzPDX/learn_python | /projects/MyDungeon/mydungeon/mydungeon.py | 6,510 | 3.96875 | 4 | # Classes file
from random import choice
from textlist import text_list
# Class for creating the main playing area
class Dungeon(object):
def __init__(self, x, y):
self.rooms = []
self.cur_x = 0
self.cur_y = 0
for i in range(0, x):
self.rooms.append([])
... |
79901da9b4410933324ab010b6335d0d17d256f8 | hatleon/leetcode-9 | /python/4_Median_of_Two_Sorted_Arrays.py | 296 | 3.703125 | 4 | #!/usr/bin/env python
# coding=utf-8
def median(x):
if len(x) % 2:
return x[len(x) // 2]
else:
return (x[len(x) // 2 - 1] + x[len(x) // 2]) / 2
def findMedianSortedArrays(self, nums1, nums2):
nums = nums1 + nums2
nums.sort()
return Solution.median(nums)
|
9f69f60f745e6829f97731f9c0c73646ebdd20e5 | DJaymeGreen/CollegeScoreCardAnalytics | /Ostu.py | 7,826 | 3.921875 | 4 | """
Author: D Jayme Green
Date: 2/15/17
Ostu's Method and One-Dimensional Clustering
This program splits vehicles into two groups: intentionally speeding or
people who are maximizing safety. It studies traffic volume for road
planning in order to maximize traffic flow. This problem does not
cause any ethic... |
5817289b1f6c1d37720a6ca21ffde1e53fabdd95 | LYblogs/python | /Python1808/第一阶段/day10-函数/测试代码页.py | 2,162 | 3.984375 | 4 | # # str = "-123"
# # print(str[::-1])
#
# class Solution:
# def reverse( x):
# """
# :type x: int
# :rtype: int
# """
# str1=str(x)[::-1]
# return int(str1)
# reverse(x=-123)
# print(2**31)
# list1=[1,2,3,4]
# print(list1[0]+list1[1])
# def twoSum(nums, target):
... |
04c9960ecb87d42f5f07eb99f1918ece1fe75652 | StefanDimitrovDimitrov/Python_Fundamentals | /Python_Fundamentals/Fundamentals level/02. Conditional Statements and Loops/Ex 09 Easter Cozonacs.py | 606 | 3.78125 | 4 | budget = float(input())
price_flour = float(input())
count = 0
current_budget = budget
count_cozonac = 0
count_eggs = 0
price_pack_of_egg = price_flour * 0.75
price_milk_250ml = (price_flour + price_flour * 0.25) / 4
price_cozonac = price_flour + price_pack_of_egg + price_milk_250ml
while current_budget > price_cozon... |
caca5867fc73561fdecb0cb607f649dd5363d500 | AugustoSavi/Python-primeiros-passos | /Desafio_026.py | 303 | 4.03125 | 4 | frase = input('Digite a Frase:')
print('Numeros de vezes que aparecem o "A":{}'.format(frase.upper().count('A')))
print('A letra "A" apareceu primeiro na posição:{}'.format(frase.upper().find('A')))
print('A letra "A" apareceu por ultimo na posição:{}'.format(frase.upper().rfind('A')))
|
78f7afd6aedaebd8ce4fcc76b7a888e19baa35e4 | EdenPlus/codingground | /PythonSandbox/main.py | 3,636 | 3.796875 | 4 | # Importing some stuff we'll need
from itertools import permutations, product
import urllib
import urllib2
# Creating our method to remove stuff that isn't in standard english alphabet
def ExtractAlphabetic(InputString):
from string import ascii_letters
return "".join([ch for ch in InputString if ch in (ascii_... |
d3b4d92da9e737ef3986430c2e307ce3784b5f51 | ORFMark/CS118 | /InClassPY/emailVal.py | 635 | 4.03125 | 4 | fail="invalid email"
hacker="hackerEmail"
success="This is a valid Email"
print("When you are finished entering email addresses, type 'done'.")
cont="Yes"
while True:
usrEmail=input("Please input an email address: ")
if usrEmail == 'done':
break
elif usrEmail.find('@') == -1:
print("Invalid ... |
744c19831d45cb143aa15fc3077bf7376304760a | adrianogil/nanogenmo17 | /src/main.py | 1,228 | 3.578125 | 4 | from island import Island
from islandstory import IslandStory
class Story:
def __init__(self):
self.story_size = 0
self.story_words = 0
def update_word_count(self, story_piece):
words = 0
inside_word = False
for s in story_piece:
if inside_word and (s =... |
b03b4d6c8a377d660b027257abee4ad48b2bf0d9 | caterinasworld/gcd | /gcd_naive.py | 419 | 3.515625 | 4 | # implementation based on "A Comparison of Several Greatest Common Divisor Algorithms"
# http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.259.1877&rep=rep1&type=pdf
def brute_force(a, b):
gcd = 0
# check whether a or b is the lower value
if a > b:
low = b
else:
low = a
fo... |
ca06a45713d58fddf8e0272c61c66ca5fc801171 | Farewell1989/Hamiltonian-Generator | /Core/BasicClass/IndexPy.py | 4,386 | 3.703125 | 4 | '''
Index.
'''
from copy import deepcopy
from re import split
ANNIHILATION=0
CREATION=1
class Index:
'''
This class provides a linear operator with an index.
Attributes:
site: integer
The site index, start with 0, default value 0.
orbital: integer
The orbital index, ... |
317fbb4a2fcfdf0575c98ee751bb8026bb84f5f3 | syurskyi/Algorithms_and_Data_Structure | /The Complete Data Structures and Algorithms Course in Python/template/Section 8 Python Lists/lists.py | 1,258 | 4.0625 | 4 | # Created by Elshad Karimov on 10/04/2020.
# Copyright © 2020 AppMillers. All rights reserved.
# Accessing/Traversing the list
shoppingList = ['Milk', 'Cheese', 'Butter']
for i in range(len(shoppingList)):
shoppingList[i] = shoppingList[i]+"+"
# print(shoppingList[i])
empty = []
for i in empty:
print... |
15615a7ecfd303f50e03bd020ad26102129679c4 | pritamsonawane/Assessment | /problemStmt12.py | 310 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 14:44:37 2017
@author: User
"""
def DogAge():
humAge=input("enter dog age in human years: ")
if humAge <=2.0:
print "dog age is 10.5 years"
else:
dogAge = float((humAge-2) * 4 +(10.5))
print "dog age is %f years"% (dogAge) |
5436bdee52c2477c3967ee9bba701ff093f75fb6 | Aayush360/Shamshad_Ansari_CV_ANN | /list_3_9.py | 856 | 3.984375 | 4 | # masking: hiding or filtering of and image
# we put focus on certain portion of the image while applying mask on the remaining portion
# masking using Bitwise AND operation
import cv2
import numpy as np
# load an image
nature = cv2.imread('../images/nature.jpg')
cv2.imshow("original nature image", nature)
# cre... |
3b1e773be979a6937c726040696c8fdc5121cde8 | rajiv8/openCv_Files | /basicOperation.py | 1,401 | 3.578125 | 4 | # basic Operations
import cv2
img = cv2.imread("./static/messi.jpg")
img2 = cv2.imread("./static/Lenna.jpg")
print(img.shape) # returns rows,columns and channels
print(img.size) # total no.of pixels
print(img.dtype) # returns datatype
# b,g,r = cv2.split(img) #splitting the three channels
# resizing the image ... |
8b290568c6858916cddbea43c3431143764507be | wanhao2015/python | /Python learning/basic python/09.py | 536 | 4.21875 | 4 | for i,value in enumerate(['A','B','C','D']):
print(i,value)
for x,y in [(1,1),(2,4),(3,9)]:
print(x,y)
#请使用迭代查找一个list中最小和最大值,并返回一个tuple:
def findMinAndMax(L):
if L == []:
return(None,None)
min = max = L[0]
for i,value in enumerate(L):
if value < min:
min = value
... |
1e32322a36f8055fbfc3a286df988f97eab32cce | yost1219/python | /labs/lab5a.py | 1,142 | 3.578125 | 4 | """
Author: Yost
Title: Lab 5A
Date: 12 Sep 2018
Lab 5A: Utilizing Modules and Packages
Instructions
Using your calculator you created from Lab4A, split up the functionality into modules and utilize packaging. Some things you could split up:
The user menu into it's own module on a higher level package
... |
1ddbe7ff165395fc9a5a78adc0be903aadbe37fb | Camacaro/python-flask | /05-ejercicios/02-task.py | 442 | 4.46875 | 4 | # ingresar nombre y apellido e imprimirlo al reves
nombre = input('Ingrese el nombre: ')
apellido = input('Ingrese el apellido: ')
# In this particular example, the slice statement [::-1]
# means start at the end of the string and end at position 0,
# move with the step -1, negative one, which means one step backwa... |
29ee4d409888c9e68e8c7a61d61bf1f3bd5bd595 | visw2290/Scripts-Practice | /Scripts-Pyc/sample game.py | 458 | 3.859375 | 4 | '''Its a program for getting Yes, no, maybe answers'''
list1 = ['Yes', 'No','Maybe']
SampleFile = open('c:\\aaa\\quiz.txt')
QuestionList = SampleFile.readlines()
try:
for i in QuestionList:
print(i)
Answer = input()
if Answer.title() not in list1:
print('Only Yes, No and Maybe ac... |
45b54e25a5d71c4cb199df93769c090dd3612e36 | SaiPrathekGitam/MyPythonCode | /Factors.py | 378 | 4.25 | 4 | # Program to find highest and smallest factor of given number
n = int(input("Enter the number : "))
for i in range(n // 2 + 1, 1, -1):
if n % i == 0:
print(f"{i} is the highest factor of {n}")
break
else:
print("prime")
for i in range(2, n // 2 + 1):
if n % i == 0:
pr... |
541bd0f34cf176850d36fdc8a94af0c64682c047 | TDBJR/Study | /Dictionary_Loops.py | 573 | 4.6875 | 5 | #Since the loop only sees the the name and not the value printing a dict in a loop will only list the names
# so if you want it to list the value instead you type the name of the dict and the first variable of the for loop inside square brakets
# the_links[keys] since keys is going to be the name it really means ... |
3e9f87cdd08a8de5630536ddc2405d574491ca3c | mehabhalodiya/Python | /11-cryptography/caesar_cipher.py | 1,373 | 4.125 | 4 | def cipher():
ans_start = input("Do you want to start? (YES/NO): ")
ans_start = ans_start.upper()
while(ans_start in 'YES'):
print("What do you prefer to do?")
ans = input("Press E to Encrypt and D to Decrypt: ")
ans = ans.upper()
if(ans=='E'):
user_input = inpu... |
d8c5b81a7b66a63c7d8c9e6d8f85482a9e464337 | mohammedSlimani/exercism | /python/isogram/isogram.py | 589 | 4.0625 | 4 | def is_isogram(string):
# string is all lower case
string = string.lower()
# Searching for the repeated strings
existing = []
for _str in string:
if _str != ' ' and _str != '-':
if _str in existing:
return False
else:
existing.append(_... |
d4ed9ae0104f9055df6da5ab41f4001ed98b0f4e | Jnava3/Programming-Assignment- | /PA2.py | 854 | 4.15625 | 4 | """ John Nava
Program #2: The Discount Calculator
COSC 1306
Fall 2019
"""
#Insert no. of items & original price
itemnum=int(input("Items being sold: "))
cost=float(input("Original Cost ($): "))
#If the total cost is greater than or equal to $200
if(float(cost) >= float(200) and int(itemnum)... |
dc35ff0c809696894b857e645416208ceda31c1c | BrandonLim8890/python | /automate_the_boring_stuff/chapter3/collatz.py | 421 | 4.28125 | 4 | def collatz(number):
if number % 2 is 0:
print(str(number) + " // 2")
return number // 2
else:
print("3 * " + str(number) + " + 1")
return 3 * number + 1
number = 0
while number is not 1:
print('Enter a number: ')
try:
guess = int(input())
number = col... |
41cdbe1b06ed21acb858b28635a52efbfcacc667 | jtorain21/CS-115 | /Property_Tax.py | 1,924 | 4 | 4 | # Joshua Torain CIS - 115 FON04
# write main function to control logic
# write function to ask user for the value of their land
# write function to calculate the assessment value of the land, which is 60% of actual value
# write function to calculate the property tax, which is $0.72 for every $100 of the assessment va... |
6977809a8350e89c3f9e5475c445750bac37ece5 | mohitleo9/interviewPractice | /Linked_Lists/2-6.py | 217 | 3.71875 | 4 | # Q this is about detecting the loop in a linkedList and printing out where the loop is?
from LinkedLists import LinkedList, Node
def loop(l):
pass
def main():
pass
if __name__ == '__main__':
main()
|
70e257694c47f412482f5035ea9178a0bb4e2dde | JessicaDeLuca/HelloWorld | /ex17_MoreFiles.py | 1,304 | 3.84375 | 4 | # Exercise 17
# Important functions
# open(),read(),raw_input(),len(),exists(), write(), close()
print "Begin Exercise 17: More Files \n"
#Copy one file to another file
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we c... |
2b0e4748d13be67e76c5c30deeb562f2ee83de08 | ostin-r/Calculator | /calculator.py | 3,816 | 3.796875 | 4 | '''
Austin Richards 1/5/21
this project made from the help of freeCodeCamp.org !!!
'''
from tkinter import *
gui = Tk()
gui.title("Simple Calculator")
# make the display
e = Entry(gui, width=40, borderwidth=2)
e.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# functions for the buttons
def button_click(numb... |
5412807d0657adf397e9221827a23d6dccdb0f33 | wzds2015/RemoteSensing_Geophysics | /glacier/quadtree/quadtree.py | 4,090 | 3.640625 | 4 | import numpy as np
import math
import matplotlib.pyplot as plt
def quadtree(data,th,max_l):
'''
function used for generating a quadtree
data (float): 2D image file (numpy array)
th (float): threshold for standard deviation
max_l (int): max level of leave (step=2**max_l)
'''
... |
70393e5145ded52cda4f8caec0eb63927c0a9a7b | Gabrielly1234/Python_WebI | /estruturaRepetição/questao28.py | 442 | 3.984375 | 4 | #Faça um programa que calcule o valor total investido por um colecionador em sua coleção de CDs
# e o valor médio gasto em cada um deles. O usuário deverá informar a quantidade de CDs
# e o valor para em cada um.
print("quant cd:")
quant= int(input())
i=0
soma=0
for i in range (quant):
print(" valor:")
valo... |
af332c5181e584b3eaaba4c0b1234912a529c6eb | nandybishal23/Calender-using-Python | /main.py | 1,463 | 3.6875 | 4 | from tkinter import *
import calendar
def showCal() :
new_gui = Tk()
new_gui.config(background = "#00154f")
new_gui.title("CALENDER")
fetch_year = int(year_field.get())
l1=Label(new_gui,text=fetch_year,bg = "#f4af1b",fg="#00154f",font = ("times", 30, 'bold'),width=20)
l1.gri... |
a69f311c9f7461171120713da699a0ad171b1f1c | henry808/euler | /033/eul033.py | 1,951 | 3.859375 | 4 | #! /usr/bin/python
from __future__ import print_function
from fractions import Fraction
# Project Euler # 33
def cancellable(num, den):
""" returns a list of all digits except 0
that are in both numerator and denominator"""
numorator = list(str(num).replace('0', ''))
denominator = list(str(den).repla... |
5ae034500e720a2bc12b2c6251b5ef7f59c21415 | Rich43/rog | /albums/4/problem9.py/code.py | 408 | 3.796875 | 4 | def is_member(lst, a):
'''(list,str) -> bool
return whether str is a member of lst
'''
x = 0
while x <= len(lst) - 1:
if lst[x] == a:
return True
x += 1
continue
... |
639995ac96283a256eeb5d03395a1bb3e56f96f3 | frclasso/Apresentacao_Biblioteca_Padrao_Python_Unifebe_2018 | /07_Date&Time/03_futureTimes_calendar.py | 670 | 4.03125 | 4 | #!/usr/bin/env python3
# Calculating future times
from datetime import datetime, timedelta
now = datetime.now()
testDate = now + timedelta(days=2) # 2 days from now
treeWeeksAgo = now - timedelta(weeks=3)
# print(f"Daqui a dois dias: {testDate.date()}") # it's a datetime instance
# print()
#
# print(f"Tree weeks ag... |
3166e0875614fd7d814834f2991adead058728f9 | 17mirinae/Python | /Python/DAYOUNG/14_동적 계획법1/1_피보나치수.py | 175 | 3.671875 | 4 | n = int(input())
fibo = [0, 1]
if n < 2:
print(fibo[n])
else:
for i in range(2, n+1):
num = fibo[i-1] + fibo[i-2]
fibo.append(num)
print(fibo[n]) |
7e0a51bb9192ce583f83a56ffae9f6ffdd4e184f | jwsoat/Python-Game | /test.py | 2,961 | 3.921875 | 4 | def gameselector():
import random
import time
game = 0
while game == 0:
game= int(input("Pick a game 1 - 3? "))
if game == 1:
while game == 1:
print("Game 1 Selected")
print("Maths Calc rounding to 2dp")
num1 = float(input("Number 1 "))
n... |
fc956051e95c71d1bb53748ee7da6f2cac42d95c | zihuan-yan/Something | /DataStructure/Mapping/__init__.py | 13,035 | 3.578125 | 4 | """
映射
"""
from abc import abstractmethod, ABCMeta
from typing import *
from random import randrange
class MapBase(MutableMapping, metaclass=ABCMeta):
class Item(object):
__slots__ = 'key', 'value'
def __init__(self, key, value):
self.key = key
self.value = value
... |
fb17b5e9dd3cb2059afa76cc1f376151c9e738d7 | denemorhun/Python-Reference-Guide | /Lesson 3 - More DS Examples/Ch07 - sets/07_02/start_07_02_sorting_friends.py | 1,352 | 3.84375 | 4 | """ Sorting Friends into Sets """
# set of all friends
friends = set(['Mark', 'Rae', 'Verne', 'Richard',
'Aaron', 'David', 'Bruce', 'Garry',
'Bill', 'Connie', 'Larry', 'Jim',
'Landon', 'Dillon', 'Frank', 'Tom',
'Kyle', 'Katy', 'Olivia', 'Brandon'])
# set of ... |
faac6d3557770a3d1ebb5d2d2dbaab4487ed422b | jefinagilbert/problemSolving | /hr97_findMedian.py | 112 | 3.71875 | 4 | def findMedian(arr):
arr.sort()
return arr[len(arr)//2]
arr = [5,3,1,2,4]
print(findMedian(arr)) |
caaae06f5becb0434e27280b4fcd19b9ad62aed1 | binrohan/30days_30problems | /problem010/day5.py | 434 | 3.75 | 4 | import math
def isPrime(num):
for x in xrange(2, int(round(math.sqrt(num))) + 1, 1):
if num%x == 0:
return False
return num!=1
sum = 77
n = 20
while n<2000000:
n += 1
if n>20 and n%2 != 0 and n%3 !=0 and n%4 !=0 and n%5 !=0 and n%6 != 0 and n%7 != 0 and n%8 != 0 and n%9 != 0 and n%11... |
2211445cdaeb1d2b65f4ef8acefce04d9a6450b7 | mygit20031984/py100exercises | /1_25/20.py | 113 | 3.765625 | 4 | d = {"a": 1, "b": 2, "c": 3}
print(sum(d.values()))
sum = 0
for e in d.values():
sum = sum + e
print(sum) |
39369c7228441056831214351e7bb0a782bddf0a | hudginspj/blue-limits | /experiments/collector.py | 927 | 3.65625 | 4 |
MIN_WINDOWS = 10
WINDOW_SIZE = 10
class Collector(object):
# The class "constructor" - It's actually an initializer
def __init__(self):
self.columns = 5
self.points = []
self.counter = -1
def addPoint(self, point):
self.points.append(point)
self.counter += 1
... |
722272b9c526fc90582909fb1479c231c3f4b973 | msmiel/mnemosyne | /books/Machine Learning/Machine Learning supp/code/appendixa-regular-expressions/FindCapitalized.py | 144 | 4.3125 | 4 | import re
str = "This Sentence contains Capitalized words"
caps = re.findall(r'[A-Z][\w\.-]+', str)
print('str: ',str)
print('caps:',caps)
|
5a86cc6a1b4ef28ca5bd741504d89f4985feb615 | alvas-education-foundation/Rakshith_Rai | /coding_solutions/chocolatefeast.py | 303 | 3.6875 | 4 |
def chocolateFeast(n, c, m):
k=n//c
n=k
while(n>=m):
n=n-m
n=n+1
k+=1
return k
t = int(input())
for t_itr in range(t):
ncm = input().split()
n =int(ncm[0])
c = int(ncm[1])
m = int(ncm[2])
result = chocolateFeast(n, c, m)
print(result)
|
2851c4ed95a9a90b8b717590400447a6736d1875 | SimeonTsvetanov/Coding-Lessons | /SoftUni Lessons/Python Development/Python Basics April 2019/Lessons and Problems/12 - Nested Loops Lab/05. Building.py | 363 | 3.71875 | 4 | levels = int(input())
rooms = int(input())
what_type = None
for i in range(levels, 0, -1):
for j in range(0, rooms):
if i == levels:
what_type = "L"
elif i % 2 == 0:
what_type = "O"
elif i % 2 != 0:
what_type = "A"
print(f"{what_type... |
9669b179d98ac843b0469cad4de591487d9a068e | shukhrat121995/coding-interview-preparation | /heap/kth_largest_element_in_an_array.py | 634 | 3.859375 | 4 | """
Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
"""
import heapq
class Solution:
def findKthLargest(self, nums: list[int], k: int) -> int:
heap = nums[:k]
hea... |
bea598056323e203609226ca17706eaa137d3c01 | JaydeepKachare/Python-Classwork | /Session12/Practice/02.py | 597 | 3.609375 | 4 | # Access specifiers in python Inheritance
class Base :
def __init__(self):
pass
def fun(self) : # public method
print("Inside Base.fun")
def _gun(self) : # protected method
print("Inside Base._gun")
def __sun(self) :... |
d9cf8c38b4f7d37210a597b0f86dec23e8e618ce | ingliscj/NCL-MSc-PORTFOLIO | /Python/BlackjackProject.py | 5,863 | 3.75 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
from IPython.display import clear_output
import random
suits = ['Diamonds', 'Hearts', 'Clubs', 'Spades']
ranks = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack'
,'Queen','King','Ace']
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six... |
0eeabcf630404d36f1521182bdda6369426636c7 | NickSeyler/MySortingAlgorithms | /Python/QuickSort.py | 1,548 | 4.25 | 4 | def quick_sort(arr):
# if we don't know whether or not the array is sorted...
if len(arr) > 1:
# set pivot to the first index
current_index = 0
# check all other items in the array
for i in range(1, len(arr)):
# if the item of the compared index is less tha... |
aaecacbd2de47f4bc441cfc7a26ae7703c5f1138 | david-sk/projecteuler | /src/problems/0062_cubic_permutations/v1.py | 1,067 | 3.65625 | 4 | #
# Cubic permutations, v1
# https://projecteuler.net/problem=62
#
# The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3)
# and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three
# permutations of its digits which are also cube.
# Find the smallest cube ... |
ff8cab7193a3b3858033dac06f67f0287b827aa7 | edinhooliveira/pyControl | /tkinter-matplot-test.py | 458 | 3.53125 | 4 | from tkinter import *
from PIL import ImageTk, Image
import numpy as np
import matplotlib.pyplot as plt
root = Tk()
root.title('Codemy.com - Learn to Code!')
#root.icobitmap('c:/GitHub/Python/Controle/ico/ifsp.ico')
root.geometry("400x200")
def graph():
house_prices = np.random.normal(200000, 25000, 5000)
... |
14f447b8fe4bb3e93c6df88f60bbb3c6b097f23f | chicocheco/automate_the_boring_stuff | /pdf_encrypting.py | 842 | 3.75 | 4 |
import PyPDF2
pdf_file = open('meetingminutes.pdf', 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
pdf_writer = PyPDF2.PdfFileWriter()
# Copy the PDF page by page.
for page_num in range(pdf_reader.numPages):
pdf_writer.addPage(pdf_reader.getPage(page_num))
# Encrypt the newly created PDF with the password '... |
6f3de8d13c6efdd7ab1d8119c8796127813ee7c8 | dkhroad/fictional-barnacle | /p5/linkedlist.py | 780 | 3.96875 | 4 | class Node(object):
def __init__(self,value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
self.last = None
self.current = None
def add(self,item):
node = Node(item)
if self.last:
se... |
c4dc7c5f0bd443c9bd32c53f4149c88a71b1095b | anto2318/python-blog | /bin/temp/openw.py | 1,046 | 3.625 | 4 | import requests
def main(dict):
city=dict["city"]
q=dict["q"]
if(city=="caracas"):
r=requests.get("http://api.openweathermap.org/data/2.5/forecast?q=caracas&APPID=3b31a7e394e41c3a30759dfde1a3383e&units=metric")
else:
r=requests.get("http://api.openweathermap.org/data/2.5/forecast?q=madr... |
b044102a3523535f1d12834626e232ccfe401ebe | catli/cs224 | /assignment1/q2_neural.py | 7,302 | 3.765625 | 4 | #!/usr/bin/env python
import numpy as np
import random
from q1_softmax import softmax
from q2_sigmoid import sigmoid, sigmoid_grad
from q2_gradcheck import gradcheck_naive
def output_sigmoid(X, W1, b1):
"""
Step 1 of forward propogation
Generate the sigmoid and the sigmoid gradient from input data
"... |
3e31997ffcefceaaed3e15ddeb8a70cfddc6f867 | kumakiwi/pypp | /29.py | 176 | 3.5625 | 4 | import sys
x = raw_input("input a number: ")
c = len(x)
print "the number has %d digits" % c
a = [i for i in x]
a.reverse()
for i in range(len(x)):
sys.stdout.write(a[i])
|
ad2453475b7d1ff3c48e088ca0fca1f98eccbff5 | codenigma1/Python_Specilization_University_of_Michigan | /Using Database with Python/Week-3/umich_rel_insert.py | 1,633 | 4.21875 | 4 | import sqlite3
conn = sqlite3.connect('relational.db')
cur = conn.cursor()
def create_table():
cur.execute("CREATE TABLE IF NOT EXISTS Artist (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT)")
cur.execute("CREATE TABLE IF NOT EXISTS Genre(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT)")... |
7f606e6bfeaf00925e792108ed24f162a072bdc8 | fernandofalla/Tarea1LFP | /Tarea1/PrintFunction.py | 167 | 3.9375 | 4 | def print_function(n):
cadena = ""
for i in range(n):
cadena += str(i+1)
return cadena
n = int(input("Ingrese numero: "))
print(print_function(n)) |
9b8bc108d4ccdfb5b80068cdf8e47d02ef1caba7 | ClaytonStudent/leetcode- | /OfferPython/18_delete_next_node.py | 599 | 3.828125 | 4 | # 题目:在O(1)时间内删除链表的节点
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Soluton(object):
def deleteNode(self,head,val):
if head.val == val:
return head.next
pre,cur = head, head.next
while cur and cur.val != val:
... |
19af0effc4f19b5f799c1562e40b639a8d2dfd8a | GBobzin/sqlalchemy-challenge | /app.py | 4,436 | 3.84375 | 4 | # Step 2 - Climate App
#Now that you have completed your initial analysis, design a Flask API based on the queries that you have just developed.
#* Use Flask to create your routes.
#Libraries
import numpy as np
import pandas as Pd
import datetime as dt
#Other tools
import sqlalchemy
from sqlalchemy.ext.automap ... |
ffadd78aaf27bedcde5084ac80500ddcaf870cab | claudejin/leetcode | /solutions/203_Remove_Linked_List_Elements.py | 692 | 3.640625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
# trim heads
while head and head.val == val:
head = head.... |
3133bf6f6b28c6c3996614742bd68e74a8f55131 | KBALDE/oc_ai_eng_2021 | /oc_p04_gthub/utils/utils_eng.py | 6,090 | 3.703125 | 4 | #import libraries
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn.metrics i... |
9f084c12bb463631ecdf20e2a97a4ec33595ea82 | Vadim91200/BlackJack | /ISN - Black Jack.py | 5,234 | 3.59375 | 4 | # -*- coding: utf-8 -*-
from random import *
jeu = [11, 11, 11, 11]
#Création de la liste jeu
def ajout_carte(main):
a = choice(jeu) #On sélectionne aléatoirement une carte dans la liste 'jeu'
main.append(a) #On ajoute cette carte a la liste 'main'
jeu.remove(a) #On retire cette carte de la liste 'je... |
bc0b134380f7b6ee4e9ce25bedaea8eb59c6fc81 | int-0/python-pce | /pre-src/rects.py | 2,612 | 3.90625 | 4 | #!/usr/bin/env python
"""
This simple example is used for the line-by-line tutorial
that comes with pygame. It is based on a 'popular' web banner.
Note there are comments here, but for the full explanation,
follow along in the tutorial.
"""
#Import Modules
import os, pygame
from pygame.locals import *
if not pygame... |
cfa73e903f7f28209ec2662d3b785323b3d12952 | JayaramachandranAugustin/python_tutorial | /variables/variableassignment.py | 444 | 4.0625 | 4 | import sys
a=2
print(type(a))
x,y,z=1,2,3
print("x is {} y is {} z is {}".format(x,y,z))
p,q=1,2
print("Before swap : p is {} q is {}".format(p,q))
p,q=q,p
print("After swap : p is {} q is {}".format(p,q))
l,m,n=[1,2,3]
print("l is {} m is {} n is {}".format(l,m,n))
#assign tuple to multiple variables
d,e,f=(1,2,3... |
627a073f5330942b70679bb92e29d5bc17cccba2 | PJHutson/prg105 | /7.2.py | 1,339 | 4 | 4 | def main():
import random # randomize
random_list = []
for i in range(20): # set it to 20 numbers
random_list.append(random.randrange(1, 101, 1)) # give the bounds
return random_list
def user(): # set up the user input
count = 0
... |
a07af432f7ab546c4daa2662a96b5c80806d04cb | SuperHong94/2020_1_ | /파이썬공부/python example/5week/simpleset.py | 692 | 3.578125 | 4 | from functools import *
def intersect(*ar): #함수인자이름앞에*은 가변인자리스트 (3장)
return reduce(__intersectSC,ar)
def __intersectSC(listX,listY):
setList=[]
for x in listX:
if x in listY:
setList.append(x)
return setList
def difference(*ar):
setList=[]
intersectSet=intersect(*ar) #여기 ... |
60c802a0dda1df93cae267073fb6f5d1a8780889 | HughP/comp-think | /2017-2018/exams/python/second-partial-examination_ex_5_binary_search.py | 1,278 | 3.90625 | 4 | def binary_search(item, ordered_list, start, end):
if start <= end:
mid = ((end - start) // 2) + start
mid_item = ordered_list[mid]
if item == mid_item:
return mid
elif mid_item < item:
return binary_search(item, ordered_list, mid + 1, end)
else:
... |
486a75558ba5ef70d72e374111774c28bf65860d | ankur990/pythonlab | /ankur.py20.py | 293 | 3.71875 | 4 | st = st.split(" ")
for i in range(0, len(st)):
st[i] = "".join(st[i])
dupli = Counter(st)
s = " ".join(dupli.keys())
print ("After removing the sentence is ::>",s)
if __name__ == "__main__":
st = input("Enter the sentence")
remov_duplicates(st)
|
02bb96b73e239bd30977e7093f78b11f6998b79e | Ankitmandal1/Hactoberfest2021 | /preOrder.py | 598 | 3.671875 | 4 | class TreeNode:
def __init__(self,val):
self.val = val
self.left = None
self.right = None
def preorderTraversal(root):
answer = []
preorderTraversalUtil(root, answer)
return answer
def preorderTraversalUtil(root, answer):
if root is None:
return
answer.appe... |
30de8c01b85f269adfb81d1aa667e6e0938b208a | kcildo/exercicios_python | /exercicios_aula09_persistencia_de_dados_arquivo/metodo_readline.py | 472 | 3.828125 | 4 | # O Método readline()
# lê somente uma linha
# dados = open('teste.txt', 'r')
# linha = dados.readline()
# print(linha, end='')
# dados.close()
# lê a o texto todo
nomeArquivo = input(
'Digite o nome do arquivo que deseja visualizar: ') # pede para o usuário entrar com o nome do arquivo a ser lido
dados = open(... |
2ebe212d0b04d55cda54f9eeca765199f5bb966c | barry800414/NewsCrawler | /method/DepBased/WFMapping.py | 1,512 | 3.5625 | 4 |
import json
'''
This code implements the function for
reading word-frequency mapping from files
'''
WF_Folder = './'
# load word-frequency mapping for each statement
def loadWFDict(filename):
with open(filename, 'r') as f:
WFDict = json.load(f)
# convert string to integer
newDict = dict(... |
54da56b836f6177fb1afdf4e8d9f8f65d87f54d7 | kangkang59812/LeetCode-python | /231.2-的幂.py | 885 | 3.578125 | 4 | #
# @lc app=leetcode.cn id=231 lang=python3
#
# [231] 2的幂
#
# https://leetcode-cn.com/problems/power-of-two/description/
#
# algorithms
# Easy (47.85%)
# Likes: 176
# Dislikes: 0
# Total Accepted: 52.6K
# Total Submissions: 109.9K
# Testcase Example: '1'
#
# 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。
#
# 示例 1:
#
# 输入: 1
# 输出:... |
a24863847403346d52b8545371042b96886bb558 | mohitsh/python_work | /ProbSolv/binary_search2.py | 531 | 3.796875 | 4 |
def binary_search(alist,item):
first = 0
last = len(alist)-1
found = False
while first <= last and not found:
mid = (first+last)/2
if item == alist[mid]:
found = True
else:
if item > alist[mid]:
first = mid+1
elif item < alist[mid]:
last = mid-1
return found, mid
alist = [1,4,7,10,15,1... |
c6268e6ae2d51e15017d1a2f081993f155e18e27 | JJader/python | /Lista/main.py | 1,507 | 3.984375 | 4 | from classes.celula import Cell
from classes.lista import Lista
import os
def cabecario():
print("1 --> adicionar no final")
print("2 --> adicionar no index")
print("3 --> remover")
print("4 --> pesquisar item")
print("5 --> pesquisar posição")
print("6 --> modificar")
print("7 --> imprimi... |
93794f6b08bd7f83a0176236a4fe89470f8a01e8 | Andremarcucci98/Python_udemy_geek_university | /Capitulos/Secao_13/seek_cursors.py | 1,596 | 4.53125 | 5 | """
Seek e Cursors
seek() -> É utilizada para movimentar o cursor pelo arquivo
arquivo = open('texto.txt')
print(arquivo.read())
# Movimentando o cursor pelo arquivo com a função seek()
# seek() -> A função seek() é utilizada para movimentação do cursor pelo arquivo. Ela recebe um parâmetro
arquivo.seek(0)
print(ar... |
98b15ef2f8a851640a3fc75a95925f83729ceb37 | junyechen/PAT-Advanced-Level-Practice | /1023 Have Fun with Numbers.py | 1,517 | 4.03125 | 4 | """
Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it ag... |
ada3c504c621b94ed8acc5c19ff95329b1a719a8 | zischuros/Introduction-To-Computer-Science-JPGITHUB1519 | /Lesson 2 - Problem Set/Median/median.py | 903 | 4.21875 | 4 | # Define a procedure, median, that takes three
# numbers as its inputs, and returns the median
# of the three numbers.
# Make sure your procedure has a return statement.
def bigger(a,b):
if a > b:
return a
else:
return b
def smaller(a,b):
if a < b:
return a
else :
re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.