blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
11b2c589eb9c058b6867419ac7481ed85dc7c9c6 | amytfang/checkers | /board.py | 2,018 | 3.625 | 4 | from piece import Piece
class Board:
def __init__(self):
self._generate_game_board()
def _generate_game_board(self):
grid = []
for row in range(8):
grid.append([])
for col in range(8):
if row <= 2 and (row + col) % 2 != 0:
... |
070bdd3632866f6d636890a882c1c3edb5fd5ba1 | YusufBritton1990/Django_tutorial_backup | /django_project/pagination.py | 635 | 3.546875 | 4 | from django.core.paginator import Paginator
posts = ['1','2','3','4','5']
# this will show two post at a time on the page
p = Paginator(posts, 2)
print(p.num_pages) #return 3 pages
#using page_range will make an interable
for page in p.page_range:
print("page " + str(page)) # return 1,2,3. these are the page nu... |
6fe26b14fa2da6eaf4d3a06b9e23320345d43195 | lwy1471/DesignPattern | /5. Command/command_remotecontrol_simple.py | 1,295 | 3.828125 | 4 | from abc import ABC, abstractmethod
# command interface
class Command(ABC):
@abstractmethod
def execute(self):
pass
# command concrete class
class LightOnCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.on(... |
be99040544704fb97b933944f939e17060b8584d | magmarnowak/LPTHW | /ex15.py | 606 | 4.0625 | 4 | from sys import argv
script, filename = argv
txt = open(filename) #creates a file object that later can be read by .read()
print "Here's your file %r:" % filename
print txt.read() # gives the opened a file (the txt file object) a command to \n
#read its contents and prints them
print "Type the filename again:"
file_ag... |
b53183a2c329ea080d4dd00ac321e5f2c5127b1a | boyima/Leetcode | /lc002.py | 1,463 | 3.90625 | 4 | #You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#... |
26fe738a21d5ddfa8b31ae1bd22b9e72f7f8c51e | oldman1991/learning_python_from_zero | /demo_07.py | 3,024 | 4.125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# create by oldman
# Date: 2019/01/10
# 面向对象oo
# 定义一个类
# class Car:
#
# #
# def print_info(self):
# print("I am a car")
#
#
# # 实例化一个类的对象
# car = Car()
#
# # 给类对象的属性复制
# car.color = "黑色"
# car.wheel_num = 4
# print(car.color)
# print(car.wheel_num)
# # 调用对... |
321797dc5d3c36ae6e01d2fc9089dbb6f1385159 | kaust-cs249-2020/fernando-zhapa | /chapter3/_391_k_d_composition.py | 619 | 3.90625 | 4 | def printListOfTuples(list):
string = ""
for item in list:
string += '('+item[0]+'|'+item[1]+') '
print (string[:-1])
def k_d_composition(k, d, string):
#returns the k-d composition of the text. k-d composition are pairs of k-mers separated by distance d
composition = []
for i in range(... |
7b9ce3a73ec0b638d01e9df42cba0186bea37dff | MayurMah/RandomForest-From-Scratch | /decision_tree.py | 5,313 | 3.59375 | 4 | from util import entropy, information_gain, partition_classes
import numpy as np
import ast
class DecisionTree(object):
def __init__(self):
# Initializing the tree as an empty dictionary or list
# self.tree = []
self.tree = {}
# pass
def learn(self, X, y):
"""Train the... |
2d3baf4b0690dd6e7815daf3cd93942dfda48b27 | ultraman-agul/python_demos | /元组列表/findTheBiggest.py | 217 | 4 | 4 | print("How many numbers are there?", end=" ")
n = int(input())
ls = []
for i in range(0, n):
print("Enter a number >>", end=" ")
ls.append(eval(input()))
print("The largest value is %d" % max(ls)) |
a725d3fd7d8db877ee9206551d5fe26c68924cd6 | BaeVic/201819A_cityu_com5507 | /py_codes/05_ds_dic.py | 138 | 4.1875 | 4 | # dictionary
dic1 = {'one':1, 'two':2, 'three':3}
print(dic1)
print(len(dic1)) # how many elements in total in the dictionary (dict1)?
|
3ad6a4ff68af59742ceedd02d8ae1207fa74ba1d | harshildarji/Python-HackerRank | /Sets/Set add().py | 192 | 3.703125 | 4 | # Set .add()
# https://www.hackerrank.com/challenges/py-set-add/problem
n = int(input().strip())
countries = set()
for i in range(n):
countries.add(input().strip())
print(len(countries))
|
ad36a00ddb252a48269726cce87f575e047c7b5a | itnks/Dominos | /Node.py | 3,683 | 4 | 4 | class Node(object):
def __init__(self, data, next):
self.data = data
self.next = next
###########################################
###########################################
class SingleList(object): ... |
986665f3ebde3dddd37e76333dc6c526da120d93 | souvinix/HS | /Ball_test.py | 952 | 3.8125 | 4 | from tkinter import *
from random import *
class Ball:
def __init__(self, canvas, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.canvas = canvas
self.ball = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill="red", tags = 'ball')
... |
d53489c13dd78ae42d877aad36bfb98e84d2c04e | SeanFoley123/word_reader | /word_reader2.py | 4,208 | 3.828125 | 4 | class Node(object):
"""This will ONLY work for words that all start with the same letter. It starts checking at the children level, not the grandparent.
You also need to specify if the first letter begins a word.
Also credit goes to http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html
"""
def __init__(self, value, chil... |
394ca6b951197ef52d366cc693b6ec0d492e5181 | rambler-digital-solutions/aioriak | /aioriak/datatypes/set.py | 2,987 | 3.5625 | 4 | import collections
from aioriak.datatypes.datatype import Datatype
from aioriak.datatypes import TYPES
class Set(collections.Set, Datatype):
'''A convergent datatype representing a Set with observed-remove
semantics. Currently strings are the only supported value type.
Example::
myset.add('barist... |
ef6c96d27f6fe639e573985a4dc0a578bde79d6d | Yosha2707/data_structure_algorithm | /asigments_files/dp_2/knapsack.py | 1,487 | 4.125 | 4 | # 0 1 Knapsack - Problem
# Send Feedback
# A thief robbing a store can carry a maximal weight of W into his knapsack. There are N items, and i-th item weigh 'Wi' and the value being 'Vi.' What would be the maximum value V, that the thief can steal?
# Input Format :
# The first line of the input contains an integer valu... |
f3efb1a19070aef58b0fdc559104a9b7ebcb1f8a | Anjualbin/workdirectory | /Regular exprn/Quantifiers.py | 1,556 | 3.734375 | 4 | # quantifiers
# x='a+' a including group
# x='a*' count including zero number of a
# x='a?' count a as each including zero no of a
# x='a{2}' 2 no of a position
# x='a{2,3}' minimum 2 a and maximum 3 a
# x='^a' check starting with a
# x='a$' check ending with a
# import re
# x='a+' # a in cluding groups, checks for... |
232cb05114455c02109bfe3d5e9a9d6e4d8dbfce | nigefanshu/mytools | /bitcoin_tools.py | 1,131 | 3.5 | 4 | # 输入难度位计算出目标值、难度值
def compute_target_diff():
# 难度值为1的目标值:
maxcurrenttargettarget = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
nbits = input("输入难度位:")
nbits = int(nbits, 16)
print("难度位十进制:", nbits)
power = (nbits // (16 ** 6) - 3) * 8
base = nbits % (16 ** 6)
curr... |
32ea312bd7c1d2095e0105bb59b89607c3847437 | Ksammar/EduPy | /task_4.6.py | 1,279 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# Реализовать два небольших скрипта:
# - итератор, генерирующий целые числа, начиная с указанного;
# - итератор, повторяющий элементы некоторого списка, определённого заранее.
# Подсказка: используйте функцию count() и cycle() модуля itertools.
# Обратите внимание, что создаваемый цикл не должен... |
f4417fc146577566eec3baf04283c1bc63dabb36 | ckimani/Data-Types | /BinarySearch.py | 597 | 3.890625 | 4 | class BinarySearch(ListComprehension):
'''
Child class BinarySearch
'''
def search(self, item):
self.item=item
dictionary={}
if self.a==0:
return False
else:
dictionary[item]+=1
###########################
class ListComprehension(object):
'''
Implementation of the parent class
... |
3be8d98efbfea88518d975e925f86a604d5a48c3 | fernandojampa/Lista-Hibrida | /ListaHibrida.py | 5,471 | 3.734375 | 4 | # Classe que vamos usar para tratar as exceções.
from node import Node
class ListaException(Exception):
def __init__(self, msg):
super().__init__(msg)
# Inicio da classe Lista, para instanciar as listas como objetos.
class Lista:
def __init__(self):
self._vetor = []
self._head = Non... |
9d64cc55747a9e9c6c3f745c73a7de755ba89359 | MrsKamran/pythonFunctionsDeliverable | /pythonFunctionsDeliverable.py | 997 | 3.765625 | 4 | # def sum_to(num):
# sum = 0
# for i in range(num+1):
# sum = sum + i
# return sum
# print(sum_to(6))
# print(sum_to(10))
# def largest(num_list):
# if len(num_list):
# large = num_list[0]
# for num in num_list:
# if large<num:
# large = num
# return large
# print(largest([1,2,3,4,0]))
#... |
383677a97d6c15585b51408148284d9e6f4faf21 | etothemanders/Skills1 | /skills1.py | 2,214 | 4.15625 | 4 | # Things you should be able to do.
# Write a function that takes a list and returns a new list with only the odd numbers.
def all_odd(some_list):
new_list = []
for num in some_list:
if num % 2 == 1:
new_list.append(num)
return new_list
# Write a function that takes a list and returns a... |
ab9bab4760411cbc145718547fa209b7593aa6a7 | a-phillips/ProjectEuler | /P204.py | 1,472 | 3.890625 | 4 | """A Hamming number is a positive number which has no prime factor larger than 5.
So the first few Hamming numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15.
There are 1105 Hamming numbers not exceeding 10^8.
We will call a positive number a generalised Hamming number of type n, if
it has no prime factor larger than... |
e1139675321c700fff279dc5ed11d32585478a69 | freedom-zjw/JPEG_python | /JPEG/tools/Zigzag.py | 1,170 | 3.59375 | 4 | # coding=utf-8
M = 8
def check(i, j):
return i >=0 and j >=0 and i < M and j < M
def zigzag(matrix, Zigzag_order):
"""
zigzag扫描
"""
temp = []
i, j =0, 0
direct = 1 # 0 for 左下, 1 for 右上
temp.append(matrix[0])
for k in range(0, M * M - 1):
if direct == 0:
if check... |
e25f7a750223910b8988798415ca8ab5f7e64afc | shuklaumesh/AviStuff | /TablesNew.py | 747 | 4.28125 | 4 | while True:
input_one=input("This is a multiplication/division table whatever number you type it will give u answer.. ")
input_two=input("What is the length of the table? .. ")
getOut = 0
while getOut==0:
input_three=input("Do u want to use multiplication or division ( *or/ )")
var2=1
... |
1f0d0327860fbe39f904aab7624c50cf42e67bd8 | li-zeqing/learn_python | /tiantianxiangshang.py | 559 | 3.71875 | 4 | #以1个月为一个周期,连续学习10天能力值不变,从第11天开始至第30天每天能力增长N
#对于不同的N,当连续学习360天后能力值(年终值)是多少
def dayUp(N):
dayup = 1.0
for j in range(12):
for i in range(30):
if i >=10 :
dayup = dayup *(1+N)
else:
pass
return dayup
dayfactor = (0.01,0.02,0.04,0.06,0.08,0.1)
prin... |
57b2d795c71ba6c10c4d92d0f92efeff5c7898ca | ziozn/zio | /untitled/函数的定义/公约(倍)数.py | 159 | 3.578125 | 4 | """
函数的定义和使用 - 求最大公约数和最小公倍数
Version: 0.1
Author: 骆昊
Date: 2018-03-05
"""
for x in range(10, 1, -1):
print(x)
|
503bba517b8eaba9653f1fa40eae0dcb699c6c23 | AdityaJ42/Multi-Document-Extractive-Summarization | /modules/shortest.py | 963 | 3.515625 | 4 | class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
self.parent = {}
def maxDistance(self, dist, sptSet):
maximum = -1
for v in range(self.V):
if dist[v] >= maximum and sptSet[v] == False:
maximum = dist[v]... |
3329a1f343eb882982ed3feaedf307723320ca03 | ankitbaluni123/GPS-Route-Analyser | /analysis.py | 3,754 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 22 06:53:40 2020
@author: piyush
"""
import time
import pandas as pd
import matplotlib.pyplot as plt
import os
import gpxpy
import math
def gpx_dataframe(file):
"""
Parameters
----------
file : string
path of the gpx fi... |
ba44a596e83e52ea7d6fdef0f1fa20d417bf0a32 | NickATC/GUI_design | /DataBase/create_test_db.py | 1,530 | 3.9375 | 4 | # Execute this file to create a database. It also adds information for testing purposes.
# Execute only once!
# A file called 'my_database.db' should be created on this same folder
#
# This script doesn't do anything else.
import sqlite3
con_db = sqlite3.connect("my_database.db")
cursor = con_db.cu... |
5739f4f8e83f41a8eff8b548af7999349b6c70ff | abhisheksansanwal/rankwatch17_py_csvbreakdown | /observe raw directory.py | 368 | 3.703125 | 4 | #To work on data analysing us package pandas
import panda as pd
#To read the csv file
pd.read_csv('Testdata.csv'
#The data is merging
frame1=pd.Dataframe ({key:range(5)})
frame1=pd.Data frame ({key:range(5)})'frame1':['a','b','c','d','e']})
frame2=pd.Data frame ({key:range(5)})'frame2':['t','u','v','w','x']})
... |
d16abdffc0d5cc9519e7ef13ebfc490bed815607 | Abooow/BattleShips | /BattleShips/framework/animation.py | 2,742 | 4.09375 | 4 | ''' This module contains the Animation class
'''
import pygame
import config
import surface_change
class Animation():
''' The base class for an animation, this class can either be instantiated directly or inherited
The Animation class uses a list of images as frames and changes what frame to draw after ... |
bf475b710f8cce53a37add53eef87726cd5751ec | rhildred/MB215Lab2 | /Iknow2.py | 417 | 3.5 | 4 | class Game:
def __init__(self):
self.__nCurrent = -1
def takeTurn(self, sInput):
if(self.__nCurrent == -1):
self.__nCurrent = 0
return["Welcome to I know you are",
"This is an annoying game you might have played",
"with your sibling."... |
55982594b465e0e6ef952d909ce808404118cd81 | BilelBouquoyoue/Mads-op | /calcul.py | 9,466 | 3.8125 | 4 | from random import *
class Calcul:
"""
Classe permettant d'appeler les autres classes et de démarrer le jeu
:type resultat_algo = int
:type resultat_utilisateur = int
"""
def __init__(self, tableau_chiffre):
"""
Initialisation du calcul
:param tableau_chif... |
a3c2dd3f6574e6215d9b9b30cce6e8655582822c | xiez/leetcode | /706*design-hashmap/solution.py | 2,253 | 3.9375 | 4 | class MyHashMap(object):
class Entry:
def __init__(self, key, val, next=None):
self.key = key
self.val = val
self.next = next
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 7919
self.ls... |
d392c285808d079b423c0214ac1ce6a020bc5dae | jieunin1213/NLP | /nlp_class_day1-master/04_word_count_ex02.py | 456 | 4.0625 | 4 | '''
dict를 여러가지 방법으로 정렬
'''
mydict = {'a':20, 'b':30, 'c':10}
# 값(value)이 가장 큰 거부터 역순으로 정렬
byValues = sorted(mydict.values(), reverse=True)
print( byValues )
# 키를 기준으로 역순 정렬
byKeys = sorted(mydict.keys(), reverse=True)
print( byKeys )
# 값(value)을 역순으로 정렬하되 키를 보여 주기
keysortByValue = sorted(mydict, key=mydict.get, rev... |
d9754b7ab5b52ad8dcaad1ca5abe63c638ed4817 | lly102799-git/python-cookbook | /第5章 文件和IO/5.4 读写二进制数据/read_write_binary_data.py | 931 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
@project: python-cookbook
@date: 2020-11-24 15:35
@author: Li Luyao
"""
# 使用open()函数的rb或者wb模式就可以实现对二进制数据的读或写
# Write binary data to file
# with open('somefile.txt', 'xb') as f:
# f.write(b'Hello World!')
# Read the entire file as a single byte string
with open('somefile.txt', 'rb') as... |
29b5060ba13f6239537a2a099aa3acbb3381b8f7 | sorengoyal/python-practice | /sourcewise/leetcode/20-palindromic -substrings/solution.py | 650 | 3.5 | 4 | class Solution:
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
count = 0
for i in range(0,n):
for j in range(i,n+1):
#print(j,end=' ')
if self.isPalindrome(s[i:j]):
coun... |
bd4b5381f131f6ade1979c259df006d3bb852896 | codeforgirls-sa/python | /unit2/challenge-operators-meal-recommendation.py | 448 | 3.71875 | 4 | hot = True
cold = False
morning = True
evening = False
night = False
soup = False
biscuit = False
cereal = False
pizza = False
if morning:
if cold:
biscuit = True
else:
cereal = True
elif evening:
pizza = True
if cold:
soup = True
elif night:
pizza = True
cereal = Tru... |
00db2655f9cb4633d6088618cb5e1c1833efd0ff | elabraha/CodingInterviewQuestions | /two_egg_drop.py | 3,405 | 4.28125 | 4 | # If an egg is dropped from above that floor, it will break. If it is dropped
# from that floor or below, it will be completely undamaged and you can drop the
# egg again.
#
# Given two eggs, find the highest floor an egg can be dropped from without
# breaking, with as few drops as possible.
def floor_egg_break(floors... |
2f5191c402c894a161091309a9b8ea7bf9cdd8cb | StephenLingham/MachineLearning | /raymondTitanicForest.py | 2,887 | 3.59375 | 4 | from sklearn.ensemble import RandomForestClassifier
import pandas
from sklearn import tree
import pydotplus
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import matplotlib.image as pltimg
import numpy as np
import types
from sklearn import metrics
from sklearn.model_selection import t... |
fb5f9f57ab1079bea1539c5e871c792616df86ee | murlinochka/ICT | /6.py | 114 | 3.515625 | 4 | a = float(input("Cost of a meal: "))
nalog = 0.5
chaev = 0.18
b = (a*nalog) + (a*chaev) + a
print(b)
|
01a77c6668337b65cc340579c2a2f02cca5b8b22 | ru04ru041989/MOOC | /Project_Euler/Q25.py | 507 | 3.59375 | 4 | # 1000-digit Fibonacci number
'''
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fi... |
7e584fec705fcae19c979ecd64fc3c487e7f9c70 | bwats2/CSCIE7-Final-Project | /tests/regextest.py | 264 | 4.125 | 4 | import re
def fraction(phrase: str) -> str:
"Return first fraction or blank"
find = '[+-]\d\d*/\d\d*'
match = re.search(find, phrase)
if match:
return match
else:
return ""
print(fraction("This is +1 /3 true and -2/ 3 false")) |
6e9aeecb1e38aae3e1253033b919038d2c02bb95 | angelavuong/python_exercises | /coding_challenges/intro_sorting.py | 401 | 3.921875 | 4 | '''
Name: Intro to Sorting
Input:
V = the value that has to be searched
n = the size of the array
ar = numbers that make up the array
Output:
The index of V in the array
Sample Input:
4
6
1 4 5 7 9 12
Sample Output:
1
'''
V = int(input().strip())
n = int(input().strip())
arr = list(map(int, input().strip().split(... |
86b9c9a2d23767dd6be05f5fc8e969206ba78840 | Lucass96/Python-Faculdade | /Python-LP/Trabalho/Exercicio01.py | 1,493 | 4.125 | 4 | while True: # este while esta servindo para validar se o usuario quer inserir os dados ou nao
dados = input('Inserir dados? 0- Nao 1- Sim ')
if dados in '0': # caso o usuario digite 0, o programa sera encerrado.
print('encerrando programa...')
break
if dados not in '1': # caso o u... |
21e1663fb39b5a47784ddb5a0cadb8bdd9d183ff | eternity6666/university | /CS/2/DataStructure/help_app/code.py | 113 | 3.53125 | 4 | n = input()
s = "void menu();"
print s
for i in range(n):
s = "void code" + str(i + 1) + "();"
print s
|
5f81277878f77ef3f02eb9c971a5314edecd251f | changwei0708/pylearning | /00x1_numpy/02_numpy_array.py | 1,332 | 3.5625 | 4 | # -*- coding: utf-8 -*-
'''
假设一个团队里有5名学员,成绩如下表所示。
1.用NumPy统计下这些人在语文、英语、数学中的平均成绩、最小成绩、最大成绩、方差、标准差。
2.总成绩排序,得出名次进行成绩输出。
'''
import numpy as np
a = np.array([[4,3,2],[2,4,1]])
print(np.sort(a))
print(np.sort(a, axis=None))
print(np.sort(a, axis=0))
print(np.sort(a, axis=1))
print("\npart 6 作业\n")
persontype = np.dtype(... |
488c1a45036d087275bb1aaee84a6b9897e42416 | Yanl05/LeetCode | /one_thousand_twenty_five.py | 985 | 3.671875 | 4 | # -*- coding: UTF-8 -*-
"""
# @Time : 2019-06-25 22:53
# @Author : yanlei
# @FileName: one_thousand_twenty_five.py
爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。
最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作:
选出任一 x,满足 0 < x < N 且 N % x == 0 。
用 N - x 替换黑板上的数字 N 。
"""
class Solution(object):
def divisorGame(self, N):
"""
... |
68e8783c97600c2f78d1bde98bf8f4b2476b54c7 | Bilibotter/LeetCode | /leetcode4Z字型变换hahaha.py | 520 | 3.515625 | 4 | class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
length = len(s)
if numRows == 1 or numRows > length:
return s
List = ['']*numRows
queue = numRows*2-2
for num, ... |
c7f63de02773b0bb645a6b93d2825f7b4c83c3bf | linsze/scrabble | /scrabble.py | 26,088 | 4.0625 | 4 | """
Author: Lin Sze Khoo
Created on: 21/11/2020
Last modified on: 23/11/2020
Description: This program is a solo terminal scrabble game. Run the program and start playing.
"""
import exception
BOARD = []
DICTIONARY = [] # Stores a list of valid words
SCORES = {} # A map with letters as key... |
c8124bb38f2db2e434523d5f369ef271c1535d12 | thisistom/checkout | /python/Promos.py | 3,116 | 4.03125 | 4 |
class _PromoEntry(object):
"""
Base class for promotional groupings of items.
"""
def __init__(self, items):
"""
Initializes an instance of the class.
Args:
items (list of Item): The items for this promo.
"""
self._items = items
def cost(self... |
5562886747c8b8d777529894ac51927c9135d90e | peterbat/rubikon | /matrix.py | 8,870 | 3.703125 | 4 | import math
import random as rand
class Matrix:
def __init__(self, a):
if len(a) == 9:
self.data = a
else:
print('ERROR: failed to initialize matrix with wrong dimensional data.')
def lmultiply(self, b):
data2 = [0] * 9
data2[0] = self.data[0] * b.data[0] + self.data[1] * b.data[3] +... |
61132296b1611a80b747186e8e9e5afefee44450 | Jason0221/backup | /HOME/笔记/考试/Python基础考试2-12.16/6.py | 2,561 | 4.25 | 4 | #!/usr/bin/python
#coding=utf-8
'''
6. 编写python程序: 实现一个双向循环链表,封装结点和其他方法。
要求至少实现创建和增删方法,并且要求实现其__getitem__和__setitem__两个魔法方法。
(如果你的__setitem__即可实现链表的插入那么可以不必写额外的插入方法)
'''
class Node(object):
def __init__(self,value,prior=None,next=None):
self.value = value
self.prior = prior
self.next = nex... |
06fc470787100bb4695a18968e85cec9c6384cd2 | rifatmondol/Python-Exercises | /145 - [Listas] Diferença Entre Listas.py | 230 | 3.71875 | 4 | #145 - Write a Python program to get the difference between the two lists.
lista1 = ['Dorgival', 'Cecilia', 'Shiro', 'Kauane']
lista2 = ['Cecilia', 'Kauane', 'John', 'Juliana']
dif = set(lista1).difference(set(lista2))
print(dif) |
21473ff39aff7856d4f000e69b990e3056cafead | hellyab/CompetitiveProgramming | /week-3/largest_rectangle.py | 274 | 3.75 | 4 | def largestRectangle(h):
h.sort()
n = len(h)
max_ = 0
for height in h:
if max_ - (height * n) < 0:
max_ = height * n
n -= 1
print(max_)
largestRectangle([8979, 4570, 6436, 5083, 7780, 3269, 5400, 7579, 2324, 2116]) |
276555d94d3d9de35ea55b46dc39e09948456d0d | LinvernSS/daily_assignments | /week1/day3/day7.py | 2,320 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# Lucas Invernizzi Day 7 Assignment
# 1)
# In[143]:
def divisible():
out = []
for i in range(1500,2701):
if i % 7 == 0 and i % 5 == 0:
out += [i]
return out
# In[144]:
print(divisible())
# 2)
# In[145]:
def convertTemp(t):
if t[-1] ... |
f970e234a0312385121ce671dc042f7bb8eba9c3 | ayannroys/Journal | /s3q3.py | 377 | 3.9375 | 4 | num=list(eval((input("Enter numbers"))))
x = []
N = int(input('enter size of list : '))
for i in range(0, N):
element=int(input('Enter element:'))
x.append(element)
print('Numbers in the list are ')
print(x)
for i in x:
if (i%5==0):
print(i,'is divisable by 5 but not by 7')
elif(i%7==... |
df0717288696309bad4a704952be2c9e52e485b9 | poo250696/python_training | /lists/exml1.py | 190 | 3.515625 | 4 | a_lists = []
b_lists = [1, 3, 4, 5]
c_lists = ["apple", "bat", "cat"]
d_lists = ['', 1, "string"]
print(a_lists)
print(b_lists[2])
print(c_lists)
for item in d_lists:
print(item)
|
e74a81c3c2aba3de70af51b91ab41efa8d692380 | Bibhuti4086mukhiya/python-practical-first-semester | /lab 4.py | 161 | 4.15625 | 4 | ''''
num=int(input("enter ur number"))
result=1
for i in range(num,0,-1):
result=result*i
print("the factorial of",num,"is",result)
'''
list=[2,3,4,5,6]
|
f1e2465427c61ea8743ca3df75a2184c945a0454 | estebansolo/PythonScripts | /platzi_coding_challenge/03_clock.py | 557 | 4.21875 | 4 | from datetime import timedelta
def seconds_per_hours(hours):
return 60 * 60 * hours
def seconds_per_minutes(minutes):
return 60 * minutes
def main():
hours = int(input("Add hours: "))
minutes = int(input("Add minutes: "))
seconds = seconds_per_hours(hours) + seconds_per_minutes(minutes)
prin... |
aed6de507e084a6cd97d04abdf5d7206a10e548a | ke1222/PythonZY | /day03_11.py | 170 | 4.03125 | 4 | list1 = []
for i in range(1,8):
for j in range(1,8):
if i != j and sorted([i,j]) not in list1:
list1.append([i,j])
print(list1) |
911b394fd260120b82645732310a9ed1a9996479 | Nv99/Sorting_Algorithm_Visualizer | /Algorithm_visualizer.py | 2,957 | 3.6875 | 4 | from tkinter import *
from tkinter import ttk
import random
from bubblesort import bubble_sort
from quicksort import quick_sort
from mergesort import merge_sort
root=Tk()
root.title('Sorting Algorithm Visualization')
root.maxsize(900,600)
root.config(bg='black')
#variables
selected_alg= StringVar()
data... |
ed2da6b57c26cb15b67ffa960cc4d75030f59564 | gabriellaec/desoft-analise-exercicios | /backup/user_058/ch28_2019_08_26_19_24_01_715539.py | 183 | 3.75 | 4 | def velocidade(x):
if x>80:
return "Você foi multado em R$ {0:.2f}".format((x-80)*5)
else:
return "Não foi multado"
x=float(input("Velocidade "))
print(velocidade(x)) |
9a1736519605ac21d2ec7e66d398c4b1d7848cc3 | august-Lee-Yang/Python-Data-Structure-and-Algorithem | /Root_method.py | 1,695 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 30 16:20:12 2020
@author: Administrator
"""
def bisection(left,right,tol=1.0e-9,max_iter=100):
if f(left)==0:
return left
if f(right)==0:
return right
if f(left)*f(right)>0:
raise ValueError('No root in the interval')
... |
ce1858f344af9d9611efb488b30974470491d028 | jorenvandeweyer/Python_SudokuSolver | /sudoku.py | 6,559 | 3.5 | 4 | # -*- coding: utf-8 -*-
# @Author: Joren Vandeweyer
# @Date: 2017-07-04 19:18:17
# @Last Modified by: Joren Vandeweyer
# @Last Modified time: 2017-08-07 20:50:25
class Sudoku():
"""docstring for Sudoku"""
def __init__(self):
# self.sudoku = [
# [0,0,0,1,0,4,9,0,0],
# [2,0,3,0,5,7,4,1,0],
# [4,0,0,0,8,... |
66e7a0529336367d58fa6cb0c7d1601ed2202b27 | devanand73/learnpython | /function.py | 457 | 4.03125 | 4 | #function id defined by key word def and can accept parameters and they return value to the caller using keyword return inside the function.
##code after return keyword don't get executed as function exits once it encounter return statement
print("function to cube a number")
def cube(num):
result=num*num*num
... |
cd82e115337943c8ee6d510d4a421e784cf793e2 | Pramod-Shrinivas/Project-Euler | /Python/007-3.py | 1,168 | 3.984375 | 4 | #!/usr/bin/python
'''
Purpose: https://projecteuler.net/problem=7
Sieve of Erasthonese Algorithm used.
Using enumerate() function.
Usage: enumerate(thing), where thing is either an iterator or a sequence, returns a iterator
that will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so fort... |
20d99281a37dcceee1243942ed94be1d8538d458 | joshmalek/leetcode-solutions | /DynamicProgramming/BuyAndSellStock.py | 311 | 3.65625 | 4 | # Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
for k in range(len(prices)-1,0,-1):
if(min(prices[0:k]) < prices[k]):
max_profit = max(max_profit,prices[k] - min(prices[0:k]))
return max_profit |
de3f84f5258cef30c7c1b00ccfb90fb343d34b94 | pyoumg/computational_thinking_hw | /s5/5-3.py | 196 | 3.640625 | 4 | a = 3.141592
b = 1000
c = 'Python'
print("a:{}, b:{:>7d}, c:{:9s}".format(a,b,c))
print("a:{:>+8.4f}, b:{}, c:{:>13s}".format(a,b,c))
print("a:{:>8.3f}, b:{:,}, c:{}".format(a,b,c))
|
acd30ee73ba84f6949268933863ed2ae3cc4a575 | qademo2015/CodeSamples | /Python/003_reverse_words_in_string.py | 856 | 4.53125 | 5 | ######################################################################
# this file contains different implementations of reverse words
# in string without reversing their order
######################################################################
# this method does not change original string
def reverse_words_1(stri... |
335688028b62f7f3aefeee310f225f0066ea590d | Shaashwat05/Predictive_speech | /text.py | 765 | 3.5625 | 4 | import speech_recognition as sr
import pyttsx3
from pydub import AudioSegment
r = sr.Recognizer()
#audio_file = AudioSegment.from_wav('output.wav')
while(1):
try:
with sr.Microphone() as source2:
r.adjust_for_ambient_noise(source2, duration=2)
audio2 = r.listen(source2)
... |
3e83ee55746f071268c510fa0c1be9b19c605e41 | gmt710/leetcode_python | /high/2_sortList.py | 1,813 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# https://blog.csdn.net/qq_34364995/a... |
ac54a80869c640e1f07dbc364b7f000c2cb24b0d | pinobatch/little-things-nes | /rgb121/tools/bitbuilder.py | 6,272 | 3.890625 | 4 | #!/usr/bin/env python3
"""
"""
from __future__ import with_statement, print_function
def log2(i):
return int(i).bit_length() - 1
class BitBuilder(object):
def __init__(self):
self.data = bytearray()
self.nbits = 0 # number of bits left in the last byte
def append(self, value, length=1... |
4eb506aafc70283bb2e38cd8fc96dda63600e330 | HollyMccoy/InCollege | /menus/Languages.py | 1,025 | 3.921875 | 4 | # Menu commands for the "Languages" submenu
# Path: Main menu / important links / privacy policy / guest controls / languages
import globals
def ShowMenu():
"""Present the user with a menu of guest control settings."""
while True:
selection = input(
"\n" + "-- Languages --: " + ... |
7b3b51d1eae737d1be879db113210be7332d8b7b | tnotstar/talgostar | /competitive/codefights/arcade/intro/level-1/03_checkPalindrome/checkPalindrome.py | 777 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def checkPalindrome(inputString):
los = len(inputString)
for i in range(los // 2):
if inputString[i] != inputString[-(i+1)]:
return False
return True
if __name__ == "__main__":
assert checkPalindrome("aabaa"), "Test #1"
assert not ... |
5de0b354def226b5dfc61489e7ad29bf3baed479 | zxy199803/fluent_python_exercise | /part2-数据结构/chapter3-字典和集合/3.4映射的弹性键查询.py | 1,769 | 3.71875 | 4 | """
某个键在映射里不存在时候希望能取到一个默认值
collections.defaultdict
背后是
特殊方法__missing__,所有映射类型都可以选择去支持
d.__getitem__(k) 让字典d用d[k]的形式返回键k对应的值
d.__missing__(k) 当__getitem__找不到对应的键时调用该方法
dict.keys()的返回值是视图,再其中查找元素很快
"""
# StrKeyDict0在查询的时候把非字符串的键转换为字符串
class StrKeyDict0(dict): # 继承自dict
def __missing__(self, key):
if isi... |
c73d0a7e87d0d8fa6b8904916f37113bfc6b3f4e | imanahmedy29/hello-world | /collatz.py | 402 | 4.15625 | 4 |
numb=int(input("Enter a number: "))
def collatz(numb):
print(numb)
while numb>1:
if numb%2==0:
numb=numb//2
print(numb)
else:
numb=(numb*3)+1
print(numb)
collatz(numb)
ques=input("Would you like to input another number? ")
while ques=="yes":
numb=int(input("Enter a number: "))
... |
aa328384d9bfa0f72b97d27a58c0e49a021b4380 | Omardyab/data-structures-and-algorithms-python | /python/code_challenges/Merge_Sort/merge_sort.py | 778 | 3.96875 | 4 |
def merge_sort(unsorted_list):
if len(unsorted_list) > 1:
mid = len(unsorted_list)//2
L = unsorted_list[:mid]
R = unsorted_list[mid:]
print(L)
print(R)
merge_sort(L)
merge_sort(R)
merge(L,R,unsorted_list)
def merge(L,R,unsorted_list):
i,j,k =0,0... |
e9eeed6edcd206f5fe70cab7743f8dd09a29e389 | jimbobsweeney/HDipPythonScripts | /unix-commands/head.py | 2,538 | 3.5625 | 4 | #!/usr/bin/python
def main():
# Import argparse and add all the arguments. Also import 'exit' to exit if there
# is an error.
import argparse
from sys import exit
parser = argparse.ArgumentParser()
parser.add_argument("files", nargs="+", help="Enter the file path on which to run the command.")
parser.add_argu... |
204680d695c3d64ef43f711978941b302c1e4814 | fifajan/py-stuff | /algorithms/sorting/merge_sort.py | 1,773 | 3.671875 | 4 | #! /usr/bin/python
# to test it run:
# $ ./merge_sort.py array.txt
# tests:
# Array state Time (array is 10^4 integers text file)
# ---------------------------
# random 0.2 s
# inverted 0.1 s
from sys import argv
from collections import deque
def sort(arr):
'''
Merge Sort impl... |
dfad4102b24c3c4f22633f232d6159d77f89047b | akweiss/cfd-simulations | /code/step-4-nonlinear-convection-2D.py | 2,776 | 3.734375 | 4 | """
STEP FOUR: Nonlinear convection in two dimensions.
In this step we want to solve 2D nonlinear convection, which is represented
by these corresponding PDEs:
du/dt + u * du/dx + v * du/dy = 0
dv/dt + u * dv/dx + v * dv/dy = 0
We can discretize and solve these in a similar fashion to step three and get:
u^... |
6a15fe90cb5845b16e2700cf6b6a6d3fdecec245 | CodeFreezers/DSA-GFG | /Recursion/Palindrome/Python/main.py | 276 | 3.8125 | 4 | #1
def CheckPalindrome(s):
return helperCheck(s, 0, len(s) - 1)
def helperCheck(s, start, end):
if start >= end:
return True;
return (s[start] == s[end]) and helperCheck(s, start + 1, end - 1)
print(CheckPalindrome("abbcdba"))
print(CheckPalindrome("abbcbba"))
|
0d9ff2ed63aa009b75a283b0a80b0ba0e2a0096b | bobbyplubell/EulerProblems | /p27.py | 694 | 3.765625 | 4 | import bobmath
def primes_quad(a, b):
primes = 0
n = 0
num = (n * n) + (a * n) + b
while bobmath.is_prime(num):
primes += 1
num = (n * n) + (a * n) + b
n += 1
return primes
if __name__ == "__main__":
most_primes = 0
a_most = 0
b_most = 0
for a in xrange(-100... |
a2b56664e8038821f440a7ad4ec59d3fdd8edf22 | RayHuo/MyBlog | /python/IfElse.py | 546 | 4.0625 | 4 | a = input("First : ")
b = input("Second : ")
# if-elif-else
# remeber the ":" at the end of the condition
if a == b :
print "first is equal to second!"
elif a < b :
print "first is less than second!"
else :
print "first is larger than second!"
# python has no switch
if a + b < 10 and a * b < 20 :
p... |
8c0c6ea1dc5850d9d46c246e36900f437eef9c99 | kenchoi523/data_structures | /cs260_hw5/heap.py | 2,489 | 3.984375 | 4 | class Heap:
def __init__(self):
self.heap = []
self.last = 0
def __str__(self):
return str(self.heap)
def makenull(self):
self.heap = []
self.last = 0
def insert(self, x):
self.heap.append(x)
self.last += 1
if self.last == 2:
... |
63c39b2cb47c1d363e95eaa1d9e5e0c046b46d85 | UjeanPoloz/python_hw | /homework_13.py | 693 | 3.96875 | 4 | catheter_a = int(input('Введите длину катета А:\n'))
catheter_b = int(input('Введите длину катета B:\n'))
def triangle_square_and_perimeter(a, b):
square = 1/2 * a * b
c = (a**2 + b**2)**0.5
perimeter = a + b + c
return square, perimeter
def print_answer(number):
if number - int(number) == 0:
... |
5db0c9d61f67946dabac5edb0705d26901b173cd | blueclowd/leetCode | /python/1424-Diagonal_traverse_II.py | 722 | 3.796875 | 4 | '''
Description:
Given a list of lists of integers, nums, return all elements of nums in diagonal order as shown in the below images.
'''
class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
table = {}
for row_idx in range(len(nums)):
for col_idx in range... |
344ebfe82f4c7935d980e01b72b3ee0021775b2b | uncleLonli/homework | /second.py | 543 | 4.28125 | 4 | # coding=utf-8
"""Домашнее задание
Написать функцию find_multiples
Принимает два аргумента число и лимит
Возвращает таблицу умножения этого числа до лимита (включительно)
Например find_multiples(5, 25) вернет [5, 10, 15, 20, 25]
"""
def find_multiples(integer, limit):
list_multiples = []
for i in range(1, l... |
74e54697962a450bc4653e9a8c2f405a78a65ebe | Allamaris0/Python | /petlecwiczenia.py | 797 | 3.671875 | 4 | for i in range(1,8):
if i==5:
print("Znalazłem " + str(i) + "!")
continue
print(i)
a = list(range(1,9))
print("Moja lista",a)
for x in a:
if x==5:
break
print(x)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
b=0
while b<20:
b+=1
if b%3==0:
... |
a8da2413e4d0e4a31098328cb55a59322b1a4b67 | BJV-git/leetcode | /string/valid_palindrome.py | 577 | 3.65625 | 4 | # logic: rather checking at each level, can simply check teh middle ones
# learned: we can just compare from the point, where the unnecessary is to be avoided
import time
x = time.time()
def del_1_palindorme(s):
slen=len(s)
i=0
j=slen-1
while i<j:
if s[i]==s[j]:
i+=1
... |
58bc8e6c85215fc3c9bbc36f405db5fb9f3de6a7 | Forif-PythonClass/Assignments | /Sangjin/HW2/2-4.py | 90 | 3.75 | 4 | sum_list=[1,2,-20]
sum=0
for i in range (0,3):
sum=sum+sum_list[i]
print("sum: ",sum)
|
c8f1a1f0224007e1cbaa9fd26119792fee5cda43 | haoccheng/pegasus | /coding_interview/edit_distance.py | 1,569 | 3.828125 | 4 | # Implement a function that finds the edit distance of two input strings.
# 3 edit operations.
# insert, delete, substitution.
# saturday : sunday -> 3
# saturday : sturday -> 1
# sturday : surday -> 1
# surday : sunday -> 1
# Dynamic programming.
# Table format to keep some sort of states/scores/memory.
# How to ini... |
5b4bd18358fe2e2d485aaf70ab34578ee0077737 | nazarov-yuriy/contests | /yrrgpbqr/p0636/__init__.py | 1,458 | 3.65625 | 4 | import unittest
from typing import List
class Solution:
def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
res = [0] * (n+1)
stack = [-1]
start = 0
for i, event in enumerate(logs):
func, action, time = event.split(":")
func = int(func)
... |
42565a4d2c42ee11cc990817234d11c580bf68ae | OATOMO/study | /python/project_py/2048/atomDraw.py | 2,506 | 4 | 4 | #!/usr/bin/python
#coding=utf-8
import math
class Point(object):
def __init__(self,x,y):
self.x = x;
self.y = y;
def __sub__(self,other):
return Point(self.x-other.x,self.y-other.y)
def __add__(self,other):
return Point(self.x+other.x,self.y+other.y)
@property
def ... |
8eb7aa289e24758589fa8d53fe0c275910297fd3 | xilixjd/leetcode | /Tree/107. Binary Tree Level Order Traversal II (easy).py | 1,836 | 4.09375 | 4 | '''
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3... |
d209291021d84876cc8e1fba2c4ac606510cecb7 | wxhheian/hpip | /ch5/ex5_1.py | 652 | 3.734375 | 4 | # cars = ['audi','bmw','subaru','toyata']
#
# for car in cars:
# if car == 'bmw':
# print(car.upper())
# else:
# print(car.title())
#
# car = 'Audi'
# print(car == 'audi')
#
# requested_topping = 'mushrooms'
# if requested_topping != 'anchovies':
# print('Hold the anchovies!')
#and or
#检... |
ca94c4e27aaa425b0481ca39707ff3ac6e49154a | graycarl/algorithms_c | /chapter2/insertsort.py | 492 | 3.59375 | 4 | #!/usr/bin/env python
def read_in(filename):
f = file(filename, 'r')
nums = []
for s in f: nums.append(int(s))
return nums
def write_out(filename, nums):
strs = [ str(n) for n in nums]
file(filename, 'w').write("\n".join(strs))
return
def ins_sort(nums):
length = len(nums)
for i in range(1, length-1):
key... |
3bcfa78c189ee5d5db328b1e464bc3dfd2e8276b | Collinbarlow98/Assignments | /Calculate/FizzBuzz.py | 446 | 4.03125 | 4 | fizz = "Fizz"
buzz = "Buzz"
no_fizz_buzz = "Where is FizzBuzz?"
def ask_user_input():
greet = "Hello please enter an integer!"
print(greet)
def fizz_buzz():
number = int(input("Number: "))
if (number % 3 == 0 and number % 5 == 0):
print(fizz + buzz)
elif (number % 5 == 0):
print(bu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.