blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
a0cb315d486e5be8ac2c9e910dfeaeeed49ce238 | MatiwsxD/ayed-2019-1 | /Labinfo_4/punto_3.py | 361 | 3.703125 | 4 | from sys import stdin
def mochila(x,y,n):
if x == 0 or n == 0:
return 0
elif y [n-1]> x:
return mochila(x,y,n-1)
else:
return max (mochila(x,y,n-1),1 + mochila(x - y[n-1],y,n-1))
def main():
prec = [int(x) for x in stdin.readline().split(" ")]
dine = int(input())
pr... |
be46099f6f6631f66d6dcc5044413589e7fc02c8 | MatiwsxD/ayed-2019-1 | /Labinfo_7/B - String reverse.py | 323 | 3.71875 | 4 | from sys import stdin
def reverse(lista,vacio):
while len(lista) != 0:
vacio.append(lista.pop())
x = ""
for i in range(len(vacio)):
x += vacio[i]
return x
def main():
x = input()
lista = []
for i in range(len(x)):
lista.append(x[i])
print(reverse(lista,[]))
mai... |
3b23c557ebbba3ff8d5a0ec958e054f11be80937 | Pankirey/web | /week8/1/b.py | 102 | 3.796875 | 4 | a =int(input())
b=a+1
c=a-1
print("The next number for the number "+str(a)+" is "+str(b))
|
f79ec881de35f556e4872c0f850a0af5684657c3 | yongfang117/data_process | /DataProcess/PCADim/pcanews.py | 2,303 | 3.765625 | 4 | # coding:utf8
from numpy import *
import matplotlib
import matplotlib.pyplot as plt
'''
Description:PCA新闻数据降维并可视化分析
Author:伏草惟存
Prompt: code in Python3 env
'''
'''加载数据集'''
def loadDataSet(fileName, delim='\t'):
fr = open(fileName)
stringArr = [line.strip().split(delim) for line in fr.readlines()]
datArr ... |
b247d17e042d33f72d1699733b0cb2e7314e7757 | yongfang117/data_process | /DataProcess/ExtractText/ConvFormat.py | 2,377 | 3.671875 | 4 | # coding=utf-8
"""
Description: 批量文档格式自动转化txt
Author:伏草惟存
Prompt: code in Python3 env
"""
import ExtractTxt as ET
import os,time
'''
功能描述:遍历目录,对子文件单独处理
参数描述:1 rootDir 根目录 2 deffun:方法参数 3 saveDir: 保存路径
'''
class TraversalFun():
# 1 初始化
def __init__(self,rootDir,func=None,saveDir=""):
self.rootDir =... |
808f7e1ab95187468e9904ea83525b673ffe16db | enio-infotera/VernamCipher | /py/encrypt.py | 441 | 3.640625 | 4 | #
#
# Use: encrypt("hello", "XMCKL")
# => "eqnvz"
#
#
def encrypt(st, key):
if len(st) != len(key):
return "Text and Key have to be the same length."
alphabet = list("abcdefghijklmnopqrstuvwxyz")
nText = []
kText = []
for i in range(len(st)):
nText.append(alphabet.index(st[i].lower()))
kText.append(alphabet.... |
f1fd9da0eed37c4f65f9217a3db04173c8e6b000 | rebeccahawke/msl-qt | /msl/qt/toggle_switch.py | 3,378 | 3.5 | 4 | """
A toggle switch :class:`QtWidgets.QWidget`.
"""
from . import QtWidgets, QtCore, QtGui
class ToggleSwitch(QtWidgets.QAbstractButton):
def __init__(self, parent=None, height=None, checked_color='#009688', unchecked_color='#B4B4B4'):
"""Constructs a toggle switch, |toggle_switch|
.. |toggle_sw... |
b5f9fab2a9f7ad2e2bdd40637e34c8b35dabc9ed | sudo-hemant/curated_questions_dsa | /tree/inorder_traversal.py | 2,018 | 3.796875 | 4 |
# https://leetcode.com/problems/binary-tree-inorder-traversal/
# NOTE: using stack
class Solution:
def inorderTraversal(self, root):
if not root:
return []
stack = []
result = []
stack.append(root)
current = root.left
... |
872479c15c4c5e2e9f17f8ae0d1416f0c7059901 | sudo-hemant/curated_questions_dsa | /searching-and-sorting.py/find-missing-and-repeating.py | 359 | 3.75 | 4 |
def findTwoElement(arr):
ans = []
for i in range(len(arr)):
if arr[abs(arr[i]) - 1] < 0:
ans.append(abs(arr[i]))
else:
arr[abs(arr[i]) - 1] *= -1
for i in range(len(arr)):
if arr[i] > 0:
ans.append(i + 1)
return ans
... |
2203621573e93df69067c62301c89799e7a527f7 | sudo-hemant/curated_questions_dsa | /graph/manucian_and_liverbird_go_bar_hopping.py | 3,429 | 3.734375 | 4 |
# TODO: NOT COMPLETED YET
# NOTE: THIS METHOD WILL GIVE US TLE BCOS WE WILL REVERSE AND TRAVERSE GRAPH AGAIN AND AGAIN TO
# FIND THE ANS, SO TO OPTIMIZE WE WILL STORE IT IN ARRAY, LOOK AT METHOD -- 2
from collections import defaultdict
def dfs(node, adj_graph, count):
for neighbour in adj_graph[node... |
4f85dc8a026ff62378e0aa6e16b615a08e5329f2 | sudo-hemant/curated_questions_dsa | /tree/diagonal_traversal_binary_tree.py | 1,075 | 4 | 4 |
# https://www.geeksforgeeks.org/diagonal-traversal-of-binary-tree/
# NOTE: this problem is quite similar to vertical traversal of binary tree,
# here we keep track of a the current level, and assign +1 to its left child
# and same level to right child and store it in dictionary i.e., default d... |
659c48af7f0de3a942a34744d9fa9aaf7f231ce6 | sudo-hemant/curated_questions_dsa | /searching-and-sorting.py/weighted-job-scheduling.py | 3,262 | 3.609375 | 4 |
class Job:
def __init__(self, start, end, profit):
self.start = start
self.end = end
self.profit = profit
# -------------------------------------------------------
# NOTE: SOLUTION - 1 ( RECURSION )
# TC : O( N * 2^N)
# n for finding latest non conflicting job and 2 options for... |
9a71665d3569a1b1db259ee0f04b5eedc1c38087 | pankajnuaa/LearningPython | /_06ControlStatements.py | 122 | 4 | 4 | # if statement
if 4>5:
print("if is true")
elif 4>3:
print("elif is true")
else:
print("else is true") |
373ef96ccb789124d4c34ef4b12310fc6c9e5816 | Kevinliao0857/Road-of-Python | /checkio electronic station/words order.py | 1,129 | 4.03125 | 4 | def words_order(text: str, words: list) -> bool:
text_words = {w for w in text.split() if w in words}
return list(sorted(text_words, key=text.index)) == words
if __name__ == '__main__':
print("Example:")
print(words_order('hi world im here', ['world', 'here']))
# These "asserts" are used for self... |
60f2e7afeae3d4fdb84aaef829d45791682e5104 | gamahead/htm_cla | /htm.py | 9,975 | 3.609375 | 4 | import random
import random as r
from math import *
import numpy
# =============================================
# Utilities
# =============================================
def partition(vector, left, right, pivotIndex):
pivotValue = vector[pivotIndex]
vector[pivotIndex], vector[right] = vector[right], vecto... |
3ef3ce08a8abc0f0a8093e0322ca561bd549a691 | ArnavRupde/cs50 | /pset6/greedy.py | 519 | 3.640625 | 4 | import cs50
def main():
while True:
print("O hai! How much change is owed?")
amount = cs50.get_float()
if amount >= 0:
break
number_of_coins = 0
cents = int(round(amount * 100))
number_of_coins += cents // 25
cents %= 25
number_of_coins += cent... |
6270514755856bede4d6144a3493fccc9627e836 | ucd-python-bootcamp/bootcamp2020 | /TutorialFiles/day1_tutorial.py | 7,821 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Python Workshop 9/22/20
The Basics
"""
"""
Part 1
-Variable Types: Integers, Floats, Strings
-Print Statements
"""
a = 10
b = 10.1
c = 'ten'
#a is an integer, b is a float, c is a string
print('integer:',a)
print('float:',b)
print('string:',c)
print(a,b... |
7f5d67d5e20cdc67f839886d39b207df0585d247 | ZeroVM-dot/lecture2 | /loops0.py | 138 | 4.15625 | 4 | for i in range(5):
print(i)
print("=====Other Loop type=====")
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
|
615efb92487e6d4043e69ec3d7a137beff7364e7 | Erdalien/Movies | /Movies/main.py | 4,084 | 4.09375 | 4 | '''
Problem:
We want to build a system to pick the best (or worst) movies for the person provided.
The algorithm makes its decision based on Euclidian scoring and users opinions.
To run the code you have to specific an user, e.g:
python3 main.py --user "Adam Tomporowski"
Author:
Adam Tomporowski,... |
c7d37dda67399bb51fd436305f1bd17a6846a77b | atsss/nyu_deep_learning | /examples/beginner/ABC085B.py | 234 | 3.53125 | 4 | # from collections import Counter
#
# N = int(input())
#
# D = []
# for i in range(N): D.append(int(input()))
#
# counter = Counter(D)
#
# print(len(counter))
N = int(input())
D = [int(input()) for i in range(N)]
print(len(set(D)))
|
22211d989fd3f2e16b2b089ce09b2fd6a4b1a3dc | atsss/nyu_deep_learning | /algorithm/combination.py | 394 | 3.5625 | 4 | from itertools import permutations, combinations,combinations_with_replacement,product
a=['a','b','C']
print(list(permutations(a)))
print(list(combinations(a,2)))
print(list(combinations_with_replacement(a,3)))
a=list(product(['+','-'],repeat=3))
print(a)
s=['5', '5', '3', '4']
for i in a:
ans=s[0]+i[0]+s[1]+i[1]+... |
7b63664677834170f014c9885e6f1ccc220e5fcf | ldaniil32l/course_work_2021 | /course_work.py | 9,794 | 3.578125 | 4 | # Автор: Попов Даниил
# Группа 131-Мко
from math import factorial, sin, log2, pi
from cmath import cosh, sinh
from tkinter import *
from tkinter import ttk
# Функция произведения матриц (для поиска степеней матриц)
def multi_matrix(A, B):
multi_AB = []
for i in range(len(A)):
multi_row = []
fo... |
98f13d4436271e68b559c29ca72a85f3718254f7 | Davidwang20201101/demo | /venv/2020/10/25.py | 6,144 | 3.609375 | 4 | # names =['Adeam','David','Lucy']
# print(names)
# names[2]='ass'
# print(names)
# names.insert(0,'billy')
# names.insert(2,'car')
# names.append('kris')
# names.remove('kris')
# print(names)
# 得到
# /Users/wangyueqiu/PycharmProjects/demo/venv/bin/python /Users/wangyueqiu/PycharmProjects/demo/venv/2020/10/25.py
# ['Adea... |
9073d1f2d25f33fa6522ef6fe619974d9e9a6146 | Davidwang20201101/demo | /1206.py | 2,372 | 3.546875 | 4 | # 猴子吃桃问题:
# 猴子第一天吃了若干个桃子,当即吃了一半,还不解馋,又多吃了一个; 第二天,吃剩下的桃子的一半,还不过瘾,又多吃了一个;以后每天都吃前一天剩下的一半多一个,到第10天想再吃时,只剩下一个桃子了。问第一天共吃了多少个桃子?
# x=1
#
# for peach in range(9):
# x=(x+1)*2
# print(x)
# 1234四个数字,能组成那些3位数
# numbers=(1,2,3,4)
# for i in numbers:
# for j in numbers:
# for k in numbers:
# ... |
46b36e657e801721592b3de22e2085d5f3ea8924 | zjw641220480/pythonfirst | /src/simple/simple_if.py | 563 | 3.796875 | 4 | '''
Created on 2017年10月3日
@author: lengxiaoqi
'''
x=0
if x>0:
print("x is positive");
elif x<0:
print("x is negative");
else:
print("x is zero");
#在if判断中也可以使用各种表达式来作为判断条件;他们会被当做ture来处理
#None,0,空字符串,空列表,空集合会被当做false来处理;
#当然这种方式是不推荐的,推荐使用len(mylist)>0来判断一个列表是否为空
mylist=[1,2,3,4,5];
if mylist:
print("The... |
bf009002e5a2a62dafe139fefdec3c3d2e407754 | bsk17/LibraryPython | /main.py | 15,802 | 3.515625 | 4 | # tkinter is the GUI library like PyQt
from pymongo import MongoClient
from tkinter import*
from tkinter import ttk, messagebox
import random
from datetime import datetime
import tkinter.messagebox
client = MongoClient(port=27017)
db = client.Books
books = db.books
class Library:
# as soon as the class is initiat... |
a213dd7895b140e92ecf9cd41ee429e477352849 | vikash-india/MathematicsNotes2Myself | /mathematics/concepts/01-basics/P007_Algebra_IndentityElement.py | 384 | 3.796875 | 4 | # Description: Identity Elements
from numpy import identity, zeros, ones
# Additive Identity
print zeros (3) # Returns 1X3 additive identity matrix with all element as 0.
# Multiplicative Identity
print identity(3) # Returns 3X3 multiplicative identity matrix.
# Related Functions
print ones(3) ... |
0971d34016d5a38b6f7aa8d801fc1cb0c1a525bf | 17-76018348/mycode | /data-structure/bubblesort.py | 1,678 | 3.84375 | 4 | import random
def performSelectionSort(lst):
for itr1 in range(0, len(lst)):
for itr2 in range(itr1+1, len(lst)):
if lst[itr1] < lst[itr2]:
lst[itr1], lst[itr2] = lst[itr2], lst[itr1]
return lst
def bubblesort(lst):
for idx1 in range(0, len(lst)):
for idx2 in ra... |
177116fdac6e2827d8d3ddb567ac8bc15952d7ad | anuradhaschougale18/PythonFiles | /ExceptionHandling/nestedtryException.py | 506 | 3.625 | 4 | '''
Nested try block
'''
def calc():
try:
try:
x=int(input("Enter value=>"))
y=int(input("Enter value=>"))
a=x/y
print("Answer is=",a)
except ZeroDivisionError as ze:
print(ze)
try:
l=[10,20]
... |
95b5d44432371958fb85efcb606729590797041d | anuradhaschougale18/PythonFiles | /21st day-BinarySearchTreee.py | 1,346 | 4.28125 | 4 | '''
Task
The height of a binary search tree is the number of edges between the
tree's root and its furthest leaf. You are given a pointer, root,
pointing to the root of a binary search tree.
Complete the getHeight function provided in your editor so that it returns the height of the binary search tree.
'''
cla... |
7ce0712c715ebc1a5eadac7d45520f3bd87bd947 | jalani2727/HackerRank | /Counting_Valleys.py | 770 | 4.1875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
# reverse engineer
# Every time you return to sea level (n) after n has decreased, one valley has been travelled through
def countingValleys(n, s):
valley_counter=0
compare_to = n
for l... |
fae91623b850d6208f9dbe4cfb0b0a67088913c3 | liqinglu/my_python_pattern | /myfactory.py | 346 | 3.59375 | 4 | # -*- coding: utf-8 -*-
class A(object):
def get(self):
print "in A"
class B(object):
def get(self):
print "in B"
def factory(where):
fact = dict(fromA=A,fromB=B)
return fact[where]()
def main():
a,b = factory("fromA"),factory("fromB")
for i in range(4):
if i%2:
a.get()
else:
b.get()
if __nam... |
5b7b5b58d9f4cfc3c04e29db7ed222fd904b35f1 | suruchishrey/Client-Server-Systems | /client.py | 1,783 | 3.515625 | 4 | import socket
import sys
BUFFER_SIZE = 1024
def prompt():
sys.stdout.write("> ")
sys.stdout.flush()
class Client:
def __init__(self):
self.host = sys.argv[1]
self.port = int(sys.argv[2])
self.sock = None
self.connect_to_server()
def connect_to_server(self):
t... |
621414d67c36c071b343e8979240cf5f051107a9 | Anaisdg/python-challenge | /PyPoll/main.py | 1,151 | 3.546875 | 4 |
# coding: utf-8
# In[69]:
import os
import csv
# In[70]:
file_to_open = "election_data_2 copy.csv"
with open(file_to_open, 'r') as election_data:
reader = csv.DictReader(election_data)
contents= set()
[contents.add(x["Candidate"]) for x in reader]
list_contents = list(contents)
#votes = []
... |
da8a8d569e99d24ac98074dc6a49855586957c68 | labeee/cdd-calculator | /CDD.py | 2,249 | 3.59375 | 4 | '''
Calculates CDD or CDH for different temperature thresholds defined
'''
import glob
import pandas
# Creates a list with the degrees chosen to be the threshold.
# If it's not needed to pick one by one, you can create a list called "THRESHOLDS"
# with whatever values you want.
MIN_THRESHOLD = 15
MAX_THRESHOLD = 22
T... |
11baed41c81dafe19b3380c39a8d9adb442bf8ac | fanpl-sourse/mytestenv | /UIautoPlatform/test_case/test_wrapper.py | 813 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2020/8/3 17:35
# @Author : 饭盆里
# @File : test_wrapper.py
# @Software: PyCharm
# @desc : 装饰器
def wrapper(func):
print('hi')
func()
print('bye')
def wrapper1(func):
#允许所有类型的入参
def hello(*args,**kwargs):
print(args)
func()
print(kwarg... |
85a46d9a4b047e7fbb62f20cc5aefe1692627a86 | yuwenfu/python-pratice | /table_cases.py | 710 | 4.0625 | 4 | #P33 3-1
name = ['python','linux','arm','avr','stm32']
print(name[0].title())
print(name[1].upper())
print(name[2].lower())
print(name[3])
print(name[4])
#P33 3-2
message = "My best friend is "+name[0].title()+'.'
print(message)
message = "My best friend is "+name[1].title()+'.'
print(message)
message = "My best friend... |
770ff29a7d5a80c9dcb269a6a6978189ce367aa9 | BCombs/python-projects | /crack.py | 3,137 | 4.03125 | 4 | import cs50
import sys
import crypt
def main():
#make sure there are 2 arguments at command line
if len(sys.argv) != 2:
print("Usage: python filename key")
exit(1)
#Get the hash entered at command line and the salt from userHash
userHash = sys.argv[1]
salt = userHash[0:3]
... |
6a6f40a8b8dddb89b04b2a0b9f6859f56d5dee9c | DesignCell/Euler | /P007.py | 645 | 3.796875 | 4 | # Problem 7
# 10,001st Prime
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
# we can see that the 6th prime is 13.
# What is the 10 001st prime number?
from time import time
from math import sqrt
start = time()
def prime(cnt2):
for cntp in range(2, (int(sqrt(cnt2)+1))):
if cnt2 % cntp == 0:
... |
d4fa68dc7565ac9b4412f36d2e35831e8643c8c7 | DesignCell/Euler | /P050.py | 1,919 | 3.59375 | 4 | # Problem 050
# Consecutive Prime Sum
# The prime 41, can be written as the sum of six consecutive primes:
# 41 = 2 + 3 + 5 + 7 + 11 + 13
# This is the longest sum of consecutive primes that adds to a prime below one-hundred.
# The longest sum of consecutive primes below one-thousand that adds to a prime,
# cont... |
da5488b7a450d4bb23d5967b82bbf9299d56444f | DesignCell/Euler | /P043.py | 1,532 | 3.671875 | 4 | # Problem 043
# Sub-String Divisibility
# The number, 1406357289, is a 0 to 9 pandigital number because it is made up
# of each of the digits 0 to 9 in some order, but it also has a rather interesting
# sub-string divisibility property.
# Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note t... |
9a522eca985244fb52ecdbc9b295764f8e2bacac | DesignCell/Euler | /P001.py | 706 | 4.0625 | 4 | # Problem 1
# Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
from time import time
start = time()
# sumnum=0
# for num in range(1,1000):
# if num%3==0 ... |
0feeb803fd420ce45b3afc5a986733d27123b364 | DesignCell/Euler | /P019.py | 997 | 3.90625 | 4 | from time import time
stime = time()
import datetime
# Problem 19
# Counting Sundays
# You are given the following information, but you may prefer to do some research for yourself.
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alo... |
ae6c90d344ea05a85e0e03e67ea5ea2df54e47ae | DesignCell/Euler | /P062.py | 1,773 | 3.765625 | 4 | # Problem 062
# Cubic Permutations
# The cube, 41063625 (345**3), can be permuted to produce two other cubes:
# 56623104 (384**3) and 66430125 (405**3). In fact, 41063625 is the smallest cube
# which has exactly three permutations of its digits which are also cube.
# Find the smallest cube for which exactly five perm... |
cb7f42bde72c51f3c08da9e9cc528c3ab424ffe0 | SyntaxStacks/Dev-test-project | /1-finding-the-source/locations.py | 581 | 3.859375 | 4 | class Locations():
def __init__(self):
self.locations = []
def addLocation(self, location):
if location not in self.locations:
self.locations.append(location)
def cleanUpLocations(self):
pass
#TODO: remove all but the single point that all circles go through
... |
daea4f195777b8a1c925a68a2d5a3e58172a8e1a | zdravkob98/Python-Advanced-September-2020 | /Functions Advanced - Exercise/03. Min Max and Sum.py | 386 | 3.734375 | 4 | def min_res(*args):
min_result = min(*args)
return min_result
def max_res(*args):
max_result = max(*args)
return max_result
def sum_res(*args):
sum_result = sum(*args)
return sum_result
n = [int(x) for x in input().split()]
print(f'The minimum number is {min_res(n)}')
print(f'The maximum ... |
796cc3ea8feadf2156d6734bdbf62f83015ab51d | zdravkob98/Python-Advanced-September-2020 | /Multidimensional Lists - Exercise/01. Diagonal Difference.py | 409 | 3.6875 | 4 | rows = int(input())
matrix = [[int(x) for x in input().split()] for _ in range(rows)]
first_diagonal = 0
second_diagonal = 0
for i in range(rows):
first_diagonal += matrix[i][i]
second_diagonal += matrix[i][-i - 1]
# for i in range(rows):
# first_diagonal += matrix[i][i]
# for i in range(rows, 0, -1):
#... |
4abdbbab21357a288a4cd7f92d09393e9b15f08e | zdravkob98/Python-Advanced-September-2020 | /Functions Advanced - Exercise/04. Negative vs Positive.py | 421 | 4.21875 | 4 | def find_biggest(numbers):
positive = sum(filter(lambda x: x >= 0, numbers))
negative = sum(filter(lambda x: x <= 0, numbers))
print(negative)
print(positive)
if abs(positive) > abs(negative):
print("The positives are stronger than the negatives")
else:
print("The negatives ar... |
3b4ade606a2d8794bab84fa6ff1a364488ee15e7 | zdravkob98/Python-Advanced-September-2020 | /comprehensions - exercises/01. Word Filter.py | 102 | 3.671875 | 4 | text = input().split()
result = [word for word in text if len(word) % 2 == 0]
print('\n'.join(result)) |
a971623c1136cdad93427ede0855662339fe0e56 | zdravkob98/Python-Advanced-September-2020 | /Tuples and Sets - Exercise/05. Phonebook.py | 500 | 3.890625 | 4 | from _collections import defaultdict
phonebook = defaultdict(str)
search = input()
while True:
if search.isdigit():
break
else:
token = search.split('-')
name = token[0]
number = token[1]
phonebook[name] = number
search = input()
n = int(search)
for _ in range(n):... |
d8915245d0075e79e67d20e476a098d827f8dc96 | zdravkob98/Python-Advanced-September-2020 | /Multidimensional Lists - Exercise/04. Matrix Shuffling.py | 760 | 3.6875 | 4 | rows, cols = [int(x) for x in input().split()]
matrix = [input().split() for i in range(rows)]
command = input()
while command != 'END':
token = command.split()
if len(token) == 5:
swap = token[0]
row1 = int(token[1])
col1 = int(token[2])
row2 = int(token[3])
col2 = int... |
bfb2e47d54a5fc7dbbbff14894db301a57113a19 | zdravkob98/Python-Advanced-September-2020 | /Multidimensional Lists - Exercise/02. 2x2 Squares in Matrix.py | 318 | 3.609375 | 4 | rows, cols = [int(x) for x in input().split()]
matrix = [input().split() for i in range(rows)]
count = 0
for i in range(rows - 1):
for j in range(cols - 1):
if matrix[i][j] == matrix[i+ 1][j] and matrix[i][j] == matrix[i][j+1] and matrix[i][j] == matrix[i + 1][j + 1]:
count += 1
print(count) |
d5b40e563b08098cdf293765d8db62ee2a210bee | zdravkob98/Python-Advanced-September-2020 | /Lists as Stacks and Queues - Exercise/06. Balanced Parentheses.py | 408 | 3.9375 | 4 | text = input()
par = []
parentheses = {'(': ')', '{': '}', '[': ']'}
status = True
for i in text:
if i in parentheses:
par.append(i)
else:
if len(par) == 0:
status = False
break
paren = par.pop()
if parentheses[paren] != i:
status = False
... |
67d5c2ebec2c72df9fcb33435c0347607b645863 | DT9/programming-problems | /job/dtruong/spiral.py | 1,198 | 3.625 | 4 | def createSpiral(N):
spiral = [[0 for i in range(N)] for j in range(N)]
top = left = 0
bottom = right = N - 1
RIGHT, DOWN, LEFT, UP = 0, 1, 2, 3
direction = RIGHT
count = 1
while top <= bottom and left <= right:
if direction == RIGHT:
for i in range(left,right+1):
... |
808bb7a2aa620a8d4e966978a141103163838bca | sanjaybabu2210/mycaptain | /checkpos.py | 201 | 3.796875 | 4 | def pos_find(num):
lis = []
for x in num:
if x<0:
continue
else:
lis.append(x)
return lis
num = eval(input('enter the list'))
print(pos_find(num))
|
9f4b64cbf1ce55b9e0536454f048e8f6476bf67d | wilsonsamarques/OpenCV | /Intro_and_Images.py | 650 | 3.875 | 4 | # Contents Covered:
# Installation and Setup
# Loading an image
# Displaying an image
# Resizing an image
# Rotating an image
import cv2
img = cv2.imread('resources/lena.png', 1)
# img = cv2.resize(img, (0,0), fx=0.5, fy=0.5)
# img = cv2.rotate(img, cv2.cv2.ROTATE_90_COUNTERCLOCKWISE)
# cv2.imwrite('new_lena.jp... |
b4223446ccb2dc8d7e248ca50b84b44a60d802e7 | knshkp/hacktoberfest2021 | /Python/heapsort.py | 485 | 3.71875 | 4 | def heap(arr, n, i):
a = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
a = l
if r < n and arr[a] < arr[r]:
a = r
if a != i:
arr[i],arr[a] = arr[a],arr[i]
heap(arr, n, a)
def hS(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heap(arr, n, i)
for i in range(n-1, 0, -1):
arr[... |
01165803a5ece1682e91f49d604a47f39bdba27a | jerryeml/Python_Class | /Class_List01.py | 769 | 4.125 | 4 | a_tuple = (12,3,5,15,6)
b_tuple = 2,4,6,7,8
a_list =[12,3,67,7,82]
a_list.append(0) #添加
a_list.insert(2,11) #添加在指定位置
a_list.remove(12) #只會刪除碰到第一個12
for i in range(len(a_list)): #依照list長度分別輸出第幾個元素的value
print(i,a_list[i])
print('Last element:',a_list[-1])#從最後一個開始數
#print(a_list)
print('first to three element:',a_list... |
5f60295d61b3be636d5015b934c3a79ded323c92 | bsherrill480/catch_phrase | /anny2/circle_graph.py | 5,062 | 4.1875 | 4 | class Node:
"""
its a node
"""
def __init__(self, data=None, name=None):
self.next = next
self.data = data
self.name = name
class Organizer:
"""
class to interact with data.
Uses nodes
"""
def __init__(self):
self.nodes = dict()
def make_and_give... |
0de01265da280f211a9dfca29b13bc8427e746a5 | deeppavlov/learning-to-learn | /learning_to_learn/controller.py | 13,969 | 3.890625 | 4 | import copy
from learning_to_learn.useful_functions import construct, get_elem_from_nested
class Controller(object):
"""Controller is a class which instances are used for computing changing learning parameters. For example
learning rate. It is also responsible for training stopping
Usage:
1. Cons... |
56ed53478852a695eaab1d6b41d5c867fa48909e | LoyalSkm/Home_work_2_base | /hw2_task_3.py | 1,866 | 4.25 | 4 | print(''' 3. "Нарисовать" в консоли прямоугольный треугольник из символов "*",
пользователь задаёт высоту и ширину(в количестве элементов).
''')
print('''Задавай какую хочешь высоту, но триугольник будит пропорциональным только если высота<ширины в 2 раза
''')
import numpy #позволит мне сделать список из е целых чис... |
1e2e21bc8a6f6854b8b4bbb637e7a41af0490221 | viren-nadkarni/codu | /madf/ms.py | 729 | 4.0625 | 4 | #!/bin/python
# Sorting a List using Mergesort in Python
# 2011-05-16
def mergeSort(toSort):
if len(toSort) <= 1: #if single/no element, return
return toSort
mIndex = len(toSort) / 2 #find midpoint
left = mergeSort(toSort[:mIndex]) #split into left
right = mergeSort(toSort[mIndex:]) #and right arr... |
416b3647bf749bbb017c22c0bfb33aa43252730f | viren-nadkarni/codu | /dm/4b_covariance.py | 760 | 3.5 | 4 | #!/usr/bin/env python
import math
x = [-3, 6, 0, 3, -6]
y = [ 1, -2, 0, -1, 2]
def mean(x):
m = 0
for i in x:
m += i
return m/float(len(x))
def covar(x, y):
if len(x) != len(y):
raise AssertionError
mx = mean(x)
my = mean(y)
print 'mean(x) =', mx
print... |
fd9cb978295bc517b3bcd61dcc50b19210879064 | NhanNgocThien/IlearnPython | /counter_gui.py | 3,859 | 3.75 | 4 | # Date created: 27/01/2019
# A simple GUI counter provides two mode: count up, count down. It also has stop, and reset button
# Import modules
try:
from tkinter import *
except:
from Tkinter import *
# Constants
SCREEN_W = 350
SCREEN_H = 200
BUTTON_W = 10
BUTTON_H = 1
S_START = 1
S_STOP ... |
5709f54d68f6ae8d2dadbee5418d5162ac644852 | josayko-courses/chess_tournament | /chess_tournament/models/round.py | 731 | 3.84375 | 4 | """Round information
"""
from datetime import datetime
class Round:
"""Holds round information"""
def __init__(self, name, games, start=None, end=None):
self.name = name
if start is None:
self.start = datetime.today().strftime('%Y-%m-%d %H:%M')
else:
self.sta... |
c2903426b0ef376db087dc5559bf8a176d7c6835 | lavalleed/IntroToProgramming-Python | /Assigment05_v1_5.py | 6,968 | 3.875 | 4 | # Title: Working with Dictionaries#
# Dev: DLaVallee
# Date: November 12, 2012
# ChangeLog: (Who, When, What)
# RRoot, 11/02/2016, Created starting template
# <DLaVallee>, 11/17/2018, Added code to complete assignment 5#
# Known bugs: List creation key to value pair is showing additional ':'?
# -- Data -... |
e57b325221d17e8abd6b44545967238017d2f616 | ARLbenjamin/PythonGames | /panecillos.py | 2,574 | 3.921875 | 4 | import random
def obtenerNumeroSecreto(digitosNum):
#retorna el numero secreto, el cual se crea al alzar
numeros = list(range(10))
random.shuffle(numeros)
numSecreto = ''
for i in range(digitosNum):
numSecreto += str(numeros[i])
return numSecreto
def obtenerPista(conjetura, ... |
9d304c08122377649b4809d338a3388a93c85060 | Tdaycode/Data-structure-Algorithm-solutions | /binary-search-challenge.py | 425 | 3.890625 | 4 | import math
# Implementing binary search
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
def binary_search(array, item):
low = 0
high = len(array) - 1
while low <= high:
mid = low + high
guess = array[mid]
if guess == item:
return mid
if guess > item:
... |
63fdb9f87bd84fab72406225ec083ea0f92427d4 | redhead520/LearningCode | /Design pattern/01.Factory Method(工厂方法).py | 3,561 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
' Factory Method'
__author__ = 'redhead'
# 定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。
# 适用性:
#
# 当一个类不知道它所必须创建的对象的类的时候。
# 当一个类希望由它的子类来指定它所创建的对象的时候。
# 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
# 简单工厂模式
class LeiFeng():
def buy_rice(self):... |
0f162bbed4a38ed2c2098cb823728ae115e2b218 | redhead520/LearningCode | /Algorithms/3.0数据结构-栈和队列.py | 2,491 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
' 3.00 数据结构:栈和队列'
# 栈:stack, 后进先出 last-in,first-out LIFO
# 队列:queue 先进先出 first-in,first-out FIFO
# 栈S
# S.push(), S.pop(), S.top, S.isempty()
# 栈下溢underflow, 栈上溢owerflow
class STACK():
def __init__(self, num=50, type=list):
if type == dict:
self.... |
fa1493d82201cb35e25484d00d21191a9e1322b2 | ZiHaoYa/1807-2 | /14day/01-计算器.py | 247 | 3.734375 | 4 | class student():
count = 0
def __init__(self,name):
self.name = name
self.count += 1
def add():
print("欢迎")
Student = student("美丽")
Student = student("狗威")
Student = student("高波")
Student = student("科林")
Student.add()
|
ba667451d2d80b621e1a5ae6f4166f148c4c0d74 | andyruwruw-old/coding-challenge-for-kids | /Labs_Python/2._Intermediate_Python/1._Strings/Tic-Tac-Toe/solution.py | 2,791 | 3.71875 | 4 | import math
board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
turn = 0
def printBoard(board):
for i in range(0, len(board)):
string = ""
for j in range(0, len(board[i])):
item = " "
if board[i][j] == 1:
item = "X"
elif board[i][j] == 2:
i... |
82c94fb9df5e8ae0628300f263ecbbe9da32e901 | andyruwruw-old/coding-challenge-for-kids | /Labs_Python/3._Advanced_Python/2._Input_and_Output_Files/Censored_Files/solution.py | 598 | 3.75 | 4 | inFile = open("input.txt", "r")
outFile = open("output.txt", "w")
badWords = []
while True:
badWord = input("What word would you like removed (/done to move on): ").lower()
if badWord == "/done":
break
badWords.append(badWord.lower())
for line in inFile:
words = line.split()
newLine = ""
... |
ac52662a8ec3f30a9d706264a369cb71ae1d8834 | zephyrzth/FP-PemrogramanJaringan | /menu.py | 1,535 | 3.53125 | 4 | from tkinter import *
class Menu:
def __init__(self, master):
self.root = master
self.button_inputname = None
self.button_exit = None
self.generate_gui()
def generate_gui(self):
namalabel = Label(self.root, text = "")
namalabel.pack()
self.topframe ... |
f2277ac69ee272fee0239569dd7dbe406a5aa4c5 | zephyrzth/FP-PemrogramanJaringan | /logic-othello.py | 7,154 | 3.765625 | 4 | # array dengan value 0 brarti belum berisi
# array dengan value 1 terisi dengan bidak hitam
# array dengan value 2 terisi dengan bidak putih
class Othello:
board = [[0 for i in range(8)] for j in range(8)]
whitePieces = 0
blackPieces = 0
# Variabel untuk menghitung jumlah player yang gabisa gerak
c... |
ca53b0e726e6c8f8f527739fc80c850bd05465e1 | agb32/aotools | /aotools/turbulence/turb.py | 1,960 | 3.578125 | 4 | """
General equations and definitions describing turbulence statistics
"""
import numpy
from scipy.special import gamma, kv
__all__ = ["phase_covariance","calc_seeing"]
def phase_covariance(r, r0, L0):
"""
Calculate the phase covariance between two points seperated by `r`,
in turbulence with a given `r0 ... |
fd88cc6462b59a357c3d5612afe7ae334f651ccd | superxiangsx/python-ex | /ex17.py | 168 | 3.90625 | 4 | x = input("please input some words: ")
print(f"The words you input is {len(x)}")
y = input("please input some other words: ")
print(f"The words you input is {len(y)}")
|
731fca158d965092ca59f3f063d1e917fb56a84e | superxiangsx/python-ex | /test.py | 439 | 3.65625 | 4 |
#求绝对值的函数,即两点间距离的函数
'''def abs(x,y):
if x > y:
return x-y
else:
return y-x
'''
# y = |x-1| + 2*|x-2| + 3*|x-3| + 4*|x-4| + ...... + 100*|x-100|
#描述上述函数,min_x和max_x为区间的上下限
def jisuan(x,min_x,max_x):
j = min_x
z = 0
for j in range(min_x, max_x+1):
z = z + j * abs(x - j)
print(f"x = {x}, the resu... |
6b73ba38506e9fe8456532d627230062d9adbd16 | jstratman33/text-blackjack | /src/Player.py | 1,580 | 3.5 | 4 | '''
Created on Oct 5, 2017
@author: Jason
'''
import os
class Player:
def __init__(self, name):
"""
Builds the player object with name and sets the bank from file
Args:
None
Returns:
None
"""
self.name = name
self.bank = 0
se... |
a24b998f495ff7e20561903ed543b09f54520a6a | SIDDHARTHSS93/Computer-Security-Assignments | /Siddharth_Shyamsunder_1802772/ass2.py | 5,069 | 3.78125 | 4 | import numpy
import random
import time
#We will store the values of private keys into private 1 and 2, private 1 and 2
#will be the output of combined congruential method.
#We will have alpha and q to obtain the public keys(x1 and x2) for the Diffie
#Hellman's Algorithm.
#we will use public keys x1 and x2 to generate s... |
c9e7fd34fbbd2ae8fd3a81cfd08877310ffc88b0 | NagahShinawy/dev.to | /tips-tricks/3-python-tips-tricks-that-no-one-teach.py | 873 | 3.859375 | 4 | # https://dev.to/worldindev/6-python-tips-tricks-that-no-one-teaches-4j73
import random
import datetime
answers = ["A", "B", "C", "D", "E"]
books = ["Harry potter", "Don Quixote", "Learn Python", "Dracula"]
book = random.choice(books)
for _ in range(10):
answer = random.choice(answers)
print(answer)
# Un... |
4e070270f812ddd28e7a7d7453cd10397b16631c | Janarbek11/ifElse | /ifelse.py | 832 | 4.34375 | 4 | # Написать программу которая проверит число на несколько критериев:
# Чётное ли число?
# Делится ли число на 3 без остатка?
# Если возвести его в квадрат, больше ли оно 1000?
с = int(input("Введите число: "))
if с % 2 == 0:
print ("Четное число!")
else:
print("Нечетное число!")
o = int(input("Введите число: ... |
88dda3900d59832cd686572ace19c943c888dfd6 | dsweed12/My-Projects | /Project II - Python MITx/week2.py | 3,271 | 4.15625 | 4 | import math
def iter_power(base, exp):
"""
base: int or float
exp: int >= 0
returns: int or float, base^exp
"""
if exp == 0:
return 1
else:
result = base
while exp > 1:
result *= base
exp -= 1
return base
def recurPower(base, exp):
"""
bas... |
c793c49002dae5ccb185c42dad3cddbc3bb8fcd6 | PolyMaG/python-project-lvl1 | /brain_games/games/gcd.py | 568 | 3.796875 | 4 | from random import randint
GREETING = 'Find the greatest common divisor of given numbers.'
def get_gcd(number1, number2):
max_number = max(number1, number2)
min_number = min(number1, number2)
gcd = 1
while gcd <= min_number:
if max_number % gcd == 0 and min_number % gcd == 0:
resu... |
fe33826633b2348dc4fe943c9591c6737ff46416 | tracyyu/UCLA-CS-145-Cuisiner | /Cuisinier-Tracy/CuisinierClassifier.py | 3,860 | 3.609375 | 4 | from Cuisinier import Recipe, ClassifiedRecipe, Cuisinier
"""
Uses ingredients to categorize the cuisine of a recipe via the
One-Vs-All algorithm.
@author: Alan Kha
"""
class CuisinierOVA(Cuisinier):
def __init__(self):
super().__init__()
def preprocess(self):
super().preprocess()
... |
9e47611cfa3d80554715e98da0f9f1c08b8331ff | tboydv1/project_python | /Python_book_exercises/chapter6/exercise_11/online_purchase.py | 1,288 | 4.25 | 4 | """Suppose you are purchasing something online on the Internet. At the website, you get
a 10% discount if you are a member. Additionally, you are also getting a discount of
5% on the item because its Father’s Day.
Write a function that takes as input the cost of the item that you are purchasing and
a Boolean variable i... |
c5c23ee5b021fe7b7c6ee442ab3c32cece6831ff | tboydv1/project_python | /Python_book_exercises/chapter6/examples/word_search.py | 583 | 4 | 4 | # read through file one line at a time
def clean_word(word):
return word.strip().lower()
def get_vowel_in_word(words):
vowel = "aeiou"
vowel_in_word = ''
for char in words:
if char in vowel:
vowel_in_word += char
return vowel_in_word
# main program
# def main():
file_obj = ... |
2112a1c6e94348196d065f4748b6454345c2e112 | tboydv1/project_python | /Python_book_exercises/chapter2/exercise13.py | 331 | 4.125 | 4 | #Validate for and integer input
user_str = input("Input an integer: ")
status = True
while status:
if user_str.isdigit():
user_int = int(user_str)
print("The integer is: {}".format(user_int) )
status = False
else:
print("Error try again")
user_str = input("Input an in... |
6b0e05cdb97a6ca0eee0c64096017f46fd05cafe | tboydv1/project_python | /practice/circle.py | 223 | 4.3125 | 4 | from math import pi
tmp_radius = input("Enter radius of circle ")
radius = int(tmp_radius)
circumference = 2 * (pi * radius)
print("Circumference is: ", circumference)
area = pi * radius**2
print("Area is: ", area)
|
76bfd7b4ce465902718576aa06d26cc654c9e599 | tboydv1/project_python | /Python_book_exercises/chapter1/cosine.py | 1,060 | 4.34375 | 4 | from math import *;
print("Angles of triangle with lengths: 7, 3, 9", end = "\n\n")
##Find angle C when side a = 9, b = 3, c = 7
##formula= c**2 = a**2 + b**2 - 2 * a * b * Cos(c)
side_a, side_b, side_c = 9, 3, 7;
a_b = -(2 * side_a * side_b);
#Square all sides
pow_a = side_a**2
pow_b = side_b**2
pow_c = side_c**2... |
682fa2b9c64d20165751d9a44a135dda1779f5be | tboydv1/project_python | /Python_book_exercises/chapter2/exercise11.py | 627 | 4.0625 | 4 | """Write a program that prompts for an integer—let’s call it X—and then finds the
sum of X consecutive integers starting at 1."""
value_str = input("Enter a value ")
sum = 0
count = 0
try:
#convert input to int
value_int = int(value_str)
print("Consecutive sums: ")
for i in range(1, value_int + 1):
... |
42fe32b3336b638d54746970963d3a8dccf07171 | tboydv1/project_python | /Python_book_exercises/projectMatrix/matrix/matrix_program.py | 231 | 3.59375 | 4 | from matrix import Matrix
def main():
A = Matrix([[1,2,3], [2, 4, 4], [4, 4, 4]])
B = Matrix([[1,2,3], [2, 40, 4], [4, 4, 4]])
print(A)
print(B)
print(B.add(A))
if __name__ == '__main__':
main()
|
53c8eeb9ebc1c83debeecea5f0d5a42e7d365ba4 | tboydv1/project_python | /Python_book_exercises/chapter6/examples/program2.py | 346 | 3.796875 | 4 |
def func1 (str1, str2):
if str1 > str2:
result_str = str1[1:]
else:
result_str = str2[:-1]
return result_str
#main program
responses1_str = input("Enter a string:")
responses2_str = input("Enter a second string:")
dir(list)
print(func1(responses1_str, responses2_str))
print(func1(response... |
f1d8cf960efa1ba7bafb12d84d48afc8b947d61c | tboydv1/project_python | /practice/factors.py | 284 | 4.125 | 4 | #get the input
num = int(input("Please type a number and enter: "))
#store the value
sum = 0
print("Factors are: ", end=' ')
#generate factors
for i in range(1, num):
if(num % i == 0):
print(i, end=' ')
#sum the factors
sum += i
print()
print("Sum: ",sum)
|
bbfc551d1ee571c9be6c68747b56ca85a56fcf4b | abaratif/code_examples | /sums.py | 813 | 4.34375 | 4 |
# Example usage of zip, map, reduce to combine two first name and last name lists, then reduce the combined array into a string
def combineTwoLists(first, second):
zipped = zip(first, second)
# print(zipped)
# [('Dorky', 'Dorkerton'), ('Jimbo', 'Smith'), ('Jeff', 'Johnson')]
# The list comprehension way
listCom... |
139af95efa48672d9d38ea31f30320e6fbdce184 | jonnysfarmer/python-learning | /webscraper/main.py | 1,077 | 3.8125 | 4 | from bs4 import BeautifulSoup
import requests
search = input('Search For: ')
params = {'q': search}
# does a request for first page of bing search resuls
r = requests.get('https://www.bing.com/search', params=params)
# uses beautiful soup to pass the html into text
soup = BeautifulSoup(r.text, 'html.parser')
# So it... |
a54d2cbae58df936803b259917a95ed7f960f92b | sree-07/PYTHON | /escape_sequences.py | 1,829 | 4.25 | 4 | """sep & end methods"""
# a="python";b="programming"
# print(a,b,sep=" ") #python programming
# print(a,b,end=".") #python programming.
# print("sunday") #python programming.sunday
""" combination of end & str &sep """
# a="food"
# b="from swiggy"
# c="not av... |
9cdf697a26228c198b2915a66ea9d32fae0fa091 | sree-07/PYTHON | /type_casting_convertion.py | 1,113 | 4.46875 | 4 | """int--->float,string"""
# a=7
# print(a,type(a)) #7 <class 'int'>
# b=float(a)
# print(b,type(b)) #7.0 <class 'float'>
# c=str(b)
# print(c,type(c)) #7.0 <class 'str'>
# x=10
# print("the value of x is",x) #the value of x is 10
# print("the value of x is %d"%x) #the value of x is 10
# z=s... |
2127d708907ad975ca11a7ae89276e035dc84341 | bilakhiyaasif/SoloLearn_Project | /Python/C-46 Fibonacci series/Solution.py | 283 | 3.875 | 4 | #Fibonacci series
#Recursive Approach
#enter n any number
#like comment
def recu(x1,x2,n):
if n!=0:
z=x1+x2
print(z,end="\n")
x1=x2
x2=z
return recu(x1,x2,n-1)
n=int(input())
x1=0
x2=1
print(x1,end="\n")
print(x2, end="\n")
recu(x1,x2,n-2)
|
212723fd86585c17d19b8b4579e19b8f4d038a49 | mariantirlea/python-blackjack | /utilities/Line.py | 1,893 | 3.859375 | 4 | import re
from abc import ABC, abstractmethod
from colors import strip_color
class Line(ABC):
center_h = False
def __init__(self):
super().__init__()
def center(self, columns, text):
return text.rjust(int((columns - len(text)) / 2) + len(text))
@abstractmethod
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.