blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6d6f43a664218851da589bd35209e32221085cd2 | ntkaggarwal/Two-Pointers-2 | /Search_2D_matrixII.py | 1,068 | 3.828125 | 4 | #Time Complexity : O(m+n)
#Space Complexity : O(1)
#Did this code successfully run on Leetcode : Yes
#Any problem you faced while coding this :None
# =============================================================================
# Solution: Start from a corner which is increasing in one direction and decreasing in ... |
c3634a25b84548821150df641d54187a2e8d41c2 | eber-kachi/scripts_servidores | /agregarUnaPc.py | 617 | 3.640625 | 4 | ######## ejemplo para dar ip a una maquina
# host windows7-pc {
# hardware ethernet 00:0c:29:e6:75:b9;
# fixed-address 192.168.50.20;
# }
print("para saber cual es mi mac addres en otra PC (ifconfig | grep ether)")
print("dijite la mac de la PC que desea agregar")
mac=input()
print("nombre de la pc (pc1)")
no... |
5c45f5892ea0ff74668914a3371e7f175a097b0d | CStrue/python-ai | /neuralNetwork.py | 5,152 | 3.609375 | 4 | #!/bin/usr/python
# -*- coding: utf-8 -*-
import numpy
import scipy.special
import matplotlib.pyplot
#neural network class definition
class neuralNetwork:
#initialise the neural network
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
#set number of nodes in each inout, hidden, output laye... |
8551a9e749940d669b7c15ad0f930a2064425c1a | topheadliner/Stepik | /A few tasks.py | 3,493 | 3.859375 | 4 | Напишите программу, которая считывает список чисел lst из
первой строки и число xx из второй строки, которая выводит все позиции,
на которых встречается число x в переданном списке lst.
Позиции нумеруются с нуля, если число xx не встречается в списке,
вывести строку "Отсутствует" (без кавычек, с большой буквы).
Позиции... |
bb04a986834327a073002898027990390b7e66e6 | aghotikar/ComputationalBiology | /dummy.py | 211 | 3.625 | 4 | def overlaps1(a, b):
for i in range(1, min(len(a), len(b))):
if a[-i:] == b[:i]:
print(a + b[i:])
def overlaps2(a, b):
overlaps1(a, b)
overlaps1(b, a)
overlaps2('bbb', 'bbab') |
9596e52eae1915dda99761693b24efc58d4c0891 | destinysam/Python | /concatenation of strings.py | 345 | 3.5625 | 4 | # CODED BY SAM@SMAEER
# EMAIL:SAMS44802@GMAIL.COM
# DATE:11/08/2019
# PROGRAM: CONCATENATION OF STRINGS
first_name = "sameer "
last_name = "ahmad"
address = " from tarigam"
college = " studying in cluster university\n "
full_name = first_name + last_name + address + college
print(full_name) # PRINTING SINGLE TYMZ
prin... |
d41a8a5147296836010b435c0d3fbc43f012123c | sagnitude/leetcode | /Python/2/AddTwoNumbers.py | 1,160 | 3.703125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def addTwoNumbers(self, l1, l2):
overflow = 0
val = ListNode(None)
han... |
0dbe7bdd21f1ad72734583356c82368c82110144 | darshitpandya18/algorithm-implementations | /RockPaperScissor.py | 797 | 4 | 4 | import random
def RNG():
# Function defines, selects and returns the output
# of one of those
return random.randint(1,3)
def check_winner(input_1, input_2):
#Checks the winner as per the input 1 an input 2
if input_1 == 1 and input_2 == 2:
print("Computer Wins")
elif input_1 == 1 and input_2 == 3:
print(... |
f1b55a0f351d21af467b93c89e846f487300daa7 | SEDarrow/PythonCode | /ScheduleOptions.py | 7,426 | 3.65625 | 4 | class Node():
def __init__(self, data=None, nextNode=None, prevNode=None):
self.data = data
self.nextNode = nextNode
self.prevNode = prevNode
def getData(self):
return self.data
def setData(self, data):
self.data = self
def getNext(self):
... |
bbe88f09f50e37049841e8d23bcbee2d7f3b5e78 | NathanNNguyen/challenges | /leetcode/shuffle_string.py | 1,012 | 3.890625 | 4 | # Given a string s and an integer array indices of the same length.
# The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.
# Return the shuffled string.
# Example 1:
# Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3]
# Output: "leetcode"
# Explanati... |
2c074079e92d8fb56a935e8c530d9a0fee595b80 | patrick-du/python-dsa | /algorithms/recursion.py | 1,105 | 4.03125 | 4 | # Converting an Integer to a String in Any Base
def toStr(n, base):
convertString = "0123456789ABCDEF"
if n < base:
return convertString[n]
else:
return toStr(n//base, base) + convertString[n%base]
print(toStr(769,10))
# Write a function that takes a string as a parameter and returns a new... |
b0851fcee1bf15ec57febe20a8c2581c4e7bea3d | rachel6854/Python-Projects | /python_functions/exercise2.py | 246 | 4.03125 | 4 | def longest_string(string1, string2):
if len(string1) > len(string2):
return string1
elif len(string2) > len(string1):
return string2
else:
return "same length"
#print(longest_string("helloo","world"))
|
7205f5faeb43a19f7027b92d6326a0bf534c1af3 | anderson-s/Python | /Secao9/atividade5.py | 348 | 3.78125 | 4 | #variaveis
vetor = []
aux = False
for n in range(0, 10):
num = int(input("Digite um valor para o vetor"))
vetor.append(num)
for n in vetor:
if n > 50:
print("O número {0} maior que 50 na posição: {1}".format(n, vetor.index(n)))
aux = True
if aux == False:
print("não existem ... |
a67dc63b645232730a78291bde47db4370415a46 | rostykusvasyl/StartDragon-m5_lesson5 | /task_max/password_check.py | 754 | 4.3125 | 4 | #! /usr/bin/python3
''' Password Verification Program
'''
import re
def password_verification():
''' Check the password entered by the user.
'''
print('The password must contain at least one character from'
'the following groups: (a-z), (A-Z), (0-9).')
print("Must contain at least one char... |
22f7624e2cd54c3c539c1a00d8b343401fd8af46 | yanmarcossn97/Python-Basico | /Exercicios/exercicio084.py | 1,172 | 3.640625 | 4 | grupo = []
dados = []
pessmenpeso = []
pessmaipeso = []
cond = ''
menpeso = maipeso = 0
while cond != 'N':
dados.append(str(input('Nome: ')))
dados.append(float(input('Peso(Kg): ')))
grupo.append(dados[:])
dados.clear()
cond = str(input('\nCadastrar outra pessoas[S/N]? ')).strip().upper()... |
daee7e883daa846cb144581ec5742fee0364532b | jsutch/Python-Algos | /number_to_string.py | 1,868 | 4.375 | 4 | #!/usr/local/bin/python
#Write a program that takes an array of numbers and replaces any number that's negative to a string. For example if array = [-1, -3, 2] after your program is done array should be ['somestring', 'somestring', 2].
my_array = [-3, 3, -50, 10, 14, -2, 21, -4]
loop = 0
while loop < len(my_array):
... |
00a5e20233fcf29f7cafaf9acdc18cf97b0ed834 | ZhengLiangliang1996/LeetcodePyVersion | /16_WordSearch.py | 1,448 | 3.796875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 22:58:48 2019
@author: liangliang
"""
import numpy as np
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
# get 1, then df... |
08dc88202fcc42c598b3946e5717e1840c822b9f | amitshipra/PyExercism | /simple-cipher/cipher.py | 1,678 | 3.546875 | 4 | __author__ = 'agupt15'
import string
class Caesar:
def __init__(self):
self.all_letters = string.ascii_lowercase
def get_cipher(self, ch):
ch = ch.lower()
if ch == ' ' or ch not in self.all_letters:
return ''
idx = self.all_letters.index(ch) + 3
if idx > l... |
554442bd9fe8129b3e7ad7f1418070093cad7950 | smueksch/pdf2txt | /src/postprocessors/unknown_char_fixer.py | 659 | 3.609375 | 4 | import re
class UnknownCharFixer:
""" Replace unknown character with best interpretation. """
name = 'UnknownCharFixer'
desc = 'Replace unknown character with best interpretation'
def __call__(self, raw_text: str):
text = re.sub(u'', r'0', raw_text)
text = re.sub(u'', r'1', text)
... |
13d545fa660c77dffe6de472180e184206ed68ea | bfialkoff/pytorch-thesis-stuff | /utils/losses/numpy_losses.py | 1,891 | 3.6875 | 4 | import numpy as np
def compute_stable_bce_cost(Y, Z):
"""
This function computes the "Stable" Binary Cross-Entropy(stable_bce) Cost and returns the Cost and its
derivative w.r.t Z_last(the last linear node) .
The Stable Binary Cross-Entropy Cost is defined as:
=> (1/m) * np.sum(max(Z,0) - ZY + log(... |
983dbbba3483c14d50e4cf9761ad477693065b83 | Epilena/Python-Challenge | /PyPoll/main.py | 2,181 | 3.609375 | 4 | #import the os module to create file paths across operating system
import os
#import module for reading CSV files
import csv
# os.chdir(os.path.dirname("election_data.csv"))
elect_data = os.path.join("PyPoll","Resources", "election_data.csv")
#read the CSV file
with open (elect_data) as csvfile:
#create a csv r... |
0aa0273049b58bdfb7ec0d5b56b6a8b297b1a8d2 | sangyuan6122/kaikeba-wangwentao | /exercise11/utils.py | 338 | 3.78125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
def print_line(text):
total=90;
lenTxt = len(text)
lenTxt_utf8 = len(text.encode('utf-8'))
size = int((lenTxt_utf8 - lenTxt) / 2 + lenTxt)
remainder=(total - size)%2
left= (total - size)//2
right=left if remainder==0 else left+1
print("*" * left... |
af399acca911c72c397f3c5dfe7289da92b69c16 | Comyn-Echo/leeCode | /常见的数据结构.py | 2,716 | 3.5625 | 4 | #
# #初始化数组
# dp = [0 for i in range(5)]
# [0, 0, 0, 0, 0]
# #定义二维数组
# dp = [[0 for i in range(5)] for i in range(3)]
# [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
# # 排序数据结构
# my_dict = {"a":"2", "c":"5", "b":"1"}
#
# result = sorted(my_dict)
# #默认对dict排序,不指定key参数,会默认对dict的key值进行比较排序
# #result输出: ['... |
65951cf0009b7a71adf343a66e73d84eb3d73ff4 | pennywong/mooc | /Rice-Algorithmic Thinking/module1-Graphs and brute-force algorithms/project1.py | 1,207 | 3.828125 | 4 | """
Degree distributions for graphs
"""
EX_GRAPH0 = {0:set([1,2]), 1:set(), 2:set()}
EX_GRAPH1 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3]), 3:set([0]), 4:set([1]),
5:set([2]),6:set()}
EX_GRAPH2 = {0:set([1,4,5]), 1:set([2,6]), 2:set([3,7]), 3:set([7]), 4:set([1]),
5:set([2]),6:set(),7:set([3]),8:set([1,2]),9:set... |
115b864e68805e0937bcd6fb1841951cb60260fd | Mozes721/PythonCrashCourse | /chapter_8/City_name.py | 250 | 3.8125 | 4 | def city_country(city,country):
return(city.title() + ", " + country.title())
city1 = city_country('Riga', 'Latvia')
print(city1)
city2 = city_country('Tallin', 'Estonia')
print(city2)
city3 = city_country('Copenhagen', 'Denmark')
print(city3) |
f40defd2208ece1a088ec0e7489b55d3ac07741b | AKHILESH1705/programing_questions | /func2.py | 443 | 4.125 | 4 | #cheack which number is greater
def number(num1,num2):
if num1>num2:
return a
else:
return b
a=int(input("enter num1 = "))
b=int(input("enter num2 = "))
bigger=number(a,b)
print(f"{bigger} is greater")
# diffrent way
def number(num1,num2):
if num1>num2:
return "num1 is greater"... |
498bdf0186335a845c4d342eae60ff8e7cf6c024 | sidgan/Who-Said-it- | /gaura.py | 756 | 3.625 | 4 | #!/usr/bin/env python
#import regex
import re
#start process_tweet
def processTweet(tweet):
# process the tweets
#Convert to lower case
tweet = tweet.lower()
#Convert www.* or https?://* to URL
tweet = re.sub('((www\.[\s]+)|(https?://[^\s]+))','URL',tweet)
#Convert @username to AT_USER
tweet = re.sub('@[^\s]... |
7b9d3877238a7e7c984087ee20383ad7e8c017b2 | jonathanpan777/hashcode | /car.py | 254 | 3.546875 | 4 | class Car:
def __init__(self, length, path):
self.length = length
self.path = path
self.current = path[0]
self.path_length = 0
def car_sum(self,street_dict):
s = 0
for p in self.path:
s += street_dict[p].length
self.path_length = s
|
00d1173f8e8c319e19cae4203c5010f91870cbe9 | Ayush10/CSC-3530-Advance-Programming | /ayush_ojha_swap_without_temp.py | 250 | 3.984375 | 4 | # Taking input from the user
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Variables before swapping")
print(a, b)
# Swapping Algorithm
a = a + b
b = a - b
a = a - b
print("Variable after swapping")
print(a, b) |
52d828c4720c9bbf09217572c419e3ac6d94f30f | arthurDz/algorithm-studies | /leetcode/minimum_difference_between_largest_and_smallest_value_in_three_moves.py | 1,050 | 3.921875 | 4 | # Given an array nums, you are allowed to choose one element of nums and change it by any value in one move.
# Return the minimum difference between the largest and smallest value of nums after perfoming at most 3 moves.
# Example 1:
# Input: nums = [5,3,2,4]
# Output: 0
# Explanation: Change the array [5,3,2,4] ... |
794071c39fabacf515ea33f3549ba76a9df5535a | Sahil12S/DataCompass | /Python/userv2.py | 1,060 | 3.84375 | 4 | class User:
def __init__(self, name):
self.username = name
self.balance = 0
def make_deposit(self, amount):
self.balance += amount
return self
def make_withdrawl(self, amount):
self.balance -= amount
return self
def display_user_balance(self):
p... |
a3213f10753b87a4030453dfe7f3ba1109c672c9 | jinsuupark/chapter0601 | /ex01.py | 355 | 3.71875 | 4 | student =1
while student <=5:
print(student, "번 학생의 성적을 처리합니다.")
student += 1 #복합대입연산자
print()
num = 1
even_total =0
odd_total =0
while num<=100:
if num%2 ==0:
even_total +=num
else:
odd_total += num
num +=1
print("짝수의 합:", even_total)
print("홀수의 합:", odd_total)
|
85a0c9f580327c276fb9ed8a5a6fca7ceeb8403a | Smelly-calf/python-calf | /calf/basic/lambda_func.py | 645 | 3.984375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
简约而不简单的匿名函数:lambda
匿名函数是函数, 不是变量
lambda函数用在 常规函数不能用的地方:列表内
map(func, iterable): 返回新的可遍历的集合
filter(func, iterable)
reduce(func, iterable)
1、对字典d值由高到低排序:d={'mike':10,'lucy':2,'ben':30}
2、使用匿名函数的场景
"""
if __name__ == '__main__':
print("请开始你的程序")
square = lambda ... |
403b7068c5e178983c0273a204a382ef970721f4 | Leeoku/anagram | /backend/anagram.py | 740 | 3.828125 | 4 | from collections import Counter
class AnagramCheck:
def __init__(self):
self.anagram_counter = Counter()
# Take in two words and determine if they are anagram
def is_anagram(self, first_word, second_word):
first_word = first_word.lower()
second_word = second_word.lower()
... |
11d4b3f27e6a65d5a1365a9b5bd865dda79a899b | Sammion/PythonStudy | /source/Notebook/test1_15.py | 912 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on 11/26/2018
@author: Samuel
@Desc:
@dependence: Noting
"""
rows = [
{'addr': "shanghai", "name": "Amy", "date": "1/12/2018"},
{'addr': "sichuan", "name": "Bmy", "date": "1/12/2018"},
{'addr': "shanghai", "name": "Cmy", "date": "1/12/2018"},
{'addr': ... |
a6e6822a1a121aac2d8489725a80117e91c63130 | npradheep/home-automation-system | /gateway/utilities/ConfigUtil.py | 1,035 | 3.515625 | 4 | '''
Created on 28-Jan-2020
@author: Pradheep
This class parses the configuration file and makes the data usable in python
'''
import configparser
import os.path
import sys
parser = configparser.ConfigParser()
path = '../../ConnectedDevicesConfig.props'
class ConfigUtil():
# Checks if the file has any va... |
94dbb9870a35ed7a5033f184a7d7f279e88fe7f2 | athirarajan23/luminarpython | /inheritence in advanced python/multilevel or heirarical inheritence.py | 530 | 3.8125 | 4 | class Person:
def details(self,name,age):
self.name=name
self.age=age
print(self.name)
print(self.age)
class Employee(Person):
def print(self,emp_company):
self.emp_company=emp_company
print(self.emp_company)
class Staff(Employee):
def info(self,salary):
... |
552cf7122307e51188a3e223cef916ab28f533b4 | re4lfl0w/codewars | /kata/length_of_the_line_segment.py | 696 | 3.96875 | 4 | from math import sqrt
def length_of_line_my1(array):
a, b = array
tmp = sum(abs(a[i] - b[i]) ** 2 for i in range(len(array)))
tmp = '{:1.2f}'.format(sqrt(tmp))
return tmp
def length_of_line_my2(array):
a, b = array
tmp = sum(abs(a[i] - b[i]) ** 2 for i in range(len(array)))
result = '{:1... |
9881cf3d8ff828b9728916db69dc1c768cbfa5ef | Nayyx/energy_quest | /equest_namur_gr_50.py | 30,258 | 3.8125 | 4 | # imports
import copy
import math
import colored
def display_board(dict_board, height, width, players, dict_army):
"""display the board at the beginning of the game
parameters
----------
dict_board: dictionnary with all the characteristic of the board (dict)
height:height of the board(int)
wi... |
779c72597383aca077c634ce4b24a9f30854a18c | annaxarkhipova/geekbrains | /Lesson_1/task_1.py | 632 | 4.21875 | 4 | # 1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь.
# https://drive.google.com/file/d/1ydDhgRFY0F_4WXiqLSupQQdnR_XbU7Fo/view?usp=sharing
print("Введи трехзначное число") # целые числа
a = int(input("Первая цифра - "))
b = int(input("Вторая цифра - "))
c = int(input("Третья цифра - ")... |
69b25938b1d5b4f42058e1b3823afb4e3a8d06b5 | ashutoshdumiyan/CSES-Solutions | /string/requiredsubstring.py | 353 | 3.53125 | 4 | mod = 10 ** 9 + 7
def power(a, b):
res = 1
while b:
if b & 1:
res = (res % mod * a % mod) % mod
b -= 1
else:
a = (a % mod * a % mod) % mod
b = b // 2
return res % mod
n = int(input())
s = input()
k = len(s)
t = n - k + 1
... |
bfe0a562736ffc80081730035e912e73a9353eae | today4king/leetcode | /1-20/11-container-with-most-water.py | 1,430 | 3.671875 | 4 | # Copyright 2021 jinzhao.me All rights reserved
# #
# Authors: Carry Jin <today4king@gmail.com>
from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
i = 0
j = len(height) - 1
area = 0
last_min_h = 0
while j > i:
d ... |
829dfc3ddf9d8e2caf5cefba3affa3de5d467b3b | nithyaraman/pythontraining | /chapter1/src/data_type_conversion.py | 622 | 4.53125 | 5 | """ Get the input from user and convert it into different data types and print it """
float_num = float(raw_input("enter any float="))
print"this float can convert as int %d" % (int(float_num))
int_num = int(raw_input("enter any integer="))
print"this int convert as float %f" % (float(int_num))
name = raw_input("... |
b199c98ea9d46d88bd9518241055ddc7759c3c4c | vladvesa/PEP20G06 | /modul5/homework5.py | 5,122 | 4.46875 | 4 | # We want to create class for an object that behaves like a triangle, that has flexible sides and angles.
# Because of approximations in python the triangle will get distorted after some of the changes so this is not a
# perfect model
# 30P
# - class constructor can receives 3 arguments for angles (with default value... |
3905188b18eee497e3e7fd039fcf867026643345 | dinnguyen1495/daily-coding | /DC29.py | 1,324 | 4.34375 | 4 | # Daily Coding 29
# Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent
# repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA"
# would be encoded as "4A3B2C1D2A".
# Implement run-length encoding and decoding. You can assum... |
7ec2d675b00c391393f28eba0a2d1c8bfc074b3a | hari007/First-Program | /methods/variable local scope.py | 469 | 3.671875 | 4 | _Author_ = " HS "
a = 10
def test(a):
print("The value of local 'a' is "+ str(a))
a = 2
print("The value of local 'a' is "+ str(a))
print("Value of Global 'a' is " + str(a))
test(a)
print("Value of Global 'a' is " + str(a))
a = 10
def test():
global a
print("The value of local 'a' is "+ str(a))
... |
d6cf9cee6c5fa297dc0faa77f18eaf32bb1e56ba | hienpham15/Codeforces_competitions | /Codeforces_round739/A.py | 996 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 18 16:34:12 2021
@author: hienpham
"""
import os
import math
import sys
parse_input = lambda: sys.stdin.readline().rstrip("\r\n")
def check(val):
str_val = str(val)
if val%3 != 0 and str_val[-1] != '3':
return True
else:
... |
688c841517d66e9f0c2f503748779e7d5dbffd3e | GemmaLou/iteration | /class ex rev 4.py | 328 | 4.21875 | 4 | #Gemma Buckle
#17/10/2014
#rev ex 4
user_num=int(input("Please enter a number between 10 and 20, 10 and 20 included: "))
while user_num<10 or user_num>20:
user_num=int(input("Invalid! Please try again. Enter a number between 10 and 20, 10 and 20 included. "))
print("Thank you! {0} is within range! :)".forma... |
173dbd81f2f2c3ddbf59970d83366e12248795f0 | yasarkocyigit/MYSQL-PYHTON-DATA-SCIENCE- | /CREATING DATABASE copy.py | 949 | 4.21875 | 4 | """
i will upload everything about mysql as part once you learn previous part you will be ok for next one!
i uploaded how to connect mysql to python as previous project.
"""
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user ="root",
passwd = "gs163264"
)
# on this lesson... |
de801ddeeb1be30e13afc1897a8da6875baa6eaf | cicerohr/Practice_Python | /exercicio001.py | 883 | 3.953125 | 4 | """exercicio001.py em 2018-09-29. Projeto Practice Python.
tipos de strings de entrada int
Crie um programa que peça ao usuário para inserir seu nome e sua idade. Imprima uma mensagem endereçada a eles,
informando o ano em que completará 100 anos.
"""
from datetime import datetime
from cicero import cabecalho
def ... |
dfda2e2a2477771b3220876536d25bea34c26ab7 | ph0ph0/Python--Stepping-Motor | /L16_StepMotor.py | 2,187 | 3.515625 | 4 | import RPi.GPIO as GPIO
import time
motorPins = (12, 16, 18, 22) #define pins connected to four phase ABCD of stepper motor
CCWStep = (0x01, 0x02, 0x04, 0x08) #define power supply order for coil rotating anticlockwise
CWStep = (0x08, 0x04, 0x02, 0x01) #define power supply order for coil rotating clockwise
def setup... |
5e4cf687d3f1108f851e0454a9e4f60a76962d5b | DaryaFilimonova7/cp8 | /1.py | 2,366 | 3.875 | 4 | def bin1(a,answer):
while True:
if a // 1 != 0:
if a % 2 == 0:
answer.append(0)
a = a // 2
elif a % 2 != 0:
answer.append(1)
a = a // 2
else:
answer.reverse()
... |
43f8184842e82139aad1e08ca2ff2b4246a4755d | samuelhwolfe/pythonPractice | /programs/lists/chapterFourProblems.py | 506 | 3.6875 | 4 | spam = ['apples', 'bananas', 'tofu', 'cats']
myFavoriteThings = ['Beer', 'Pizza', 'Family', 'Snowboarding', 'Murphy',
'Kona', 'Movies', 'Cheese']
def listString(myList):
myList.insert(-1, 'and ')
firstPortion = myList[0:-2]
for x in firstPortion:
print((x) + ', ', en... |
e6cc2cc7eef22b44a794e50796773312c5c998fb | EwertonWeb/UriOnlineJudge | /1021_urionlinejudge.py | 441 | 3.9375 | 4 | values = float(input())
cash = [100,50,20,10,5,2]
coins = [1,0.50,0.25,0.10,0.05,0.01]
print('NOTAS:')
for cash in cash:
volume_cash = int(values / cash)
print('{} nota(s) de R$ {:.2f}'.format(volume_cash,cash))
values -= volume_cash * cash
print('MOEDAS:')
for coins in coins:
volume_coins = int(roun... |
aa6af6724f5e3b9d89b604ddf5471bce8243cbb5 | musram/python_progs | /real_python_tutorails/print_topic/printsa.py | 3,588 | 4.03125 | 4 |
if __name__ == "__main__":
#Three ways to declare string
var = 'I am god'
var = "I am god"
var = """ I am god """
# supporting two types of string allows to putting quote in a string easier
var = ' hellow "sai" bye'
print(var)
print(70*'=')
print( " my name \n is \n sa... |
85a756985a57c9de154a1a0bcaeacc3d749f970d | abbykahler/Python | /bank_account/BankAccount.py | 936 | 3.796875 | 4 | class BankAccount:
def __init__(self, name,int_rate, balance):
self.int_rate = .1
self.balance = 0
def make_deposit(self, amount):
self.balance += amount
return self
def make_withdrawal(self,amount):
self.balance -= amount
return self
def ... |
96bb453aaa5d8dd68d1027605286eff0bfe37fed | wballard/mailscanner | /mailscanner/layers/reverse.py | 670 | 3.734375 | 4 | '''
Layers for the reversing of input tensors.
'''
import keras
class TimeStepReverse(keras.layers.Layer):
"""
A custom keras layer to reverse a tensor along the first
non batch dimension, assumed to be the time step.
# Input shape
nD tensor with shape: `(batch_size, time_step, ...)`.
... |
85500269ddf322186da7058d9bc924f5cc733fbb | daniel-reich/ubiquitous-fiesta | /6pEGXsuCAxbWTRkgc_21.py | 227 | 3.671875 | 4 |
def loves_me(n):
new = ""
for i in range(n - 1):
if i % 2 == 0:
new += "Loves me, "
else:
new += "Loves me not, "
if n % 2 == 0:
new += "LOVES ME NOT"
else:
new += "LOVES ME"
return(new)
|
e3dc46220ad0317677ad848b648c2eef15ba7eef | AShoom85/MyPythonCode | /L1/numberL1_3.py | 452 | 4.1875 | 4 | #Напишите программу, которая считывает целое число и выводит текст
#The next number for the number число is число+1. The previous
#number for the number число is число-1. С начала
num = int(input("Input number = "))
print("The next number for the number " + str(num)+" is " + str(num + 1))
print("The previous number fo... |
533e1904b02e6e8af91609c22228daf9f39aa907 | yareddada/CSC101 | /CH-06/check-points.py | 3,656 | 4.125 | 4 | check_point = {
'6.1 What are the benefits of using a function?' : '\n\tcode reusability and simplification \n',
'6.2 How do you define a function? How do you invoke a function?' : '\n\tdef name(params):body, m = main() \n',
'6.3 Can you simplify the max function in Listing 6.1 by using a conditional expression?' : '... |
0935d43e0e117a48a2487a6a533ad4944eec4e29 | SHJoon/Algorithms | /arrays/3_insert_at.py | 434 | 4.15625 | 4 | # InsertAt
# Given an array, index, and additional value, insert
# the value into the array at the given index. Do this
# without using built-in array methods. You can
# think of PushFront(arr,val) as equivalent to
# InsertAt(arr,0,val).
def insert_at(lst, idx, val):
lst.append(0)
for i in reversed(range(idx, ... |
1bc3db01b3f33d50978332c4c80ea8ce150f4214 | yuquanle/JZOffer | /Num16_MergeListNode.py | 1,320 | 3.78125 | 4 |
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
if pHead1 == None and pHead2 == None:
return None
if pHead1 == None and pHead2 != None:
return p... |
b84e6857963d0c28fcbb89a0925556a3b0f25324 | Creedes/HarvardCourse | /python/loops.py | 268 | 4 | 4 | for i in range(5): # one Statement
print("Durchgang:", i)
print("\n")
for i in range(0, 10, 2): # start, stop, iteration (auch negative Werte erlaubt)
print("Durchgang:", i)
print("\n")
name = "Harry"
for character in name:
print(character)
print("\n") |
70769f84a37c8544e1ac7db39e7e7c886f61154a | SindiCullhaj/pcs2 | /lecture 5 - sorting/quick.py | 353 | 4.1875 | 4 |
def quickSort(list):
pivot = list[0]
left = []
right = []
for i in range(1, len(list)):
if (list[i] > pivot):
right.append(list[i])
quickSort(right)
else:
left.append(list[i])
quickSort(left)
a = [5, 1, 4, 2, 6, 3]
print("Initial: ", a)... |
b2433b131ace21324eeb17e6c47ab02258cbc5ef | eskuye11/python | /myPy/studentGrades.py | 3,187 | 4.28125 | 4 | def student_rank(students):
""" This function takes ('dictionary' or 'list of (name, grade) tuples')
of students 'name' and 'numeric' grades and Returns the names and
'letter' grade's as (student_name, letter_grade) if a student had a single grade
or (student_name, [letter_grades]) if ... |
4218346877ba8848669e657408fdfdad55bcc215 | Jamesical/Python | /Python Batch/Project 1/Exam_Student.py | 807 | 3.9375 | 4 | #Travis Saulat Python Programming Assignment: Exam Student 1/22/2021 DUE:1/29/2021
held = float(input('How many classes have been held?: ')) #series of inputs for the questions
atte = float(input('How many classes have you attended?: '))
temp = float(input('What is your current temperature in Faren... |
528fd137efc4263e3f54b7509b682426b9d9803f | A-Mitch/apythonaday | /week8/setsntuples.py | 1,166 | 4.21875 | 4 | # Lists (review), tuples, and sets
# Lists - mutable
# Exclusive list
names = ['Alex','Samantha','Jun','Ravi','Eric']
morenames = ['Jeff','Michael']
# exlcusive range print/slicing
print(names[0:3])
names.insert(1,'Jay')
print(names)
print("adding multiple values with extend")
names.extend(morenames)
print(names)
... |
fde35cc2c7496ebef4303743a3169e343454e482 | houyizhong/ATM-of-python | /core/demo_shoplist.py | 1,406 | 3.640625 | 4 | import pickle,os
from demo_login import login
import demo_credit
filename=os.path.abspath(__file__)
dirname=os.path.dirname(filename)
product_path=dirname+os.sep+'product.txt'
def shopping():
shopping_list=[]
price=0
'''read product'''
f=open(product_path,'rb')
product_list=pickle.load(f)
f.close()
@log... |
d9a35952d09592a48da868243b7d09e5941f28e3 | AlSavva/Algorytms_and_data_structure | /task6_les1.py | 1,414 | 4.21875 | 4 | # По длинам трех отрезков, введенных пользователем, определить возможность
# существования треугольника, составленного из этих отрезков. Если такой
# треугольник существует, то определить, является ли он разносторонним,
# равнобедренным или равносторонним.
a = float(input('Введите длинну отрезка АВ: '))
b = float(inpu... |
5cd14bb498d4ccd1e2edc726149cf196428be70b | naye0ng/Algorithm | /SWExpertAcademy/D4/1238.py | 1,016 | 3.5 | 4 | """
1238.Contact
"""
def contact(start):
queue = []
queue.append([0, start])
depth = 0
maxitem = 0
while queue:
node = queue.pop(0)
# 깊이가 깊어질때
if depth < node[0]:
depth = node[0]
maxitem = node[1]
# 깊이가 같은데 현재 노드의 값이 더 클때
if depth == ... |
0f512c04af480cc001ad8324770cb98309139a64 | NMBURobotics/IMRT100 | /python/basics/04_if_statements_and_while_loops.py | 687 | 4.21875 | 4 |
program_is_running=True
while program_is_running:
# Get user name and age
user_name = input("Please enter your name: ")
user_age = int(input("Please enter your age: "))
# Evaluate input, and output answer to user
if user_age < 18:
print("You are too young to drive a car, " + user_na... |
13526b556b43f6ab8d26ce0cd1267db867cd9621 | ongaaron96/kattis-solutions | /python3/2_4-lindenmayorsystem.py | 332 | 3.53125 | 4 | num_rules, iterations = map(int, input().split())
rules = dict()
for _ in range(num_rules):
x, _, y = input().split()
rules[x] = y
word = input()
for _ in range(iterations):
new_word = ""
for char in word:
if char in rules:
new_word += rules[char]
else:
new_word += char
word = new_word
... |
38d903f220b44c57f00820a12d76108a99520245 | berkayalatas/data-structures-and-algorithms | /hastTable.py | 5,089 | 3.875 | 4 | class Hashtable:
# Assumption: table_length is a prime number (for example, 5, 701, or 30011)
def __init__(self, table_length):
self.table = [None] * table_length
## An internal search function.
# If it finds the given key in the table, it will return (True, index)
# If not, it will ret... |
c3a9135833a2ec2da1a3cabab427ef83d9216b12 | HaseebGitWitIt/MachineLearningGroceryListMobileApp | /Python/GrocListObj.py | 1,454 | 3.59375 | 4 | import os
import sys
import ItemObj
file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)
class GrocList(object):
def __init__(self, name, items=[]):
if type(items) != list:
raise ValueError("Error in GrocListObj: items parameter must be a list")
self.setName(name)
self.items = []
for item in ... |
75ce897730a8fa73c53d0324e86be8137adf2204 | khayatioualid/LangageDeScrips2021 | /ListeCreation Analyse Probleme.py | 715 | 3.90625 | 4 | def createList1D(d1):
return [0]*d1
def createList2D(d1,d2):
L=createList1D(d1)
for i in range(len(L)):
L[i]=createList1D(d2)
return L
def createList3D(d1, d2, d3):
L=createList1D(d1)
for i in range(len(L)):
L[i]=createList2D(d2, d3)
return L
def createList4D(d1,d2, d3, d4):
... |
2dccb8cb72f6f83ff04f8f24a4030f37e4522c9a | arinablake/python-selenium-automation | /hw_algorithms_3/fibonacci_element.py | 402 | 4.15625 | 4 | #Домашнее задание: Написать программу для вывода только указаного элемента последовательности Fibonacci
num = int(input("Enter the Number: "))
first = 0
second = 1
for i in range(1, num+1):
if i <= 1:
fib = i
else:
fib = first + second
first = second
second = fib
print(fib)
|
7f5b279c95835a9f795044c0473b9344148cd8ef | emrectn/Python_Tutorial | /db_sqlite.py | 2,510 | 3.625 | 4 | import sqlite3
"""
Python ile Sqlite Veritabanı nasıl kullanılır öğrenmeye çalışacağız. Bu bölümde basit anlamda Sqlite veritabanı
kodları bulunmaktadır.
"""
# Sqlite'yı dahil ediyoruz
import sqlite3
# Tabloya bağlanıyoruz.
con = sqlite3.connect("kütüphane.db")
# cursor isimli değişken veritabanı üzerinde ... |
a723b86e700204e88cb7c6021cbd20367d819ebe | hc973591409/python | /13.py | 632 | 3.828125 | 4 | # str遍历
str_1 = '1234abcd'
for ch in str_1:
print(ch,end=',')
print("")
# 列表遍历
list_1 = [1,2,3,4,5,6,7,8,9]
i = 0
for li in list_1:
print('%d %d' %(i,li),end=',')
i += 1
print("")
# 元组遍历
tuple_1 = (9,8,7,6,5,4)
i = 0
for item in tuple_1:
print("%d %d" %(i,item),end=',')
i += 1
print("")
# 字典遍历
i... |
6277d44114bd1a6ababda0ec482fdc8b6b1dcbe6 | smothly/algorithm-solving | /boj-11003.py | 766 | 3.515625 | 4 | '''
백준 11003번 최솟값 찾기
링크: https://www.acmicpc.net/problem/11003
풀이방법
- 슬라이딩 윈도우
- deque
'''
from sys import stdin
from collections import deque
stdin = open("input.txt", "r")
# N: 숫자의 개수
# L: 임의의 수
N, L = map(int, stdin.readline().split())
numbers = list(map(int, stdin.readline().split()))
queue =... |
c2ec4d21e129253f2afd8b0230a2721a34a41104 | fimanishi/DigitalCrafts-Week1 | /list_multiply_items.py | 146 | 4.125 | 4 | #!/usr/env/bin python3
def multiply_list(l,f):
for i in range(len(l)):
l[i] = l[i]*f
a = [1,2,3,4,5]
multiply_list(a,3)
print(a)
|
e4155922478979ee193220d2d72b2cedb45e4d64 | botelhomn/4linux | /4linux-master/aula03/ex03.py | 1,085 | 4.09375 | 4 | #!/usr/bin/python3
"""
Script para realizar funções de uma calculadora
Autor:
Data:
Alterações....
"""
def escolhe_op():
opcao = int(input("Digite a opcao desejada:"))
while opcao < 1 or opcao > 4 :
print("Opcao Invalida")
opcao = int(input("Digite a opcao desejada:"))
ret... |
acf919ca7c07f8cbc7d89b31aca2e748b938b729 | Cocoolanu/Problem-Solving-with-Algorithms-and-Data-Structures-Using-Python | /Chapter3_DataStructures/disQ1.py | 363 | 3.78125 | 4 | from stack import Stack
def binaryConvert(num):
myStack = Stack()
binaryString = ''
while num > 0:
temp = num % 2
myStack.push(temp)
num = num // 2
while not myStack.isEmpty():
binaryString += str(myStack.pop())
return binaryString
print(binaryConvert(17))
print(b... |
368a7793a6123ca4d5fe08014311a27c46792958 | Mauzzz0/study-projects | /python/lab2_python/15.5.py | 410 | 3.515625 | 4 | lst = list()
for _ in range(int(input())):
"""
Ivanov came
Kyznetsov came
Polivanov came
Zorina over Kyznetsov
Ivanova gone
"""
g = input().split(" ")
if len(g) == 2:
if g[1] == "came":
lst.append(g[0])
elif g[1] == 'gone':
lst.remove(g[0])
... |
5cd3c407bc16e8294ce7ba1a9e0443ccd2bf6e54 | threedworld-mit/tdw | /Python/tdw/object_data/transform.py | 1,253 | 3.828125 | 4 | import numpy as np
class Transform:
"""
Positional data for an object, robot body part, etc.
"""
def __init__(self, position: np.ndarray, rotation: np.ndarray, forward: np.ndarray):
"""
:param position: The position vector of the object as a numpy array.
:param rotation: The r... |
92262f345e002d6e6b8674be374852ed98774f92 | syurskyi/Python_Topics | /010_strings/examples/Python 3 Most Nessesary/6.11.Listing 6.4. Summing an indefinite number of numbers.py | 1,046 | 3.859375 | 4 | # -*- coding: utf-8 -*-
print("Введите слово 'stop' для получения результата")
summa = 0
while True:
x = input("Введите число: ")
if x == "stop":
break # Выход из цикла
if x == "":
print("Вы не ввели значение!")
continue
if x[0] == "-": # Если первым символом является минус
... |
0756adeb749b37c885b4a761960aa492ded3597c | tosha96/euler-solutions | /p23.py | 749 | 3.875 | 4 | def sumofpd(number):
sum = 0
for divisor in range(1, number + 1):
if number % divisor == 0 and number != divisor:
sum = sum + divisor
return sum
abundants = []
cantbesummedsum = 0
#generate list of abundants less than number which all integers greater than it can be created by the sum of abundant number
for n... |
775354f0027e52973d7fe0570a0168e63c665ec2 | Python-Learn-Training/Python_Learn_1 | /Learn-Training/random-statistics.py | 1,198 | 3.78125 | 4 | # 隨機模組
import random
###########################################
# 隨機選取 choice&sample
# data=random.choice([1,4,6,10,20]) #隨機選取
# data=random.sample([1,4,6,10,20],3) #隨機選取3筆
# print(data)
###########################################
# 隨機調換順序(洗牌) shuffle
# data=[1,5,6,10]
# random.shuffle(data)
# print(data)
#######... |
a9cf35cfcc4b2eccda75811a7af8b3c5a1ca53e2 | Aierhaimian/LeetCode | /Queue/0232_ImplementQueueUsingStack/queue_by_stack.py | 1,212 | 4.4375 | 4 | #!/usr/bin/env python3
# -*-coding: utf-8 -*-
"""
Version: 0.1
Author: Earl
"""
"""
Time Complexity: O(2n)
Space Complexity: O(2n)
"""
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
input_stack = []
output_stack = []
def push(self, x:... |
8e8fc74768d12bf8cb021954668873693d3a1b72 | emeee/simple-binary-search-tree | /BST.py | 3,261 | 3.671875 | 4 | from node import Node
class BST:
def __init__(self):
self.root = None
self.size = 0
def length(self):
return self.size
def insert(self, key, val):
if self.root:
self._insert(key, val, self.root)
else:
self.root = Node(key ,val)
self... |
7defa3430066cb81cb821a8b7ea92b5205c1c417 | SergeyHess/kek | /binarySearch.py | 288 | 3.890625 | 4 | def binary_search(arr, value):
top = len(arr) - 1
bott = 0
mid = len(a) // 2
while arr[mid] != value and bott <= top:
bott = mid + 1 if value > arr[mid] else top = mid - 1
mid = (top + bott) // 2
print('No value') if bott > top else print(mid)
|
a1e93ffb4724066747c1d1421f67b16b2e81b30c | debrekXuHan/core_python | /chap3/read_modified.py | 377 | 4.1875 | 4 | #!/usr/bin/env python
'readTextFile.py -- read and display text file'
import os
# attempt to open file for reading
while True:
fname = input('Enter a filename: ')
if not os.path.exists(fname):
print('ERROR: %s does not exist\n' % fname)
else:
break
# display contents to the sceen
fobj = open(fname, 'r')
for ... |
136cc2404cb01fb3a2a4862ca82051d43f301e0d | SkrGitRepo/MyPythonDjango | /PYTHON_TRANING/CG_Python_Training/Day1/VariableArgument.py | 221 | 4 | 4 | def Var(*arg):
print arg
Var(4,6,'hello')
#-------------------------
#Mult(1,2,3,4) = (1*2*3*4)
def Mult(*arg):
mul =1
for num in arg:
mul = mul*num
print mul
Mult(5,2,3,4)
|
771e7f001e4b0cff78390b28d316534ad441f2e0 | konradluberapolsl/Algorytmy | /Zad2/Zad2.1 Kolejka/Zad2.1.py | 1,430 | 4.03125 | 4 | class Queue:
def __init__(self, capacity):
self.Queue = []
self.capacity = int(capacity)
def __str__(self):
if self.is_empty():
return "kolejka jest pusta"
else:
return str(self.Queue)
def size_of_queue(self):
return len(self.Queu... |
4b44d25c71da627c2cb2c268f6f6070bc7f81636 | bojan-popovic-devtech/UdemyPython | /Section 6 - Program Flow/IfChallenge.py | 506 | 4.25 | 4 | #Write a small program to ask for a name and an age.
#When both values have been entered, check if the person
#is the right age to go on an 18-30 holiday ( they must be over 18 and under 31)
#If they are, welcome them to the holiday, otherwise print
#a (polite) message refusing them entry
name = input("Please enter yo... |
784bf76695b67e8d3c076b9cd811a1cb1d72ca6f | khaveesh/DAA-DoubleHelix | /anarc05b_double_helix.py | 2,036 | 3.96875 | 4 | """Author - Khaveesh N IMT2018036. Solves the ANARC05B problem in SPOJ."""
import typing
from dataclasses import dataclass
@dataclass
class DoubleHelix:
"""Class to solve the double helix problem."""
first: typing.List[int]
second: typing.List[int]
iter_first = 0
iter_second = 0
sum1 = 0
... |
6f6593de948aa86144b6b386e1220ff7d19d0d00 | vinayhg87/SeleniumUdemy | /Classes/MethodOverloading.py | 763 | 3.9375 | 4 | # In Python, overloading is not an applied concept.
# we need to use a package like pythonlangutil to get the method overloading functionality or use the below technique.
# None is a keyword which is equivalent to null.
# Python does not support method overloading, that is, it is not possible to define more than one me... |
2324ee5121b21c3411493e6c7316e7af75efadaf | danielmmetz/euler | /euler006.py | 829 | 3.921875 | 4 | """
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural
numbers and the square of the sum is 3025 - ... |
45e76d81b85d837979f07126a032f75f7644d4c8 | zzarbttoo/TMT | /YJ/20200629_2_1.py | 935 | 3.546875 | 4 | #풀이 1
def solution(phone_book):
answer = True
phone_book = sorted(phone_book)
for i in range(0, len(phone_book)):
for j in range (i+1, len(phone_book)):
if phone_book[j].startswith(phone_book[i]):
#바로 return 을 하면 효율성 테스트를 통과할 수 있다
return False
retu... |
43dc2bd7661fbb4b1e0c1fc3ee4d3c4706337eb8 | minccia/python | /python3/exerciciosOOP/pessoa.py | 902 | 3.78125 | 4 | class Pessoa:
def __init__(self, nome, idade, peso, altura):
self.nome = nome
self.idade = idade
self.peso = peso
self.altura = altura
def envelhecer(self):
self.idade += 1
print(f'A pessoa envelheceu mais um ano, e agora tem {self.idade} anos.')
if ... |
262823bab54e7c7fd1b9f441819687bf061ec238 | asmitamahamuni/python_programs | /fibonacci_series.py | 511 | 3.953125 | 4 | # Print Fibonacci Series using Iterrator, Recurssion and Generator
# iterative
def fibi(n):
a, b = 0, 1
for i in range(0,n):
a, b = b, a+b
return a
# recursive
def fibr(n):
if n == 0: return 0
if n == 1: return 1
return fibr(n-2)+fibr(n-1)
for i in range(10):
print (fibi(i), fibr(i))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.