blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0dea73e437e14c4bdb734eec868dadf2726a11c8 | rosmoke/DCU-Projects | /week3/sum-five.py | 202 | 3.625 | 4 | first = input()
second = input()
third = input()
fourth = input()
fifth = input()
calculate = 0
while calculate < 1:
sum = first + second + third + fourth + fifth
print sum
calculate = calculate + 1
|
7dfc66d2695913fb69d2579177bfc4e5aafcc6b7 | HabibullahMetin/Python-Examples | /Python Eğitimi/Kodlama Egzersizleri/kullanici_girisi_yeni.py | 809 | 3.90625 | 4 | print("Kullanıcı Girişi Programına Hoşgeldiniz")
sys_kullanici_adi = "habib"
sys_parola = "123"
girisHakki = 3
while True :
kullanici_adi = input("Kullanıcı Adı :")
parola = input("Parola :")
if (kullanici_adi != sys_kullanici_adi and parola == sys_parola):
print("Kullanıcı Adı hatalı"... |
22cddc641f224027da3f019ea46080523b284491 | GGbb2046/ST018 | /Assignments/Assignment04/Part04.py | 278 | 4.15625 | 4 | t=float(input("Please enter the temperature in Fahrenheit "))
if t>=212:
print("The water at this temperature is in gaseous state")
elif t<=32:
print("The water at this temperature is in frozen state")
else:
print("The water at this temperature is in liquid state") |
3bd64ddcd4f74653dc4c447be8dc37e743a62ea6 | SupriyaPT/PythonPrograms | /Encapsulation/student.py | 691 | 4.09375 | 4 | class Student:
def __init__(self):
#private variable
self.__id =123
self.__name="John"
#public variable
self.class_name="first"
#To access private variables
def display(self):
print(s.__id ) #private variables can be accessed from within the class
pr... |
70dfcd7155b8fa1a7a96c9dc7fe0718c4d3bfd9b | minas528/a2sv | /Introdution to Competitive Programming/Camp/D8 -dynamic programming/palindromicSubstring.py | 597 | 3.53125 | 4 | class Solution:
def countSubstrings(self, s: str) -> int:
if len(s) == 0:
return 0
count = 0
def checkPalindrom(string, i, j):
nonlocal count
while i >= 0 and j < len(string) and string[i] == string[j]:
count += 1
i -= 1
... |
20071e83a74f21e815e0d599a66b9685197cf084 | pocceschi/aprendendo_git | /python_para_zumbis_lista2/7.py | 224 | 3.625 | 4 | m2 = float(input("Quantos metros quadrados serão pintados? "))
if m2 % 54 == 0:
latas = m2 / 54
else:
latas = int(m2 / 54) + 1
print(f"Latas necessárias: {latas}")
print(f"Valor à pagar: R${latas * 80:.2f}")
|
032a438edcb88047723321253746d963d623687a | krishnamanchikalapudi/examples.py | /PythonTutor/session-4/basicoperators.py | 682 | 4 | 4 | """
Session: 4
Topic: Basic Operators
"""
num1 = 21
num2 = 2
num3 = 23
# add
print('num1 + num2 = ', 100 + num2)
# sub
print('num1 - num2 = ', num1 - num2)
# multiply
print('num1 * num2 = ', num1 * num2)
# division
print('num1 / num2 = ', num1 / num2)
# reminder = 1
print('num3 % num2 = ', num3 % num2)
# Power 2 is ... |
51fda0262df05cede9a603ad1af9504cf2ba39fb | aigerimzh/BFDjango | /Week1/Hackerrank/neslists.py | 342 | 3.65625 | 4 | if __name__ == '__main__':
students = []
s = []
n = int(input())
students = [[input(), float(input())] for x in range(n)]
#print(students)
s = list(set([s for n, s in students]))
sh = sorted(s)[1]
#print (sh)
r = (n for n, s in students)
print ("\n".join([n for n, s in sorted(st... |
42363e3f8257700d98c417004ac96252e28c6378 | Hansimov/cs-notes | /剑指offer_2nd/JZ-17 打印从1到最大的n位数.py | 917 | 3.609375 | 4 | """
* 面试题17. 打印从 1 到最大的 n 位数(分治算法 / 全排列,清晰图解) - 打印从1到最大的n位数 - 力扣(LeetCode)
* https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/solution/mian-shi-ti-17-da-yin-cong-1-dao-zui-da-de-n-wei-2/
"""
# class Solution:
# def printNumbers(self, n: int) -> List[int]:
# return list(range(1... |
b309556e6cf8d7af8e8b26f888deacb65f9e67c3 | dana19-meet/YL1-201718 | /lab6/lab6.py | 1,288 | 4.03125 | 4 | from turtle import *
import random
import math
class Ball(Turtle):
def __init__(self,radius,color,speed):
Turtle.__init__(self)
self.shape("circle")
self.shapesize(radius/10)
self.radius=radius
self.color(color)
self.speed(speed)
def check_collision... |
5ed8757db5bd8d7b72f48b448fa6d60008e44b29 | mdaalam/testRepo | /hw2.py | 2,095 | 3.78125 | 4 | # Name: Md Alam
# Id: 106976395
import sys
import os
file = sys.argv[1]
# open input file, read only and universal newline support, and read in data
data = open(sys.argv[1],'rU').read()
# split rows by newlines and columns by tabs, and represent as list of lists
rows = [line.split('\t') for line in data.split('\n')... |
1c594f1f365bd067e51bec7758b5c2452fe2b985 | t-yuhao/py | /基本语法/e1.py | 277 | 3.90625 | 4 | i = 5
print (i)
i = i + 1
print (i)
s = "This is a multi-line string.\
This is the second line."
print(s)
print('a', end=' ')
print('b')
print('{0:.3f}'.format(1.0/3))
print('{0:_^11}'.format('hello'))
print('{name} worte {book}'.format(name='TYH',book='A byte of python')) |
f14ed608e2f120da51fe548a65560260ba639a62 | nickatnight/wall | /python_wall.py | 5,014 | 3.546875 | 4 | import os.path, sys, getpass
from collections import OrderedDict
import cPickle as pickle
from users import User
def displayMenu():
print 57 * '#'
print '# WELCOME TO THE PYTHON/WEBDEV WALL #'
print '# ---------------------------------------------- #'
print '# Here, we ... |
be90fb31c8daf2101f98c94750e03035ea1cf20e | ryndovaira/leveluppythonlevel1_300321 | /topic_08_functions/examples/15_named_args.py | 237 | 3.828125 | 4 | def hello(name, prefix="Hello, ", suffix="!"):
print("{}{}{}".format(prefix, name, suffix))
hello(name="world") # Hello, world!
hello(prefix="Hi ", name="world") # Hi world!
hello("world", prefix="!!!!") # !!!!world!
|
4032db4cc50c4a3d0b862847194ad648dbb13ce4 | HaoboChen1887/leetcode | /stack_queue/155_min_stack/155.py | 988 | 4.125 | 4 | class MinStack:
# when pushing values, if x <= min_val, push current min_val onto the stack for record
# then update min_val
# when poping, if the top values is min_val, we pop it out and reverse min_val to the next top value
# because we maintained the stack in a way such that if min_val is u... |
ca6712471e78bf6b25a460054377791a67e1f1d7 | Karanpalshekhawat/cs_50_problem_set | /pset6/credit.py | 1,134 | 3.625 | 4 | from cs50 import get_int
def main():
ccnum = get_int("Enter Credit card number: ")
digits = len(str(ccnum))
if digits == 16 or digits == 13 or digits == 15:
con = check_validity(ccnum, digits)
else:
con = False
if con:
if str(ccnum)[0] in ['4']:
print("VISA")
... |
d4b55b2ebf55429fd6bc9188053aa51c1fa42291 | MartinSeeler/euler-python | /problem-2.py | 252 | 3.734375 | 4 | sum_of_even = 0
prev = 0
current = 1
next = current
while (prev+current) <= 4000000:
next = prev + current
prev = current
current = next
if next % 2 == 0:
sum_of_even += next
print "The sum of all even is %s" % sum_of_even
|
573ef6559fb21c2248b9f8d568565aa1cd1a98c4 | flyingfox2017/python-practice | /qiantao.py | 339 | 4 | 4 | # if 嵌套
num = int(input("输入一个数字: "))
if num%2==0:
if num%3==0:
print("输入的数字可以同时被2和3整除")
else:
print("可以被2整除,但是不能被3整除")
else:
if num%3 == 0:
print('可以被3整除,但是不能被2整除')
else:
print("不能被2和3整除") |
77abb58bc3166e3748aa0fabe2c00c77e7b155a8 | jiang2533001/Cracking-the-Coding-Interview | /Chapter 4/graph.py | 1,248 | 3.8125 | 4 | class Node(object):
def __init__(self, label, neighbor=None)
self.label = label
if neighbor!=None:
self.neighbors = [neighbor]
self.neighbors_num = 1
else:
self.neighbors = []
self.neighbors_num = 0
def add_neigbor(self, node)
self... |
6cd5422b0757ea7c4008aa0fb60664b4b9000cf2 | TerrayTM/pytimize | /pytimize/graphs/_directed.py | 17,872 | 3.71875 | 4 | import math
from collections import deque
from typing import Dict, Iterable, List, Optional, Set, Tuple, Union
class DirectedGraph:
def __init__(
self,
graph: Optional[Dict[str, Set[str]]] = None,
arcs: Optional[Dict[Tuple[str, str], float]] = None,
nodes: Optional[Dict[str, float]... |
f64eda66bb5115081750a669a90fab0092176fb0 | Adosha/ud120-projects | /decision_tree/dt_author_id.py | 3,112 | 3.703125 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 3 (decision tree) mini-project.
Use a Decision Tree to identify emails from the Enron corpus by author:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import prep... |
ced6978ca2e4da57145afa447b4de07723672afd | Gaju27/Assignment_17_B | /minimum_possible_sum.py | 1,473 | 4 | 4 | # Minimum sum possible by assigning every increasing/decreasing consecutive pair with values in that order
#
# Given an array arr[] of size N, the task is to find the minimum sum of positive integers that can be assigned to each array element arr[i],
# such that if arr[i] > arr[i + 1] or arr[i – 1],
# then the posi... |
672863e7018d9ee42c078d9f9a14a5928fc836ae | HK017/scripts | /面试题/栈.py | 869 | 3.703125 | 4 | class Stack(object):
def __init__(self):
self.items = []
def push(self, data):
self.items.append(data)
def isEmpty(self):
return self.items == []
def pop(self):
if self.items == []:
return []
else:
return self.items.pop()
def peek(s... |
560b532fc722195a0098a99d1abd6134ca2a73ef | khrystyna21/Python | /lesson17/decorator_example.py | 428 | 3.65625 | 4 | from functools import wraps
def stop_words(words):
def stop_words_dec(func):
@wraps(func)
def wrap(*args):
result = func(*args)
for word in words:
result = result.replace(word, '*')
return result
return wrap
return stop_words_dec
@sto... |
c61fb708807a53e7bfbc174b83f4351a599618f2 | AmberHsia94/Scary_Leetcode | /groups_anagram.py | 505 | 3.921875 | 4 | # coding=utf-8
# Given an array of strings, return all groups of strings that are anagrams.
# Given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"].
# Given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].
import numpy as np
def groups(alist):
res = {}
for i in alist:
... |
2f260fc02cf744e51dd7c5febea741771a3c6a49 | Michelleoc/myWork | /week06-Functions/squareroot.py | 2,466 | 4.4375 | 4 | # Weekly Task 6
# Take a positive floating point number as the input and output an approximation of its square root
# Author : Michelle O'Connor
# https://www.youtube.com/watch?v=-5e2cULI3H8
# https://surajregmi.medium.com/how-to-calculate-the-square-root-of-a-number-newton-raphson-method-f8007714f64
# Newton formula... |
91ebed6f0dcc55303a2347aca26f92c951d20a8f | erickapsilva1/desafios-python3-cev | /Desafios/031.py | 255 | 3.53125 | 4 | # programa que calcula preço de viagem, sendo 0,50 por km em rolês até 200km
# e 0,45 para acima dessa km.
role = int(input('Qual a distância da viagem: '))
if role <= 200:
print('Total: R$', role * 0.50)
else:
print('Total: R$', role * 0.45) |
86cb1c3dbcfbb3c2fa76a4fd755890108ade38ef | ino-jeong/study-practice | /baekjoon online judge/09012 parenthesis/parenthesis.py | 358 | 3.515625 | 4 | cases = int(input())
for c in range(cases):
line_input = input()
stack = []
vps ='YES'
for ch in line_input:
if ch == '(':
stack.append('(')
else:
if len(stack) == 0:
vps = 'NO'
else:
stack.pop()
if len(stack) != ... |
38aece7977b7596102ccfcfbd0806445b94bfc7c | 100ballovby/AutomationWithPython_Course | /01_lesson_2307/00_strings.py | 236 | 3.71875 | 4 | msg = input('Введите сообщение: ')
phone = ''
for symbol in msg:
if symbol.isdigit(): # если символ - число
phone += symbol # я добавляю его в переменную
print(phone)
|
b512b85477876c36843eff3acd0f1a8b69d9ccef | ZSPASOV/softuni-python-fundamentals | /07-Dictionaries-Lab/demo11-iterating-through-values-v2.py | 143 | 3.75 | 4 | # We can also use the keys to get the values
squares = {1: 1, 2: 4, 3: 9}
for key in squares.keys():
print(squares[key], end=" ") # 1 4 9 |
9d75cc74b2eed6d886c18950f5aa75adebdd5334 | DerekAyala/Trabajos_Python | /82.py | 235 | 3.953125 | 4 | if __name__ == "__main__":
pi:int=3.1416
r:int=int(input("Ingresa el radio: "))
while r<0:
r:int=int(input("Ingresa el radio: "))
print(f"El area es : {pi*(r**2)}")
print(f"la circuferencia es : {pi*(r*2)}") |
e4dc1bde20020979715df5ce7fecba7847e95d26 | abdullahglobaledx89/python-notes-programmes | /cla/test5.py | 109 | 3.640625 | 4 | from sys import argv
sum=0
s=argv[1:]
for s1 in s:
n=int(s1)
sum=sum+n
print("THE SUM =",sum)
|
23266f9b601e2ad93c337ea19c39c8dad065bfb9 | anuragpatil94/Python-Practice | /python-data-structure-book/formatting.py | 2,509 | 4.09375 | 4 | name = "John"
age = 24
print("My name is %s and my age is %d" % (name, age))
a_list = [1, 2, 3, 4, 5]
print("list: %s" % (a_list))
a_list = (1, 2, 3, 4, 5)
print("Tuple: %s %s %s %s %s" % (a_list))
try:
a_list = [1, 2, 3, 4, 5]
print("list: %s %s %s %s %s" % (a_list))
except Exception:
prin... |
51349571dcef77e4ecbc7318ea54ce5f198a7540 | acctwdxab/project-3.a | /min_max.py | 305 | 3.921875 | 4 | n = int(input("How many integers would you like to enter?\n"))
print("Please enter",n, "integers.")
max_num = -999999
min_num = 9999999
for i in range(0, n):
k = int(input())
if k < min_num:
min_num = k
if k > max_num:
max_num = k
print("min:", min_num)
print("max:", max_num)
|
95b7862dd9cfe21ac845f11283484c4ff1b3cce5 | SaravananThanigachalm/Shape_generatorV2 | /Shape generator v2.py | 3,209 | 3.78125 | 4 | """
Welcome to the Shape generator V1
@author: Saravanan T
last edited date - 3/7/2020
"""
import random
import turtle
import math
t1 = turtle.Turtle()
t2 = turtle.Turtle()
t1.up()
t1.goto(0,250)
style1 = ('Arial', 24, 'italic')
t1.color("red")
t1.write('Welcome to Shape Generator V2', font=styl... |
d604effae098364909b59008da157491b87dead1 | brianchiang-tw/leetcode | /No_0065_Valid Number/valid_number_by_type_conversion_exception.py | 827 | 3.65625 | 4 |
class Solution:
def isNumber(self, s: str) -> bool:
try:
float(s)
return True
except:
return False
# n : the length of input string
## Time Complexity: O( n )
#
# Although it seems O(1) at forst glimpse,
# but float(s) does che... |
453170ff6501f42859640d021c0948d7076bc46a | Alan-Cha/PDF2Signatures | /main.py | 1,345 | 3.625 | 4 | # importing required modules
import PyPDF2
# given the number of pages in a booklet, return an array with the appropriate
# order
#
# NOTE: the numbers of pages must be divisable by 4 because each page will be
# divided into 4 pages
def pageOrder(numOfPages):
# used to flip the order of pages depending on the side... |
c2787f5071241c50915d509dfd18932047985b09 | cindychea/python_reinforcement_exercises | /may7exercise1.py | 798 | 4.25 | 4 | documentary = 'Becoming Warren Buffett'
drama = 'Black Panther'
comedy = 'The Mask'
dramedy = 'Silver Linings Playbook'
print("Do you like documentaries?")
likes_docs = input()
print("Do you like dramas?")
likes_dramas = input()
print("Do you like comedies?")
likes_comedies = input()
if likes_docs == 'yes' or likes_d... |
bb3acc212a41fbc9394935c289c5d43c2f8af91d | Grazziella/Python-for-Dummies | /exercise7_2.py | 1,060 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Exercise 7.2 Write a program to prompt for a file name, and then read through
# the file and look for lines of the form:
# X-DSPAM-Confidence: 0.8475
# When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart
# the line to extract the floating-point nu... |
2033b6366a112e7e89301ca14b2fd6840ed3e860 | GrassShi/Multi-Agent-Systems | /Extension3.py | 3,131 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 15 13:24:07 2020
@author: graceshi
Instructions: Just click run! The code will run 10 iterations (changeable in the main) and generate the graph, and return
True for cop win and False for robber win.
"""
import random
import networkx as nx
impo... |
91b32ead0458a61ea85f7041e7411a80def8fb73 | SamBumgardner/csc-131-computational-thinking | /lecture_materials/higher_order_functions/jump_table.py | 1,194 | 4.15625 | 4 | """"
jumpTable.py
A toy program on jump tables.
Program displays a menu to a user and prompts user to make a selection.
Menu options are keys in the jump table --- a dicionary--- with corresponding values
as aliases/references to the functions associated with the menu options/commands
"""
def insert():
print("a ne... |
661c6795d19d912029a1f3f00e301521fca4f08c | moxi624/python_learning | /code/11类属性和实例属性.py | 603 | 3.59375 | 4 | '''
Created on 2018年10月10日
@author: Administrator
'''
class Person(object):
name="zhangsan"
# def __init__(self, name,age):
# self.name=name
# self.age=age
@classmethod
def test(cls):
print("类方法")
def test2(self):
print("test2")
@staticmethod
def test3():
... |
2b7d85217cc24ef811ba8155a6134d4e2ff176eb | ToWorkit/Python_base | /函数/变量指向函数.py | 168 | 3.734375 | 4 | foo = abs
print(foo(-10))
# 引入内部函数
import builtins
# builtins.abs = 10
print(builtins.abs)
def add(x, y, f):
return f(x) + f(y)
print(add(-3, -4, abs))
|
78c6c49a1b58eed44c755ed22c637f05035968b2 | jkatem/Python_Practice | /Palindrome.py | 201 | 4.09375 | 4 | # CHALLENGE
# Write a python function to determine if a given string is a palindrome
# Input: String to evaluate
# Output: Boolean Value
# Only consider letters A-Z
# Ignore case
def ifPalindrome(): |
b4eb3c0a7fa311f3ad18456c7fd32f0ff7c5071a | rvighne/ProjectEuler | /57SqrtConv/_57SqrtConv.py | 260 | 3.703125 | 4 | from fractions import Fraction
from math import log10
if __name__ == '__main__':
frac = Fraction(3, 2)
count = 0
for i in range(1000):
frac = 1 + 1 / (1 + frac)
if int(log10(frac.numerator)) > int(log10(frac.denominator)):
count += 1
print(count) |
c5d2bae0c6b729414b1c5298f19701838f033ee4 | rishabhyadavv/ML-Algorithms | /TensorFlow/Fibonacci.py | 195 | 3.5625 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 5 16:28:00 2018
@author: risyadav
"""
a = 0
b = 1
c = 0
for i in range(7):
print(a)
c= a + b
a = b
b = c
|
27ccc3780dfb4cbf11e1f70f792a58b28b639dbf | Anulaa001/Tests_amazon | /amazon.py | 1,837 | 3.75 | 4 |
def is_triplet(arr):
n = len(arr)
for i in range(n):
arr[i] = arr[i] * arr[i]
arr.sort()
for i in range(n - 1, 1, -1):
j = 0
k = i - 1
while j < k:
if arr[j] + arr[k] == arr[i]:
return True
else:
if arr[j] + arr[k... |
d6a86b0120b84aca8f9be022c2c3abddf5bb8f15 | ChuXiaoYi/Algorithms | /leetcode/26demo.py | 726 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# ---------------------------------------------
# @Time : 2019/2/28 下午5:04
# @Author : cxy =.=
# @File : 26demo.py
# @Software: PyCharm
# @Desc : 26. 删除排序数组中的重复项 https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/solution/
# -----------... |
c3259fc9104f8ddff94b36625facc53fb22de80f | kevin5112/triangle-date | /date.py | 2,570 | 4.125 | 4 | def main():
month = int(input("enter a month: "))
day = int(input("enter a day: "))
year = int(input("enter a year: "))
if not checkValidMonth(month):
print("Value of month not in the range 1...12.")
return
if not checkValidDay(day):
print("Value of month not in the range 1...31.")
return
if not checkV... |
c4c712b7a19cca7c1b97eec6dcb094bfb9d57826 | amberanana/Python-Crash-Course-Practice | /8-2_deliver_actual_parameter.py | 2,222 | 3.5625 | 4 | # 8.2 Deliver Actual Parameter
# 8.2.1 位置实参
def describe_pet(animal_type, pet_name):
"显示宠物的信息"
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + "."
)
describe_pet('hamster', 'harry')
# 1. 调用函数多次
def describe_pet(animal_type, pet_name):
"... |
6b99d3974680f69f8b3fdf920c486d90284b256b | EdilsonDanieldeSouza/Design_Patterns. | /calculador_de_descontos.py | 746 | 3.734375 | 4 | # -*- coding:UTF-8 -*-
from descontos import Desconto_por_cinco_itens, Desconto_por_mais_de_quinhentos_reais, Sem_desconto
class Calclador_de_descontos(object):
def calcula(self, orcamento):
desconto = Desconto_por_cinco_itens(
Desconto_por_mais_de_quinhentos_reais(Sem_desconto())
).ca... |
b06ea3b42a7b5a1566d698690ced8d59942601b5 | ekomissarov/edu | /2022_probe/descriptor1.py | 949 | 3.75 | 4 | import logging
logging.basicConfig(level=logging.INFO)
class LoggedAccess:
def __set_name__(self, owner, name):
print("set name:", self, owner, name)
self.public_name = name
self.private_name = '_' + name
def __get__(self, obj, objtype=None):
value = getattr(obj, self.private... |
cdf0a5a064bd6c8ce30a9bc184a21f877da8207c | zhenggang587/code | /leetcode/ZigZagConversion.py | 571 | 3.609375 | 4 |
class Solution:
# @return a string
def convert(self, s, nRows):
if nRows == 1:
return s
ret = ''
for row in range(nRows):
col = row
while col < len(s):
ret = ret + s[col]
temp = col + 2 * (nRows - row - 1)
... |
85e5c43ce481cb172b1b00b00969bf3ea86b3707 | RaquelFonseca/P1 | /Unidade6a10/soma_valores.py | 445 | 3.65625 | 4 | # soma valores
# coding: utf-8
def f(lista):
soma = 0
for i in range(len(lista)):
soma += lista[i]
return soma
contador = 0
numeros = []
while True:
numero = int(raw_input("valor? "))
contador += 1
if numero == -1:
break
numeros.append(numero)
media = f(numeros) / len(nu... |
53cf3d946b8e8d24044752c79bd4c123414d1d68 | ReemShalaata/Algorithmic-Toolbox-Coursera-MySolutions | /weeks/week2_algorithmic_warmup/1_fibonacci_number/my_solution.py | 280 | 3.8125 | 4 | # Uses python3
def calc_fib(n):
array=[None]*(n+1)
if n==0:
array[0]=0
if n>=1:
array[0]=0
array[1]=1
for i in range(2,n+1):
array[i]=int(array[i-1])+int(array[i-2])
return array[n]
n = int(input())
print(calc_fib(n))
|
ff910fe9e8128fc63cfee83b359e0b384344e934 | SlientMe/teaching | /郑继涵/茹沫霖/day10.py | 476 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/7/21 9:59
# @Author : liuqi
# @FileName: day10.py
# @Software: PyCharm
# 猜字游戏
import random
x = random.randint(0, 99)
while(True):
num = input("请猜猜是多少")
if(num.isdigit()):
num = int(num)
if(x == num):
print("恭喜你,猜对了")
... |
3f3b54ca499de619dfd804aa2ec456be584bcc0c | dhood/shape_learning | /src/shape_learning/shape_modeler.py | 8,760 | 3.5625 | 4 | """ Class to decompose a dataset of shapes into its principle components,
and to make and show new shapes which are represented by the mean shape
plus some amount of said principle components.
"""
import numpy
import matplotlib.pyplot as plt
from matplotlib.mlab import PCA
import random
from copy import deepcopy
clas... |
5f6899ad20d4a6b64627f2193c171efd745c389c | J-Larose/SchoolWork | /Comp 1405B/assigments/assignment 6/Larose_101013798_Q1.py | 2,700 | 3.9375 | 4 | from SimpleGraphics import *
import sys
class Entry:
def __init__(self, id, name, faculty, photo):
self.__id = id
self.__name = name
self.__faculty = faculty
self.__photo = photo
def getId(self):
return self.__id
def getName(self):
return self.__name
def... |
6326d380e81fcfb823b25bf7369b8a43750f36aa | lakshyatyagi24/On-Screen-Keyboard | /keyboard.py | 2,427 | 3.8125 | 4 | from tkinter import *
import tkinter
Keyboard_App = tkinter.Tk()
Keyboard_App.title("On Screen Keyboard")
Keyboard_App.resizable(0,0)
shift_active=False
def select(value):#made shift work, remove character works now and you add character at cursor position
global shift_active
if value == "<-":
... |
3b522aa1eaab978d6fdf9a98d0ec4c7cb5cb25c8 | rimesta21/ZombieGame | /Zombies/inTheMomentZombie.py | 1,306 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 30 16:15:41 2021
@author: rimes
"""
from Zombies.Zombie import Zombie
import random
class inTheMomentZombie(Zombie):
def __init__(self):
super().__init__()
self.numTimes = random.randint(1,4)
self.name = "In the Moment Zombie"
d... |
c25591e2a8597c44fbe3e7a050d380057fb3c6a7 | yifange/leetcode | /sort_colors.py | 616 | 3.546875 | 4 | class Solution:
# @param A a list of integers
# @return nothing, sort in place
def sortColors(self, A):
i = j = k = 0
for p in range(len(A)):
if A[p] == 0:
A[k] = 2
A[j] = 1
A[i] = 0
i += 1
j += 1
... |
3b00b68a1f4908ce86a4a5d6c668adb888daf351 | wrightrocket/python-exceptions | /not_handled.py | 706 | 4.21875 | 4 | '''
Example of why exception handling may be needed.
'''
__author__ = 'Keith Wright'
# Assign numerator by default to 1000
numerator = 1000
# Receive user_input for a number to use as denominator as a 'str'
user_input = input('Number to divide 1000 by: ')
# Convert user_input to a floating point value for the denomin... |
03ae20fdc41806c600759d105315680ec3d59ccb | tillmannheigel/osm_postcodes | /postcodes.py | 1,699 | 3.640625 | 4 | """
Converts a file from one format to another.
This example shows how to write objects to a file.
"""
import osmium as o
import sys
ways = set()
nodes = set()
class Relation(o.SimpleHandler):
def __init__(self, writer):
super(Relation, self).__init__()
self.writer = writer
def relation(se... |
8c885869cd6bced18080f5ae92233d2085532f89 | Charnel2500/Zadania | /najwiekszy_z_trzech.py | 250 | 3.78125 | 4 | # Największa liczba bez użycia funkcji max()
a = int(input("Wpisz liczbę: "))
b = int(input("Wpisz drugą liczbę: "))
c = int(input("Wpisz trzecią liczbę: "))
if a>b and a>c:
print(a)
elif b>c and b>a:
print(b)
else:
print(c)
|
44cc00d4d73e92f150e0e80bca9c1d7c1dcf0344 | Cindy-fight/python | /a_index.py | 891 | 3.921875 | 4 | # _*_ coding:utf-8 _*_
# Quick Python Script Explanation for Programmers
import os
def main():
print('Hello World!')
print("这是Alice\'的问候.")
print('这是Bob\'的问候')
foo(5, 10)
print('=' * 10)
print('这是直接执行'+os.getcwd())
counter = 0
counter += 1
food = ['apple', 'pear', 'orange', 'g... |
be7fbb0ef3a825fa36f561056af586db49a9ce68 | caioalexandred/python_inicio | /ex014.py | 410 | 3.828125 | 4 | p1 = input('Qual sua profissão?')
print('Sua profissão é ', p1)
print('esse dado resultou em', p1.isnumeric(), 'para numérico')
print('esse dado resultou em', p1.isspace(), 'para uso de espaços')
print('esse dado resultou em', p1.isidentifier(), 'para identificador')
print('esse dado resultou em', p1.isalpha(), 'p... |
e8a6eb252513247f446013f3d34ee0d54df2ca5d | Anirban6393/Anirban-Projects | /python-developer/pdf_integral.py | 409 | 3.59375 | 4 | import numpy as np
import math
from scipy.integrate import quad
def f(y, x):
"""this is the rhs of the ODE to integrate"""
if x>0 and y>0:
return math.exp(-x-y)
else:
return 0
##For P(Y>X), integrate Y wrt infinity while setting value of x to inifinity as well
# We find the... |
d7d2edc4cd2ad0d8c13eb8269a53b4a3f4d0a353 | nathangreene3/Dynamics-Chaos | /LangtonsAnt.py | 3,110 | 3.734375 | 4 | # LangtonsAnt.py
# Nathan Greene
# Summer 2018
#
# This script simulates Langton's ant.
#
# Source: https://www.futilitycloset.com/2014/04/06/langtons-ant/
import random
import sys
import time
def main():
LA = LangtonsAnt(10, "empty")
LA.run(iters=10000, sleeptime=0.2)
class LangtonsAnt:
"""
Langton's ant cons... |
898fdb7d0ed74b205975890a540a954957674061 | LipatJob/IT101-2 | /PracticalLearning/LE3.py | 1,481 | 3.84375 | 4 | class A:
def test(self):
print("test of A called")
class B(A):
def test(self):
print("test of B called")
super().test()
class C(A):
def test(self):
print("test of C called")
super().test()
class D(B, C):
def test2(self):
print()
obj = D()
obj.test()
p... |
16781c0228466a40ab2f75229d3f32aacae1ab34 | ptyork/au-aist2120-21sp | /Code_Before_Jan_21/BTu/greet_0112.py | 371 | 4.125 | 4 | print("AWESOME GREETER")
# OPTION 1
print("Enter your first name: ")
fname = input()
print("Hello " + fname)
# OPTION 2 (BETTER IMO)
lname = input("Enter your last name: ")
print("Hello " + fname + " " + lname)
age_str = input("Enter your age: ")
age = int(age_str)
real_age = age * 2
print("Yeah right, you're real... |
995342efdb7219caf106d4e6aaa55c1023a78456 | Zernach/hash-tables | /applications/crack_caesar/crack_caesar.py | 2,260 | 4.0625 | 4 | """
Use frequency analysis to find the key to ciphertext.txt, and then
decode it.
"""
# For checking if something is punctuation
import string
# For sorting a dictionary
import operator
# Dict of letters of overall frequency used in written English.
english_frequencies = {
'E': 11.53,
'T': 9.75,
'A': 8.46... |
7e82058cb20da948f03347f741870ddcc4bdd379 | sudo-hemant/test | /geeksForGeeks/tree/diameter-binary-tree.py | 615 | 3.921875 | 4 | # the code can be better by using a global variable insted of an array to store diameter
# here array is taken bcos it is passed by reference and unmutable variables are passed by value
def diameter(root):
max_diameter = [0]
calculate(root, max_diameter)
return max_diameter[0]
def calculate... |
bb48a50146b11b942e5057a2dc072916c919a1a9 | k22o/software2 | /6.5/6.5kadai4-inter.py | 387 | 3.65625 | 4 | import math
def f(x):
return math.sin(x)
def integration_small(a,b,n,i):
width = (a-b)/n
x1 = a + i * width
y1 = f(x1)
x2 = x1 + width
y2 = f(x2)
return (y1+y2)*width/2.0
def integration(a,b,n):
sum = 0
for i in range (n):
sum = sum + integration_small(a,b,n... |
52b26c2419bd3f599cd1ba35e2e723e545cf4f4c | poppynut/coolpython | /pst2.py | 305 | 3.921875 | 4 | """
items = 1, 3.3, 'peter pan', 'R'
print items
"""
#tuple assignment or parallel assignment
name, age, gender = 'sara', 4, 'female'
print name
print gender
#functions could return more than one value
q, r = divmod(5, 2)
print q
print r
def sqr_and_cube(n):
return n**2, n**3
print sqr_and_cube(6) |
09664092ee00c00c5f32c1b393093573b48c7cde | Audarya07/99problems | /P26.py | 1,290 | 4.03125 | 4 | # Generate the combinations of K distinct objects chosen from the N elements of a list.
def generate_combination(arr, n, r):
''' A function to generate combination of size r.
Parameters:
arr (List): Input array.
n (int): Size of input array.
r (int): Size of combination to be gener... |
89885fa6683a1af6667c2890be29bfc0937034a2 | Suryashish14/Suryashish-Programs | /Max Number.py | 230 | 3.671875 | 4 | a=int(input('Enter 1st Number -->'))
b=int(input('Enter 2nd Number -->'))
c=int(input('Enter 3rd Number -->'))
d=int(input('Enter 4th Number -->'))
e=int(input('Enter 5th Number -->'))
numcopy=a,b,c,d,e
print(max(numcopy))
|
eb3fea7230450a34792c8032f4d02cf7221762fb | CallyCa/Project-in-Python | /EX3 - EstruturaDeRepeticao/27.py | 700 | 3.9375 | 4 | '''
27. Faça um programa que calcule o número médio de alunos por turma.
Para isto, peça a quantidade de turmas e
a quantidade de alunos para cada turma.
As turmas não podem ter mais de 40 alunos.
'''
turmas = int(input('Digite a quantidade de turmas: '))
soma = 0
for i in range(1, turmas + 1):
while True:
... |
0e8ea82c1fc52c24f33f37f9fab586b1ad2842d7 | harshitacodes/python | /LIST/duplicate.py | 510 | 3.5 | 4 | # print only those nomber whicch has duplicates
n = [19, 17, 12, 17, 17, 18, 10, 17, 14, 12, 19, 17, 12, 13, 11]
# for new duplicatelist
duplicate_list=[]
i=0
while i < len (n):
j=i+1
while j < len (n):
if n[i]==n[j]:
a=n[i]
if n not in duplicate_list:
if a in dup... |
9fd2f57cb432fa202a988e4f7bffa6de659e3a9f | GBAleksandrGB/Tomilov_Aleksandr_dz_1 | /task_1_1.py | 846 | 3.625 | 4 | duration_list = [53, 153, 4153, 400153]
duration = int(input('Введите продолжительность времени в секундах '))
duration_list.append(duration)
minute = 60
hour = minute * 60
day = hour * 24
for duration in duration_list:
if duration < minute:
print(f'{duration} сек')
elif duration < hour:
print(... |
20178f52cd874bd6e47a119fd8558c936af5c4bc | Piskmannen/RandomTests | /Pythonscripts/cointoss.py | 821 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 1 11:53:43 2017
@author: Robert
"""
import random
count= 0
checklist = ['heads','heads','heads','heads','heads','heads','heads','heads','heads','heads']
result = []
def addtolist(dict):
dict.append(random.choice(['heads','tails']))
global count
count ... |
4e96579582f46cbe252d4d28ed8028bfc660ffe2 | lixiang2017/leetcode | /leetcode-cn/0279.0_Perfect_Squares.py | 5,056 | 3.71875 | 4 | '''
每次选择最大的,逐渐减小。这种贪心是错误的。反例:
12 = 9 + 1 + 1 + 1 4次
12 = 4 + 4 + 4 3次
所以DP
T: O(N * sqrt(N) = N^1.5)
S: O(N)
执行用时:7132 ms, 在所有 Python3 提交中击败了5.00% 的用户
内存消耗:15.4 MB, 在所有 Python3 提交中击败了22.55% 的用户
通过测试用例:588 / 588
'''
class Solution:
def numSquares(self, n: int) -> int:
dp = list(range(n + 1))
... |
7a39474bd26b7a5ece0fd3871a51dcecd8ab4975 | viniciusramos91/fuzzy-monitor | /load_cpu.py | 623 | 3.609375 | 4 | """
Produces load on available CPU cores
"""
from multiprocessing import Pool
from multiprocessing import cpu_count
def load_cpu(x):
while True:
x * x
if __name__ == '__main__':
# Get number or CPUs
processes = cpu_count()
if processes > 1:
print('Using %d cores\n' % (processes-1))... |
8f9473fda80d84340f739fa97d1cdc6c8ccdb6c3 | 21350010/Week6 | /week6.1.py | 270 | 3.5625 | 4 |
#Finding the errors in the following statement
##if scoreA = scoreB :
## print("Tie")
scoreA=int(input("scoreA :"))
scoreB=int(input("scoreB :"))
if scoreA == scoreB :
print("Tie")
# scoreA=scoreB Changed to scoreA==scoreB, instead of = , ==
|
2a78e4df22a9d8bc83b126d53236635068104c15 | NUsav77/Python-Exercises | /CSV_test/main.py | 788 | 4.03125 | 4 | import csv
desired_wage = int
high_wages = []
with open('wage.csv', 'r') as infile:
# Two steps required here
reader = csv.reader(infile) # 1. Create CSV reader
next(reader) # Consumes lines one at a time
for row in reader:
job_id = int(row[0])
job_title = str(row[1])
annual_... |
4aa7cbf941f0e192516b33e7f254a51f8da3c886 | DillGromble/Algo-Repo | /Strings/palindromeEditDistance.py | 2,496 | 4.03125 | 4 | #------------------------------------------------------------------------------#
# You are given a string. The only operation allowed is to insert characters in#
# the beginning of the string. How many minimum characters are needed to be #
# inserted to make the string a palindrome string ... |
b5e8cd8bfe05a6b04e2af4be095197100f1165ae | keinuma/self-taught | /part2/challenge/chapter13.py | 1,471 | 3.9375 | 4 | class Shape:
def __init__(self):
pass
def what_am_i(self):
name = self.__class__
print('I am a shape {}'.format(name))
class Rectangle(Shape):
def __init__(self, w, l):
super().__init__()
self.width = w
self.len = l
def calculate_perimeter(self):
... |
7af84a0d862c8299eefb96be0680d254822d3aee | fernandoantoniodantas/DO2RDF | /Util.py | 2,765 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 16 20:54:24 2019
@author: Fernando
@author: Hermann
Esta classe atribui valores numéricos (parser) às informações do tipo string do diário oficial.
"""
class Util():
def retornaMes(self, mes):
if mes == 'JANEIRO' or mes ==... |
b112ea7794a28876dea40b8bfd516462ba2b3b9b | oscarmellizoangulo/prueba_fedesoft | /python/009_funciones_parametros.py | 406 | 3.578125 | 4 | # -*- coding: utf-8 -*-
def foreing_exchange_calculator(ammount):
mex_to_col_rate = 145.97
return mex_to_col_rate * ammount
def run():
print('CALCULADORA DIVISAS')
ammount = float(raw_input('Ingresa la cantidad de pesos mexicanos:'))
result = foreing_exchange_calculator(ammount)
print('${} p... |
18e6f2fb71bb5607cd9cf2c8905dde1becdc32b1 | viswamol/ReminderApp | /Test.py | 2,535 | 4.0625 | 4 | # Reminder program
import datetime
import sqlite3
# Defining function for create reminder
def create_data():
cursor = db.cursor()
date = input("Enter date to be remind (must be specify in order DD/MM/YYYY):")
time = input("Enter time to be remind(must be specify in order HH:MM AM/PM):")
message = ... |
062f4a6bf5efdec744604aac1a1f41395b714f34 | BenHewett/MScProject-master | /Web_Application_Data_Collection_Prototype/File_name_generator.py | 707 | 4.25 | 4 | import random
import string
def file_name_generator(length: int) -> str:
"""
Generate a random string to act as a unique file name.
A combination of lower and upper case letters.
Attaches '.wav' to end of generated string
:param length: length of string to be generated
:return: concatenation o... |
43ca025c52fa33c33bcad39a283ad56e38ee4fca | Gopipo/pcl2_ex4 | /fun_with_strings.py | 1,772 | 3.765625 | 4 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
# Programmiertechniken in der Computerlinguistik II
# Übung 4 - Aufgabe 02
# Author: Silvio Magaldi und Vivien Angliker
# Date: 30.04.2019
# Matrikel-Nr: Silvio: 14-921-936 Vivien: 14-721-948
def longest_substrings(x: str, y: str):
x = x.lower()
y = y.lower()
... |
976078404266a1e6faeee9aaf73463b971a39a6c | williamsmichael/edX_MIT_cs_python | /quiz/p6.py | 1,223 | 4.59375 | 5 | # Problem 6
# (15 points possible)
# Write a function to flatten a list. The list contains other lists, strings, or ints. For example, [[1,'a',['cat'],2],[[[3]],'dog'],4,5] is flattened into [1,'a','cat',2,3,'dog',4,5]
def flatten(aList):
'''
aList: a list
Returns a copy of aList, which is a flattened v... |
b746e855314296cb8564c0621ba77cedcf32e171 | Suraj-Siddharudh/Leetcode | /array_intersect.py | 532 | 3.734375 | 4 | import collections
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
result = []
data = collections.Counter(nums1)
for elem in nums2:
count = data[elem]
if... |
57f41930c8ca5ac220e52998c46efbd0d63dfd74 | vicentedpsantos/best-movies-list | /media.py | 773 | 3.84375 | 4 | class Movie():
"""Responsible for creating Movie objects
Parameters
----------
movie_title : string
Title of the movie
movie_storyline : string
Brief description of the story of the movie
poster_image_url : string
Link to image of official movie poster
trailer_yo... |
39039cca7860bee4121cd91e175ae1f6a2ea044a | kanimozhi0112/python-programming | /beginner level/vowel or consonant.py | 177 | 4.21875 | 4 | a1=input("letter")
if((a1=='a' or a1=='e' or a1=='i' or a1=='o' or a1=='u') or (a1=='A' or a1=='E' or a1=='I' or a1=='O' or a1=='U')):
print("Vowel")
else:
print("consonant")
|
209910102d86e0a3ff74028e96eacdaf3a46ac03 | b166erbot/300_ideias_para_programar | /média_ponderada2.2.3.py | 241 | 3.71875 | 4 | def main():
entradas = (float(a) for a in input('números: ').split())
temp = ((número * entrada) for número, entrada in enumerate(entradas, 1))
média = sum(temp) / 10
print(média)
if __name__ == '__main__':
main()
|
f8adfd97c89c8b921f4583ffbfa8f616f88093fc | VANSHDEEP15577/TEST | /duplicate.py | 153 | 4.0625 | 4 | r=[]
num=int(input("ENTER NO:"))
for i in range(0,num):
e=input("ENTER:")
r.append(e)
print(r)
f=set(r)
print("THE FINAL LIST IS",list(f)) |
f85769de5ce5045faf0778451cfdd99e0e3d155a | yeloblu/Python | /OOPS/AbstractDecoder.py | 1,422 | 4.09375 | 4 | from abc import ABC , abstractmethod
class Employee(ABC):
def __init__(self,mname,amt):
self.__name=mname;
self.__salary=amt;
def getName(self):
return self.__name;
def getSalary(self):
return self.__salary;
@abstractmethod
def netSalary(self):
... |
9e50a96e22d847349dee2a360955e56c9b80b9bc | VagnerGit/PythonCursoEmVideo | /desafio_049_tabuada_v2.0.py | 300 | 4.15625 | 4 | '''Exercício Python 49:
Refaça o DESAFIO 9, mostrando a tabuada de um número que o usuário escolher, só que agora
utilizando um laço for.'''
multiplicador = int(input('Digite um Nº ára ver a tabuada: '))
for n in range(0, 11):
print(f'{multiplicador} x {n:2} = {multiplicador * n}')
|
d42a018a51e059ebe19755e4e3ff58628a17f0b3 | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#265 Quarter of the year.py | 341 | 3.84375 | 4 | # Given a month as an integer from 1 to 12, return to which quarter of the year
# it belongs as an integer number.
#
# For example: month 2 (February), is part of the first quarter; month 6 (June),
# is part of the second quarter; and month 11 (November), is part of the fourth
# quarter.
def quarter_of(month):
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.