blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
b6e7ec827a7599e859210944760d69423c3d6178 | Nyuhnyash/lab | /oop/lab10/4.py | 213 | 3.78125 | 4 | from math import sqrt
def pow_fun(n):
return lambda x: x ** n
sqr = pow_fun(2)
cube = pow_fun(3)
x = 1
while True:
y = 2 * cube(x) + 17
if sqrt(y).is_integer():
break
x += 1
print(x)
|
916ed922a0ae9b0aece9b4eb9e7b3c84b008d3e6 | Nyuhnyash/lab | /oop/lab8/3.py | 205 | 3.90625 | 4 | from math import sqrt
def only_squares(array: list[int]):
for num in array:
if sqrt(num).is_integer():
yield num
numbers = [1, 2, 3, 4, 5, 6]
print(list(only_squares(numbers)))
|
9420e9f73fb74350a4e0eeb525fc3df19cd79811 | Sztaat/Lens-Calculator | /lenscal2.py | 2,000 | 3.546875 | 4 | # -lenscalculator.py *- coding: utf-8 -*-
"""
Created on Fri Apr 3 09:45:13 2020
@author: Bartek Dell
Script calculating lens magnification
"""
option = [[1, 0.64], [2, 1], [3, 1.3], [4, 1.5], [5, 1.6], [6, 2.0],
[7, 2.7], [8, 4.55], [9, 5.62]]
def calcul(matrix):
fmin = int(input("Input m... |
c0a95dfdf5d086724bbb96875598facac45618fd | eliseoarivera/cs50transfer | /intro-python/day-one/ageCheck.py | 485 | 4.28125 | 4 | age = input("How old are you?")
"""if age >= "18":
print("You're old enough to vote!")
else:
print("You're not old enough to vote.")"""
age = input("How old are you?") # Read this as "Set age equal to whatever string the user types."
age = int(age) # We reassign the variable information here.
# In essence, "Set... |
56bd713a364a7abd0657341e45f71b57e2a611ef | eliseoarivera/cs50transfer | /intro-python/day-one/functions.py | 1,551 | 4.4375 | 4 | """def shout(name):
name = name.upper()
return "HELLO " + name + "!"
print(shout("Britney"))"""
"""def costForDisney(adults, children, days):
adult_cost = adults * 100
print("Calculated adult cost at " + str(adult_cost))
child_cost = children * 90
print("Calculated child cost at " + str(child_cost))
dail... |
12bc7e504d8e82868aba7292915a6f7463dec4d7 | Leandroborba-coder/Computacao-I-Python-UFRJ | /Machine Teaching.py | 24,061 | 3.828125 | 4 |
def num_bombons(d,p):
'''Insira o valor (d) referente ao dinheiro e o valor (p) referente
ao preço unitário do bombom para a função calcular a quantidade
máxima de bombons que podem ser comprados'''
return d//p
from math import *
def carros(p,c=5):
'''Função calcula a quantidade de carros... |
08453ee14f29d2ce397c6bf772649454e7965d65 | hsgdydh/selenium_basic | /2019-01/01-13/popup_dialog_Alert.py | 1,689 | 3.65625 | 4 | # encoding: utf-8
'''
今日练习:
一、selenium 处理弹出对话框,包括 提示框:alert(),确认框:confirm(),提示输入框:prompt()
拿到对话框的方式有两种:
1. Alert库 selenium.webdriver.common.alert.Alert
2. webdriver.switch_to_alert() 方法
对话框操作属性和方法有:
text 提示文本
accept() 确定
dismiss() 取消
... |
0e86ddd31f5e325abdfdfd4d46986f819fd4de24 | atlasbc/cs224n_2019 | /a5_public/cnn.py | 1,502 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS224N 2018-19: Homework 5
"""
### YOUR CODE HERE for part 1i
import torch
import torch.nn as nn
import torch.nn.functional as F
class CNN(nn.Module):
"""
A CNN that consists of Conv1d
@param input_size: (char_embedding_size, maximum_word_length) > ... |
fa899efa57d8d6fc54a94fecb3dce1c4a0fd5f6b | evamaina/Real-world-problem | /realworldproblem.py | 740 | 3.8125 | 4 | class Student:
def __init__(self,name,age,gender):
self.name=name
self.age=age
self.gender=gender
def __str__(self):
return"Hello,{}".format(self.name)
def details(self):
return "Name:{},Age:{},Gender:{}\
".format(self.name,self.age,self.gender)
class Registration(Student):
#method overloading
def __... |
42be07953e125f87fdea48c396005e7c7313a3e4 | RoqaiyyaMahmood/Ant-Colony-Optimization-Algorithm | /info_antcolony.py | 826 | 3.703125 | 4 | """
Args:
distances (2D numpy.array): Square matrix of distances. Diagonal is assumed to be np.inf.
n_ants (int): Number of ants running per iteration
n_best (int): Number of best ants who deposit pheromone
n_iteration (int): Number of iterations
... |
ee181b5a5acdb917e8fb265f469f99a81140e716 | yiaqing/CMPUT291_MINI_Project1 | /search_user.py | 3,643 | 3.796875 | 4 | import sqlite3
# Q5
# ********Search for users********
def search_user(cursor, keyword):
# Concatenate the strings to enable the use of LIKE function
keyword = '%' + keyword + '%'
# Select users containing the keywords
# the keywords are set to be case insensitive
cursor.execute('''SELECT *
... |
6d97b15eb7c90183bf61418bedba22a0fbe5d429 | lexipenia/repetition-bot | /repetition-bot.py | 1,328 | 3.5625 | 4 | from datetime import datetime
from random import choice
import tweepy
from config import *
from invisibles import *
def run():
print("Running repetition-bot.py at", str(datetime.now()))
tweetQuote()
print("Finished.")
def tweetQuote():
# authenticate and set up the Twitter bot
try:
auth... |
a8803c9a755d33efa0a111eae2b80cc2573803de | tcraven96/Cracking-the-Coding-Interview | /Cracking the Coding Interview/Question1-1.py | 798 | 4.1875 | 4 | # Implement an algorithm to determine if each string has all unique characters.
# What if you cannot use additional data structures?
import unittest
# Goes through string, replaces element found once with "" so that duplicates are not replaced.
# Will return if duplicate characters are found in the string.
def unique... |
7d9982d39a2f8a6937dfded0ddc2a03f00a6017d | jeanggabriel/jean-scripts | /curso em video/programaresolucaoporcramer3x3empython.py | 1,761 | 4.21875 | 4 | print ("\n Programa em Python para resolver um sistema de equa��es com tr�s inc�gnitas")
print ("\n Estou definindo um sistema de tr�s equa��es com tr�s inc�gnitas desta forma:")
print ("\n \n ax + by + cz = R1 \n dx + ey + fz = R2 \n gx + hy + iz = R3 \n")
print ("\n Digite os valores para: \n")
# O usu�rio d� valore... |
59e7f05076e7e7be68a818c394b38a34fcab7330 | devkudasov/py4e | /assignment_3_3.py | 322 | 4.0625 | 4 | rate = input("Enter rate (from 0 to 1)")
try:
r = float(rate)
except:
print("Enter number please")
quit()
if r < 0 or r > 1:
print("Number should be between 0 and 1")
elif r > 0.9:
print("A")
elif r > 0.8:
print("B")
elif r > 0.7:
print("C")
elif r > 0.6:
print("D")
else:
print("F"... |
ea9b0ef3655a3c1c8a71de6acce48e1b0c093bf9 | jaydeepdholakia/KBC_software | /quiz.py | 2,314 | 3.578125 | 4 | from pytrivia import Diffculty, Type, Category, Trivia
import random
import time
import textwrap
# initialising the text wrapper for question
wrapper = textwrap.TextWrapper(width=60)
# initialising the trivia
my_api = Trivia(True)
category_list = [Category.Animals, Category.Sports, Category.Books,Category.Art,
... |
a7a22cd1dbb90b317927f6b20e2bda03211ac055 | spencerwuwu/py-concolic | /pyex_exceptions/reverseWords.py | 718 | 4 | 4 | from symbolic.args import symbolic, concrete
@symbolic(s="a good example")
def reverseWords( s):
s = s.strip(' ')
array_s = []
last = ' '
for i in range(len(s)):
if s[i] != ' ':
array_s.append(s[i])
else:
if last != ' ':
array_s.append(s[i])
... |
610cd784e5c739e6c7fa0f032886abce9f675144 | homa0910/Python | /fibonacci_last_digit.py | 335 | 3.875 | 4 | # python3
import sys
input = sys.stdin.read()
tokens = input.split()
n = int(tokens[0])
def fibonacci_last_digit(n):
a = 0
b = 1
for i in range(0,n+1):
if i == 0:
c = a
elif i == 1:
c = b
else:
c = a + b
a = b
b = c
return c % 10
print (fibonacci... |
47b2fd3181a3bf11f4cadd1f9b3dfa1359d3f170 | aapetsi/Sprint-Challenge--Data-Structures-Python | /names/stretch.py | 1,593 | 3.8125 | 4 | import time
def binary_search_recursive(arr, target, low, high):
if low > high:
return -1
if low == high:
if arr[low] == target:
return low
else:
# mid = int((high - low) / 2 + low)
mid = low + ((high - low) // 2)
if target > arr[mid]:
return... |
f5bc910e44639ae828c56017c5f659e8c02c370c | LizaShengelia/100-Days-of-Code--Python | /Day10.Project.py | 1,278 | 4.3125 | 4 | from art import logo
#add
def add(n1, n2):
return n1 + n2
#subtract
def subtract(n1, n2):
return n1 - n2
#multiply
def multiply(n1, n2):
return n1 * n2
#divide
def divide(n1, n2):
return n1 / n2
operations = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide
}
def calculator():
print(log... |
86395c29c7a83c5fae7cd46030e581fd541adc02 | CYJGoh/Walletoro | /MinCashFlow.py | 2,107 | 3.71875 | 4 | import locale
locale.setlocale(locale.LC_ALL,'')
#Return the index of minimum value
def getMin(arr):
minInd = 0
for i in range(1, N):
if (arr[i] < arr[minInd]):
minInd = i
return minInd
#Return the index of maximum value
def getMax(arr):
maxInd = 0
... |
b11e9cd116ce1dd819ecebf8a878426bdf28ae8c | voronoff2803/cs102 | /Home Work 1/caesar.py | 1,360 | 4.03125 | 4 | def encrypt_caesar(plaintext, shift):
"""
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("")
''
"""
ciphertext = ""
for i in plaintext:
if 64 < ord(i) < 64 + 26:
if ord(i) > 64 + 26 - shift:
ciphe... |
3a1a946d7b4436ed11cc995fd95fdd293eed2048 | kshitij-v-mehta/adiosvm | /Tutorial/gray-scott/size_calculator.py | 949 | 3.734375 | 4 | #!/usr/bin/env python3
import sys
#----------------------------------------------------------------------------#
def check_argv():
if len(sys.argv) < 2:
print("Need arguments: L num_steps (optional, default=1)")
sys.exit(1)
size = int(sys.argv[1])
num_steps = 1
if (len(sys.argv) ... |
d4bdda4bb911e6b208192ca9a8c458cd9ff1f84b | aamirg/MapReduce | /friend_count.py | 1,041 | 3.90625 | 4 |
import MapReduce
import sys
"""
Friend Count Example in the Simple Python MapReduce Framework
For each record we emit the count alongwith the name of the first person.
In the reduce phase all the keys are grouped and the total count is calculated by adding the values
"""
mr = MapReduce.MapReduce()
# ===============... |
838199a2c086e0d14c80d30162e3ed2d8a658f56 | ermanh/dailycoding | /20200722_concurrent_intervals.py | 1,205 | 3.828125 | 4 | '''
2020-07-22
[from dailycodingproblem.com #21]
Given an array of time intervals (start, end) for classroom lectures
(possibly overlapping), find the minimum number of rooms required.
For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
'''
def classrooms(array):
rooms = 1
for i, (a, b) ... |
3e45bfb5c992d8e0e0f8daf003cbb5a2c56cb602 | ermanh/dailycoding | /20200712_subset_sum.py | 1,247 | 3.65625 | 4 | '''
Work In Progress
[from dailycodingproblem.com #42]
Given a list of integers S and a target number k, write a function that
returns a subset of S that adds up to k. If such a subset cannot be made, then
return null.
Integers can appear more than once in the list. You may assume all numbers in
the list are posit... |
df6c4c6355a62b8545bb50779b624a3ad6ce8a3c | ermanh/dailycoding | /20200715_inversion_count.py | 2,116 | 4.1875 | 4 | '''
2020-07-15
[from dailycodingproblems.com #44]
We can determine how "out of order" an array A is by counting the number of
inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j]
but i < j. That is, a smaller element appears after a larger element.
Given an array, count the number of inver... |
89a63d37c1520e8a2e2adeb42a92fbf0214cf72a | ermanh/dailycoding | /20200706_balanced_brackets.py | 1,509 | 4.25 | 4 | '''
2020-07-06
[from dailycodingproblem.com #27]
Given a string of round, curly, and square open and closing brackets, return
whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
'''
def balan... |
f06e6cb2349160b53b3897dee89b9a8620b47a4a | ermanh/dailycoding | /20200727_line_breaks.py | 1,604 | 4.25 | 4 | '''
2020-07-27
[from dailycodingproblem.com #57]
Given a string s and an integer k, break up the string into multiple lines
such that each line has a length of k or less. You must break it up so that
words don't break across lines. Each line has to have the maximum possible
amount of words. If there's no way to bre... |
ef42e596a5907e276a457ac0483200b0936516aa | Leoni-Ferreira/python_classes | /solutions/cap01/ex6.py | 509 | 3.59375 | 4 | #lendo os votos
b = int(raw_input("qtos votos brancos? "))
n = int(raw_input("qtos votos nulos? "))
v = int(raw_input("qtos votos validos? "))
#converte para porcentagem
# total - 100%
# brancos - x
# x * total = brancos * 100
# x = (brancos * 100)/total
t = b + n + v
pB = float(b * 100) / t
pN = float(n ... |
7e4a9961db420a2b43313c86268ebb25fe425d26 | Leoni-Ferreira/python_classes | /solutions/cap03/ex02.py | 125 | 4.125 | 4 | numero = 0
while numero <= 100:
numero = int(raw_input("digite numero: "))
numero = numero * 3
print numero
|
fd9a494748b880434574764477c727099815bf09 | Leoni-Ferreira/python_classes | /solutions/cap02/ex06.py | 250 | 3.84375 | 4 | n1 = float(raw_input("digite o n1 "))
n2 = float(raw_input("digite o n2 "))
if n1 == n2:
print "sao iguais"
else:
print "sao diferentes"
if n1 > n2:
print str(n1) + " 7 " + str(n2)
else:
print str(n2) + " " + str(n1) |
54865da35ad389158e5d9e23d5c50dd6bfc5912e | Leoni-Ferreira/python_classes | /solutions/cap05/ex04.py | 1,222 | 3.96875 | 4 | # -*- coding: utf-8 -*-
from math import pi
def calculaAreaCirculo(raio):
area = raio**2 * pi
return area
def calculaAreaRetangulo(altura, largura):
area = altura * largura
return area
def calculaAreaTriangulo(base, altura):
area = (base*altura)/2
return area
def menu():
print "C... |
92527fefbbb9e13cd7ed2badd7026707e678781a | Leoni-Ferreira/python_classes | /solutions/cap01/ex13.py | 112 | 4.09375 | 4 | from math import sqrt
num = float(raw_input("digite um numero: "))
r = sqrt(num)
print "a raiz eh: " + str(r) |
2a5c5f4b0edb07418979a585060f03c59fe1d771 | chenya1123236324/python-examples | /function_module/os_example.py | 1,541 | 3.5625 | 4 | # -*- coding:utf-8 -*-
import os
import sys
import chardet
__author__ = 'Evan'
# 获取父级完整路径
print(os.path.dirname(__file__))
# 获取当前路径的文件名
print(os.path.basename(__file__))
print('getcwd ==>', os.getcwd()) # 获取当前目录路径
print('path ==>', sys.path[0]) # 获取当前目录路径
print('dirname ==>', os.path.dirname(os.path.abspath(__fil... |
5b359fff4ad6f99ebe45d8912ebd97b015d4f20f | dominikjurinic/geometric-integrator | /python-implementation/skew.py | 290 | 3.640625 | 4 | import numpy as np
def skew(x):
x_skew = np.zeros((3,3))
x_skew[0,1] = (-1)*x[2]
x_skew[0,2] = x[1]
x_skew[1,2] = (-1)*x[0]
x_skew[1,0] = x[2]
x_skew[2,0] = (-1)*x[1]
x_skew[2,1] = x[0]
return x_skew
|
d6a249c5f49bae6495eeaaf2fe118286fe9f55e5 | cartoonshow57/SmallPythonPrograms | /multiples_of_num.py | 386 | 4.46875 | 4 | """This program takes a positive integer
and returns a list that contains first five multiples of that number"""
def list_of_multiples(num1):
lst = []
for i in range(1, 6):
multiple = num1 * i
lst.append(multiple)
return lst
num = int(input("Enter a positive number: "))
print("The first... |
de55a87bc414dc26a65f9b12d350550779446579 | cartoonshow57/SmallPythonPrograms | /nested_loop.py | 252 | 4.25 | 4 | # A dummy program for how a nested loop works
print("Nested loop example")
print("-------------------------------")
for i in range(1, 4, 1):
for j in range(1, 1001, 999):
print(format(i * j, "8d"), end="")
print()
print("EOP")
input()
|
5cf128f4cb83571f291b8d6981914cb0106c372a | cartoonshow57/SmallPythonPrograms | /sum_of_array.py | 392 | 4.21875 | 4 | # This program prints the sum of all the elements in an array
def sum_of_array(arr1):
total = sum(list(arr1))
return total
arr = []
n = int(input("Enter the number of elements in the array: "))
for i in range(n):
arr.append(int(input("Enter no. in array: ")))
print("The given array is,", arr)
print("... |
89a4b8735d13a7a2536d3fa18c80cda5c8b46b68 | cartoonshow57/SmallPythonPrograms | /array_replacement.py | 661 | 4.21875 | 4 | """Given an array of n terms and an integer m, this program modifies
the given array as arr[i] = (arr[i-1]+1) % m and return that array"""
def array_modification(arr1, m1):
test_arr = []
index = 0
for _ in arr1:
s = (arr1[index - 1] + 1) % m1
test_arr.append(s)
index += 1
retur... |
40247c58ddd68593214c719ac84db9252174b69c | cartoonshow57/SmallPythonPrograms | /first_and_last.py | 431 | 4.1875 | 4 | """This program takes an array
and deletes the first and last element of the array"""
def remove_element(arr1):
del arr1[0]
del arr1[-1]
return arr1
arr = []
n = int(input("Enter number of elements in the list: "))
for i in range(n):
arr.append(int(input("Enter array element: ")))
print("The give... |
e94bea13a8664f51adbcfaaff50367a157678dda | cartoonshow57/SmallPythonPrograms | /replicate_elements.py | 609 | 4.0625 | 4 | """This program takes a list and an integer and replicates each array element
by integer times"""
def replicate_n_times(lst1, n1):
lst2 = []
for i in lst1:
if i not in lst2:
for j in range(n1):
lst2.append(i)
return lst2
lst = []
num = int(input("Enter the number of ... |
33cc317f27a59d9b6e58b3426c734740d7f5c621 | motirase/holbertonschool-higher_level_programming-1 | /0x03-python-data_structures/7-add_tuple.py | 701 | 3.796875 | 4 | #!/usr/bin/python3
def add_tuple(tuple_a=(), tuple_b=()):
val1 = 0
val2 = 0
if len(tuple_a) == 0:
val1 = 0 + tuple_b[0]
val2 = 0 + tuple_b[1]
elif len(tuple_b) == 0:
val1 = tuple_a[0] + 0
val2 = tuple_a[1] + 0
else:
list_tmp1 = list(tuple_a)
list_tmp2 ... |
8c841eabc2a03af875f2b7286a86c2e5ac14eae4 | motirase/holbertonschool-higher_level_programming-1 | /0x07-python-test_driven_development/0-add_integer.py~ | 472 | 4.21875 | 4 | #!/usr/bin/python3
"""
function 0-add_integer
adds two integers
"""
def add_integer(a, b=98):
"""adds two numbers
>>> add_integer(4, 3)
7
>>> add_integer(5, 5)
10
"""
fnum = 0
if type(a) is int or type(a) is float:
fnum += int(a)
else:
raise TypeError("a must be a... |
3546fc7444e73e0d2164905195fb1f3abc2d0a97 | RRFreitas/SongPopHack | /SongPop.py | 1,182 | 3.59375 | 4 | import json
import sys
"""
Usage:
python SongPop.py (and put the json in console)
or
python SongPop.py -f (read the json from file "input.json")
"""
def main(args=[]):
try:
if(len(args) > 1 and args[1] == "-f"):
arq = open("input.json")
... |
495492eecfa2b13be33be63b0b56ffa0f4f840be | Sharmagajendra/python | /database/insert_row.py | 605 | 3.59375 | 4 | #-------------------------------------------------------------------------------
# Name: insert row
# Purpose: add a new record in any existing database table
#
# Author: rakesh kumar
#
# Created: 12-04-2018
# Copyright: (c) acer 2018
# Licence: MIT
#-------------------------------------------... |
050c85beefc6d9fda27cf3caf22081cf8d7c1b80 | Techzune/ISE-Group2 | /Algorithm/BubbleSort.py | 5,470 | 3.578125 | 4 | # Title: BubbleSort
# Author: Avan Patel, Kohler Smallwood, Azlin Reed, Jordan Stremming, Steven Huynh, Zach Butterbaugh, Thea Furby
# Purpose: Take in List and check the element at index I and I+1. If element i > i+1, then it swap the element.
# At the end of 1st run, the last element in the array will be largest..... |
278381ec6d365736b93cfd168780008c070d3302 | Techzune/ISE-Group2 | /Algorithm/MergeSort.py | 5,310 | 3.703125 | 4 | # title: MergeSort
# author: Avan Patel, Kohler Smallwood, Azlin Reed, Jordan Stremming, Steven Huynh, Zach Butterbaugh, Thea Furby
# purpose: algorithm;
import Utils
from Algorithm.Algorithm import Algorithm
from GUI.CodeHighlightWindow import CodeHighlightWindow
from GUI.VisualizationWindow import VisualizationWindow... |
c2bffd3b8b625c1ec5e0729ecb067ff7005fcfdf | brunarodrigues/programacao-orientada-a-objetos | /prova/oo/conta.py | 2,403 | 3.609375 | 4 | import datetime
class Conta:
def __init__(self,numero,titular, saldo, limite,data_abertura):
self.numero = numero
self.titular = titular
self.saldo = saldo
self.limite =limite
self.data_abertura = data_abertura
self.historico = Historico()
def deposita(self,valo... |
aa837ca727cf3d0002e0cb787689f5357388efba | brunarodrigues/programacao-orientada-a-objetos | /listas/lista-de-exercicios-07/questao-8.py | 994 | 3.53125 | 4 | class Tamagotchi:
def __init__(self,nome="luz",fome=10,saude=10,idade=0):
self.nome = nome
self.fome = fome
self.saude =saude
self.idade =idade
def alterar_nome(self,novo_nome):
self.nome = novo_nome
def retornar_fome(self):
return self.fome
def retorn... |
9430f4ada072bbd63d7f622ccf73de8889526b2e | brunarodrigues/programacao-orientada-a-objetos | /listas/lista-de-exercicio-02/questao-08.py | 254 | 3.875 | 4 | ganho_por_hora = float(input('Quanto você ganha por hora:'))
horas_trabalhadas_no_mês = float(input('Horas trabalhadas no mês:'))
calculo = ganho_por_hora*horas_trabalhadas_no_mês
print('O salário no referido mês é igual a:{:.2f}'.format(calculo)) |
1dbb5b6a02279a5765d5f74ed94660f6eac07147 | brunarodrigues/programacao-orientada-a-objetos | /prova/oo/teste_conta.py | 439 | 3.9375 | 4 | def cria_conta(titular,numero,saldo,limite):
'''cria uma conta'''
conta = {"titular": titular, "numero": numero,"saldo": saldo, "limite": limite}
return conta
def deposita(conta,valor):
#conta na posiçao saldo é igual conta na posiçao saldo mais valor
conta['saldo']+= valor
def saca(conta,valor)... |
00bceec1df11f381f00ee177593c7557777264f2 | varishtyagi786/My-Projects-Using-Python | /Percentage and grade.py | 727 | 4.0625 | 4 |
hindi = int(input("HINDI "));
english = int(input("ENGLISH "));
maths = int(input("MATHS "));
science = int(input("SCIENCE" ));
history = int(input("HISTORY"));
sum = hindi + english + maths + science + history;
average = sum/5;
if(average>=91 and average<=100):
print("Your Grade is A+");
elif(average>=81 and a... |
947a91e08a5bea6a872f0ff18d39b2791d352a70 | varishtyagi786/My-Projects-Using-Python | /LargeNumb.py | 102 | 4.125 | 4 | a=float(input("Enter A "))
b=float(input("Enter B "))
print("A is Greater" if a>b else "B is Greater") |
d63d6b0e3a2695195a24b7445af3e22ef85d4175 | varishtyagi786/My-Projects-Using-Python | /format.py | 230 | 3.875 | 4 | t1='My name is {name}, I am {age} years old.'.format(name='Varish',age=23)
print(t1)
t2='My name is {}, I am {} years old.'.format('Varish',23)
print(t2)
a={'x':'Varish','y':'Tyagi'}
print('{x} last name is {y}'.format_map(a)) |
b553ce6c22ed0080c7d20ae90d512a9b45f1701a | varishtyagi786/My-Projects-Using-Python | /polindrome.py | 100 | 3.765625 | 4 | val=input('ENTER A NAME: ')
if val[::1]== val[::-1]:print('Ploindrome')
else:print('Not Polindrome') |
b6eaa8e95f0765bc55f96c554e7da1c6153b7daf | varishtyagi786/My-Projects-Using-Python | /matrix.py | 1,296 | 4.09375 | 4 | import numpy as np
# Get the size m and n
m , n = 4, 4
# Function to calculate sum of each row
def row_sum(arr) :
sum = 0
print("\nFinding Sum of each row:\n")
# finding the row sum
for i in range(4) :
for j in range(4) :
# Add the element
... |
bf094483c1d4fcc049e9fcb3aab8c57e8429badf | hly189/hw | /lab3.py | 1,585 | 4.1875 | 4 | def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1)
def sum(n):
if n==0:
return 0
else:
return n + sum(n-1)
def ab_plus_c(a,b,c):
if b==0:
return c
else:
return a + ab_plus_c(a, b-1,c)
def square(x):
return x*x
def summation(n, term):
"""
>>> summation(3, square)
14... |
5526dec00b1d75c7e3b63f308811fabedb70eb24 | JBMatthews/python-for-everybody | /python-data-structures/assignments/9.3_dictionaries-and-files.py | 841 | 3.9375 | 4 | # 9.3 - Lecture Code
# ---wordcount---
# counts = dict()
# print('Enter a line of text:')
# line = input('')
#
# words = line.split()
#
# print('Words:', words)
#
# print('Counting...')
# for word in words:
# counts[word] = counts.get(word,0) + 1
# print('Counts', counts)
#-----------------
# ---iteration---
# cou... |
587b57636c109e71d07512604cfee2bfe3742b5a | JBMatthews/python-for-everybody | /python-data-structures/assignments/10.2_assignment/solution.py | 878 | 4 | 4 | # 10.2 Data Structures - Tuples
#
# Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
#
# From stephen.marquard@uct... |
fb7d4013fd9394072a043c958e1e35b1ff8f3b63 | Dyke-F/Udacity_DSA_Project1 | /Task4.py | 1,441 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to i... |
fe0ef3a5f54b126f48851e0cb5c624573e39525e | Savanahruss/HPM573S18_RUSS_HW1 | /HW 1 Question 3.py | 272 | 3.90625 | 4 | #----Question 3
#Iterative Function
def sum_it(n):
sum=0
for i in range(1,n+1):
sum+=i
return sum
print(sum_it(100))
#Recursive Function
def sum_rec(n):
if n==1:
return 1
else:
return n+sum_rec(n-1)
print(sum_rec(100)) |
7ddf777449a1f238ea4b871de0e99b4145860a1a | nawabsherif/Python | /largest.py | 111 | 3.8125 | 4 | a=input("")
b=input("")
c=input("")
if(a>b and a>c):
print(a)
elif(b>c and b>a):
print(b)
else:
print(c)
|
97d37723bc1007274843b2191809912082796416 | littlefishna/algorithm012 | /Week_01/[42]Trapping Rain Water.py | 1,395 | 3.828125 | 4 | # Given n non-negative integers representing an elevation map where the width of
# each bar is 1, compute how much water it is able to trap after raining.
#
#
# The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In
# this case, 6 units of rain water (blue section) are being trapped. Thanks... |
d6396e1980649d9fcfbe3e5a50f3fb6f37016731 | aditya-sengupta/misc | /ProjectEuler/Q19.py | 1,067 | 4.21875 | 4 | """You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs o... |
f2ab261697d8f04b5456bc720aac6c29f65763c3 | wicrant/Practice | /Tables.py | 266 | 4.0625 | 4 |
def main():
number = int(input ("Enter a number: "))
printtable (number)
def printtable (number):
i = 0
for i in range (11):
print (int(number),"\tx\t", i, "\t=\t", number * i)
return
main()
input ("Press any key to exit\n")
|
7d0a06f1a2e5fc215a732701453d9d8fe29cd903 | Ahmad-Magdy-Osman/DataAnalysisVisualization | /7-IMDB500TopMoviesAnalysis/scrapper.py | 3,520 | 3.578125 | 4 | import requests
from lxml import html
import json
import csv
def main():
# Using XPath and JSON to extract a dictionary of all top 500 IMDB movies IDs
imdb = requests.get("https://www.imdb.com/list/ls003073623/")
tree = (html.fromstring(imdb.content))
movies = tree.xpath('//html/head/script[@type="app... |
4a23e0c6f4d83ccc06d85bf80abc8afd2ffbd12e | LevariUlnerWork/IR | /parser_module.py | 27,435 | 3.578125 | 4 | import calendar
import re
from document import Document
from spellchecker import SpellChecker
class Parse:
def __init__(self, indexer):
#self.stop_words = stopwords.words('english') - we are not use this stop words
full_path = open('stop-words.txt',"r")
listOfStopWords = full_path.read()
... |
e49f98c842e904d7abd6fe08eb55f1276c49d6a9 | activateslikestacos/csusb-demo | /main.py | 15,343 | 4.59375 | 5 | '''
Author: Christopher Cox
Email: chris15588@gmail.com
Description: This program's purpose is to help demonstrate some basic principles
of Python coding, and to serve as a reference guide for later programs.
'''
# -- Defining Variables --
'''
What are variables? If you've ever taken a math class, you probably alr... |
5d393e90f23624f1a27ca7af73fa9606e08beaf4 | B3rtje/dataV2-labs | /module-1/Code-Simplicity-Efficiency/your-code/challenge-2_test.py | 1,678 | 4.25 | 4 |
import string
import random
def new_string(length):
letters = string.ascii_lowercase+string.digits
str = ''.join(random.choice(letters) for num in range(length))
return str
#print(get_random_string(10))
def string_gen ():
strings = []
number_of_strings = input("How many strings do you want... |
f7f1743eda2a97de802de5cd5e19d4301f494a0d | ECNUzhaoming/10.10class | /Untitled.py | 3,602 | 4.375 | 4 |
# coding: utf-8
# In[1]:
#字符串
str="Hello,world!"
# In[2]:
str[5]
# In[3]:
len(str)
# In[4]:
max(str)
# In[5]:
print(str.upper())
# In[6]:
print(str.lower())
# In[7]:
print(str.title())
# In[8]:
#任何一个有返回值的函数在原则上都不会改变字符串自身
# In[9]:
str="hello"
name="zm"
print(str+name)
# In[10]:
str.join(nam... |
7eb7c17f239d8e78c77bf8a7bcf8bc384862c232 | lunar-logan/desi-ada-commercial-edition | /compile-master/evilx.py | 3,257 | 4.25 | 4 | def foo(x):
"""Python will do constant folding and make this method equivalent to
foo_fold."""
return 1 + 2 + 3 + 4 + x
def foo_fold(x):
return 10 + x
def baz(x):
"""Python will also do constant folding and make this function equivalent
to baz_fold."""
return x + (1 + 2 + 3 + 4)
def baz_f... |
169d2f11038906f6852645dfb742fc0b372c5a84 | lunar-logan/desi-ada-commercial-edition | /compile-master/exprblock.py | 1,683 | 3.96875 | 4 | # exprblock.py
'''
Project 7: Basic Blocks and Control Flow
----------------------------------------
This file defines classes and functions for creating and navigating
basic blocks. You need to write all of the code needed yourself.
See Exercise 7.
'''
class Block(object):
def __init__(self):
self.instr... |
486440929bfc62b5fc48823002c695afeacd67bb | sailesh190/pyclass | /mycode/add_book.py | 252 | 4.375 | 4 | address_book = []
for item in range(3):
name = input("Enter your name:")
email = input("Enter your email:")
phone = input("Enter your phone number:")
address_book.append(dict(name=name, email=email, phone=phone))
print(address_book) |
b8ab10bf9a92e47f6dca4572e58db96a5d02bf91 | franpad8/advent-of-code-solutions | /Day18/puzzle.py | 2,114 | 3.734375 | 4 | import fileinput
HEIGHT = 50
WIDTH = 50
def print_grid():
for x in range(0, HEIGHT):
row = ""
for y in range(0, WIDTH):
row += grid[x][y]
print(row)
def add_points(p1, p2):
return (p1[0] + p2[0], p1[1] + p2[1])
def adjacents(x, y):
ds = [(x ,y) for x in range(-1,2) for y in range(-1,2) if (x, y) != (0... |
405fbc0f2d07a41d15ff248af2e429e45de498e7 | AhmUgEk/tictactoe | /tictactoe_functions.py | 1,974 | 4.125 | 4 | """
TicTacToe game supporting functions.
"""
# Imports:
import random
def display_board(board):
print(f' {board[1]} | {board[2]} | {board[3]} \n-----------\n {board[4]} | {board[5]} | {board[6]}\
\n-----------\n {board[7]} | {board[8]} | {board[9]} \n')
def player_input():
marker = 0
... |
de3dc642ada2cbf706ad730522cf2dd8b0f042b0 | AlexHahnPublic/EulerProblems | /problem3_LargestPrimeFactor.py | 1,453 | 4.03125 | 4 | # Euler Problem 3:
# The prime factors of 13195 are, 5, 7, 13, and 29
# What is the largest prime factor of the number 600851475143?
import time
def largestPrimeFactor(n):
start_time = time.time()
original_n = n
i = 2
# This next statement is often confused/ not stated correctly as "the largest
# pri... |
d78a3feb7959670aab6684a069d23e7d96feae43 | AlexHahnPublic/EulerProblems | /problem5_SmallestMultiple.py | 3,103 | 3.546875 | 4 | # Euler Problem 5:
# 2520 is the smallest number that can be divided by each of the numbers
# from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the
# numbers from 1 to 20?
# Solution: starting at 1 and incrementing until we find a number that is
# divisible ... |
e5e4011f6e565eeb106995e94a5d42b0ca5ec02b | AlexHahnPublic/EulerProblems | /problem8_LargestProductInASeries.py | 1,581 | 3.953125 | 4 | # Euler Problem 8:
# The four adjacent digits in the 1000-digit number that have the greatest
# product are 9x9x8x9=5832
# number place holder
#Find the thirteen adjacent digits in the 1000-digit number that have the
# greatest product. What is the value of this product?
# Solution:
# I think the best way to go... |
f59d1cdb320110df45c4594d131216bb073e5546 | AlexHahnPublic/EulerProblems | /problem1_3sand5s.py | 750 | 4.09375 | 4 | # Euler Problem 1:
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we
# get 3, 5, 6, and 9. The sum of these multiples is 23
# Find the sum of all the multiples of 3 and 5 below 1000.
# Solution: trial division, check each number up to n, if divisible by 3 or 5
# add it to the running tota... |
2805c79ba63c5cd76586f7e49b123a9b836aec59 | karnikkanojia/TicTacToe-AI | /tictactoe.py | 4,225 | 4.09375 | 4 | """
Tic Tac Toe Player
"""
import math
from copy import deepcopy
DEPTH = 5
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
... |
7db3f3aabd6068ea1a1b4e1ffb9c810a3d7b1579 | mayank26saxena/youtube-video-like-count-prediction | /channel_description.py | 1,835 | 3.546875 | 4 | import urllib
import json
import sqlite3
db_connection = sqlite3.connect(
'./youtube.db')
db = db_connection.cursor()
all_channel_ids = []
#db_connection.close()
#db.execute("CREATE TABLE CHANNEL(channelId NOT NULL, channel_commentCount INT, channel_viewCount INT, channel_videoCount INT, channel_subscriberCount I... |
f45720d574a99966b56d1be747219e84e2606c13 | pandeyank/LearningPython | /pythonProject/GFG Program/insertion.py | 295 | 3.890625 | 4 | arr=[12,11,13,5,6]
def insertion_sort(arr,i):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while j>=0 and key < arr[j]:
arr[i+1]=arr[j]
j=j-1
arr[j+1]=key
i=len(arr)
p=insertion_sort(arr,i)
for i in range(len(arr)):
print(arr[i])
|
739da6e64758a14cc011f344fd844e325a82009a | pandeyank/LearningPython | /pythonProject/factorprime.py | 269 | 3.984375 | 4 | n=int(input("Enter the number:"))
def prime(n):
for i in range(2,n):
flag=True
for j in range(2,i):
if(i%j==0):
flag=False
break
if flag==True:
print("The prime factors is:",i)
c=prime(n) |
7624b2e53e58db0a9da9e2087f9ba36b7852f37b | pandeyank/LearningPython | /pythonProject/subarray1.py | 404 | 3.546875 | 4 | a=[10,-25,130,10,80,-180,160,70]
def maxsum(a,n):
cross_sum=0
max_sum=0
for i in range(n):
max_sum=a[i]
for j in range(i,n):
cross_sum=cross_sum+a[j]
if cross_sum>max_sum:
max_sum=cross_sum
if cross_sum<0:
cross_sum=0
... |
3f08543d935ea58f044f3a725b67e5558804a191 | ealmuina/DS_Parallel_Tasks | /parallel_tasks/libraries/string.py | 436 | 3.515625 | 4 | import os
import random
def get_random_file(filename, length):
with open(os.path.join('input', filename), 'w') as f:
s = get_random_string(length)
f.writelines((s + '\n',))
def get_random_string(length):
result = ''
for i in range(length):
a = random.choice(('a', 'A'))
re... |
2d6ec931165dbfabd46c713fd994060d9a288f42 | vickyKesavan/vignesh | /Vowels.py | 210 | 3.703125 | 4 | am=(input())
if ((int(ord(am))>=65 and int(ord(am))<=122)):
if am in ('a','e','i','o','u','A','E','I','O','U'):
print("Vowels")
else:
print("Consonants")
else:
print("Invalid")
|
1d41b23c669a817488206bad27b1e67cfbb2de90 | vickyKesavan/vignesh | /Repeated.py | 306 | 3.65625 | 4 | def repeat(a):
size=len(a)
repeated=[]
for i in range(size):
j=i+1
for k in range(i):
if a[i]==a[k] and a[i] not in repeated:
repeated.append(a[i])
return repeated
b=int(input())
a=list(map(int,input().split()))
a.sort()
print(repeat(a))
#vignesh
|
0cf09ec8378967fb5072d7b12a71c9788580e400 | vickyKesavan/vignesh | /Arm.py | 175 | 3.53125 | 4 | a=int(input())
order=len(str(a))
temp=a
num=0
while temp>0:
rem=temp%10
num += rem**order
temp=temp//10
if a==num:
print("yes")
else:
print("no")
#vignesh
|
da721e68614ec96c24d5cf52dc769d6bcd97b479 | AndrewQuijano/w4156-lecture-code | /lectures/ooad/intro/oo/bodega.py | 2,557 | 3.921875 | 4 | from collections import defaultdict
"""
Admittedly - this is not a direct translation of the procedural version (this one is richer functionality)
"""
class Product:
"""
A product is a thing we sell
"""
def __init__(self, sku, name, price):
self.sku = sku
self.name = name
self... |
1e996b0083d2a6db7c7cf90cca58a994c2e04db4 | princekumar840946/preprocessing-data- | /linear regression model.py | 1,146 | 4.03125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#importing dataset
dataset=pd.read_csv("salary_data.csv")
x=dataset.iloc[: , :-1].values
y=dataset.iloc[: , 1].values
#splitting the data set into trainig data and test data
from sklearn.model_selection import train_test_split
x_train,x... |
17294e691b308ac465ddaa3e46c99e746f7aa075 | Kevin0920/Python-basics | /multiple-sum-avarage.py | 379 | 3.65625 | 4 | # Multiples
# 1
# for index in range(1,1000):
# if index%2 != 0:
# print index
#2
# for index in range(5,1000000):
# if index%5 == 0:
# print index
# Sum List
a = [1, 2, 5, 10, 255, 3]
sum = 0
for index in range(0,len(a)):
sum +=a[index]
print sum
# Average List
a = [1, 2, 5, 10, 255, 3]
sum = 0
for in... |
f68c7c1b684a6d8feab33ee858b1b616ebbe3608 | Kevin0920/Python-basics | /stars.py | 278 | 3.671875 | 4 | # x = [4, 6, 1, 3, 5, 7, 25]
x = [4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"]
def draw_stars(list):
for x in list:
if type(x) == str:
for star in range(len(x)):
print x[0].lower(),
print ""
else:
for star in range(x):
print "*",
print ""
draw_stars(x)
|
654c23b535cc46a822f9982b7816d7571c8c068a | jcohenadad/spinalcordtoolbox | /scripts/sct_nurbs.py | 16,783 | 3.625 | 4 | #!/usr/bin/env python
## @package sct_nurbs
#
# - python class. Approximate or interpolate a 3D curve with a B-Spline curve from either a set of data points or a set of control points
#
#
# Description about how the function works:
#
# If a set of data points is given, it generates a B-spline that either app... |
f0434f50b2b1ed8dc2bae3b8b4df67d84a9d8ee4 | Ar-Kareem/dynamic_telegram_bot | /src/handlers/telegram_only/telegram_examples_dir/timerbot.py | 3,464 | 3.59375 | 4 | """
Simple Bot to send timed Telegram messages.
This Bot uses the Updater class to handle the bot and the JobQueue to send
timed messages.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until w... |
ffb3e738084703eff80cf5b5db566d46a124f40a | Zain1298/Python-Codes | /shape.py | 340 | 3.953125 | 4 | import numpy as np
#This function prints 20 random numbers from 1 to 50
arr = np.random.randint(1,50,20)
print(arr)
#shape is 1D array
print(arr.shape)
#Now this will convert 1D array into 2D array
arr = arr.reshape(2,10)
print(arr)
#Now the shape is 2D array
print(arr.shape)
#Rearrnage into 1D array
arr = arr.resh... |
f05a142a0bb3dabe5b6f184534a77c8e813dbba4 | arthurregolin/Projeto | /programinho.py | 773 | 3.71875 | 4 | import requests #livraria de requisição de informações de sites
import json # JavaScript object notation
# input da data desejada,base de câmbio e cotação
data=input('Insira a data(Ano-Mês-Dia) em que desejar verificar a cotação:')
base=input('Digite qual a moeda base de câmbio(Ex:USD): ')
city=input('Digite qual moed... |
9fcfaa9f44da4bf5f76da38841bc32f1d980572e | lecw199/algorithm | /leetcode/algorithm2.py | 1,643 | 3.53125 | 4 | # coding : utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
... |
5cef3f3412831000381131a41f2d46af2f3671a5 | gaurav0529/Python_Questions | /Loops and Conditional Statements/Ques5_loop&cond.py | 124 | 3.921875 | 4 | print("Question 5")
print("Enter String")
a=input()
l=len(a)
r=""
for i in range(l-1,-1,-1):
r=a[i]
print(r,end="")
|
12b2af52b659157b2710db3ed67c7ff0b7eee77d | gaurav0529/Python_Questions | /Loops and Conditional Statements/Ques28_loop&cond.py | 206 | 3.875 | 4 |
# Question 28
st=""
for r in range(7):
for c in range(5):
if (((c==0 or c==4)and r!=6)or(r==6 and(c>0 and c<4))) :
st+="*"
else:
st+=" "
st+="\n"
print(st)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.