blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
42c0521c1e092ccec6538319d1aa4f40d3c01284 | blue-eagle-089/class-110 | /python/SDP.py | 551 | 3.8125 | 4 | import csv
import math
with open('data.csv', newline='')as f:
reader = csv.reader(f)
datalist = list(reader)
data = datalist[0]
def mean(data):
length = len(data)
total = 0
for i in data:
total = total+int(i)
mean = total/length
return mean
squares = []
... |
92f25d14a48f8f182d06f0b07cc13be2e36d5755 | yenext1/python-bootcamp-september-2020 | /lab11/exercise_5.py | 690 | 4.09375 | 4 | # get rand num (1,1M) and return if can be divided by 7,13,and 15
from random import randint
n1 = randint(1,10)
n2 = randint(1,10)
print(f"N1 is {n1}, N2 is {n2}")
for i in range(n1*n2):
num = i+1
if (num % n1 + num % n2 == 0):
print(f"The smallest multiplpliable number is {num}")
break
"""
Uri... |
eb1282fcb31e82f4b2278cac77e0b6ecd70f7c84 | bread-kun/MyGobang | /gobang_min.py | 6,914 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
class GoBang():
PLAYER_1,PLAYER_2 = 1,2
history_1 = []
history_2 = []
WIN,LOSS = 500000000,-500000000
GUESS_RANGE = 2
def __init__(self, size):
self.map = [[0]*size for i in range(size)]
def move(self, player, node):
assert len(node) is 2 , ("An Erro... |
c78eb372194d81c21efe8005bedfa6a4a807e7cb | RadkaValkova/SoftUni-Web-Developer | /Programming Fundamentals Python/Preparation/Next Happy Year.py | 405 | 3.703125 | 4 | current_year = int(input())
next_happy_year = current_year
while True:
a = str(next_happy_year)[0]
b = str(next_happy_year)[1]
c = str(next_happy_year)[2]
d = str(next_happy_year)[3]
if a != b and a != c and a != d and b != c and b != d and c != d:
next_happy_year = (f'{a}{b}{c}{d}')
... |
fa42a64780f1d8e4132362adc54f18e70f0777fe | Lukezio/gamestyle-imitation | /bounding_box.py | 1,788 | 3.84375 | 4 | """This module provides all functionalities for bounding boxes"""
from point import Point
class BoundingBox:
"""Represents a bounding box"""
TL_TO_BR = 0
BR_TO_TL = 1
POINT_ORDER = 0
def __init__(self, label, point_1, point_2):
self.label = label if label is not None else ''
sel... |
f9a45ece6c4b02ab294cc9c658658b439182fd4f | SLarbiBU/Homework | /ps1pr1.py | 1,408 | 3.890625 | 4 | #
# ps1pr2.py - Problem Set 1, Problem 1
#
# Indexing and slicing puzzles
#
# name: Sarah Larbi
# email: slarbi@bu.edu
#
# If you worked with a partner, put his or her contact info below:
# partner's name:n/a
# partner's email: n/a
#
#
# List puzzles
#
pi = [3, 1, 4, 1, 5, 9]
e = [2, 7, 1]
# Example puzzle (puzzle ... |
f3b280b452dd96cc471b8e91db79423abc1a979d | richardochandra/PrakAlPro-B | /LAB-4-Modular Programing.py | 2,602 | 3.5625 | 4 | # Richardo Chandra H
# 71200642
# Universitas Kristen Duta Wacana
# Pertemuan 4 ( Modular Programming )
""" Pak Roni mendapat pekerjaan baru yang sangat sensitif dengan waktu sehingga dia harus benar-benar melakukan hal yang diperintahkan oleh atasannya di waktu yang
sudah di tentukan oleh atasannya. Pak Roni m... |
1716bbc31bd9f0f91114e31e43b3a50405c03009 | UrvashiBhavnani08/Python | /Maximum_three_numbes.py | 155 | 3.71875 | 4 | def Maximum(num1, num2, num3):
tup1 = (num1, num2, num3)
return max(tup1);
num1 = 100
num2 = 202
num3 = 30
print(Maximum(num1,num2,num3))
|
140cc4a1d14db1a453f8280a279850c2ab712bce | lldenisll/learn_python | /aulas/busca_sequencial.py | 184 | 3.6875 | 4 | def busca(lista,elemento):
for i in range(len(lista)):
if lista[i] == elemento:
return i #fazer retornar a posição sem usar a função index
return False |
4cfe556db8573dd1cef05719c712d1dd9198d0cb | piyush-arora/kodingBackup | /laravel/public/ML/hello_world/hello_world.py | 885 | 3.859375 | 4 | # for reshaping
import numpy as np
# for ML
import sklearn
# Describe features as arrays as training sets
features = [
[140 , 1] , # 140g smooth
[130 , 1] , # 130d smooth
[150 , 0] , # 150g bumpy
[170 , 0] , # 170g bumpy
... |
e63042bd361dd38beb304b96fba2b10e2bdadfd1 | jinxiang2/L1 | /Action2 jx.py | 752 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
班里有5名同学,现在需要你用Python来统计下这些人在语文、英语、数学中的平均成绩、
最小成绩、最大成绩、方差、标准差。然后把这些人的总成绩排序,得出名次进行成绩输出
(可以用numpy或pandas)
@author: JinXiang2
"""
from pandas import Series, DataFrame
data = {'语文': [68, 95, 98, 90,80], '数学': [65, 76, 86, 88, 90], '英语': [30, 98, 88, 77, 90]}
df1 = DataFrame(data)
df2 ... |
be395b94f6424f6c82a65e1ac37d2dd770bbbf48 | 5064/algorithms | /sort/merge_sort.py | 958 | 4.125 | 4 | def merge_sort(list_, left, right):
if right - left == 1:
return
mid = left + (right-left) // 2
# 左半分 [left, mid) をソート
merge_sort(list_, left, mid)
# 右半分 (mid, right] をソート
merge_sort(list_, mid, right)
# 左と右のソート結果をコピー(右はリバース)
buffer = []
i = left
while i < mid:
... |
3f2cb4cfdf35c690a36f078a52afec79bb4e53a0 | darrenwshort/itp_week_3 | /day_3/exercise.py | 1,749 | 3.546875 | 4 | import os
import requests
import json
import openpyxl
response = requests.get("https://rickandmortyapi.com/api/character")
# print(response)
# json.loads() - takes text string and converts it to dict (clean_data)
clean_data = json.loads(response.text)
# grab only results list from clean_data dict
# 'results' is lis... |
9d9d79e9640bd41ef4633a70d7c3dd0331d98c59 | wiggiddywags/python-playground | /pascals_triangle.py | 779 | 4.46875 | 4 |
# Udacity Exercise: Write a function to produce the next layer of Pascal's triangle
# Each layer is one larger than the previous layer, and each element in
# the new layer is the sum of the two elements above it in the previous
# layer. For example, `(1, 3, 3, 1) -> (1, 4, 6, 4, 1)`.
# Add a layer/row to Pascal's tr... |
3bd3de9948e931c067350b65c5982b94354591ed | alekseiaks/asjfgh | /task_2 .py | 266 | 3.953125 | 4 | seconds = int(input("Какое количество секунд перевести в формат времени - чч:мм:сс? "))
hh = seconds // 3600
mm = (seconds - hh * 3600) // 60
ss = seconds - mm * 60 - hh * 3600
print(f"{hh:02d}:{mm:02d}:{ss:02d}")
|
27d54a10d99da8f9fce0d22521b586e50e816189 | Nihadkp/MCA | /Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/16-String-Swapping/String_swapping.py | 494 | 4.25 | 4 | # purpose Create a single string separated with space from two strings by swapping the character at position 1
string = input("Enter 2 string separated by space : ")
string = string.split(' ')
# swapping two at position 1
print(string[0][0] + string[1][1] + string[0][2:] + " " + string[1][0] + string[0][1] + string[1][... |
aa7b05e701a74934562ca0ddba710606778a596c | Bohdan-Panamarenko/oop-second-lab | /2.py | 755 | 3.78125 | 4 | class Rational:
def __init__(self, numerator: int = 1, denominator: int = 1):
biggest_dem = self._biggest_denominator(numerator, denominator)
if biggest_dem != 0:
numerator /= biggest_dem
denominator /= biggest_dem
self._numerator = int(numerator)
self._denom... |
f87b68525023f7c231b86614afa65e8c681a2bbb | jinshunlee/ctci | /2-linked-lists/1_removeDups.py | 1,314 | 3.890625 | 4 | # Remove Dups! Write code to remove duplicates from an unsorted linked list.
# FOLLOW UP
# How would you solve this problem if a temporary buffer is not allowed?
from LinkedList import LinkedList
# Time O(n)
# Space O(n)
def removeDuplicates(xs):
seen = set()
cur = xs.head
prev = None
... |
3362a29d83724e4dfdb2c666510a88eca0ae5a4d | brian-tle/csc645-networks | /labs/lab8/server.py | 3,938 | 3.8125 | 4 | ########################################################################################################################
# Class: Computer Networks
# Date: 02/03/2020
# Lab3: TCP Server Socket
# Goal: Learning Networking in Python with TCP sockets
# Student Name:
# Student ID:
# Student Github Username:
# Instructions:... |
7a18406342ff44d555b6f737f01629128455ed04 | bhavybhatia/password-generator | /pasgenerator.py | 359 | 3.9375 | 4 | import random
chars="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789!@#$%^&*"
len=int(input("Enter Length of password : "))
n=int(input("Enter number of passwords you want : "))
passwords=''
for i in range(n):
passwords=''
for c in range(len):
passwords+=random.choice(chars)
print(passwords)
... |
ac75656a5b4c2420e9a32095cb1f14c46ad3dcf0 | Jaybsoni/Orbit-Simulator | /objects.py | 2,634 | 3.78125 | 4 | class SpaceDebri(): # Quick Update
def __init__(self, mass, position, velocity):
"""
:param mass: float
:param position: list of floats
:param velocity: list of floats
:param acceleration: list of floats
Initializes an instance of the SpaceDebri object with above specifications
"""
self.mass = mass... |
1e87f8304843df12c463f191b24b66a5ecffc2ef | code5023/python_proj | /1week/homework-04-diamond.py | 1,043 | 3.59375 | 4 | total_lines = 10 # 표현 할 전체 라인수
lines = int(total_lines / 2) # 상단 하단을 구분하기 위한 중간 라인
print("===== 다이아몬드 =====")
# # 우측만 튀어나온 형태
# for i in range(1, total_lines):
# if i <= lines:
# zero = lines - i
# one = i
# print("1 " * one)
# else:
# zero = i - lines... |
cb306dff4134be19d2940658e141d74f4b1871ea | Ktsunezawa/Python-practice | /3step/0702/for_dic.py | 282 | 3.515625 | 4 | addresses = {
'名無権兵衛': '千葉県千葉市美芳町1−1−1',
'山田太郎': '東京都練馬区蔵王町2−2−2',
'鈴木花子': '埼玉県所沢市大竹町3−3−3',
}
for key, value in addresses.items():
print(key, ':', value)
|
7579afdc211671b68087eccbc1c6af6919ff700c | Seanistar/Carmen | /science/4_maxtrices.py | 550 | 3.84375 | 4 | # functions for working with matrices
#
def shape(A):
num_rows = len(A)
num_cols = len(A[0]) if A else 0
return num_rows, num_cols
def make_matrix(num_rows, num_cols, entry_fn):
return [[entry_fn(i, j) for j in range(num_cols)]
for i in range(num_rows)]
def matrix_add(A, B):
if shape(... |
97b711496e5c087883c82ea79f9d2b1d6c4d5362 | Murbr4/Python | /PythonExercicios/ex015.py | 192 | 3.65625 | 4 | dias = int(input('Quantos dias você ficou com o carro: '))
km = float(input('quantos km rodado: '))
total = (dias * 60) + (km * 0.15)
print('O preço total a pagar é {:.2f}'.format(total)) |
03c87803bec04a8fd63508a7f23bb7489ac05153 | shiraz-30/Intro-to-Python | /Python/Python_concepts/twoD_list.py | 306 | 3.6875 | 4 | li = [[1,2,3], [4,5,6], [7,8,9]]
for i in range(0, len(li)):
print(li[i])
y = []
n = int(input())
m = int(input())
for i in range(0, n):
y.append([]) # appending the 'i'th row
for j in range(0, m):
x = int(input())
y[i].apppend(x)
print(y)
print(y[0][1]) # accessing 1st column of the 0th row
|
b4448e467b38fefe05ef32a4ec43f6a89eb5ccab | fulcorno/Settimane | /Settimana04/leggidato.py | 927 | 4.09375 | 4 | # Lettura di un dato dall'utente controllando che sia nell'intervallo giusto
# ESEMPIO: leggiamo un dato intero tra 1 e 100
valido = False
while not valido:
dato = int(input("Inserisci un numero tra 1 e 100: "))
if dato < 1 or dato > 100: # condizione di errore
print('Dato errato, ripeti')
else:
... |
c21acb3cfdc8914512ca30d88c5ccda754054930 | T3ch1n/MathProject | /main.py | 891 | 3.859375 | 4 | from tkinter import *
window = Tk()
window.title("My application")
window.geometry("500x500")
head = Label(text="Welcome to Application").pack()
def calculation():
age=txt_age.get()
age=int(age)
disease=txt_disease.get()
disease=int(disease)
if disease==1:
disease=True
... |
e94ae8c0ff205b067db3b5d8beaad0406fbeef23 | joaovlev/estudos-python | /Desafios/Mundo 2/desafio042.py | 816 | 4.1875 | 4 | # Refazendo o exercício 35 do mundo 1 (triângulo)
print('Analisador de Triângulos\n')
r1 = float(input('Digite um segmento: '))
r2 = float(input('Digite outro segmento: '))
r3 = float(input('Digite mais um segmento: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2 and r1==r2==r3:
print('Os segmentos podem form... |
12e58e334c8b2376febc0a1550ed574a2ed9285f | Aditya-Pundir/VSCode_python_projects | /VS_Code_Folder_2/python_learning_in_1_video_cwh/pr_2_Q5.py | 171 | 3.53125 | 4 | letter = "Dear Harry, This Python course is nice! Thanks!"
print(letter)
formatted_letter = "\nDear Harry,\n\tThis Python course is nice!\nThanks!"
print(formatted_letter) |
68f0d7933980ca89b97f1ac9d1ab5d8f8e8389dd | ToT-2020-PA/digital.chest | /Test_Cel.py | 138 | 3.875 | 4 | t1 = float(input('qual a temperatura em Fahrenheit? °F '))
t2 = (t1-32)*(5/9)
print('A temperatura em Celsius é {:.1f}°C'.format(t2)) |
bc3397b8b71118e290b4c04a945a4f7a079fdfec | ngrundback/Fall_2019_Lessons | /daily_problem/49_binary_tree_check.py | 777 | 3.875 | 4 | class Node():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.root = False
def binary_tree_check(root, l=None, r=None):
if root is None:
return True
if (l != None and root.data <= l.data):
return False
if (r != None... |
200bafee7d2e29f111111761fe73e13869903719 | siramkalyan/wordcheats | /__init__.py | 594 | 3.71875 | 4 | from itertools import permutations
from nltk.corpus import words
def valid_word(list_of_words,list_of_sizes):
if type(list_of_sizes) == int :
list_of_sizes = list(list_of_sizes)
list_of_english_words=[]
for i in list_of_sizes:
possible_permutations=list(permutations(list_of_words,i))
... |
8877f359a4cde598d561c2c72c790aa7c8b67f04 | jorgeOmurillo/Python | /sorting and searching/insert_sort.py | 288 | 3.828125 | 4 | def insert_sort(A):
for x in range(1, len(A)):
current = A[x]
index = x
while index > 0 and A[index-1] > current:
A[index] = A[index-1]
index -= 1
A[index] = current
return A
print(insert_sort([78,89,123,2,5,9,1]))
|
85572e470c172c4f1ceae678eeb0ae5b2a806d18 | bexcite/interview-zoo | /codility/2-cyclic-rotation.py | 1,386 | 4.0625 | 4 | '''
A zero-indexed array A consisting of N integers is given. Rotation of the array
means that each element is shifted right by one index, and the last element of
the array is also moved to the first place.
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The
goal is to rotate array A K times... |
6a7298ac93df72e398f28fc909350f19049cac47 | sabrinachowdhuryoshin/30-Days-of-Code-Challenge-HackerRank | /Day04.py | 301 | 3.875 | 4 | # Day04
# Given an integer n, print its first 10 multiples. Each multiple n x i (where 1 <= i <= 10) should be printed on a new line in the form: n x i = result.
# Constraints 2 <= n <= 20
# The code starts here:
n = int (input())
for i in range (1,11):
x = n*i
print (n, "x", i, "=", x)
|
735addbec8387512368fc3e3acc6b44ad2866e07 | birgire18/Assignment-5-Algorithms-and-git | /git_sequence.py | 341 | 3.84375 | 4 | n = int(input("Enter the length of the sequence: ")) # Do not change this line
count = 3
sequence = [1, 2, 3]
print(sequence[0])
print(sequence[1])
print(sequence[2])
while count != n:
newnum = int(sequence[count-3]) + int(sequence[count-2]) + int(sequence[count-1])
sequence.append(newnum)
print(sequence[co... |
574b2f94c787bb2c0d32ca02c06634509c589a1c | iarimanfredi/Esercitazione | /main.py | 267 | 3.84375 | 4 | def tree(n):
for j in range(n+1):
print('{}'.format(mess), end = ' ')
print('\n')
print('Scrivi il messaggio da stampare e quante volte lo vuoi stampare\n')
mess = input('Messaggio --> ')
t = int(input('Numero --> '))
for i in range(t):
tree(i)
|
130b5eb05fffcd522e3abde49e714d028e996b4b | fivetentaylor/intro_to_programming | /leet_solutions/taylor_swap_nodes_in_pairs.py | 1,078 | 4.03125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def make_list(iterable):
head = ListNode(0)
ptr = head
for i in iterable:
ptr.next = ListNode(i)
ptr = ptr.next
if head.next:
return head.next
def li... |
2754829119354f71fa4a181fb9b560da5223dfe7 | rafaxtd/URI-Judge | /AC02/donation.py | 208 | 3.578125 | 4 |
buy = True
vic = 0
while buy == True:
n = float(input())
if n == -1.0:
buy = False
else:
vic += n
real = vic * 2.50
print(f'VC$ {vic:.2f}')
print(f'R$ {real:.2f}')
|
45b4cf78245c2b4dde6b5df53c262eba40a92058 | daniel-reich/ubiquitous-fiesta | /6CGomPbu3dK536PH2_15.py | 129 | 3.625 | 4 |
def accumulating_list(lst):
relst=[]
for i in range(1,len(lst)+1):
relst.append(sum(lst[:i]))
return relst
|
3db957615cb0f6fe50d1ae5583777cac35349e9f | SCismycat/AlgoWithLeetCode | /algos/Random_areas.py | 355 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Leslee
# @Email : leelovesc@gmail.com
# @Time : 2019.10.15 13:33
import random
# 给定一个1-5的函数,随机生成1-7的函数
def random7():
a = random.randint(0,5)-1
b = random.randint(0,5)-1
num = 5*a +b
if(num>20):
return random7()
else:
r... |
adeb41f43ffcd09d1e20e6004688c075c2d7c467 | shubhi1998/Beginner-Python-Programming- | /Course 2: Python Data Structures/Week 2/Ex-2.py | 894 | 4.25 | 4 | 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 number on the line. Count these lines and
then compute the total of ... |
ed608d54ea2240467c60b231313280a45de13e15 | adityamhatre/DCC | /dcc #4/first_missing_positive_integer.py | 3,276 | 4.25 | 4 | import unittest
"""
Given an array of integers, find the first missing positive integer in linear time and constant space. In other
words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and
negative numbers as well.
For example, the input [3, 4, -1, 1] should give ... |
84ab96e19c7cc9d821681a534b8988fd868c5d3b | mashpolo/leetcode_ans | /400/leetcode461/ans.py | 716 | 3.71875 | 4 | #!/usr/bin/env python
# coding=utf-8
"""
@desc:
@author: Luo.lu
@date: 2018-11-5
"""
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
bin_x = bin(x)[2:]
bin_y = bin(y)[2:]
if len(bin_x) >= len(bin_y):
... |
91216a83c779698ad7952bae61efb4890d2a4c1b | Bertram-Liu/Note | /NOTE/02_PythonBase/day08/exercise/set_del_repeat.py | 733 | 3.96875 | 4 | # 练习:
# 1. 写程序,任意输入多个正整数,当输入小于零的数时结束输入
# 1. 打印出您输入的这些数的种类有多少种?(去重)
# 2. 去掉重复的整数,把剩余的这些数的和打印出来!
# 如:
# 输入: 1
# 输入: 2
# 输入: 2
# 输入: 3
# 输入: -1
# 种类 : 3
# 和是 : 6
L = [] # 列表容器放入用户输入的原始数据
while True:
x = int(input("请输入正整数: "))
if x < 0:
break # ... |
97f72cf10a81d856078ad13144e46820a589222a | Valleka/Ucode_Python_Marathon | /spr03/t07_calculambdor/calculator.py | 608 | 3.84375 | 4 | operations = {
'add' : lambda x, y : x + y,
'sub' : lambda x, y : x - y,
'mul' : lambda x, y : x * y,
'div' : lambda x, y : x / y,
'pow' : lambda x, y : x ** y
}
def calculator(operator, num_1, num_2):
if operator not in operations:
raise ValueError('Invalid operation. Available operati... |
847003c2fb0e52dec3d3728ff3dabe51d10cc53a | xggxnn/webApp | /python3/jiujiuchengfa.py | 203 | 3.53125 | 4 | # -*- coding: UTF-8 -*-
# Filename : jiujiuchengfa.py
# author by : xggxnn.top
# 九九乘法表
for i in range(1,10):
for j in range(1,i+1):
print('{0}X{1}={2}\t'.format(j,i,i*j),end='')
print("") |
6567fdea0696752c141af9eee62692fd1bffc4dc | Gowtham-cit/Algorithms-Python | /Code/linear_search.py | 758 | 3.84375 | 4 | """
Linear search is one of the simplest searching algorithms,
and the easiest to understand. We can think of it as a ramped-up version of o
ur own implementation of Python's in operator
"""
#return the position of the element if available
def LS(lst, find):
for i in range(len(lst)):
if... |
6f64e64ac8407f423447f448ce2d8451ec053a40 | Team-Tomato/Learn | /Juniors - 1st Year/Subhiksha.B/employee_info2.py | 1,400 | 4.21875 | 4 | class Employee:
Member = 0
Name = ""
Age = 0
Gender = ""
Salary = 0
def get_info(self):
self.Member = int(input("Enter the number of employee detail to be entered:"))
for i in range(self.Member):
print(i +1,end =".")
self.Name = input("Enter employee name... |
113d507a5970e1db48dcb3c039723f0250b8280b | prernaranjan123/pythan | /table.py | 137 | 4.03125 | 4 | n=int(input("Enter number whose table is to print : "))
print("Table of number : ",n)
for i in range(1,11):
print(n,"*",i,"=",n*i) |
1f0fbfeae970acf5e549edf14d9a24b6b10f4110 | paalso/learning_with_python | /ADDENDUM. Think Python/09 Case study - word play/9-1.py | 277 | 3.921875 | 4 | '''
Exercise 9.1. Write a program that reads words.txt and prints only the words
with more than 20 characters (not counting whitespace).
'''
with open('words.txt', 'r') as f:
words_longer20 = [line.rstrip() for line in f if len(line) > 21]
print(words_longer20)
|
192b375424e1f940f314ab82889d6aa730a8a7af | praveendareddy21/ProjectEulerSolutions | /src/project_euler/problem6/__init__.py | 3,469 | 3.8125 | 4 | '''
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural
numbers and the square of the sum is 3025 - 3... |
84a7a218d63595d45065b74480eeb28352ec61b4 | poojagmahajan/python_exercises | /full_speed_educative/List/average_list.py | 268 | 3.953125 | 4 |
# Average of given list
def getAverage():
l1 = [1, 4, 9, 10, 23]
avg = sum(l1) / len(l1)
return avg
avg = getAverage()
print(avg)
########## OR
l = [1,4,9,10,23]
list_sum = sum(l)
list_length = len(l)
average = list_sum/list_length
print(average)
|
2665eaabe98d2654c7bd2222f35eec2bfab04d62 | wrzzd/AlgorithmCode | /LeetCode/94.py | 827 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
# if not root: return []
# return self.inorderTraversal(root.lef... |
d9e6142a29f8024d9e90061aa3adbe9348fe809d | DayGitH/Python-Challenges | /DailyProgrammer/DP20120927C.py | 1,072 | 3.640625 | 4 | """
[9/27/2012] Challenge #101 [difficult] (Boolean Minimization)
https://www.reddit.com/r/dailyprogrammer/comments/10lbjo/9272012_challenge_101_difficult_boolean/
For difficult 101, I thought I'd do something with binary in it.
Write a program that reads in a file containing 2^n 0s and 1s as ascii characters. You ... |
0b02745df7f650b7860c9420c6d5ce92fa624522 | MaximSungmo/practice01 | /prob09.py | 382 | 3.625 | 4 | # 주어진 if 문을 dict를 사용해서 수정하세요.
menu = input('메뉴: ')
# if menu == '오뎅':
# price = 300
# elif menu == '순대':
# price = 400
# elif menu == '만두':
# price = 500
# else:
# price = 0
#
# print('가격: {0}'.format(price))
menu_list = {'오뎅' : 300, '순대' : 400, '만두' : 500}
print('가격 :', menu_list.get(menu) or 0) |
62409ab4a825e5181bf951c676799a2885470658 | vishalisairam/TrustSimulation | /11Nov_ProjectPractive | 1,714 | 3.859375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 10:51:33 2020
@author: vishali
"""
import axelrod as axe
import random
class Player:
def __init__(self,name = False):
pass
class HumanPlayer:
def __init__ (self, otherStrategy, name = False):
self.otherStrategy = axe... |
3c5dfd814bd3fa93a9f8f71e1104fb6b68663df0 | kuzja111/IML | /ex3/models.py | 5,177 | 3.78125 | 4 | import numpy as np
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from abc import ABC, abstractmethod
class Classifier(ABC):
"""
abstract Classifier class that all classes inherit from
"""
def __init__(self):
sel... |
a0c6915a3e0a9a8dcb2d65b1eaf0c1763d7cbeb9 | nguyeti4/cs362_hwk4 | /test_fullname.py | 788 | 3.75 | 4 | import unittest
import fullname
class Fullname(unittest.TestCase):
def test_full(self):
actual = fullname.gen_fullname("Timothy","Nguyen")
expected = "Timothy Nguyen"
self.assertEqual(actual,expected)
def test_full_exception(self):
with self.assertRaises(ValueError) as exception... |
798b5a5e0227ba766e323eb9f91eb09821d5a34c | chousemath/pygame_projects | /breakout/homework_problem_1.py | 562 | 4 | 4 | def sum_missing_numbers(nums):
minimum = min(nums)
maximum = max(nums)
total = 0
for num in range(minimum, maximum):
if num not in nums:
total += num
return total
ans1 = sum_missing_numbers([4, 3, 8, 1, 2])
assert ans1 == 18, f'expected 18, got {ans1}'
# 5 + 6 + 7 = 18
ans2 = s... |
deb7710637b2d7d43c35fcf60e71481e059ef6a0 | jtlai0921/Python- | /ex04/for_2.py | 55 | 3.5625 | 4 | sum = 0
for x in range(-3, 3):
sum += x
print(sum)
|
72fd26de55a4748d45652a31191f09bece86ef5a | WayneChen1994/Python1805 | /day02/zuoye.py | 1,090 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Wayne.Chen
# year = int(input("请输入一个年份:"))
# if year%100 != 0 and year%4 == 0 or year%400 ==0:
# print("%d为闰年"%year)
# else:
# print("%d不是闰年"%year)
# num = int(input("请输入一个三位数:"))
# bai = num // 100
# ge = num % 10
# shi = num // 10 % 10
... |
fd4c6c02fc7059661fcfe861f1c156e4487f11d5 | Bidesh15-8550/Python-Machine-Learning-and-Django-Projects | /Python basics/logical operators.py | 306 | 4 | 4 | has_high_income = True
has_good_credit = True
if has_high_income or has_good_credit: #and, or,NOT are logical operators
print("Eligible for loan")
has_criminal_record = False
if has_good_credit and not has_criminal_record:
print("Eligible for loan")
else:
print("Not eligible") |
d1b6e1a8d572a5d15b6b3274b1c3de7cbee721c4 | zsakhalin/learning_py | /tutorials/book-self-taught-programmer/chapt6/6-10.py | 324 | 3.609375 | 4 | str66 = "oiuytyuil \" okonbghjlo".replace("o", "O")
print(str66)
print(str66.index("j")) # index of "j"
str69 = "t"
print(str69 + str69 + str69)
print(3*str69)
str610 = "И незачем так орать! Я и в первый раз прекрасно слышал."
ind = str610.index("!")
print(str610[:(ind + 1)]) |
0629673f5d2d7efd55941343d50096c716db6449 | shapigou123/Programming | /python_advance_skill/7_1__yy.py | 1,695 | 3.578125 | 4 | #coding=utf-8
#继承内置的tuple
class IntTuple(tuple):
#修改实例化行为,就要修改__new__方法,是一个静态方法
#当我们创建一个实例的时候,__new__要先于__init__方法
#第一个参数是一个类对象,其他参数和__init__一样
def __new__(cls, iterable):
#使用一个生成器对象,下面就是生成器表达式
g = (x for x in iterable if isinstance(x,int)
and x>0)
#在其内部调用父类的__new__方法,来创建真正的tuple
#cls是当前类的一个子类
retur... |
d3b90c124f87051c8bdd21e83dca649c3d58dda0 | angelaliu2015/mycode | /lab05.py | 814 | 4 | 4 | #!/usr/bin/env python3
dic = {"Flash":{"Speed": "Fastest", "Intelligence": "Lowest", "Strength": "Lowest"}, "Batman":{"Speed": "Slowest", "Intelligence": "Highest", "Strength": "Money"}, "Superman":{"Speed": "Fast", "Intelligence": "Average", "Strength": "Strongest"}}
char_name = input("which character do you want to k... |
dc5b3d13cab6de1badf832c8ddeb7bfc30f8205d | brtcrt/Short-Python-Todo-List | /main.py | 4,775 | 3.8125 | 4 | import tkinter as tk # Import the modules for interfaces.
from tkinter import messagebox # Fucking pop-up windows. It works brilliantly though. Also super easy to use.
import json # Standard json library. Using this for data storage. Unstable but works.
from tkinter import ttk # For quick access to parts like the B... |
5a0a7df22cc693f1378f5dcd56bd001456865165 | mogolola/Coding4Interviews | /剑指offer/032-把数组排成最小的数/myCode.py | 622 | 3.59375 | 4 | class Solution:
def isLess(self, n1, n2):
return int(str(n1)+str(n2)) < int(str(n2)+str(n1))
def merge(self, n1,n2):
j = 0;
for i in range(len(n1)):
while j<len(n2) and self.isLess(n2[j],n1[i]):
j+=1
n2.insert(j, n1[i])
j+=1
return n2;
def sort(self, numbers):
l = len(numbers)
if len(num... |
473dc60e757a98e84920bf7fd5afe033c706eedb | diwash007/Python-projects | /quiz-game/quiz_brain.py | 782 | 3.765625 | 4 | class Brain:
def __init__(self, ques_list):
self.ques_num = 0
self.ques_list = ques_list
self.score = 0
def check_answer(self,uans, ans):
if uans.lower() == ans.lower():
print("You got it right!!")
self.score += 1
else:
print("Inco... |
d347b7d6a8e1a12d32c095ae7399e1dd296310a1 | gazerhuang/PythonLearning | /08_OOP/gz_10_run+.py | 450 | 3.609375 | 4 | class Person:
def __init__(self, new_name, new_weight):
self.name = new_name
self.weight = new_weight
def __str__(self):
return "%s 体重 %.2f kg" % (self.name, self.weight)
def run(self):
self.weight -= 0.5
def eat(self):
self.weight += 1
ming = Person("Ming", ... |
5f2c0fe09c988068204ee1a81e2ce0fea8b2d111 | GroupD5Cov/D5VirtualRobotProject | /NewStartUpScreen/D5Asis.py | 20,679 | 3.625 | 4 | #importing in functions that we need for the program to work
import pygame as pg
import random
from textbox import TextBox
pg.init()
#setting up colour RGB values
white = (255,255,255)
red = (255,0,0)
blue = (0,0,255)
green = (0,255,0)
black = (0,0,0)
pink = (255,20,147)
bright_red = (200,0,0)
bright_g... |
91f42c57a8c1aabba306469e7ecd8ce43cc58320 | ChenPeng03/leetcode | /Binary_Tree_Zigzag_Level_Order_Traversal/solution.py | 476 | 3.53125 | 4 | class Solution(object):
def zigzagLevelOrder(self, root):
goRight = 1
ans = []
queue = [root]
while queue:
next_queue = []
ans.append([node.val for node in queue[::goRight]])
for i in queue:
if i.left:
next_queue... |
c2d3e85a587c11b9bae19348149545584de22a49 | Bower312/Tasks | /task4/4.py | 791 | 4.28125 | 4 | # 4) Напишите калькулятор с возможностью находить сумму, разницу, так
# же делить и умножать. (используйте функции).А так же добавьте
# проверку не собирается ли пользователь делить на ноль, если так, то
# укажите на ошибку.
def calc(a,b,z):
if z == "+":
print(a+b)
elif z == "-":
print(a-b)
... |
9e4b1567f3356e10136026fa23a5adfa6546f9f3 | miguelzeph/Python_Git | /2019/01_Curso_Geek_basico_avancado/sec 10 - lambda e func integradas/aula4_reduce.py | 699 | 4.09375 | 4 | """
Apartir das versões 3+ não é mais built-in.. ou seja temos que importá-la agora
reduce(funcão,dado)
-Como funciona a reduce()...
exemplo:
x = [a1,a2,a3...]
OBS: A FUNÇÃO TEM Q PEGAR 2 ELEMENTOS
1passo - pega a1 e a2 e aplica a função, guarda o resultado res = f(a1,a2)
2passo - pega res e a3 e aplica função... e... |
4ceb5d1ee154f8f4ae7f2bd298335d541ed94df1 | Mahay316/Python-Assignment | /Exercise/0304/string_format.py | 1,203 | 4.25 | 4 | # 测试多种拼接、格式化字符串的方式
# test code snippet #1
username = input('username: ')
password = input('password: ')
print(username, password)
# test code snippet #2.1
name = input("name: ")
age = input("age: ")
skill = input("skill: ")
salary = input("salary:")
info = ' --- info of ' + name + ' name: ' + name + ' age: ' + age + '... |
8fdbb9d30be32745bb3b75b4759005826299d0de | hartantosantoso7/Belajar-Python | /set.py | 256 | 3.625 | 4 | # belajar set
# list => [] => bisa memasukkan data yang sama
# tupple => () => bisa memasukkan data yang sama
# set => {} => datanya harus unik
nama = {"Eko", "Budi", "Budi"}
nama.add("andi")
for i in nama:
print(i)
nama.remove("Eko")
print(nama) |
359f56f2e1ff3f9cb2955071a131398ab0f15a08 | suraj13mj/Python-Practice-Programs | /23. Python 22-02-20 --- Inheritance/Marks.py | 716 | 3.625 | 4 | import Student
class Marks(Student):
def __init__(self,rollno=0,name=" ",marks1=0,marks2=0):
Student.__init__(self,rollno,name)
#OR
#super().__init__(rollno,name)
self.__marks1=marks1
self.__marks2=marks2
self.__total=self.__marks1+self.__marks2f
def readMarks(self):
Student.readStudent(self)
sel... |
77b869f94bb0d221c22debbff11f03f23c71d2f5 | sangm1n/problem-solving | /CodeUp/[070~073] 기초-종합/072.py | 265 | 3.515625 | 4 | # 1,2,3... 계속 더해 그 합이 입력한 정수보다 같거나 작을 때까지 계속 더하는 프로그램
# 마지막에 더한 정수 출력
var = int(input())
sum = 0
for i in range(1, var+1):
sum+=i
if sum>=var:
print(i)
break
|
2de622a4b93200057be6a672f1398a9d49bc50e9 | swapnil2188/python-myrepo | /write_to_file.py | 889 | 4.4375 | 4 | #!/usr/bin/python
print "\n Create a new Empty file"
f = open("myfile.txt", "x")
#Create a new file if it does not exist
f = open("myfile.txt", "w")
#OPEN a file to WRITE to it
fout = open("foo.txt", "w")
fout.write("hello world")
fout.close()
#Append to an OPEN file
f = open("demofile.txt", "a")
f.write("Now the... |
afbd545e0f47c67c1928149f254541e7f0c65f8e | gnsisec/learn-python-with-the-the-hard-way | /exercise/ex12.py | 270 | 3.921875 | 4 | # This is Python version 2.7
# Exercise 12: Prompting People
age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = int(raw_input("How much do you weight? "))
print "So, you're %r old, %s tall and %d heavy" % (
age, height, weight)
|
76daf969cd0e34779a940e09e44a5a2bb8558c0e | ndjman7/Algorithm | /Leetcode/all-elements-in-two-binary-search-trees/source.py | 606 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
answer = []
def find_node(node):
if... |
0bc567891c769605b57f5d1c5a8dc8dea1e02baf | nicovlad16/Babes-Bolyai-University-Projects | /Sem1/Fundamentals of Programming/hangman/game/domain/valid.py | 648 | 3.703125 | 4 | import re
class ValidException(Exception):
pass
class Valid():
def validate(self, sentence):
if sentence == "":
raise ValidException("invalid sentence")
match = re.match("(\s*[a-z]+\s*[a-z]*)*", sentence)
if match == None:
raise ValidException("invalid sentenc... |
e8ada52c361df28e6c2f54462296adeba372259e | terrenceliu01/python1 | /src/languageBasics/dictionary.py | 1,853 | 4.3125 | 4 | """
Dictionaries are Python's implementation of a data structure
that is more generally known as an associative array.
A dictionary consists of a collection of key-value pairs.
It is unordered, iterable, mutable, and each paire seperated by commas,
surrounded by {}. The key-value pairs seperated by colon.
{'key1'... |
02458259e145310a418cf6136d802c09e5505167 | jgarte/aoc-2 | /aoc/app.py | 586 | 3.75 | 4 | import argparse
from aoc import year_2020
def parse_args(args):
"""Parse command line arguments from user"""
parser = argparse.ArgumentParser()
parser.add_argument("--year", "-y", help="Get solutions for year", default="2020")
parser.add_argument("--day", "-d", help="Get solutions for day")
retur... |
3615c8ee1d6f4ce2054cd6b02b53d74763e5e4dd | kanhaichun/ICS4U | /Assignments/AssignmentDetails/A8Jan25.py | 1,832 | 3.6875 | 4 | '''
Assignment 8 - Photo Processing
Coding convention:
(a) lower case file name
(b) Name, Date, Title, Purpose in multiline comment at the beginning
(c) mixedCase variable names
(1) Start with the BasicFilter.py program in the Vision Apps repository from GitHub.
(2) Convert the program to work with Python 3 and Open... |
cff65b2cadaf8bcaab64d609386e4ce69ea3dba0 | cesarFrias/dojoPetropolis | /agosto/28/FizzBuzz.py | 481 | 3.5 | 4 | # coding: utf-8
def fizzbuzz(entrada):
if entrada % 15 == 0:
return 'fizzbuzz'
elif entrada % 3 == 0:
return 'fizz'
elif entrada % 5 == 0:
return 'buzz'
else:
return entrada
'''if entrada == 1:
return 1
elif entrada == 2:
return 2
elif entrada == 4:
return 4
elif entrada == 5:
return 'buzz... |
3fedd35de1ee1bcf3551e948339cb24974876100 | handol/python_study | /sh_scripts/test.py | 241 | 3.828125 | 4 | a = [1,2,3]
for n in a:
print n
b = ['aa', 'bb', 'cc']
for w in b:
print w
c = ["aa", "bb", 'cc']
for w in c:
print w
d = ('aa','bb','cc')
for w in d:
print w
print d
print d*2
print '='*3+' '*5+'='*3
print '=','b'
print "==","bb"
|
53fbea64b0b353907bc3acc38a9eccbd963812b0 | GiovanniPasserello/StatsML | /statsml/decisionclassifier/purity.py | 1,280 | 3.5625 | 4 | import math
import numpy as np
class PurityFuncs:
@staticmethod
def entropy(labels):
""" Calculate label entropy
Arguments:
labels {np.ndarray} -- A single dimensional array that we wish to calculate the entropy of
Returns:
{int} -- The entropy of the labels
... |
4e7246030914aabfb3a5267a797a048952ab7e12 | tusharmike/Assignments | /Day 6/Dequeue_Op.py | 904 | 3.984375 | 4 | class Queue:
def __init__(self, size=None):
self.size = size
self.front = self.rear = -1
self.arr = []
def enqueue(self, element):
if len(self.arr) == self.size:
print("Overflow")
return
elif self.front == -1:
self.arr.appen... |
bd6feda76e8155ffc9f5a3b2a162d201e5f18c07 | Andrewjjj/Kattis | /Python3/1.3/Planina/planina.py | 106 | 3.9375 | 4 | a=int(input())
def fib(n):
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)
print(fib(a+3)**2)
|
367c259c69ce5853f1d5464ff8ffc85993ac9a87 | kongtaoxing/Freshman-Short_Semester-Python | /实验1源码/1.数字之和.py | 67 | 3.5 | 4 | a=int(input())#number a
b=int(input())#number b
print(a+b) #a+b
|
3177f850c65a22b613d117ab2d1d150ee3707189 | moskovets/numAlgorithm4sem | /approximation(mid2).py | 3,985 | 3.5625 | 4 | """
наилучшее среднеквадратичное приближениеи
"""
from math import sin, pi, factorial, cos, exp, log
from collections import namedtuple
Table = namedtuple('Table', ['x','y', 'w']) # w = вес функции
eps_const = 0.00001
eps_otn = 0.0001
def fi(x, k):
return x ** k
# Загрузка таблицы координат точек и их весов из ... |
6d6c96e9bda4690864dd5202559a94bfdfbc7d6f | yudhinr/buku-python | /contoh/list.py | 270 | 4 | 4 | # contoh list di Python
daftar = [7, 1, 5, 3, 2, 4, 6, 8, 3, 5]
print(daftar)
print("list memiliki", len(daftar), "elemen")
# akses elemen yang pertama (dengan indeks 0)
print("daftar[0] =", daftar[0])
# menambahkan data ke list
daftar = daftar + [7, 9]
print(daftar)
|
db858c79926a87cb9eaffd5ca589bec51f40df5a | UzairIshfaq1234/python_programming_PF_OOP_GUI | /2class.py | 1,375 | 4.0625 | 4 | class login:
def __init__(self):
self.data={}
def add_data(self):
self.username=input("Enter your name :")
self.password=int(input("Enter your Password:"))
self.data.update({self.username:self.password})
print("___________________________DATA SUBMITTED!__________________... |
6572b241b7b22f5fa8573e2aeb170c9929e9b7a4 | eichingertim/WhatsAppChatBot | /ChatBot.py | 5,625 | 3.53125 | 4 | # Simple WhatsApp-ChatBot
# Future Plan: integrating machine learning, so the bot can send messages by knowledge
# author: Tim Eichinger
from selenium import webdriver
from Calender import Calender
import time
driver = webdriver.Chrome()
driver.get('https://web.whatsapp.com/')
global length_before
global already_ans... |
d58f8619a091bed85dac1ba4823ff15b3ac82d6c | c940606/leetcode | /Length of Last Word.py | 444 | 3.96875 | 4 | class Solution:
def lengthOfLastWord(self, s):
"""
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
:type s: str
:rtype: int
"""
s = s.strip()
return len(s.split()[-1])
s = "Hello World"
a = Solution()
print(a.lengthOfLastWord(s))
|
b30d05c6d4c00fb19282904b71d727f911d89f7d | MichaelrMentele/katas | /HRSecondLowestStudentGrade.py | 1,166 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 9 06:48:11 2016
@author: michaelmentele
"""
def secondLowest(students):
''' Returns the second lowest grade in an [['name', grade]...n] array of arrays'''
students = sortStudents(students)
return students[1]
def swap(s1, s2):
temp = s1
s1 = s2
... |
910a5c486f6563c44ffe91563b22060c8b33c7a6 | apugithub/Python_Self | /odd_even.py | 167 | 4.1875 | 4 | a = int(input("Enter the value: "))
def odd_even(n):
if (n%2==1):
print("The number is odd")
else:
print("The number is even")
odd_even(a)
|
327d89342b955e0d57290b37049c5a4d8cc30fbd | rastukis/curso-python-intermedio | /001_strings.py | 284 | 3.625 | 4 | my_string = ''' Este es un string que contiene
saltos de linea.'''
print(my_string)
# Concatenacion
num_1 = 1
message_1 = "Mensaje num: " + str(num_1)
message_2 = "Otro mensaje: %s" %num_1
message_3 = "Otra forma: {}".format(num_1)
message_4 = f"Otra forma {num_1}"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.