blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
3cd20b58976bc79894edbf142b71aebf1b0c8db1 | tamannasharma95/pyhton_basics20 | /lucky_num.py | 747 | 3.875 | 4 | #Initiate a dictionary
numbers={
0:'Your daya will be awesome',
1:'You will get an opprtunity today,dont miss it',
2:'Day is full of perils',
3:'You will get a lottery today',
4:'Dont go out today,its risky for you',
5:'This day will bring something best for you',
6:'You will meet your bf t... |
466e09563347f532340d0cdc5770cf848102ab4c | gerh1992/shogi | /clases/piezas.py | 13,673 | 3.625 | 4 | class Pieza():
def __init__(self, jugador):
self.jugador = jugador
class Rey(Pieza):
simbolo = "K"
def __init__(self, jugador):
super().__init__(jugador)
self.pieza = "K ^" if jugador.color == "blancas" else "K v"
def __repr__(self):
return "el rey"
def checkear_... |
d69f2baf0f740e490252e601077d5b9d90cd6732 | realmichaelzyy/Machine-Learning-Project-Python | /Perceptron.py | 10,445 | 3.953125 | 4 | #--------------------------------------------------
# UCLA CS 260 - Machine Learning Algorithm
# Yao-Jen Chang, 2015 @UCLA
# Email: autekwing@ucla.edu
#
# Function about perceptron algorithm and MLP(sequential)
# normalization method for data points
#--------------------------------------------------
import numpy as n... |
e27ca977beace4ddad46cc8f2d1165b9a3f157d0 | Venkat445-driod/Python-Assignment-3 | /prob9.py | 231 | 3.75 | 4 | skillsanta_Dict ={"name": "Sachin", "age": 22, "salary": 60000, "city": "New Delhi"}
print("Before changing:",skillsanta_Dict)
x=skillsanta_Dict.pop("city")
skillsanta_Dict["location"]=x
print("after changing:",skillsanta_Dict) |
836bfc3c1aa4d031737a19e27d750eba8f235365 | zongxinwu92/leetcode | /LargestRectangleInHistogram.py | 455 | 4.28125 | 4 | '''
Created on 1.12.2017
@author: Jesse
''''''
Given n non-negative integers representing the histogram s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest re... |
f973a746225af86be88c32e25ed4f8f305aff139 | linlin-SMU/202011_learn-python | /maizi/04/04-02 列表内的元素修改和删除.py | 629 | 3.859375 | 4 | # index():返回列表里指定元素的下标
name_list = ['damao', 'dagou', 'xioamao', 'xiaogou',11,22,33,44]
if 'damao' in name_list:
index = name_list.index('damao')
print(index)
else:
print('数据不存在')
# 列表的修改
name_list[name_list.index('xiaomao')] = 'henxiaomao' #修改的方法:找到索引值,根据元素下标修改
# 列表的删除
name_list.remove('damao... |
74eca2ff42c9eda86e35be5cc6aa001c6a6b0764 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/vnklae001/question4.py | 1,175 | 4.0625 | 4 | # Assignment 6 - Question 4
# A program that takes a list of marks and outputs them in histogram representation according to categories
# Written by: Laene van Niekerk
# VNKLAE001
marks = input("Enter a space-separated list of marks:\n")
string_list = marks.split(" ") # Creates a list of numbers represented as string... |
2a99e4dfeb5a77c0027ee7fc14fe35def59187a6 | kaush4l/Euler | /20/7kk.py | 384 | 3.671875 | 4 | # 10001st prime
import math
def isPrime(n):
if n < 4:
return True
bool = True
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
bool = False
return bool
def nthPrime(n):
num = 3
while n - 2 > 0:
num += 2
if isPrime(num):
... |
5a345a955c375b6a75eb5d8c76e7327ee97fca7b | marcbichon/tome-rater | /TomeRater.py | 16,897 | 4.09375 | 4 | import re
class User(object):
"""Keep track of Tome Rater users.
Attributes:
name (str): The name of the user.
email (str): The email of the user.
books (dict): Books read by a user, keys are Books, values are
ratings (int).
"""
def __init__(self, name, email):
... |
f22ff3c3aa6db710ed4d01d323062dae6c34f21a | SachaReus/basictrack_2021_1a | /how_to_think/chapter_3/set_3/exercise_3_4_4_1.py | 246 | 4.125 | 4 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# count how many odd numbers in the list
count_odd_numbers = 0
for number in numbers:
if number % 2 == 1:
count_odd_numbers += 1
print("The list contains", count_odd_numbers, "odd numbers")
|
47050beefd6b5487807ab069989e18e94d0407b8 | southpawgeek/perlweeklychallenge-club | /challenge-141/sgreen/python/ch-1.py | 573 | 3.96875 | 4 | #!/usr/bin/env python
def divisors(number):
# One only has one divisor
if number == 1:
return 1
# All other numbers have 1 and itself as divisors
divisors = 2
# Find other divisors
for i in range(2, int(number/2)+1):
if number % i == 0:
divisors += 1
return di... |
454a03dd1df0ed3aa6b9ab9ea841334da9dccd46 | WotIzLove/University-labs | /PythonTutor/Тьютор 6/Задача 9.py | 131 | 3.625 | 4 | x = int(input())
i = 0
max_x = 0
while x != 0:
if x > max_x:
max_x = x
i += 1
x = int(input())
print(i - 1) |
69d97fbe5830fa04bada7d0f0967759997063fd2 | wonjongah/DataStructure_CodingTest | /practice/같은 문자쌍.py | 218 | 3.71875 | 4 | def is_same(string1, string2):
s1 = list(string1)
s2 = list(string2)
if sorted(s1) == sorted(s2):
return True
else:
return False
print(is_same("yes", "sey"))
print(is_same("uy", "ui")) |
880701bd568d9f28f3deafcc866b6e320b77d0f9 | NidhinAnisham/PythonAssignments | /pes-python-assignments-2x-master/55.py | 171 | 3.875 | 4 | pound = float(input("Enter pounds to convert: "))
assert(pound>0), "Negative pound!!"
kg = pound*0.453592
print "It is ",kg
assert(kg<101), "Weight is above 100 kg!"
|
295ebf279f034ccf7bc1807bb4f2ec488231bd31 | Naman-Garg-06/Python_personal | /binarySearchTree.py | 906 | 4.03125 | 4 | class node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def addToTree(self,data):
new_node = node(data)
while True:
if new_node.data <= self.data:
if self.left == None:
self.left = new_node
... |
d55f9f2beca4d5a390cc9adea052c8236e0f7162 | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/1-200/000048/000048_algo2.py | 2,047 | 3.78125 | 4 | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
# 通过观察可以发现,替换的规律是这样的:
## (旧的)第 i 行会变成(新的)第 n-1-i 列;(旧的)第 j 列会变成(新的)第 j 行。
# 比如例子里那个四阶矩阵:
## 第0... |
9567f40c4ddfe60645d687054b48ec0dcbed2de0 | mmkvdev/leetcode | /August/Week5/Day3/deleteNodeBST.py | 1,267 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
# print(root,key)
if root == Non... |
f25eec1ea8ced9055b89adf65c8aa6153bf8ee3c | djohn833/code-snippets | /python/binary_search.py | 754 | 3.765625 | 4 | #!/usr/bin/env python
import re
from regex_helpers import escape_for_charset
def binary_search_with_compare(c):
low, high = 0x20, 0x7e
while low < high:
guess = (low + high + 1) // 2
if chr(guess) <= c:
low = guess
else:
high = guess - 1
print(low, high... |
fa2e787aa42d79e5907057848889bcf90803b30c | HarikaDevineni29/HareHoundChase | /hareHoundChase.py | 2,383 | 3.75 | 4 | import turtle
from tkinter import *
def SetHarePos(x,y):
hare.up()
hare.setpos(x,y)
hare.down()
GetHoundPos()
def SetHoundPos(x,y):
hound.up()
hound.setpos(x,y)
hound.down()
Chase()
def GetHarePos():
messagebox.showinfo("Hare Position","Click on the screen to set hare position")
... |
003a36ee609e56d9f603f81383e29b8ef178ebd9 | ChrisTimperley/EvoAnalyser.py | /src/representation/storage.py | 582 | 3.765625 | 4 | # A dictionary is used to store registered representations.
__representations = {}
# Registers a provided representation using a given name.
def register(name, cls):
print "- registering representation: %s" % (name)
if __representations.has_key(name):
print "Warning: representation already defined (%s)... |
dfa25481b959b9b68f263b89790629ff27bd796e | lub4ik/- | /Сколько раз встречается слово.py | 254 | 3.984375 | 4 | userString=input("Введите ваш текст: ").lower()
word = input("Введите слово: ").lower()
userString.count(word)
x=userString.count(word)
print("Слово встречается в тексте столько раз: ", x)
|
b860048764de3d452000ae0a4c2943fbf0e0a606 | M1c17/ICS_and_Programming_Using_Python | /Week2_Simple_Programs/Lecture_2/V-Float-Fraction-convert dec-to-bin-3py.py | 941 | 4.0625 | 4 | '''
Write code to convert any number to its binary form
and print out the summary
'''
num = 19
str_num = str(num)
is_decimal = '.' in str_num
is_negative = num < 0
if is_negative:
num = abs(num)
if is_decimal:
decimal_num = num - int(num)
decimal_summary = '.'
while True:
decimal_num... |
2ee4613a9874f1332ff22430d699ab57abf1ef85 | zfyazyzlh/hello-python | /python作业/Week2作业.py | 2,828 | 3.6875 | 4 | 1编写程序,完成下列题目(1分)
题目内容:
身体质量指数(Body Mass Index,BMI)是根据人的体重和身高计算得出的一个数字,BMI对大多数人来说,是相当可靠的身体肥胖指标,
其计算公式为:BMI=Weight/High²,其中体重单位为公斤,身高单位为米。编写程序,提示用户输入体重和身高的数字,输出BMI。
输入格式:
输入两行数字,第一行为体重(公斤),第二行为身高(米)
输出格式:
相应的BMI值,保留两位小数。注:可以使用 format 函数设置保留的小数位数,使用 help(format) 查看 format 函数的使用方法。
输入样例:
80
1.75
输出样例:
26.12
时间限制:500ms内... |
c717cd70ad8a15e670ee405f504ba7a3ba505e4c | Hansyaung/Coding-Interviews-Questions-And-Solutions-python- | /用两个栈实现队列.py | 1,085 | 4 | 4 | '''
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
'''
# -*- coding:utf-8 -*-
# 队列为 先进先出
class stack: # 定义栈结构
def __init__(self):
self.stack = []
def isempty(self):
if len(self.stack) > 0:
return False
else:
return True
def push(self, node):
... |
cc56d9e8b83fe6cfab42e7ac8222c00aba45857f | jvslinger/Year9Design01PythonJVS | /Personal/passtest2.py | 513 | 3.578125 | 4 | def chosen_pokemon():
while True:
for trial in range(3):
print "Please enter your password."
fav_type = raw_input()
if "davey" in fav_type:
print "Password Correct."
else:
print "Sorry, password Incorrect."
cont... |
6f27d4b7cb0189ef211c748494e56ba787a55880 | jordanmiracle/learnpython3thehardway | /ex44b.py | 540 | 3.875 | 4 | class Parent(object):
def override(self):
print("PARENT override()")
def player(self, health, armor, damage):
self.health = health
self.armor = armor
self.damage = damage
print (f" health is {health}. Armor is {armor}, and damage is {damage}.")
class Child(Parent):
... |
ad1659931f4ea1b3b28c8193cae8012982b05b73 | Smily-Pirate/LeetCode | /climbingStairs_LeetCode.py | 163 | 3.65625 | 4 | def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
def countWays(s):
return fib(s + 1)
s = 5
print("Number of ways = ", countWays(s)) |
27a273fb34712034aa223523747fc739aef6b3bc | Luolingwei/LeetCode | /Tree/Q100_Same Tree.py | 905 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# Solution 1 recursive 40 ms
# def isSameTree(self, p,q):
# if p and q:
# return (p.val == q.val) and self.isSame... |
d8ee9a30e47926473bf0ed84ab78e7ba4ee76ae6 | piazentin/programming-challenges | /hacker-rank/implementation/bon_appetit.py | 372 | 3.734375 | 4 | # https://www.hackerrank.com/challenges/bon-appetit
def bon_appetit(k, prices, charged):
change = charged - (sum(prices) - prices[k])//2
if change == 0:
return 'Bon Appetit'
else:
return change
n, k = [int(i) for i in input().split()]
prices = [int(i) for i in input().split()]
charged = ... |
9d16b2b151a30b3a18130ca0e6e927a47e0e4398 | standrewscollege2018/2021-year-11-classwork-NekoBrewer | /Try and Except.py | 286 | 4.125 | 4 | # Example of try and except
keep_asking = True
while keep_asking == True:
try:
number = int(input("please enter number "))
print("You chose", number)
print("**** All done****")
keep_asking = False
except:
print("That's not an integer!")
|
6e96ffcaa7d19ea1d250aca4ef490cf303e1d3ab | fontes99/EP_DSoft | /Parte_1.py | 5,006 | 3.765625 | 4 | import json
from firebase import firebase
firebase = firebase.FirebaseApplication('https://memoria-5bd26.firebaseio.com/memoria-5bd26', None)
result = firebase.get('https://memoria-5bd26.firebaseio.com/memoria-5bd26', None)
estoque = result
negativo = []
with open ('memoria.txt','r') as arquivo:
conteudo = arquiv... |
11f2f42c4b63e985a550daa67c27cdc78e3e6a79 | JIghtuse/python-playground | /crash_course/testing/names.py | 425 | 3.828125 | 4 | from name_function import get_formatted_name
QUIT_VALUE = 'q'
print(f"Enter '{QUIT_VALUE}' at any time to quit.")
while True:
first = input("\nPlease give me a first name: ")
if first == QUIT_VALUE:
break
last = input("Please give me a last name: ")
if last == QUIT_VALUE:
break
f... |
e1d7d1f817fab53e379f476b706f12a1f95c32c1 | Crepkey/AskMate | /data_manager.py | 3,426 | 3.53125 | 4 | import csv
import os
import time
ANSWERS_HEADER = ['id', 'submission_time', 'vote_number', 'question_id', 'message', 'image']
QUESTIONS_HEADER = ['id', 'submission_time', 'view_number', 'vote_number', 'title', 'message', 'image']
ANSWER_FILE_PATH = 'sample_data/answer.csv'
QUESTION_FILE_PATH = 'sample_data/question.c... |
64d3091684ced3b42adaf7c9eba3b4fe06256c76 | NikeSmitt/geekbrains_algorithms_main | /hw_4/task_2.py | 5,047 | 3.625 | 4 | import timeit
import cProfile
import matplotlib.pyplot as plt
# Написать два алгоритма нахождения i-го по счету простого числа.
# Без использования решета Эрастофена
def is_prime(value):
if value < 2:
return False
dev = 2
while dev <= value ** 0.5:
if value % dev == 0:
retur... |
90818b96d8f25ed6722dc8f49387e74f5703bded | forzen-fish/python-notes | /6高级函数/2装饰器参数.py | 792 | 3.828125 | 4 | """
多个装饰器
def zhuangshiqi1(hanshu):
print("zhuangshi1_ing")
def inner1():
print("inner1函数")
hanshu
return inner1
def zhuangshiqi2(hanshu):
print("zhuangshi2_ing")
def inner2():
print("inner2函数")
hanshu
return inner2
@zhuangshiqi1
@zhuangshiqi2
def aaa():
pri... |
0077c45f1d00caba876d5b741e4c909e0ab214c2 | pasu-t/myPython | /python_modules/unittest/test_circles.py | 840 | 3.90625 | 4 | import unittest
from circles import circle_area
from math import pi
class TestCircleArea(unittest.TestCase):
"""docstring for TestCircleArea"""
def test_area(self):
#when radius > 0
self.assertAlmostEqual(circle_area(1), pi)
self.assertAlmostEqual(circle_area(2.1), pi*(2.1**2))
... |
35469de03cca4255afa3c1ffb46c0be384dd40b4 | sumitAggarwal416/gradeModule | /gradeModule.py | 3,558 | 3.53125 | 4 | '''
I, Sumit Aggarwal, student number:0007893607, certify that all code submitted is my own code, that I have not copied it
from any other source. I also certify that I have not allowed any one else to copy my code.
'''
lab_wt= int(input("Enter the weight of labs in the course: "))
labs= int(input("Enter the numbe... |
62e8038bfc3b28d6c43cdf8255ac0e36b9c25019 | okaaryanata/Arkademy | /soal3.py | 230 | 3.703125 | 4 | def count_vowels(data):
lowerString = data.lower()
vowels = ['a','i','u','e','o']
counter = 0
for x in lowerString:
if x in vowels:
counter += 1
return counter
print(count_vowels('RobErT')) |
08c2a06792f5b78cbb7733042ed3b3753789c51b | aydentownsley/AirBnB_clone | /tests/test_models/test_amenity.py | 1,034 | 3.65625 | 4 | #!/usr/bin/python3
""" Testing Amenity Module """
import unittest
from models.base_model import BaseModel
from models.amenity import Amenity
from datetime import datetime
class TestAmenity(unittest.TestCase):
""" testing output from User class """
def test_attrs(self):
""" test attrs of Amenity when... |
6cccf7841afa7e8fc28465e4251bf108b54da7d7 | syedaali/python | /exercises/28_class.py | 328 | 4.15625 | 4 | __author__ = 'syedaali'
'''
Define a class named Circle which can be constructed by a radius.
The Circle class has a method which can compute the area.
'''
class Circle(object):
def __init__(self, n):
self.n = n
def radius(self):
return self.n * self.n
aCircle = Circle(5)
print aCircle.r... |
a801369bee18aca9961334812c2a9f912ee63226 | dvelez1402/dvelez1402.github.io | /my-website/images/FINAL PROJECT !!.py | 3,358 | 3.796875 | 4 | import time
#This is a comment
def trench():
print("We've been here the whole time. You were asleep. Time to wake up. ")
time.sleep(3)
print (' ______ _______ _ ')
print (' | ____| |__ __| | | ')
pr... |
ecd1c3a183c738f4429f7c8f24227562df902300 | Mamba-ZJP/School | /Network/Client.py | 762 | 3.5 | 4 | from socket import *
import base64
serverAddr = input("Server address:") # server ip 192.168.8.108
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverAddr, serverPort))
def encrypt(plaintext): # 加密明文
encryptedText = base64.b64encode(plaintext.encode("utf-8")) # 先将字符串转... |
7795650a2a6a3a5b487368c2f2f4d9099677115c | marydCodes/jetbrains_coffeemachine | /methods_practice.py | 2,994 | 3.875 | 4 | class Person:
def __init__(self, name):
self.name = name
# create the method greet here
def greet(self):
print(f"Hello, I am {self.name}!")
# first = str(input())
# me = Person(first)
# me.greet()
############################################################
import math as m
class Hexago... |
32ed7176e90417b266a4b71ae8af93b325f115f1 | AsthaNegi/FaultyCalculator | /FaultyCalculator.py | 1,682 | 4.0625 | 4 | #Faulty calculator by Astha Negi
while(1):
print("Enter the operation you want to perform:")
print("Enter 1 for addition:")
print("Enter 2 for sub:")
print("Enter 3 for mul:")
print("Enter 4 for div:")
a = int(input())
if a < 1:
print("invalid choice!\nTry again")
... |
21c5f1020b9babbb33d41e51e61c1689d4e194b1 | hobbyelektroniker/Micropython-Grundlagen | /006_Mengentypen - Tuple/Code/tuples.py | 1,515 | 4.3125 | 4 | # Ein Tuple mit vorgegebenen Werten erzeugen
tup1 = ("Hallo",3,1.25,"Welt",2,3,4,5)
print(tup1)
print()
# Leeres Tuple erzeugen
tup2 = tuple() # macht nicht viel Sinn !!!
print(tup2)
print()
# Aus anderen Collections erzeugen
set1 = {"Hallo",3,1.25,"Welt"}
tup2 = ("Hallo",3,"Jahr 2020",5)
tup1 = tuple(set1)
print(tu... |
fdb6344fd385f7b94b7125beda2fa3eb6c1afc07 | kiccho1101/atcoder | /atc001/b.py | 783 | 3.5 | 4 | class UnionFind:
def __init__(self, n: int):
self.par = list(range(n + 1))
def find(self, x: int):
if self.par[x] == x:
return x
self.par[x] = self.find(self.par[x])
return self.par[x]
def same(self, x: int, y: int):
return self.find(x) == self.find(y)
... |
6e22ad88e072fcf2463c7fb6fd8201b5720245a1 | imrahul22/placementProgram | /Factorial of a number.py | 164 | 4.09375 | 4 | #Factorial of a number
def fact(n):
while n==0:
return 1
while n!=0:
return n*fact(n-1)
n=int(input("Enter the number"))
print(fact(n))
|
2c762fcbfbc7919f218256247f57719d5ab595fc | ju-c-lopes/Univesp_Algoritmos_I | /Semana 6/exercicio5.3.py | 789 | 4.15625 | 4 | """
Problema Prático 5.3
Escreva a função aritmética(), que aceita uma lista de inteiros como entrada e retorna
True se eles formarem uma sequência aritmética. (Uma sequência de inteiros é uma sequência
aritmética se a diferença entre os itens consecutivos da lista for sempre a mesma.)
# >>> aritmética([3, 6, 9, 12,... |
ef5ddcff852d5192148da2cb328b108317dddcea | KevinChen1994/leetcode-algorithm | /offer/13.py | 2,029 | 3.71875 | 4 | # !usr/bin/env python
# -*- coding:utf-8 _*-
# author:chenmeng
# datetime:2020/8/17 22:27
'''
solution: 使用dfs或者bfs都可以,机器人按照当前坐标,只能移动一个格,所以不能遍历所有的位置来判断是否符合要求,
当机器人遇到一个不符合要求的位置的时候,那后边的位置肯定也是不符合要求的。
这道题的难点在于如何求位数和,其实可以使用一个比较笨的方法:
def sum(x):
s = 0
while x != 0:
s = x % 10
x = x // 10
return s
但... |
9f9ef79152fa834d7c41af8e62fbb2f6a7b580e0 | frankye1000/LeetCode | /python/Sum of Even Numbers After Queries.py | 1,649 | 4.0625 | 4 | """We have an array A of integers, and an array queries of queries.
For the i-th query val = queries[i][0], index = queries[i][1], we add val to A[index].
Then, the answer to the i-th query is the sum of the even values of A.
(Here, the given index = queries[i][1] is a 0-based index, and each query permanently modifi... |
f96004cd9d52de306c789f6b6264c7c1bb51f4cd | Knln/online-coding-judge | /leetcode/539-minimum-time-difference.py | 862 | 3.5 | 4 | from typing import List
class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
floats = [int(x[0:2]) * int(60) + int(x[3:]) for x in timePoints]
sorted_floats = sorted(floats)
minimum = 1440
day = 1440
if len(sorted_floats) == 2:
... |
8320d9e5bcd7803ebb2c4fe510f965000c205ced | fervorArd/Hackerrank-Solutions-in-Python- | /46_word-order.py | 273 | 3.609375 | 4 | num = int(input())
words = []
for i in range(num):
words.append(input())
count = {}
for i in words:
count.setdefault(i,0)
count[i] = count[i]+1
sorted_list = list(count.items()).sort()
print(len(count))
for i in count.values():
print(i,end=' ')
|
3bdc4e6299592f1578d7ac5260ad2f91822b09e4 | code-killerr/python_practise | /python practise/20.模块.py | 744 | 3.546875 | 4 | #此时为一个模块,放在调用程序的文件夹下即可调用,Py文件名为模块名,可以Import导入模块调用其中函数
def hello():
#外层调用该函数使用文件名.hello()即可
print('helo world')
#from 模块名 import 函数名可以直接导入函数,再加as可以重命名
#模块测试
def test():
print(hello())
import urllib
def translation():
url = r'https://fanyi.baidu.com/'
data = {}
data['aldtype']=r'16... |
71e859579159cc5a30a60b6f56c81cffc63c8f57 | ChAoss0910/python-programming | /Scrabbler/Program.py | 5,000 | 4.1875 | 4 | from manage import manage
#save all of the points values in a dictionary
pointValues = {"a": 1, "b": 3, "c": 3, "d": 2, "e": 1, "f": 4, "g": 2, "h": 4, "i": 1, "j": 8, "k": 5, "l": 1,
"m": 3, "n": 1, "o": 1, "p": 3, "q": 10, "r": 1, "s": 1, "t": 1, "u": 1, "v": 4, "w": 4, "x": 8,
"y": 4, ... |
d323f659521b4f869aebad8247dd52d6c695bff6 | abeaumont/competitive-programming | /atcoder/abc053/c.py | 146 | 3.5625 | 4 | #!/usr/bin/env python3
# https://abc053.contest.atcoder.jp/tasks/arc068_a
x = int(input())
print(x // 11 * 2 + int(x % 11 > 6) + int(x % 11 > 0))
|
0ded5130c5f1448adbf4bc452a8b2f24ce6d39a6 | soham0511/Python-Programs | /PYTHON PROGRAMS/function.py | 546 | 3.796875 | 4 | # def percent(marks):
# sum=0
# for i in marks:
# sum+=i
# return sum/len(marks)
# marks1=[12,56,78,99,100]
# marks2=[14,56,89,99,55]
# percentage1=percent(marks1)
# percentage2=percent(marks2)
# print(percentage1)
# print(percentage2)
# def greet(name="Stranger"):
# print("Good... |
1a3778d2a59178bc0a362d526f3dd2f7748bcfb9 | gaowanting/learnPython | /useful functions/map.py | 563 | 4.40625 | 4 | # 首先map() 是一个函数,会根据提供的函数对指定序列做映射。
# map(function, iterable, ...) --> 返回一个迭代器
# function:定义一个函数,即映射关系
# iterable:一个或多个序列
tuple1 = (1,2)
tuple2 = (3,4)
l1 = map(lambda x:x^2,tuple1)
l2 = map(lambda x,y:x+y ,tuple1,tuple2)
l3 = map(float, tuple1)
'''
注意这里不能print map 因为map返回的就是一个迭代器
<map object at 0x0000022A482686D0>
... |
0459b31b47c922a8d81a4391a2f851c59d491551 | diskpart123/xianmingyu | /python程序语言设计/E4.09/E4.09.py | 324 | 3.96875 | 4 | weight1, price1 = eval(input("Enter weight and price for package 1:"))
weight2, price2 = eval(input("Enter weight and price for package 2:"))
perprice1 = price1 / weight1
perprice2 = price2 / weight2
if perprice1 < perprice2:
print("Package 1 has the better price.")
else:
print("Package 2 has the better price... |
f0b683bb89719dede743c47f890fe81d7d5c8e8c | gkmjack/number-theory-gadgets | /code/quadratic_residue.py | 2,175 | 3.65625 | 4 | from modular import mod;
from random import randint;
from modular import multiplicative_inverse;
import primality; # No splat import
def jacobi_symbol(n, a):
"""Compute the Jacobi symbol (a/n) where n is an odd number."""
if (n%2 == 0):
raise Exception("Invalid Jacobi symbol.");
# Check that n is i... |
6899e47b4378cacd28912bced5eab55c67dc71fd | matthew-meech/ICS3U-Unit3-05-Python-Month | /month.py | 1,101 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Mr. Matthew Meech
# Created on: Sep 2021
# month namer
def main():
# input
integer = int(input("Enter number a the number of a month:"))
print("")
# if ... then ... elseif
if integer == 1:
print("your month is Jan")
elif integer == 2:
pri... |
e7008e58b21fa471257d492bc2beccb16262c44a | SaturdaysAI/Projects | /Zaragoza/AnalisisEncuestaEmpresas-main/scripts/terminal.py | 10,102 | 3.671875 | 4 | """
Procesamiento de instrucciones.
No se puede grabar o reproducir un fichero que se esté grabando o reproduciendo. Para este control empleamos listaArchivos[]
"""
import re
import os
def esEntero(s):
"""
Devuelve True si la cadena s representa un entero positivo o negaiivo
Parameters
----------
... |
dc4ef71d108b7d0b5f122cd2c3c01708edf4845b | jemisonf/closest_pair_of_points | /brute_force.py | 1,398 | 3.796875 | 4 | from lib import read_inputs, write_outputs
import math
import sys
def calculate_distance(first_point, second_point):
distance = math.sqrt(math.fabs(
(first_point[1] - second_point[1])**2 +
(first_point[0] - second_point[0])**2))
return distan... |
449591e1f1fcca76d0f2b3c172ff516638280d87 | cKompella/python-basics | /src/classes.py | 2,405 | 3.84375 | 4 | #Part1: Creating Menu, Franchise and Business classes
class Menu:
def __init__(self, name, items, start_time, end_time):
self.name = name
self.items = items
self.start_time = start_time
self.end_time = end_time
def __repr__(self):
return "{name} available from {start} to {end}".format(name=self... |
c2f03ff9fb40ccfa997e756da0b43e65a04b888a | ZYZhang2016/think--Python | /chapter15/Exercise15.2.py | 629 | 3.828125 | 4 | #coding:utf-8
class Point(object):
'''一个二维的点
'''
class Rectangle(object):
'''定义一个矩形的点和长宽
attribute:height,width,corner
'''
def move_corner(box,dx,dy):
'''移动矩形boxde1corner
:param box: Recyangle()对象
:param dx: x轴方向移动距离
:param dy: y轴方向移动距离
:return: 返回移动后的矩形
'''
box.corner.x += dx
box.corner.y += dy
return... |
760019f5052bbf63342a8834e016633f1b22217d | scottberke/algorithms | /algorithms/search/linear_search/linear_search.py | 209 | 3.78125 | 4 | def search(arr, target):
# Grab index and value
for index, val in enumerate(arr):
# If we find our target
if val == target:
# Return index
return index
# Otherwise, return False
return False
|
ec311ce99cb0e65dd7dd207b78665c62ae779dc4 | hughwin/hughpython | /tld.py | 2,242 | 4.3125 | 4 | # This program will hopefully show that I understand tuples, lists and dictionaries.
while True:
user = ""
print """
Welcome to this program. If will hopefully demonstrate that Hugh fully
understands tuples, lists and dictionaries as well as how they can be manipulated.
Hugh will also demonstrate his competence wit... |
aaf46b4583c50bb4c2cb90571fb4c6f9c6216f2c | kickscar/deep-learning-practices | /03.linear-algebra-basics/01/ex12.py | 597 | 3.984375 | 4 | # coding: utf-8
# 전치행렬(transpose matrix)
"""
1. 어떤 행렬의 행과 열을 바꿔 생성한 행렬이다.
2. 축에 대한 변경이지 요소의 변경이 아니다.
"""
import numpy as np
# a = np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])
a = np.arange(15).reshape(3, 5)
print(a)
print(a.shape)
print('=====================')
a1 = a.T
print(a1)
print(a1.sha... |
c89252a91f0ed7a40c844b5fc51f9b118415f809 | dpfeifer-dotcom/BroTalk | /openfile.py | 344 | 3.59375 | 4 | from tkinter import filedialog
import tkinter as tk
import os
def openfile():
"""
:return: file helye, file neve
"""
root = tk.Tk()
root.attributes("-topmost", True)
root.withdraw()
file_path = filedialog.askopenfilename(initialdir="/", title="Select A File", )
return file_path, os.p... |
5005be8f88be9e32e73f6d6f3f850c32f2e55ab8 | Shantanu0901/sadchatbot | /main.py | 19,127 | 3.5625 | 4 | import wikipediaapi
wiki_wiki = wikipediaapi.Wikipedia('en')
import urllib.request
import sys
import time
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np
from keras.models import load_model
model = load_model('chatbot_model.h5')
import js... |
f738b917fd7f6dd8d362ef2c5e0b9e1199b0289b | itmproject/PythonProject | /Project 4/Project 4/Project_4.py | 2,671 | 4.0625 | 4 | ##Project 4
##Nhan Nguyen
##Program that subtracts a withdrawl from a Checking Account.
import datetime
from Banking import BankingAccount
s = BankingAccount()
def validMenu(self): ##Validate input of User
while True:
try:
inputMenu = int(input(self))
if inputMenu > 5: ##Error ... |
cb81ba0af3b04365297bbe546face2475e2a235b | Leskos/ev3 | /simpleTimer_V2.py | 3,714 | 3.9375 | 4 | #!/usr/bin/env python3
from ev3dev.ev3 import *
from time import sleep
# Improved version of simpleTimer.py that is more suitable for
# performing the experiment. The timer is primed when a weight
# is placed on the start sensor, and only started upon release
#
# This is for recreating Galileo's leaning tower of ... |
9a6a6d0a1aff374b132bbef82dac50b60741e9db | KosuriLab/MFASS | /scripts/splicemod_src/src/entropy.py | 4,192 | 3.703125 | 4 | '''
A set of functions that computes the entropy, either shannon or kolmogorov, of
a string. The kolmogorov complexity is an approximation using zlip and shannon
was taken off of activestate and modified to use variable wordsizes.
@author: dbgoodman
'''
## {{{ http://code.activestate.com/recipes/577476/ (r1)
# Shanno... |
f5ebc18d7b0b08a33a3555379a9b3ad585015392 | zlatnizmaj/Advanced_Algorithm | /Moj practice MIT 60001/Lecture codes/Dictionary02_python.py | 232 | 4.09375 | 4 | grades = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 }
for s in grades: # print all keys of dictionary 'grades'
print("key '{}' have value: {}".format(s, grades[s]))
L = grades.values()
print(len(L))
print(grades.keys())
print(L)
|
75bfe42e7a0272b30380583d2849bab1757fc08e | fguedez1311/POO_Tecnologico | /producto.py | 727 | 3.6875 | 4 | class Producto:
def __init__(self,referencia,nombre,pvp,descripcion):
self.referencia=referencia
self.nombre=nombre
self.pvp=pvp
self.descripcion=descripcion
def __str__(self):
return """
Referencia \t {}
Nombre \t\t {}
pvp \t\t {}
Descripcion \t {} """.format(self.referencia,se... |
4560fbd345e37e98f20a4cb55a2906a42913ea43 | adilsonfuta/Scripty-Python | /E1.py | 260 | 3.703125 | 4 | #n=int(input('Diga o valor'))
#print('O quadrado {}'.format(n**2))
#print('O Antecessor {} Sucessor {}'.format(n+1,n-1))
dist=int(input('Diga o valor Distancia'))
comb=int(input('Diga o valor Combustivel'))
print('O consumo Medio {}'.format(dist/comb))
|
873c9b4b813be1d6edece116d6abc9a4fe11ab0d | andrew10per/TFRRS-Web-Scraper | /Athlete.py | 632 | 4.0625 | 4 | '''
A Class that defines an athlete
Athlete holds a name string ( which can also include Class)
Athlete holds an array of events, and an array of times.
These array's should be passed in mathcing
Therefore if events[0] is a 5000, then times[0] should be a 5000 time.
Written by Andrew Perreault
Canisius College Compute... |
6362b19e9c0e9edc3f5c4f5534d884ab6023c0fa | rsmbyk/computer-network | /socket-programming/tcp/code/tcp_client.py | 676 | 3.5625 | 4 | import socket
def main ():
buffer = 32
host = input ("Server IP: ")
port = 3000
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sock.connect ((host, port))
print ("Connected to", host, "on port", str (port))
print ("Format: [$number] [$operator] [$number]. Send 'exit' to stop prog... |
291478ae3d11ea71d3ab02a8a03bbb743e6b1846 | AkshayK25/File_handling | /Combination_file.py | 391 | 3.75 | 4 | with open('abc.txt') as fl1, open('test.txt') as fl2:
for line1, line2 in zip(fl1, fl2):
# line1 from abc.txt, line2 from test.txt
print(line1+line2)
print("\r")
def read_integers(filename):
with open(filename) as f:
numbers = [int(x) for x in f]
return numbers
print(read_inte... |
3d61f38ef21161da61f808360ab2b5e800e40609 | jaydenlsf/Python-Exercise | /qa-community-exercise/class.py | 396 | 3.53125 | 4 | class Students:
def __init__(self, name="student", age="student", class_name="student"):
self.name = name
self.age = age
self.class_name = class_name
def get_avg_score(self, *test_scores):
return sum(test_scores) / len(test_scores)
student_1 = Students("Jayden", 24, "DevOps"... |
f0af6d805e3a63a126f699ec2aaae20e079eec94 | Kyle628/data-structures-python | /test_b_search_tree.py | 357 | 3.609375 | 4 | from binary_search_tree import tree_node
from binary_search_tree import binary_search_tree
my_node = tree_node('k', 'kyle')
'''my_node.right = tree_node('m', 'matias')
my_node.left = tree_node('g', 'giorgi')'''
my_tree = binary_search_tree()
my_tree.put("k", "kyle")
my_tree.put('g', 'giorgi')
my_tree.put('m', 'mat... |
3ee118e8521e67959f087750172220ceafb48d6e | MathiasDarr/Algorithms | /python-algorithms/strings/palindrome/validPalindrome.py | 591 | 3.6875 | 4 | class Solution:
def validPalindrome(self,s):
def isPalindrome(left, right):
while left<right:
if s[left] != s[right]:
return False
left +=1
right -=1
return True
left =0
right = len(s) -1
whi... |
1ac77dbdcfd12e3438e2ba89ef48d6b79fc3d113 | li-black/bird | /players.py | 675 | 3.75 | 4 | players=['charles','martina','michael','florence','eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
my_foods=['pizza','falafel','carrot cake']
firend_foods=my_fo... |
7297ca60e51b68cc074a4743296604bdb02325db | SouradeepSaha/DMOJ | /CCC/Huffman Encoding.py | 279 | 3.5 | 4 | k = int(input())
store = {}
for i in range(k):
k, v = input().split()
store[v] = k
text = input()
start, ans = 0, ''
for stop in range(1, len(text)+1):
word = text[start:stop]
if word in store.keys():
ans += store[word]
start = stop
print(ans)
|
16ed81e8e55511429afefbaff25bcc9e4a17f668 | st3fan/aoc | /2015/py/day12.py | 864 | 3.703125 | 4 | #!/usr/bin/env python3
import json
def sum_int_values1(o):
match o:
case int(i):
return i
case dict(d):
return sum(sum_int_values1(o) for o in d.values())
case list(l):
return sum(sum_int_values1(o) for o in l)
case _:
return 0
... |
4b5d6d2f95bc9b0c0226e2c41aeda2e12c113984 | Munnu/interactivepython | /datastructures/trees/hb-tree-lecture/trees.py | 1,583 | 4.15625 | 4 | class Node(object):
""" Node in a tree. """
def __init__(self, data, children=None):
# children holds a list of Node types
children = children or [] # empty list if children is None
assert isinstance(children, list), \
"children must be a list!"
self.data = data
... |
d624ec60efc2d65cd77987a28e2c3ab237882c4c | RayRuizheLi/onlineShoppingApplication | /product.py | 593 | 3.5625 | 4 | class Product:
# name: string, price: double, amount: int
def __init__(self, name, price, amount):
self.__name = name
self.__price = price
self.__amount = amount
def getName(self):
return self.__name
def getPrice(self):
return self.__price
def getAmount(se... |
2c218a8e2f07808e03d6a5cb1fe81c9ecb934a64 | timmy61109/Introduction-to-Programming-Using-Python | /own_practice/two_seven.py | 529 | 3.828125 | 4 | """
程式設計練習題 2.2-2.10 2.7 找出年數.
請撰寫一程式,提示使用者輸入分鐘數(例如十億),接著顯示相對應的年數與天數。假設一年365天。以下是
範例輸出樣本:
```
Enter a number of minutes:1000000000
1000000000 minutes is approximately 1902 years and 1000000000 days
```
"""
import ast
minutes = ast.literal_eval(input("Enter a number of minutes:"))
days = minutes // 1440
years = days ... |
ba1dd5606a1c4c1425135f1b38bf9315f4811607 | rishavh/UW_python_class_demo.code | /chapter_17/a_Point_class_str_and_init_exercise_17_3.py | 501 | 4.21875 | 4 | #! /usr/bin/env python
#
# Exercise 17-3 Write a str method for the Point class. Create a Point object
# and print it.
#
class Point( object ):
"""A class which represents a point on a plane"""
def __init__ ( self, x, y ) :
"""A constructor for a point"""
self.x = x
self.y = y
de... |
158bbc37a84fce5d498def8662466ba668d33999 | penroselearning/pystart_code_samples | /15 Combining Dictionaries with Lists - Vacation Favorites V1.py | 305 | 3.96875 | 4 | vacations = {'Vienna' : [2010,'Austria','Schönbrunn Palace', 'Apple Strudel']}
print(f'{"City":10} {"Year of Visit":13} {"Country":15} {"Favorite Spot":25} {"Favorite Food":25}')
print('-'*80)
for city,info in vacations.items():
print(f'{city:10} {info[0]:13} {info[1]:15} {info[2]:25} {info[3]:25}') |
b2e9e3ded41d7ee5fbcae4c13e05591cebfd4da9 | Grey-EightyPercent/Python-Learning | /ex15.py | 1,633 | 4.53125 | 5 | # Read files
# Using argv to read filename from users
#从sys module导入argv功能
from sys import argv
#利用argvuoqu用户输入它想要打开的文件名
script, filename = argv
# !!! Function: open (). Exp.: open(filename, mode ='r')
# mode = 'r' : open for reading
# mode = 'w' : open for writing, truncating the file first
# mode = '... |
a5d9bc0017d97a2d530016b13ad68378f799d292 | leidyAguiar/exercicios-python-faculdade-modulo-1 | /2 lista_estrutura_de_decisao/exerc_018.py | 1,646 | 3.9375 | 4 | """
18. Faça um programa que receba o código correspondente ao cargo de um funcionário e seu salário atual e mostre o cargo, o valor do aumento e seu novo salário.
Os cargos estão na tabela a seguir.
CÓDIGO | CARGO | PERCENTUAL
1 | Escriturário | 50%
2 | Secretário | 35%
3 | Caixa ... |
88747b706b8cfabf220402899543fb2a972520fa | ibrahim2204/main | /main.py | 63 | 3.5625 | 4 | print("Hello World")
a=input("type the value of a: ")
print(a)
|
6729b75c316587702a74279e93ea92f83b11a570 | qram9/c_ast | /c_ast/hir/FloatLiteral.py | 1,853 | 3.671875 | 4 | from hir.Literal import Literal
class InvalidTypeFloatLiteralError(Exception):
def __init__(self, value):
self.value = value
def __repr__(self):
return 'Invalid type: (%s) for integer literal, expected: (%s)' % (value, str(type(int)))
class FloatLiteral(Literal):
"""Represents a Float l... |
6fee6347689b3cec842e9cdca4c3ffb197df97aa | tanyastropheus/holbertonschool-higher_level_programming | /0x05-python-exceptions/0-safe_print_list.py | 315 | 3.875 | 4 | #!/usr/bin/python3
def safe_print_list(my_list=[], x=0):
count = 0
try:
for i in my_list[0:x]: # slicing the list
print("{}".format(i), end="")
count = count + 1
print()
except IndexError:
pass # code after pass will still get executed
return count
|
cd5748d4289d285d7a9196c5ffa1480954cb27ea | oscarDelgadillo/AT05_API_Test_Python_Behave | /FrancoAldunate/Practice1.py | 2,339 | 4.28125 | 4 | #Excercises from slides
print(type(1))
print(type("Test"))
print(type(0.2))
Message = "String test"
print(type(Message))
n = 1000
print(type(n))
pi = 3.1416
print(type(pi))
some_variable_really_long_is_accepted = "Any_value"
print(some_variable_really_long_is_accepted)
some123_variable = 1
print(some123_variable)
hel... |
dcca07f8763ec798aa5289f392f38005f3a060df | vangaru/labs | /DM labs/lab1/test.py | 500 | 3.78125 | 4 | def partition(collection):
if len(collection) == 1:
yield [ collection ]
return
first = collection[0]
for smaller in partition(collection[1:]):
# insert `first` in each of the subpartition's subsets
for n, subset in enumerate(smaller):
yield smaller[:n] + [[ firs... |
f6119266d63e9d4aba162224f96ab9b97c07dc9b | maciekgajewski/the-snake-and-the-turtle | /examples/tdemo_geometry/tdemo_illusion_2.py | 805 | 4 | 4 | """ turtle-example-suite:
tdemo_illusion_2.py
A simple drawing suitable as a beginner's
programming example.
Diagonals moving away from the center create
an illusion of depth, which makes the parallel
horizontal lines seem to bend in the center.
Inspired by NetLogo's model of optical
il... |
fc499018a1d30890237b5b8aa2f8cef6dcee475b | MaxPoon/EEE-Club-Python-Workshop | /syntax/1_beginning_with_python/4_input.py | 176 | 3.890625 | 4 | x = input("enter an integer: ")
# x = x + 1
# this will cause an error
x = int(x)
x = x + 1
print(x,'\n')
x = input("enter a float number")
print(x)
x = float(x)
print(x+1) |
e7cd2eff9cfdfb5de86ecaca7bd7cc9e541dd1c8 | sinoop/100DaysOfCode | /day019/turtle_race.py | 1,929 | 4 | 4 | import json
import random
from turtle import Turtle, Screen
TURTLE_HEIGHT = 40
TURTLE_WIDTH = 40
class TurtleObject:
def __init__(self, color, name, start_x, start_y, max_x):
self.turtle = Turtle()
self.turtle.penup()
self.turtle.color(color)
self.turtle_name = name
self.... |
648e6d836e3992fcb0a2c7898888bb517cdb2155 | tychonievich/cs1110s2017 | /markdown/files/001/2017-02-17-fundamental_truthiness.py | 412 | 4.03125 | 4 | if 'cheese':
print('yum')
else:
print('I want cheese')
# All things have truthiness
# nothing is false
print(bool(1), bool(-12), bool(0), bool('hi'), bool(''))
def working_age2(age):
if 14 <= age < 70:
return 'True'
else:
return 'False'
age = int(input('How old are you? '))
if worki... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.