blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
36d93f0fedf6713171282e63316e4dd38e09d80e | Amdude/RandomPasswordGenerator | /RandomPasswordGenerator.py | 1,555 | 4.5 | 4 | from random import randint
import string
all_characters = [] # set up this array to hold our letters and special characters
special_characters = ['!', '@', '#', '$', '%', '^', '&', '*'] # array of special characters
password = [] # our array that will be used to store out password
def combine_chars():
for cha... |
f5745ffd80db2c13fc6dd173d41ae4293c4c9e22 | NEUAI/testchain | /testchain/incentive/wallet.py | 460 | 3.65625 | 4 | """ wallet.py
This file defines the structure and methods of class Wallet.
"""
__all__ = ["Wallet"]
__version__ = '1.0'
__author__ = 'Zhengpeng Ai'
class Wallet:
def __init__(self, coin: float = 0.0):
self.coin = coin
return
def get_coin(self):
return self.coin
def add_coin(se... |
61b1db8d7e151957d4e4faf470f41583c78e719c | S-Philp/LearningPython | /EvenOdd.py | 117 | 4.09375 | 4 | number = input("Type a number: ")
user_num = int(number)
if user_num%2==0:
print("even")
else:
print("odd")
|
b85ffbbc411490b508f4ad212c32852d48891acc | norahpack/carbonEmissions | /cs5png3.py | 3,190 | 3.515625 | 4 | import os
import sys
from PIL import Image
import time
def saveRGB(boxed_pixels, filename = "out.png"):
"""Save the given pixel array in the chosen file as an image."""
print(f'Starting to save {filename}...', end = '')
w, h = getWH(boxed_pixels)
im = Image.new("RGB", (w, h), "black")
px = im.load(... |
652cbe57599fee3423707998e98ea9a9fff30c7f | edu-athensoft/ceit4101python_student | /ceit_190910_zhuhaotian/py0923/datatype_number.py | 281 | 3.71875 | 4 | # datatype
# type()
a = 5
print(a, type(a))
b = 1.5
print(b, type(b))
c = True
print(c, type(c))
d = 'my name'
print(d, type(d))
# isinstance()
print(isinstance(a, int))
# accuracy of float
f1 = 0.1234567890123456789
print(f1)
f1 = 0.1234567890123456789012345678
print(f1)
|
5a653bdc1ce652e9ec0de67b3d3626f9396cfc38 | Redmar-van-den-Berg/newick_utils | /src/toy.py | 868 | 3.625 | 4 | #!/usr/bin/env python
import sys
from newick_utils import *
def count_polytomies(tree):
count = 0
for node in tree.get_nodes():
if node.children_count() > 2:
count += 1
return count
# Main
def main():
if len(sys.argv) < 2:
raise RuntimeError ("Usage: toy.py <-|filename>")
filename = ''
if sys.argv[1]... |
073f9272bbe3c5b4fdbfed1b575d2d1fb76d44a8 | residoo/project_euler | /archive/euler004.py | 1,300 | 3.96875 | 4 | # euler004.py
# https://projecteuler.net/problem=4
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
# From 999 to 100, and from 999 to 100....
# IMP... |
67e413eadd6433897b6ebf50eb5068315dbb7f9c | a-yildiz/ROS-Simple-Sample-Packages | /pyqt5_fundamentals/window8_QSpinBox.py | 1,064 | 3.546875 | 4 | #!/usr/bin/env python3
from PyQt5 import QtWidgets
import sys
"""
QSpinBox: Creates a textbox with increment buttons for numbers.
"""
def create_window():
# Define window:
obj = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
# Set window attributes:
window.setWindowTitle("My ... |
fb688cb1ff85bdbf9fabc24719ff0ea96c8cbebe | sbrandom/DataStructuresAndAlgorithms | /ch3-find-duplicate.py | 1,091 | 3.921875 | 4 | def has_duplicate_quadratic(list):
num_steps = 0
for i in range(len(list)):
for j in range(len(list)):
num_steps += 1
if i != j and list[i] == list[j]:
return [True, num_steps]
return [False, num_steps]
def has_duplicates_linear(list):
num_steps = 0
... |
486183f0ffe8aeb96e74d4a465a68b95f37e7085 | sicsempatyrannis/Credit-Suisse-Hackathon | /Question8.py | 832 | 3.6875 | 4 | # Participants may update the following function parameters
def countNumberOfWays(numOfUnits, numOfCoinTypes, coins):
# Participants code will be here
dp = [1] + [0]*numOfUnits
for coin in coins:
for i in range(coin, numOfUnits+1):
dp[i] += dp[i-coin]
retur... |
08deea2444709ddc59f09cfdf9996edc44b1cab2 | Vaitesh/ZipFileFinder | /Zip_file_finder.py | 193 | 4.0625 | 4 | #Listing the files/folders present in zipfile
from zipfile import Zipfile
file_name = input('Please enter the folder/file name: ')
with Zipfile(file_name, 'r') as zip:
zip.printdir()
|
23598ff071943aa907704e0e10bc5b14e3fbe419 | verisimilitude20201/dsa | /Tree/Binary Search Tree/algorithms/inorder_successor.py | 798 | 3.734375 | 4 | """
Problem
------
Find the in-order successor of a node in a Binary search tree
1. If p has a right sub-tree, its in order sucessor is the left most node of the right-subtree
2. If p does not have a right sub-tree, its in order successor is the ancestor that contains p in its left subtree
Complexity
----------
Time:... |
70b8c64148e13a932ca61ff4124aeea21d242632 | zuigehulu/AID1811 | /pbase/day02/jiangyi/day02/exercise/2numbers.py | 556 | 3.90625 | 4 | # 练习:
# 输入两个整数,分别用变量 x, y 绑定
# 1. 计算这两个数的和并打印结果
# 2. 计算这两个数的积,并打印结果
# 3. 计算 x 的 y次方并打印
# 如:
# 请输入 x: 100
# 请输入 y: 200
# 打印如下:
# 100 + 200 = 300
# 100 * 200 = 20000
# 100 ** 200 = 1000000.....
s = input("请输入 x: ") # 得到的是字符串
x = int(s) # 转为整数
y = int(input("请输入 y: "))
print(x, '+... |
88cb545d426984720c1b4878ad9b0ce5c1ceb565 | 610yilingliu/leetcode | /Python3/536.construct-binary-tree-from-string.py | 1,218 | 3.671875 | 4 | #
# @lc app=leetcode id=536 lang=python3
#
# [536] Construct Binary Tree from String
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def str2tree(... |
611383d0a30acdb4f0b6d11784c3ff2301c3ebab | Paulinakhew/project_euler_solns | /2_even_fibonacci_numbers.py | 682 | 3.90625 | 4 | #!/bin/python3
import sys
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
#assign values to the first two numbers in the sequence
num1 = 1
num2 = 1
sum = 0
# x is a placeholder that is used to represent the next number in the sequence
x = 0
while x <= n:
... |
39f66dd9587235dd4ea11d0b3a445517d355c5d9 | Baron197/Fundamental_Python_DS_4 | /meanMedianModus.py | 1,231 | 3.71875 | 4 | from math import floor
x = [ 1,2,3,2,5,2,7,2 ]
# function mean
def getMean(list) :
sum = 0
for item in list :
sum += item
mean = sum / len(list)
return mean
print(getMean(x))
# function median
def getMedian(list) :
list.sort()
median = 0
if (len(list) % 2 != 0) :
median = ... |
54b8d4b935706ef4d002d867cbae49cabd913802 | Python-Repository-Hub/image_processing_with_python | /01_pillow_basics/save_image_with_new_dpi.py | 339 | 3.546875 | 4 | # save_image_with_new_dpi.py
import pathlib
from PIL import Image
def image_converter(input_file_path, output_file_path, dpi):
image = Image.open(input_file_path)
image.save(output_file_path, dpi=dpi)
if __name__ == "__main__":
image_converter("blue_flowers.jpg", "blue_flowers_dpi.jpg",
... |
a37153363ffde178fc657284447ed4c3d2de06a0 | Splinter0/HelloWorld | /queue/nodeQueue.py | 1,077 | 3.796875 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedQ(object):
def __init__(self):
self.first = None
self.last = None
def enqueue(self, value):
n = Node(value)
if self.first == None:
self.first = n
... |
5e3a61031a1dbad713f9631f8e1b864af3126831 | rinleit/hackerrank-solutions | /Interview Preparation Kit/Recursion and Backtracking/Recursion: Fibonacci Numbers/solutions.py | 161 | 4 | 4 | def fibonacci(n):
prev, next = 0, 1
for _ in range(2, n + 1):
next, prev = prev + next, next
return next
n = int(input())
print(fibonacci(n)) |
2c9194997d3def052890d080174a929bff7704d5 | muminurrahman/PythonExercises | /adjacentElementsProduct.py | 283 | 3.921875 | 4 | def adjacentElementsProduct(*nums):
largest = nums[0] * nums[1];
for i in range(1, len(nums) - 1):
product = nums[i] * nums[i + 1];
if product > largest: largest = product;
return largest;
print(adjacentElementsProduct(3, 6, -2, -5, 7, 3))
|
a07af7c39d9d18070f97983e3f5409fddc9987b6 | prem-banker/Hackerrank-Questions | /encryption.py | 422 | 3.625 | 4 | import math
string = raw_input()
rows = math.floor(math.sqrt(len(string)))
columns = math.ceil(math.sqrt(len(string)))
encrypt = []
for i in range(int(rows)+1):
encrypt.append("")
for i in range(int(rows)+1):
for j in range(len(string)):
if i == j%columns:
encrypt[i]+=s... |
a6626827bb23d5dbb3757f959a15a7f752653b94 | GiacomoManzoli/SudokuGenerator | /search/astar_search.py | 3,111 | 3.84375 | 4 |
from search import Problem, Node
from util import PriorityQueue
class AStarSearch(object):
def __memoize(self, fn, slot=None):
"""Memoize fn: make it remember the computed value for any argument list.
If slot is specified, store result in that slot of first argument.
If slot is false, sto... |
17166f2deed8fe8e1b0527d65a569150d69f0a47 | z-sector/algo | /05/sorting/init.py | 537 | 3.671875 | 4 | import argparse
def init_argparse() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Sorting array")
parser.add_argument("len", type=int, help="Length array N >= 0")
parser.add_argument("array", type=str, help="Array like 1,2,3,4,5")
return parser
def get_array():
parser... |
537059932cb0f1a4e0e51a2cd949cac28a67065a | crudalex/microsoft-r | /leetcode/Accepted/Implement_strStr.py | 443 | 3.5 | 4 | class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
try:
index = haystack.index(needle)
except ValueError:
index = -1
return... |
289786549752464777b58ec7349bb0fa0e00449e | Ekaterina01703/dz.python | /z4/matrix8.py | 375 | 3.734375 | 4 | #Matrix8
import random
import numpy
A = random.randrange(2,6)
M = random.randrange(2,6)
K = random.randrange(0,M)
print("A = ",A,"; M = ",M,"; K = ",K)
a = numpy.zeros((A, M))
for i in range(A):
for j in range(M):
a[i][j] = random.randrange(-5,5)
print(a)
print("Столбец ",K,": ")
for i in r... |
a5e727e115ca467d1faa1bc0cb1c02614bb84813 | aungnyeinchan351/Searching_algorithms | /JumpSearch.py | 554 | 4 | 4 | def JumpSearch(list1, val):
import math
gap = math.sqrt(len(list1))
left = 0
while(list1[int(min(gap, len(list1))-1)]<val):
left = gap
gap = gap + math.sqrt(len(list1))
if(left>=len(list1)):
break
while(list1[int(left)]<val):
left =left + 1
if(left... |
908ba7770e6aeaad0119f4dd4061a2ecd7805893 | zasdaym/daily-coding-problem | /problem-076/solution.py | 800 | 3.671875 | 4 | from typing import List, Set
def min_col_to_delete(matrix: List[str]) -> int:
# edge case
if not matrix:
return 0
col_to_delete = 0
row_len, col_len = len(matrix), len(matrix[0])
# check every col for unordered letters.
for j in range(0, col_len):
largest = matrix[0][j]
... |
b951f970887181fe8333a44ec6e4fe7a448eefea | fuckgitb/Python-1 | /projects/Thread/demo01.py | 941 | 4 | 4 |
import time
import threading
# 传统的写法
# def coding():
# for x in range(3):
# print('正在写代码%s'%x)
# time.sleep(1)
#
#
# def drawing():
# for x in range(3):
# print('正在画图%s' % x)
# time.sleep(1)
# 多线程的写法
def coding():
for x in range(3):
print('正在写代... |
2a2502917784eea402234cdb0b8fd448625e049f | supramolecular-toolkit/stk | /src/stk/ea/fitness_calculators/property_vector.py | 9,814 | 3.546875 | 4 | """
Property Vector
===============
"""
from .fitness_calculator import FitnessCalculator
class PropertyVector(FitnessCalculator):
"""
Uses multiple molecular properties as a fitness value.
Examples
--------
*Calculating Fitness Values*
.. testcode:: calculating-fitness-values
imp... |
293e0c1bbf6760ef7bc6ef8dd9ff2b7bd35ca292 | github-felipe/ExerciciosEmPython-cursoemvideo | /PythonExercicios/ex038.py | 267 | 3.875 | 4 | n = str(input('Digite dois números: ')).strip()
n = n.split()
n1 = int(n[0])
n2 = int(n[1])
if n1 > n2:
print('O PRIMEIRO número é maior')
elif n2 > n1:
print('O SEGUNDO número é maior')
else:
print('Não existe número maior, os dois são iguais!')
|
ac14452ddf91492ed3177d3f1cc386b2d1146aea | hajmat02/prog1-ovn | /kap2/upg2.7.py | 366 | 3.859375 | 4 | import math #gör så att man kan skriva mattematiska saker på ett enkelt sätt
#ett program som räknar ut en cirkels area och omkrets
svar = input ('Cirkelns radie:')
r = float(svar)
a = r*r * math.pi #räknar ut arean på cirkeln
b = (r+r) * math.pi #räknar ut omkretsen på cirkeln
print(f'Cirkelns area är:{a:.3f}')
pr... |
08b859351687fe3a43a617ed61438ed6e95aa5d0 | bm5w/sea-f2-python-sept14 | /Students/JakeAnderson/session02/series.py | 848 | 4.0625 | 4 | # coding: utf-8
#series program
""" runs the Fibonacci series """
def Fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return Fibonacci(n - 1) + Fibonacci(n - 2)
""" runs the Lucas series """
def Lucas(n):
if n <= 0:
return 0
elif n == 1:
return 2
elif n == 2:
return 1
else:
return L... |
915abf0266e543f202b41af751e0879201be1326 | Kirkirillka/network_aggregator | /utils.py | 3,337 | 3.5625 | 4 | import re
import ipaddress
def validate_net_data(net_data):
"""
# A function to check if supplied net_data meets model's requirement. Thus net_data must be a dict with
specified fields
Examples of net_data:
net_data1 = {
"value": "192.168.34.4",
"type":... |
8eb9e9de2a571d1f98b23ee1596343abb28acb2b | Adi-Levy/TechAVSFControl | /pure_pursuit/controller.py | 3,685 | 3.5625 | 4 | import math
import numpy as np
class PurePursuitController:
"""
this a class to define a controller object of a pure pursuite controller
the controller gets
the current state of the car(x,y coordinates, velocity and current angle),
the currnet path that the car shou... |
91c070223352202f5383aa87a832c367040a6dbc | markkorenic/mayaTools | /Maya/System/Example.py | 2,481 | 4.6875 | 5 | """
Comments are used to provide descriptions or notes
in your code.
You can make large blocks of comments by surrounding your text
in sets of 3 quotation marks.
"""
# You can also use the pound sign.
"""
A Variable is used to store data.
In this case 'h' is the varaible to which
we assign the value of the string 'H... |
0740c99ca584a935b919081e1238b2acc780d74c | PeshrawSarwar/GIZ-pass-python | /python-pass.py | 1,065 | 3.765625 | 4 |
class Solution(object):
@staticmethod
def longest_palindromic(s: str):
# Square Matrix - length = length of the string [False]
matrix = [[False for i in range(len(s))] for i in range(len(s))]
for i in range(len(s)):
# major diagonal elements = True
matrix[i... |
e0673e5ac586c1d357a14a36818e6058f7926529 | nobodyh/Project-Euler | /6. Sum Square Difference.py | 304 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 30 14:14:26 2021
@author: Hayagreev
"""
import numpy as np
n=int(input("Enter the limit:"))
result = np.subtract(np.power(np.divide(np.multiply(n,n+1),2),2),np.divide(np.multiply(n,np.multiply(n+1,2*n+1)),6))
print("Result: ",result)
|
73f2e36f7df9365c97bd4dec5357320ef69de894 | hoyeonkim795/solving | /swexpert/LinkedList_again.py | 2,856 | 3.765625 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
def __repr__(self):
return str(self.data)
class linkedlist:
def __init__(self, *args):
self.length = 0
if args:
for i in range(len(args)):
if i == 0:
... |
45c71efc6be8ff112b3ccd969b1e40a3f4318873 | yeeyoung/CS-590-Data-Engineering-II | /hw1/solution.py | 3,064 | 3.765625 | 4 | #!/Users/yeeyoung/anaconda/bin/python
import sqlite3
import csv
# Open connection to the SQLite database file
con = sqlite3.connect("air.db")
# Create a cursor that will return an instance of the database for data set traversal
cur = con.cursor()
# Read the csv file and begin parsing it
with open('flights.csv', 'r') a... |
2e183afcfa1bceb67cb16a5f6c0593fda7114e55 | DaCanneAPeche/crypto-coins | /cryppy_coins/__init__.py | 1,735 | 3.5 | 4 | # import request and json for use API
import requests
import json
# url start
basic_api_url = 'https://api.coincap.io/v2'
# function for get data of a request
def return_data(end_url='/assets'):
data = requests.get(f'{basic_api_url}{end_url}')
return json.loads(data.text)
# get the 100 more expensive cryp... |
820212a00edd69a141ca27509de6dee7dc57e9d8 | joyonto51/Basic-Algorithm | /find_the_factorial.py | 105 | 3.734375 | 4 | n = int(input())
factorial = 1
i = 1
while(i<=n):
factorial = factorial*i
i+=1
print(factorial) |
9c778ef6d160d097301e31a55b9fe3ba719e0985 | paul-hohle/Python | /Python-Book/map.py | 900 | 3.890625 | 4 | #!/usr/bin/env python
#*********************************************************************
dict = {}
dict['meat'] = 'carne'
dict['arroz'] = 'rice'
dict['frijoles'] = 'beans'
dict['aqua'] = 'water'
print dict
nested = {'name' : { 'first' : 'bob', 'last' : 'smith'},
'jobs' : [ 'dev' , 'manager' ],
... |
0bedbab2222153cfa802fa18319ae48282a417db | captainjack331089/Automate-Boring-Stuff-with-Python | /Python Programming/Practice/list_dictionary_practice.py | 1,569 | 4 | 4 | """
List to Dictionary Function for Fantasy Game Inventory
Imagine that a vanquished dragon’s loot is represented as a list of strings like this:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
Write a function named addToInventory(inventory, addedItems), where the inventory parameter is a dictio... |
fcccf0005a388eea2c33a55460b49bcec790fe05 | uestcwm/search | /Sort/countsort.py | 801 | 3.5 | 4 | #! /usr/bin/env python
#coding=utf-8
'''
桶排序
复杂度O(n)
'''
def countsort( A, d ): #A待排数组, d位数 如果位置需要先修改一下知道A中最多位数
for k in range(d): #k轮排序
s[ [] for i in range(10) ] #数字0~9,建10个桶
'''对于数组中的元素,首先按照最低有效数字进行
排序,然后由低位向高位进行'''
for i in A:
s[ i//(10**k)%10 ].append(i)
... |
0d9ea89f66cb678dbdecd81ac92bc5134a61959f | pawelbicz/exercism | /python/pangram/pangram_old.py | 690 | 3.6875 | 4 | import string as s
def is_pangram(sentence):
text = remove_punctuation(sentence)
dictionary = create_dictionary()
dictionary = assert_letters_in_sentence(text, dictionary)
return verify_dictionary(dictionary)
def remove_punctuation(text):
result = ''
for i in text:
if i not in s.pun... |
76e05d14bcb2d044ab3807fdccb5579b5423aef6 | chrisjdavie/interview_practice | /leetcode/search_in_rotated_sorted_array/doubling_index.py | 2,236 | 3.703125 | 4 | # https://leetcode.com/problems/search-in-rotated-sorted-array/
"""
First result, not sure why I did it like this, doubling indicies until I found the right
one. Looking at other answers, the much more common way was starting from left and right
and halving.
Also a lot quicker than mine, which is interesting. I *know*... |
4da29ccbabaef071935aa7f2824a2d9ee2c96f12 | ShoYamanishi/PersonNamesTransliterator | /utils/character_converters.py | 8,330 | 4.03125 | 4 | # some string contain hard-to-find diacritical marks as
# independent characters.
# It is difficult to clean strings that contain such marks.
# In those cases, we just remove them from the training set.
def is_bad_word_alpha( word ):
for c in word:
# U+0300 - U+036F combining diacritical marks.
if 7... |
189b6d80031e26bb4ffde12a39baf861cb82c536 | amakridin/py_learn | /lesson2/2.py | 917 | 4.1875 | 4 | # 2. Для списка реализовать обмен значений соседних элементов, т.е.
# Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
lst = []
while True:
elem = inpu... |
2c68ed20901619c93032ec3824e1fd592cd2df9e | swhh/python_project | /problem_3.py | 1,640 | 3.640625 | 4 | import random
from sys import argv, exit
from collections import namedtuple, defaultdict
Graph = namedtuple('Graph', ['V', 'E'])
def random_contraction_algorithm(graph):
n = len(graph.V)
new_graph = graph
while n > 2:
edge = random_select(new_graph)
new_graph = merge(graph, edge)
... |
17cda7a4d78c1b3e0da8b22624a1f3244029c8d9 | edwu/Project-Euler | /euler5.py | 270 | 3.59375 | 4 | def diviser(n):
i = 1
while i<=20:
if n % i != 0:
return False
i+=1
return True
def smallest():
i=1
while (1):
if diviser(i):
return i
i+=1
return "Never Reaches Here"
k=smallest()
print k
|
c978d5114b3b2a73de285ded430cd87d18915b31 | algoitssm/algorithm_taeyeon | /Baekjoon/1991_tree_트리순회.py | 974 | 3.765625 | 4 | N = int(input())
tree = {}
for i in range(N):
root, left, right = input().split()
tree[root] = [left, right]
# print(tree) A B C = > {'A': ['B', 'C']}
# 전위 순회 : 루트/왼쪽/오른쪽
def preorder(root):
if root != ".": # 값이 존재하는 경우
left = tree[root][0]
right = tree[root][1]
print(root, end... |
d70dd71e871055c1e30f8925d9ab15768f4bbbbf | Singularmotor/test_project | /test.py | 99 | 3.828125 | 4 | #coding utf-8
print("please type in a number which less than 10")
n=int(input)
print("%d"%(a/10))
|
4cff20c39f4e07e1eab7732e2215b864bbd086a8 | hosjiu1702/Programming_Problems | /leetcode/problems/p414/main.py | 594 | 3.765625 | 4 | import sys
class Solution:
def thirdMax(self, nums) -> int:
""" Sorting """
nums.sort()
count = 0
i = len(nums) - 1
while i - 1 >= 0:
if nums[i - 1] < nums[i]:
count = count + 1
if count == 2:
return n... |
ca48b15e7349230cb1f1a05a354efcb01dcc8c6e | biefeng/Exercise | /algorithm/main.py | 552 | 3.515625 | 4 | # -*- coding: utf-8 -*-
from random import Random
from algorithm.sort import qucik_sort, merge_sort
__author__ = '33504'
if __name__ == "__main__":
arr = [Random().randint(0, 20) for x in range(20)]
arr=[4, 4, 13, 19, 12, 8, 11, 10, 8, 18, 13, 2, 8, 20, 4, 6, 7, 16, 7, 5]
print(arr)
print('******************sort ... |
9873bbfd53b603b5c5712e8dfd0b71ede078d846 | syedaali/python | /coderb/exercises/matrix.py | 249 | 4.15625 | 4 | '''
Write a python program that prints a 12x12 multiplication table matrix.
'''
for i in xrange(1,12):
for j in xrange(1,12):
print i,j
for row in range(1,12):
for col in range(1,n+1):
print(row*col, end="\t")
print()
|
ed17db17440d0cb6eff06170ca6c63c7a3b2a547 | vaquierm/RedditCommentTextClassification | /src/models/Model.py | 1,197 | 3.578125 | 4 | class Model:
def __init__(self):
self.trained = False
self.M = None
def fit(self, X, Y):
"""
Fit the model with the training data
:param X: Inputs
:param Y: Label associated to inputs
:return: None
"""
self.trained = True
self.M =... |
57b2e5c1bc218822e9a042d525e4d1fb270c51cb | mkieft/Computing | /Python/Week 5/lab 5 q 13.py | 519 | 3.765625 | 4 | #Lab 5 Q 13
#Maura Kieft
#9/29/2016
#13. Two friends (Alice and Bob) are playing a game where they roll two dice
import random
def main():
a=random.randrange(1,7)
a1=random.randrange(1,7)
a2=a+a1
print("Alice dice roll: ",a2)
b=random.randrange(1,7)
b1=random.randrange(1,7)
b2=b+b1
prin... |
2787ed5f4c5faa887d698e51e329111010359bf3 | oudin-clement/Mini-projet1 | /justeprix.py | 239 | 3.53125 | 4 | from random import*
n=randint(1,100)
reponse=""
essai=0
while reponse!=n:
reponse=int(input("->"))
if reponse > n:
print("trop grand!")
else:
print("trop petit!")
essai+=1
print("gagné en ",essai," coups") |
b5cb583bcfefcd48a137ef6974f6f466e61f78f9 | Ghostkeeper/MetaProgrammingWorkshop | /m2properties.py | 1,005 | 3.75 | 4 | class Printer:
def __init__(self, extruders, price, has_misp):
self.extruders = extruders
self.price = price
self.has_misp = has_misp
@property
def extruders(self):
print("Get extruders")
return self._extruders
@extruders.setter
def extruders(self, value):
if not isinstance(value, int):
raise Type... |
adc886d69bc57e080f0a5937233cc4d9285f950f | SilverXuz/TextBasedPythonGame | /Game.py | 4,449 | 3.765625 | 4 | import random as r
hp = 0
coins = 0
damage = 0
def printParameters():
print("У тебя {0} жизней, {1} урона и {2} монет.".format(hp, damage, coins))
def printHp():
print("У тебя", hp, "жизней.")
def printCoins():
print("У тебя", coins, "монет.")
def printDamage():
print("У тебя", dama... |
3a74f5928a15ea1410c95bedc8951e0478cfdaa5 | leetuckert10/CrashCourse | /chapter_9/exercise_9-4.py | 621 | 3.53125 | 4 | # Exercise 9-4: Number Served
# This version of Restaurant from 9-1 explorers a new attribute added to the
# the Restaurant class.
import restaurant as r
restaurant = r.Restaurant("Billy Bob's Grill", "American")
restaurant.set_number_served(28_952)
restaurant.describe_restaurant()
restaurant.open_restaurant()
# Se... |
295fb94878473164a468b154bf7af68bed2f5acc | dvir200/Data_Structures_and_Algorithms | /Queues and Stacks/basic_queue.py | 246 | 3.703125 | 4 |
""" Queue - First in, First out """
queue = []
queue.append("data1")
queue.append("data2")
queue.append("data3")
queue.append(5)
print(queue)
""" deleting data1 """
queue.pop(0)
print(queue)
""" deleting data2 """
queue.pop(0)
print(queue) |
e07f6990bef7be5b19a18897481acd73dee93067 | Warriorchief/matrixSubcount | /submatrixcount.py | 794 | 4.03125 | 4 | """
Given a rectangular matrix containing only digits, calculate the number of different 2 × 2 squares in it.
Example
For
matrix = [[1, 2, 1],
[2, 2, 2],
[2, 2, 2],
[1, 2, 3],
[2, 2, 1]]
the output should be
differentSquares(matrix) = 6
"""
def differentSquares(matrix):
w... |
be4b8fde0e3d38db5b66dbfe65147610ea648039 | mennanov/problem-sets | /other/strings/anagram_check.py | 1,101 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Given two strings check whether one string is a permutation of the other (anagram).
"""
from collections import Counter
def anagram_sort(string1, string2):
"""
Simple and straightforward solution: sort both strings and check them for equality.
Running time is O(NLogN), space c... |
6045c81a5f3d67148c0be9e9434881a849b43f2f | InjiChoi/algorithm_study | /재귀함수/1901.py | 151 | 3.703125 | 4 | # 1부터 n까지 출력하기
num = int(input())
def recursion_print(n):
if n!=1:
recursion_print(n-1)
print(n)
recursion_print(num) |
24da817d798c5aa56d839f0639d6225ff33b680f | PedroVitor1995/Uri | /Iniciantes/Questao1117.py | 296 | 3.53125 | 4 | def main():
qtd = 0
soma = 0
media = 0
while True:
nota = input('')
if nota > 0 and nota <= 10:
soma += nota
qtd += 1
else:
print('nota invalida')
media = soma / 2.0
if qtd == 2:
print('media = %.2f') % media
break
if __name__ == '__main__':
main() |
6958b0124c3e1fb84f88b8a84ea3b403ea8656f4 | Choirong/Automated-Program-Repair | /src/is_prime.py | 180 | 3.84375 | 4 | def is_prime(number):
if number < 0:
return True
if number in (0, 1):
return False
for element in range(2, number):
if number % element == 0:
return False
return True
|
8380d5ffe10e459c08b0952bca82e6ee93893a56 | Robert-Rutherford/learning-Python | /practiceProblems/BeginningAndEndPairs.py | 1,019 | 3.890625 | 4 | # Beginning and End Pairs
# site: https://edabit.com/challenge/HrCuzAKE6skEYgDmf
# Write a function that pairs the first number in an array with the last, the second number with the second to last,
# etc.
# notes:
# If the list has an odd length, repeat the middle element twice for the last pair.
# Return an empty list... |
fe57c20a41de8502c562123e6711f983d2b8406d | falkecarlsen/restful-web-service-py | /web-service.py | 4,455 | 3.6875 | 4 | import socket
import threading
import http
PRINT_LOCK = threading.Lock()
HOST = ("localhost", 8002)
DATA = dict(first="42")
def thread_print(arg):
with PRINT_LOCK:
print(arg)
def http_response(code, body) -> bytes:
"""
Constructs a HTTP response from a given code and body
:param code: the H... |
cd6de2b359b60cdd62f8269c273e16277c2f25ae | Lzffancy/Aid_study | /fancy_month02/draft_box/famliy_across_bridge.py | 452 | 3.828125 | 4 | """
小明过桥
"""
class FamilyBridge():
family = {
'p1s':1,
'p3s':3,
'p6s':6,
'p8s':8,
'p12s':12,
}
def __init__(self):
self.totall_time = 0
def across_time(self,x,y):
one_time = x + y
self.totall_time... |
9c446ab5a732358c46553c959cf73015042c3c47 | xiaolongjia/techTrees | /Python/00_Code Interview/AlgoExpert/Category/LinkedList_M_001_Construction.py | 5,474 | 4.5 | 4 | #!C:\Python\Python
#coding=utf-8
'''
Linked List Construction
Write a DoublyLinkedList class that has a head and a tail. both of which point to
either a linked list Node or None/Null. The class should support:
- Setting the head and tail of the linked list.
- Inserting nodes before and after other nodes as well as... |
0442c676af133a26717476948df3442218d7014e | JasonYRChen/DataStructures_codes | /ch8/tree/Tree/Tree.py | 2,035 | 4.15625 | 4 | import abc
class Tree(abc.ABC):
@abc.abstractmethod
def __len__(self):
"""Total node numbers"""
def __repr__(self):
return f"{self.__class__.__name__}(node_numbers: {len(self)})"
@abc.abstractmethod
def root(self):
"""Return root node"""
def is_root(self, node):
... |
c069ae0d12c705d91c52e78cbea8e001acd537c5 | paetztm/python-playground | /python-beyond-the-basics/comprehensions/google_chess.py | 4,527 | 3.546875 | 4 | import math
GRID_SIZE = 100
class Grid:
def __init__(self, rows, columns):
pass
class Point:
def __init__(self, row, column):
self.row = row
self.column = column
@staticmethod
def is_valid_point(row, column):
return 0 <= row < GRID_SIZE and 0 <= column < GRID_SIZE
... |
fa13c3dbfe728b47e92121c0e8d383660b826d13 | SmischenkoB/campus_2018_python | /Oleksandr_Kotov/10/game_package_okotov/game_package_okotov/creature.py | 1,184 | 3.890625 | 4 |
import decorators
class Creature:
"""defines basic live game creature
"""
@decorators.debug_decorator
def __init__(self, row=0, col=0, health=0):
"""init object with position
Keyword Arguments:
row {int} -- row on game map (default: {0})
col {int} -- column ... |
088a82a140362a0cfe369ddb1fd9d161fc2a83f0 | Buzz627/AdventOfCode | /2016/day8/puzzle.py | 1,332 | 3.59375 | 4 | def countCells(mat):
count=0
for row in mat:
for cell in row:
if cell=="#":
count+=1
return count
def makeRect(mat, row, col):
for i in range(row):
for j in range(col):
mat[j][i]="#"
def rotateCol(mat, col, num):
if num==0:
return
temp=mat[len(mat)-1][col]
for i in range(len(mat)-1, 0, -1):
m... |
dab97c24f66d8719a0319e45b900e7241bea38a0 | PavlikSweetheard/GB | /hw_les_1/exercise_6_les_1.py | 1,229 | 3.875 | 4 | # 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил "a" километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров.
# Программа должна принимать знач... |
a4c45098e3ce85878c92dda4615441e861762315 | MisterCruz/CSC148Notes | /recursionJan27.py | 277 | 3.703125 | 4 | def codes(r):
'''(int)->list of str
Return all binary codes of length r
'''
if r == 0:
return ['']
small = codes(r-1)
lst = []
for item in small:
lst.append('0' + item)
lst.append('1' + item)
return lst
print(codes(2))
|
fe4f821766004453b8b34e91b0acc9125a0005c2 | jiyoungkimcr/Python_Summer_2021_2 | /HW3_Stock data.py | 1,223 | 3.75 | 4 | '''
Write a program that searches for CSV files with stock rates in a given folder and for every one of them:
Calculates the percentage change between Close and Open price and adds these values as another column to this CSV file.
Code writer: Jiyoung Kim
'''
import os
import csv
from pip._vendor.distlib.compat import ... |
b3a63dfadc365724ee0b073ef3350f813ab9e9c8 | lalwanigunjan/Parking_Data_Analysis | /amount_due_per_licence/reduce.py | 2,188 | 3.6875 | 4 | #!/usr/bin/env python
"""s
The algorithm simply considers each licence type
as key and add +1 to count and the amount value
to current amount for the current key.
It averages by divding amount/count and outputs it.
"""
from operator import itemgetter
import sys
current_licence_type = None
current_co... |
5540c1a1091789bca7a573fd1b8a0f9283e46d64 | kristiyankisimov/HackBulgaria-Programming101 | /week0/is-an-bn/solution.py | 348 | 3.78125 | 4 | def is_an_bn(word):
if len(word) % 2 == 1:
return False
else:
first = word[:len(word)//2]
second = word[len(word)//2+1:]
is_true_first = all(map(lambda x: True if x == 'a' else False, first))
is_true_second = all(map(lambda x: True if x == 'b' else False, second))
return is_t... |
23f88075ffa4d482af5ad3e9370ffef77925902f | youyuebingchen/Algorithms | /paixusuanfa/quicksort.py | 584 | 3.796875 | 4 | def QuickSort(alist):
qsort_rec(alist,0,len(alist)-1)
return alist
def qsort_rec(alist,l,r):
if l > r:
return
i = l
j = r
mid = alist[i]
while i < j :
while i < j and alist[j] >= mid:
j -= 1
if i < j:
alist[i] = alist[j]
i += 1
... |
36c7b8b32bc16cb216969c51d14a4dd1255f712a | sjbarag/CS260-Programming-Assignments | /pa1/p4-2.py | 6,367 | 4 | 4 | # Leftmost Child/Right Sibling implementation of Trees
# Node class - each object of class node is a node a tree
# @param label label of the node (1, 2, 3, ...)
# @param lc left child of the node
# @param rs right sibling of the node
# @param parent the node's parent
class node :
# constructor
def __init__(self) ... |
a2487afcfa31ef00d3399ff10830ddf7bd1938b4 | baketbek/AlgorithmPractice | /LinkList/2. Add Two Numbers.py | 1,103 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#这个解题的思路是 用temp来记录进位用于下一轮循环
#每对结点相加的时候立刻创建对应结果结点 处理进位
#一开始超时了 那是因为忘了大家一起next 还是要在脑子里有个动画
#后来报错说none没有next属性 所以给l1=l1.next搞了个条件
#说了这么多其实还是。。题解区nb
class Solution:
def addTwoNumbers(sel... |
0890b32420983d05e089bde118c868195ba03b97 | msansome/Challenges | /06 - Max Min2.py | 5,118 | 4.375 | 4 | '''
OCR 20 Coding Challenges
06 Max and min list
===================
Version 2 - With Extension tasks
Mark Sansome September 2019
Max and min list
Write a program that lets the user input a list of numbers. Every time they
input a new number, the program should give a message about what the maximum and ... |
0cd36cf5389664cdf1d81c790d667eb68f83aeb8 | BansiddhaBirajdar/python | /assignment08/ass8Q2.py | 453 | 3.90625 | 4 | '''2. Accept single digit number from user and print it into word.
Input : 9
Output : Nine
Input : -3
Output : Three
Input : 12
Output : Invalid Number'''
def Dis(ino):
no={0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine'}
if(ino<0):
ino=-ino
else:
pr... |
90b2f3c3ff4ba0384027cd9ea7e124f4049bd4e6 | JoshuaSamuelTheCoder/Quarantine | /Missing_Number/main.py | 1,110 | 3.875 | 4 | """
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Example 3:
Input: [1, 2, 4, 6, 3, 7, 8]
Output: 5
Example 4:
Input: [1, 2, 3, 5]
Output: 4
Example 5:
Input... |
430f89abc9ce0dc3d148aa39b47faff37bea3b56 | Veraph/LeetCode_Practice | /cyc/math/67.py | 557 | 3.9375 | 4 | # 67.py -- Add binary
'''
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
'''
def addBinary(a, b):
# create a var to store the inc 1 situation
carry = 0
res = ''
a = list(a)
b = list(b)
while a or b... |
9423205aa24b009f76b35bec89521f56d7f602c2 | bfbonatto/roller | /advanced.py | 1,608 | 3.609375 | 4 | """
This is an advanced version of the roller script,
it functions as an arbitrary dice calculator
but it can also store and use character information in
its calculations
"""
from random import randint
import json
import click
import re
diceMatcher = re.compile('\d\d*d\d\d*')
def toString(tup):
return ' '.join(l... |
548ae50d2f7cb3b2ffc9baedf44e1f5cd5ebcd4b | kobe-mop/python | /py_test_code/test/simpleStudy/test_004.py | 216 | 3.9375 | 4 | '''
Created on 2016年8月10日
#4 全局变量global#
@author: shengxiz
'''
def func():
global x
print('x is: ',x)
x=2
print('Change Local x to',x)
x=50
func()
print('x is still',x) |
21815b97e6e71efc62e6277e346cf88fb40d98c7 | ylvaldes/Python-Curso | /Curso/ejemplosSegundo Dia/26.py | 1,006 | 3.921875 | 4 | #!/usr/bin/env python3
class inclusive_range:
def __init__(self,*args):
n=len(args)
self._start=0
self._step=1
if n<1:
raise TypeError('expected at least 1 argument, got {}'.format(n))
elif n==1:
self._stop=args[0]
elif n==2:
(self.... |
5409af81ec1ce374290d0b3bde0bb5e6930c09f0 | gjermundgaraba/py-tictactoe-withgui | /py-tictactoe-withgui/computer_player.py | 6,369 | 3.890625 | 4 |
class ComputerPlayer:
def __init__(self, game, player):
self.game = game
self.player = player
def make_play(self):
if self.two_equal_plays_in_row(0):
square = self.get_empty_square_in_row(0)
elif self.two_equal_plays_in_row(1):
square = self.get_empty_sq... |
aa471f8ccd081731cbf1e20b36e2171131f216b0 | Software-Design-Team-Carl/ourfavorites | /datasource.py | 7,220 | 3.5625 | 4 | import psycopg2
import getpass
class Nutrek:
'''
Nutrek executes all of the queries on the database
and formats the data to send back to the front end'''
def connect(self, user, password):
'''
Establishes a connection to the database with the following credentials:
user - ... |
6cd6a83aeeeeff09d9c0e0824ea6966c14aebf12 | TadpoleNew/test | /craps.py | 1,720 | 3.796875 | 4 | from random import randint
# *,是命名关键字参数,可以增加代码的可读性,在调用函数时必须给出参数名和参数值
# def roll_dice(a, *, num = 1):
def roll_dice(*, num=1):
total = 0
for _ in range(num):
total += randint(1, 6)
return total
def main():
# first = roll_dice(1, num = 2, 3) # SyntaxError: positional argument follows keyword... |
0fd5c72d9d857f759c5c245d1c03f1f60db94ea2 | Johanstab/INF200-2019-Exercises | /src/johan_stabekk_ex/ex02/file_stats.py | 1,093 | 4.25 | 4 | # -*- coding: utf-8 -*-
__author__ = 'Johan Stabekk'
__email__ = 'johan.stabekk@nmbu.no'
def char_counts(textfilename):
""" Opens the given file then reads it in to single string.
It then counts how often each character code occurs in the string, then
returns a list with the results.
Parameters
... |
bf83d5ce234e6c22cb52091a5437b8880c0bd7e9 | DidiMilikina/DataCamp | /Machine Learning Scientist with Python/03. Linear Classifiers in Python/02. Loss functions/01. Changing the model coefficients.py | 1,058 | 4.375 | 4 | '''
Changing the model coefficients
When you call fit with scikit-learn, the logistic regression coefficients are automatically learned from your dataset. In this exercise you will explore how the decision boundary is represented by the coefficients. To do so, you will change the coefficients manually (instead of with ... |
8389be742324ef0a6265493d9617e8faca089435 | MAHESHRAMISETTI/My-python-files | /tue.py | 290 | 3.75 | 4 | num=int(input('enter the table you want to print\n'))
for a in range (1,11):
print(num,'x','a','=',num*a)
a=0
while a<10:
print(a)
a+=1
for a in 'rahul':
if 'h'== a:
break
print(a)
for a in 'rahul':
if 'x'==a:
continue
print(a)
L1=[1,2,3,'hello',39.6]
print(L1[3]) |
1c824370a0d56999fbe3436725167bfee86493b6 | JonMer1198/developer | /programstarter.py | 1,133 | 3.609375 | 4 | from math import *
from sympy import *
import numpy as np
a,b,c,x = symbols('a,b,c,x')
#f = a*x**2 + b*x + c
#f = a*x**4
f = 3.0 / ((2.0*x)+2)
#f = Function('f')
x = Symbol('x')
#fprime = f(x).diff(x) - f(x) # f' = f(x)
F = integrate(f,x)
F = str(F)
# y = dsolve(fprime, f(x))
y = Symbol('y')
eqn = Eq(((3.0)/(2.0)*(np... |
bb7b35c54f69efc6274212b0c8f5603d8ad62c20 | TushaFalia/Tusha-Code | /Assignment 1 Ceaser Cipher.py | 776 | 4 | 4 |
# Final assingnment 1 encrypt :
def encrypt(x,y):
l=''
for i in range(len(x)):
b= ord(x[i])+y
d=(chr(b))
l+=d
return l
#print('Cipher:',l)
if __name__ == '__main__':
a= input("Please Enter the Text:")
c= int(input("Please Enter The Key Num... |
9655b75467b2a1b09c31b936c79142452211afce | presianbg/HackBG-Programming101 | /WEEK-1/application/caesar_encrypt.py | 988 | 3.953125 | 4 | #!/usr/bin/python
import sys, argparse
import math
def caesar_encrypt():
parser = argparse.ArgumentParser(description='Process some strings.')
parser.add_argument('-a', type=str)
parser.add_argument('-k', nargs=1 , type=int, choices=xrange(0, 26))
args = parser.parse_args()
cipher = str()
pri... |
2ddf2bbbd682d422b62c858c8e25969db28fd5fd | shehryarbajwa/Algorithms--Datastructures | /algoexpert/hatchways/depth_first_search.py | 1,094 | 3.765625 | 4 |
# Sample Input
# graph = A
# / | \
# B C D
# / \ / \
# E F G H
# After DFS - [A,B,E,F,C,D,G,H]
#Time Complexity O(V + E) O(V) for adding each vertex to the array. O(V) for the amount of times we have to traverse the children Nodes
#Space Complexity O(V) for adding DFS to the call sta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.