blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
ce27ea7227e010fedec8f2b60cf5eddf820c9e55
luozhiping/leetcode
/middle/letter_combinations_of_a_phone_number.py
843
3.6875
4
# 17. 电话号码的字母组合 # https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/ class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if not digits: return [] alphabet = {"2": "abc", "3": "def"...
aa44933a8f6a1776eab56362cf995d17a1086222
luozhiping/leetcode
/middle/count_complete_tree_nodes.py
995
3.625
4
# 222. 完全二叉树的节点个数 # https://leetcode-cn.com/problems/count-complete-tree-nodes/ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def countNodes(self, root): """ :t...
3f69ddedbac780c64476df7877ac5f58933ddb91
luozhiping/leetcode
/middle/binary_tree_right_side_view.py
1,582
3.84375
4
# 199. 二叉树的右视图 # https://leetcode-cn.com/problems/binary-tree-right-side-view/ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def rightSideView(self, root): """ ...
ae884e0ac1ba14fb7b5d9dcf0fef367d9252e606
luozhiping/leetcode
/middle/insertion_sort_list.py
1,801
3.828125
4
# 147. 对链表进行插入排序 # https://leetcode-cn.com/problems/insertion-sort-list/ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype...
5844ac8ff18bdd670873ee0ba65ad13f0ad915f7
luozhiping/leetcode
/middle/validate_stack_sequences.py
938
3.671875
4
# 946. 验证栈序列 # https://leetcode-cn.com/problems/validate-stack-sequences/ class Solution(object): def validateStackSequences(self, pushed, popped): """ :type pushed: List[int] :type popped: List[int] :rtype: bool """ if not pushed or not popped: return Tr...
fef6de4ad101b36061e83cddcf66f0d0f68048ef
luozhiping/leetcode
/middle/replace_words.py
2,187
3.625
4
# 648. 单词替换 # https://leetcode-cn.com/problems/replace-words/ class Solution(object): def replaceWords(self, dict, sentence): """ :type dict: List[str] :type sentence: str :rtype: str """ class TreeNode(object): def __init__(self, char, isWord = False): ...
f0bc2a6428da5bcc92df54444a373d07b2e1ee90
luozhiping/leetcode
/2018tencent50/easy/reverse_integer.py
597
3.71875
4
# 反转整数 # https://leetcode-cn.com/problems/reverse-integer/ class Solution: def reverse(self, x): """ :type x: int :rtype: int """ result = 0 negative = x < 0 if negative: x = -x while x > 0: result = result * 10 + x % 10 ...
e6d52eaa2c41c0b7278904b3e1a628fde2d520c0
luozhiping/leetcode
/2018tencent50/easy/reverse_words_in_a_string_iii.py
454
3.890625
4
# 反转字符串中的单词 III # https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/ class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ s = s[::-1] words = s.split()[::-1] result = "" for word in words: resul...
d6f141bfe86dbab6f06bec5a8ff691c20c9c7155
luozhiping/leetcode
/middle/basic_calculator_ii.py
1,765
3.5625
4
# 227. 基本计算器 II # https://leetcode-cn.com/problems/basic-calculator-ii/ class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ s = s.replace(" ", "") tmp = s.split("+") result = 0 for str in tmp: t = str.split("-"...
864668187bb301ca8bfb865d9ea505ae85c97b40
luozhiping/leetcode
/2018tencent50/easy/nim_game.py
545
3.5
4
# nim游戏 # https://leetcode-cn.com/problems/nim-game/ class Solution: def canWinNim(self, n): """ :type n: int :rtype: bool """ # result = [] # result.append(True) # result.append(True) # result.append(True) # result.append(True) # res...
83e7b7a6dbb2c609277218224b6802025f318823
luozhiping/leetcode
/middle/maximum_length_of_repeated_subarray.py
741
3.640625
4
# 718. 最长重复子数组 # https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/ class Solution(object): def findLength(self, A, B): """ :type A: List[int] :type B: List[int] :rtype: int """ if not A or not B: return 0 result = 0 boa...
18f9c5527e045f9a80f35196d2a23201c79432fd
luozhiping/leetcode
/2018tencent50/middle/product_of_array_except_self.py
584
3.640625
4
# 除自身以外数组的乘积 # https://leetcode-cn.com/problems/product-of-array-except-self/ class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ length = len(nums) array1 = [1] * length for i, num in enumerate(nums[:-1]...
1eb65633b243ce71ea47c830ac34b1d46b85018a
luozhiping/leetcode
/middle/reorder_list.py
1,660
3.625
4
# 143. 重排链表 # https://leetcode-cn.com/problems/reorder-list/ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reorderList(self, head: ListNode) -> None: """ Do not return anything, modify head in-place ...
4705169d9255514911d822c5752ea73b07d3c008
luozhiping/leetcode
/middle/powx_n.py
263
3.546875
4
# 50. Pow(x, n) # https://leetcode-cn.com/problems/powx-n/ class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ return pow(x, n) s = Solution() print(s.myPow(2, 10))
26880b9ea783f0a27379854b323a9b1bed02fc8c
luozhiping/leetcode
/middle/find_and_replace_in_string.py
1,145
3.71875
4
# 833. 字符串中的查找与替换 # https://leetcode-cn.com/problems/find-and-replace-in-string/ class Solution(object): def findReplaceString(self, S, indexes, sources, targets): """ :type S: str :type indexes: List[int] :type sources: List[str] :type targets: List[str] :rtype: str...
6623742d3c9b58e6e8f1fa6c3f178e8b40a9ef3f
heersaak/opdrachtenPython
/Opdrachten/Les 4/4_1.py
405
3.5625
4
## Maak een nieuwe Python file aan voor deze opdracht (vanaf nu is dat standaard en zal dat niet steeds ## meer bij de opdracht staan). Schrijf (en test) de functie som() die 3 parameters heeft: getal1, getal2 ## en getal3. De return-waarde van de functie moet de som (optelling) van deze parameters zijn! getal1 = 1 ge...
89c5d7aa305f0ed3de08ff8ed66075ad1863a117
heersaak/opdrachtenPython
/Opdrachten/Les 5/5_1.py
763
4.25
4
##Schrijf een functie convert() waar je een temperatuur in graden Celsius (als parameter van deze ##functie) kunt omzetten naar graden Fahrenheit. Je kunt de temperatuur in Fahrenheit berekenen met ##de formule T(°F) = T(°C) × 1.8 + 32. Dus 25 °C = 25 * 1.8 + 32 = 77 °F. ##Schrijf nu ook een tweede functie table() waa...
bf6a89d3bdc4e429312711f8b08840bfbd0b28d6
heersaak/opdrachtenPython
/Opdrachten/Les 2/2_2.py
1,182
3.640625
4
##De Hogeschool Utrecht wil studenten financieel ondersteunen bij hun studie, afhankelijk van de cijfers ##die een student haalt. Voor elk cijferpunt krijg je € 30,-. Voor een 1,0 krijgt je dus 30 euro, voor een 2,5 ##krijgt je 75 euro en voor een 10,0 beloont de HU een student met € 300,-. ##Maak variabelen cijferICOR...
164c4a03031619d462224fcd6194cb53954eaf60
heersaak/opdrachtenPython
/Opdrachten/Les 2/2_4.py
306
3.625
4
##Schrijf een programma dat de gebruiker vraagt om zijn uurloon, het aantal uur dat hij of zij gewerkt ##heeft en dat daarna het salaris uitprint. uren = float(input('Hoeveel uren heb je gemaakt? ' )) loon = float(input('Hoeveel verdien je per uur?')) print(uren,'uur werken levert',(uren*loon),'euro op')
40224c5ba455fb7e03e135ff2cb35e94c150e351
lyoness1/Calculator-2
/calculator.py
1,772
4.25
4
""" calculator.py Using our arithmetic.py file from Exercise02, create the calculator program yourself in this file. """ from arithmetic import * def intergerize(str_list): """returns a list of integers from a list of strings""" return map(int, str_list) def read_string(): """reads the input to determin...
45da3442cc3f3527ae6db2783f49080882df1275
MH99-prog/Py.chap8.py
/chap#8.1,8.2,8.3.py
629
3.765625
4
#8.1 def make_shirt(size, message): print("The size of shirt is "+size.upper()+".") print("The message printed on the shirt is "+message+".\n") make_shirt('XL','sunshine on the beach') make_shirt(size = 'XL',message = 'sunshine on the beach') #8.2 def make_shirt(size = 'large',message = 'I love python'): ...
1e3e4a200bf8e1db120c6d21463a9186f26b19a5
ashwinimanoj/python-practice
/findSeq.py
805
4.1875
4
'''Consider this puzzle: by starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of new numbers can be produced. How would you write a function that, given a num- ber, tries to find a sequence of such additions and multiplications that produce that number? For example, the n...
161a16a1599f3533f66f4a0dd8d738476876e376
saifuzzaman-sabuj/assignment
/Assignment.py
298
4.09375
4
number=int(input("Enter the number: ")) if number%3==0 and number%5==0: print("Consultadd - Python Training") elif number%5==0: print("Python Training") elif number%3==0: print("Consultadd") else: print("u are worng")
c27477be1d8c70538487de77bc558f3e8500b27d
steventaesungkim/py104
/square.py
200
3.90625
4
# Prints a 5X5 square of * characters row = 0 while row < 5: col = 0 while col < 5: print("*", end="") col += 1 row += 1 print() #Re-write so that row = 5*******
33e321b4dd5fd765d929daf89bc43d7dcb6a8bef
mmellone/Market-Analytics
/Data-Collection/historical.py
2,748
3.625
4
from yahoo_finance import Share import pandas as pd import os """ A collection of functions to gather and perform basic processing on historical stock data from Yahoo. Uses Pandas dataframes objects to organize data """ def generate_csv(symbol, start_date, end_date, file_name=''): """ Generates a csv of historica...
5a4798d92318b3adb88731958131babd48c2febc
konstgazha/steamrec
/steamrec/data_actualization.py
729
3.765625
4
from datetime import datetime class DataActualization: def month_to_number(self, string): month = { 'янв.': 1, 'фев.': 2, 'мар.': 3, 'апр.': 4, 'мая.': 5, 'июн.': 6, 'июл.': 7, 'авг.': 8, 'сен.': 9,...
c71327e6285ac5f58b8fed3f95dd458037d016cb
vladimirkaldin/HomeTask
/1.2.py
613
4.4375
4
#2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. # Используйте форматирование строк. seconds_time = int(input("Введите время в секундах")) print(f'Время {seconds_time} секунд') hours = seconds_time // 3600 minutes = int((seconds_time % 3600) / 60)...
c36f067185a1bfd7f0241492d533608b60588f69
vladimirkaldin/HomeTask
/4.6.py
688
4.03125
4
# 6. Реализовать два небольших скрипта: # а) бесконечный итератор, генерирующий целые числа, начиная с указанного, # б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее. # Подсказка: использовать функцию count() и cycle() модуля itertools. from sys import argv from itertools im...
bbb273a9b1dce01c6c53f0f739272490f1455859
vladimirkaldin/HomeTask
/1.1.py
609
4.28125
4
#1. Поработайте с переменными, создайте несколько, выведите на экран, запросите у пользователя несколько чисел и #строк и сохраните в переменные, выведите на экран. age = 0 age = int(input("Введите возраст")) print(f'Возраст пользователя - {age}') name = 'Имя пользователя не задано' print(name) name = input(...
95af2484b271b78212ccefd4e8d06a6df05f875b
New2object/guest2
/src/framework/test_case/demo.py
855
4
4
# coding=utf-8 ''' lists = [9, 2, 4, 7, 75, 33, 64, 1, 445] def bubble_sort(lists): # 冒泡 count = len(lists) for i in range(0, count): for j in range(i + 1, count): if lists[i] > lists[j]: lists[i], lists[j] = lists[j], lists[i] return lists print(bubble_sort(lists...
cc91a6f3d46c3089e7ee4b1b28b1d960269ecb8b
jmmoloney/hackerrank
/programming/arrays/hourglassSum_2dArray.py
662
3.6875
4
#!/bin/python3 import math import os import random import re import sys # Complete the hourglassSum function below. def hourglassSum(arr): max_sum = -63 # maximum negative value possible for i in [0, 1, 2, 3]: first_row = arr[i] second_row = arr[i + 1] third_row = arr[i + 2] fo...
1377c3aabb11ba82fd0337b1ef56f0baf0c6de21
yunge008/LintCode
/6.LinkedList/[E]Nth to Last Node in List.py
1,236
4.1875
4
# -*- coding: utf-8 -*- __author__ = 'yunge008' """ Find the nth to last element of a singly linked list. The minimum number of nodes in list is n. Example Given a List 3->2->1->5->null and n = 2, return node whose value is 1. """ class ListNode(object): def __init__(self, val, next=None): ...
846b0924cec1a3fd9dfb225af2b22404d1ca5268
yunge008/LintCode
/6.LinkedList/[M]Convert Sorted List to Balanced BST.py
1,053
4.125
4
# -*- coding: utf-8 -*- __author__ = 'yunge008' """ Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 2 1->2->3 => / \ 1 3 """ class ListNode(object): def __init__(self, val, next=None): self.val = ...
23d3516597f8de65112a3a825aeabf57795c228d
yunge008/LintCode
/2.IntegerArray/[M]Partition Array.py
972
4.09375
4
# -*- coding: utf-8 -*- __author__ = 'yunge' ''' Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that: All elements < k are moved to the left All elements >= k are moved to the right Return the partitioning index, i.e the first index i nums[i] >= k. Ex...
eb856747b12ad9296e4309679c763175f2cfc018
Marusya-ryazanova/Lesson_2
/Vasya.py
747
4.25
4
speed = float(input("Средняя скорость: ")) time = int(input("Верям в пути: ")) point = time * speed # Вычисляем точку остановки if point > 100: print("поехал по второму кругу, пройденное растояние = ", point) elif point < 0: print("велосипедист едет назад уже", point , "километров") elif point == 0: print(...
281ef4a2362cfa59001ed7e47d36cb35fc1ec6e1
Sjsatishjaiswal/ML
/ml26.py
3,576
3.828125
4
Decision Tree Algorithm Decision : Prediction involves decision making Tree : Non-linear data structure Algorithm : Aap jaante he hai The DT Algorithm develops a tree like structure in accordance with the data fed to it. This tree like structure can then be traversed for pred...
896841b93741f2b09cd36c09ff494f1bb6851059
simplifiedlearning/dummy
/function.py
1,739
4.375
4
######################FUNCTIONS#################### #SYNTAX #using def keyword #without parameters def greet(): print("hello") greet() ###add two number #with parameters def add1(x,y): z=x+y print(z) add1(2,3) ####default arguments def add2(b,c,a=12): print(a+b+c) add2(5,5) ####abritriy...
147887d5f173f6670f437c30ab380eaad6c70b42
ivansaji/TCS-IRA-practice
/Unix/Vaccination/code.py
1,516
3.6875
4
class Magazine: def __init__(self, Author, Viewers, Cost, Name): self.Author = Author self.Viewers = Viewers self.Cost = Cost self.Name = Name class publishingHouse: def __init__(self, magazineCollection): self.magazineCollection = magazineCollection def findMinimu...
18c53df6a81dddd94ffe4c7c8fb48986bdb65756
Hoanganh270400/CP1404-practicals
/prac8/taxi_test.py
471
3.59375
4
""" Github link: https://github.com/Hoanganh270400/CP1404-practicals """ from taxi import Taxi def main(): taxi = Taxi("Prius 1", 100) taxi.drive(40) print(taxi.__str__()) print("Taxi's current fare: {}".format(taxi.get_fare())) taxi.start_fare() taxi.drive(100) print("Taxi detail - Name: ...
f3e74dbb458d21bafa4e015d871ad5d66b95e05a
Hoanganh270400/CP1404-practicals
/list_exercises.py
781
3.984375
4
list = [] number_1 = int(input("Number: ")) list.append(number_1) number_2 = int(input("Number: ")) list.append(number_2) number_3 = int(input("Number: ")) list.append(number_3) number_4 = int(input("Number: ")) list.append(number_4) number_5 = int(input("Number: ")) list.append(number_5) print("The first ...
581b3eb6aa373b8abc54e01831e17adfbeca553c
KhannaRajat/python
/password_generator.py
1,346
3.640625
4
import re import string import random class PasswordGenerator: #---charset: u,l,U,L,d,D,s,S #--- length : length of password. def __init__(self, charset, length): self.charset = charset self.length = int(length) self.charset_arr = [] self.password = [] #---user...
d66322bed1140ee4d41adb835b49e924ca179425
GeodezSPB/academic
/part_01.py
371
4
4
import math name = "Eugene" print("Hello World", name) year = 2020 print("Today is", year, "year.") a=5; b=3 r = a + b print ("a =", a,"b =", b, ": a + b =", r) if ( a>b ): print ("a>b") else: print ("a<=b") print("Чай") text = input("введите текст:") print("текст =", text) pi = math.acos(-1) print("Число ПИ ...
167508f0eec81c25ac1402f1fea9ea3e95296173
tmaiman/My-Ans-for-Automate-the-Boring-Stuff-with-Python
/Chapter-9/MadLibs.py
935
3.90625
4
#Opens input file as read-mode and output file as write-mode in with wrapper with open('inputFile.txt', 'r') as inStr, open('outputFile.txt', 'w') as outStr: sentence = inStr.read() #Read string value from input file sentence = sentence.split() #Separate words by whitespace into a list adjective =...
488eb610ae5a842238c5220d70efde338548b611
thecolorkeo/cc_data_migration
/src/data_migration.py
1,810
3.5
4
# Keo Chan # Insight Practice Coding Challenge W2 ''' Read in text from a .zip file in JSON and convert it to a table in Postgres. ''' import sys import os import zipfile import json import pandas as pd from pandas.io.json import json_normalize import sqlalchemy from sqlalchemy import create_engine import summary_sta...
03a2ed80a354cec4f23f8f1cc565ed41dbe9be5e
Jshigoodies/YoutubeDownload
/downloadMusic.py
1,160
3.765625
4
from pathlib import Path from pytube import YouTube list = [] print("Enter URLs (terminate = 'STOP')") while True: url = input("") if url == "STOP": break list.append(url) for link in list: video = YouTube(link) for stream in video.streams: # the video can be many different types of thing...
b7a9a4c63b9a1ec5c233f6a67bce4972c90656a5
dpdahal/python7am-2021
/datatypes.py
870
3.59375
4
# Integer: int,float,complex # String: '' # Boolean # List [] # Tuple () # SET {} # Dictionary {} # name = "ram" # print(name.upper()) # print(dir(name)) # print(type(name)) # x =23453 int # x = 123.567 float # x = 234j # a=23 # print(a.real) # print(x.imag) # print(dir(x)) # print(type(x)) # name = "ram" # age = 2...
59c56207d7993fe8a94c4f45a96c87ea3198fd58
naomi-rc/PythonTipsTutorials
/context_managers.py
2,381
3.921875
4
# context managers : structures that allow for allocating and releasing resources upon use # Basic example - open is the context manager with open("text.txt") as file: print(file.read() + "\n") # Custom context manager as a class class TranslationResource(object): def __init__(self, text): self.open =...
c0620531c0aea733e89fda828f42333573c5dcde
naomi-rc/PythonTipsTutorials
/generators.py
638
4.34375
4
# generators are iterators that can only be iterated over once # They are implemented as functions that yield a value (not return) # next(generator) returns the next element in the sequence or StopIteration error # iter(iterable) returns the iterable's iterator def my_generator(x): for i in range(x): yield...
2f7d869fdcce5a45fd4003d771984b3c871bb921
naomi-rc/PythonTipsTutorials
/enumerate.py
417
4.3125
4
# enumerate : function to loop over something and provide a counter languages = ["java", "javascript", "typescript", "python", "csharp"] for index, language in enumerate(languages): print(index, language) print() starting_index = 1 for index, language in enumerate(languages, starting_index): print(index, lang...
7f03636f52cacc2936a523997408785079e87253
tanpv/algorithms
/data_structure/linked_list.py
2,220
4.09375
4
# Defenition # LinkedList is a data structure consisting of a group of nodes which together represent a sequence. # Under the simplest form, each node is composed of data and a reference (in other words, a link) # to the next node in the sequence. This structure allows for efficient insertion or removal of elements ...
6698467799ec9928376689ef58e4e7b66dd65f7a
E-voldykov/python_for_beginners
/les2/hmwrk5.py
2,678
4.09375
4
""" Реализовать структуру «Рейтинг», представляющую собой не возрастающий набор натуральных чисел. У пользователя необходимо запрашивать новый элемент рейтинга. Если в рейтинге существуют элементы с одинаковыми значениями, то новый элемент с тем же значением должен разместиться после них. """ # Введем стартовый список ...
b6edcfc7160d348fedf295982a0bfdb7a421aee2
E-voldykov/python_for_beginners
/les3/hmwrk6.py
1,054
4.3125
4
""" Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же, но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text. Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом. Каждое слово состоит из латинских букв в ниж...
82e1ab9b3298d3b298956414c454779742f6fed0
leonlee603/Python_projects
/password_generator.py
5,210
4.375
4
""" :::Password Generator::: This is a programme which generates a random password for the user. Ask the user how long they want their password to be. Then the programme will generate a password with a mix of upper and lowercase letters, as well as numbers and symbols. The password should be a minimum of 8 character...
0f0c440b5aa020591abc317e517dfeb6e9ad3861
baohan8850/C4T-B10
/BTss9/part1.py
159
3.75
4
list = ['blue','orange','green'] print(list) new = input('mau moi: ') list.append(new) print(list) vt = int(input('nhap vi tri muon xem:')) print(list[vt-1])
6ce89f409509f9ec77536fd4242cab33ca90f129
baohan8850/C4T-B10
/session5/game.py
803
3.71875
4
import random count = 0 while True: num1 = random.randint(1,30) num2 = random.randint(1,15) saiso = random.randint(-3,3) sum = num1 + num2 + saiso print("{} + {} = {}".format(num1, num2, sum)) ans = input("T or F?").lower() if saiso == 0: if ans == "t": print("Correct"...
01644a859828210fd834762a48e0f4f44516df33
baohan8850/C4T-B10
/BTss10/dictinlist.py
405
3.984375
4
sach = { 'name':'dragon ball', 'year':'2014', 'char':'Son Goku, Picollo, Gohan,...' } sach['conutry'] = 'Japan' print(sach) for x in sach: print(x,'-',sach[x]) sach['name'] = 'a' sach['year'] = 1999 sach['char'] = ['b', 'f', 'r'] sach['country'] = 'c' print(sach) #sach['char'].append('d') print(...
9c17a6cda08c1d3ee02942aa014473af3cbd8efa
cnorrisf18/ml-lab01-norris
/Thursday.py
2,492
3.84375
4
""" Copy paste these instructions in there. (copy out everything highlighted) Look through the "links" variable and see if you can find some image covers. Edit Proj_01_08 to make the loop in proj_01_08 print out the path to the images for all of the book cover thumb images. """ import requests from bs4 import Beautifu...
fbc9bbfbb0b4c12eb7af244cdf85a96fb726b2b2
RayGar7/AlgorithmsAndDataStructures
/Python/diagonal_difference.py
581
4.25
4
# Given a square matrix, calculate the absolute difference between the sums of its diagonals. # For example, the square matrix is shown below: # 1 2 3 # 4 5 6 # 9 8 9 # The left-to-right diagonal = 1 + 5 + 9 = 15. The right to left diagonal = 3 + 5 + 9 = 17. Their absolute difference is abs(15 - 17) = 2. def dia...
acb1fa61534dbe81758fd69243cf5baebd81edba
RayGar7/AlgorithmsAndDataStructures
/Python/matrixOperations.py
614
3.75
4
# I've realized that matrix operations are one place where I struggle a lot # so this file will be a container for me to have as reference for cmon 2Dimensional problems def checkMembership(M, data): for i in range(0, len(M)): for j in range(0, len(M[0])): if (M[i][j] == data): r...
b32bf98992bd8e41434c7ac3cf2f1bfae7b9eeda
deva-sou/pythonProjects
/Moriarty.py
8,931
3.546875
4
import sys def menu(): print("\n---- Bienvenue dans le jeu MORIARTY ----") print("\n[1] - Afficher les règles") print("[2] - Commencer une partie") print("[3] - Quitter le programme") rep = 1 while rep != 0: rep = int(input("\nQuel est votre choix ? : ")) if rep == 1: ...
c864f33ec1ec9cd25e5979e5d650bf01802d398b
rakibul7/Simple-guess-game
/Simple_Guess_Game.py
981
3.796875
4
import random #GET GUESS def get_gess(): return list(input("What is your GUESS ?")) #GENERATES COMPUTER CODE 123 def generates_code(): digits=[str(num) for num in range(10) ] # here we will shuffle the digits random.shuffle # here we will grub the first three digits return digits[:4] #GENERATES ...
c60be60cac66f6281f38d818a194a5c51ecba618
numberoverzero/UIComponents
/src/Util/Math/trig_tables.py
1,989
3.5625
4
""" Pre-computes values for sin and cos, making calculations faster, though slightly less accurate. Can compensate for this by upping resolution. Values are accurate to within 1/RESOLUTION of a degree. """ import math RESOLUTION = 2000 SIZE = int(360 * RESOLUTION) COS = {} SIN = {} for i in xrange(SIZE): __pct...
5d29c962fdb7e82378c4576c110296f20020e5ad
numberoverzero/UIComponents
/src/Util/IO/_lib.py
1,514
3.71875
4
""" IO common functions """ __all__ = ['bufcount', 'ensdir', 'ensfile', 'remove_file'] import os import os.path def bufcount(filename): """ Counts the number of lines in a file quickly. Code from (with minor change): http://stackoverflow.com/questions/ 845058/how-to-get-line-c...
d16132b76cf11d8e242b57f2e1846ce1259030ab
numberoverzero/UIComponents
/src/Util/Math/digits.py
3,403
4.125
4
"""" Common operations and queries regarding a numbers' digits. These are largely imported from various project euler problems. """ from math import floor, log10 def filter_numbers_with_digits(numbers, good_digits): """ Returns a new list w/numbers that only have digits in good_digits. For e...
1c304931003282b49dedc5ecf5743a7632e7e04e
rubelbd82/Machine-Learning
/Python/multiple_linear_regression.py
1,380
3.703125
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd # Improting the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values # print(X) y = dataset.iloc[:, 4].values # # from sklearn.preprocessing import LabelEncoder, OneHotEncoder # labelEncoder_X = LabelEncoder() # X[:,...
64466b637b49b744d34c0d37cacd212998177a0b
mohitarora3/python003
/sum_of_list.py
376
4.125
4
def sumList(list): ''' objective: to compute sum of list input parameters: list: consist of elemnts of which sum has to be found return value: sum of elements of list ''' #approach: using recursion if list == []: return 0 else: return(list[0]+sumLi...
f97acf6d6af9b6d49c17c956283fd48e429c3568
danshyles/waimea
/lthsensor.py
1,118
3.53125
4
import time import board import busio import adafruit_si7021 import RPi.GPIO as GPIO #Script for Temperature/Humidity sensing #Create library object using our Bus I2C port i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_si7021.SI7021(busio.I2C(board.SCL, board.SDA)) reading = 0 #GPIO.setmode(GPIO.BOARD) #def...
5cecdc3cb4373a598efbe015f6446f84ee950501
lsalgado97/My-Portfolio
/python-learning/basics/guess-a-number.py
2,369
4.34375
4
# This is a code for a game in which the player must guess a random integer between 1 and 100. # It was written in the context of a 2-part python learning course, and is meant to introduce # basic concepts of Python: variables, logic relations, built-in types and functions, if and # for loops, user input, program ou...
e788fb3ce07fe272a06d6adcca615c89ab1d865c
vijaypatha/pytIntro
/iffs/rps.py
887
3.96875
4
import random; player = input("Choose") player = player.lower() print ("your choice:" + player) computerChoice = random.randint(0,2) if computerChoice == 0: computer = "rock" print("computer choose:Rock") elif computerChoice == 1: computer = "paper" print("computer choose:Paper") elif computerChoice ==...
3372bd592766b84fc1a586b926783da791d95012
macthecadillac/Interacting-Fermions
/spinsys/utils/misc.py
4,501
3.609375
4
""" This file is part of spinsys. Spinsys is free software: you can redistribute it and/or modify it under the terms of the BSD 3-clause license. See LICENSE.txt for exact terms and conditions. This module provides tools that are useful but not, strictly speaking, related to quantum mechanics. Function included: ...
16a7c3cb7ab567d385631b391f59dbefc07c85d0
victoroalvarez/random-strings-python
/random-strings.py
588
3.890625
4
# libraries import import string import random # String generator function, takes an integer argument which determines string length # and another with all alpha-numeric characters def rs_generator(string_size=12, alphanumeric_characters=string.ascii_lowercase + string.digits): # returns alpha numeric string of parti...
a8ebe14c6d00aa99e4cc64e3ec5364e41a5f08e9
iamsukant/delhiretry2
/chapter1.2/pythonprep /functions.py
151
3.53125
4
def square(x): return x*x# XXX: def main(): for i in range(10): print(f"{i} time {i} is {square(i)}") if __name__=="main": main()
63046effe2594165b1161beaa9e753ae8355c5eb
wishinghyun/python
/intro/definition.py
252
3.859375
4
def hello(): return "Hello, World!" def add(num, number): return num + number nums = add(3,4) print(nums) def ran(num, number=10): return num + number nums = ran(3) print(nums) def m_num(a,b): return a-b a=3 b=4 minus = m_num(b,a)
620395a61e712ecf98438c7c2eff7b663247da51
wzz886/aaaaaa_game
/python 3 Tool/learn_def.py
2,457
4.4375
4
''' Python3 函数 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。 函数能提高应用的模块性,和代码的重复利用率。 你已经知道Python提供了许多内建函数,比如print()。 但你也可以自己创建函数,这被叫做用户自定义函数。 语法: def 函数名(参数列表): 函数体 ''' # 参数 ''' 以下是调用函数时可使用的正式参数类型: 1.必需参数 2.关键字参数 3.默认参数 4.不定长参数 ''' # 必需参数 def showInfo(str): "打印任何字符串" print(str) # 调用showInfo,必须传参 showInfo("调用showInfo,必须传...
856df03aff5291c90cdf60bf69c248ce45d9f694
wzz886/aaaaaa_game
/python 3 Tool/learn_base.py
189
4.1875
4
# 关键字end可以用于将结果输出到同一行,或者在输出的末尾添加不同的字符 print("------------------") num = 0 while num < 3: num += 1 print(num, end = ",")
3d8360f65f2266fad464266e162d044d1d871a52
myxlinh99/Homework-DoMyLinh
/Session 3/Sheep.py
539
3.625
4
ss_list=[5,7,300,90,24,50,75] print("Hello, my name is Hiep and these are my sheep sizes") print(ss_list) print("Now my biggest sheep has size", max (ss_list), "let's shear it") ss_list.remove(max(ss_list)) print("After shearing, here is my flock") print(ss_list) for i in range (1,5): print(i, "month(s) has passe...
f258277d59ff9095f8cfdbabed74b74a065465bf
robertsmukans/DMI
/python/sin_caur_summ6.py
497
3.625
4
# -*- coding: utf-8 -*- from math import sin def mans_sinuss(x): k = 0 a = (-1)**0*x**1/(1) S = a print "a = %6.2f S0 = %.2f"%(a,S) while k< 3: k = k + 1 R = * (-1) * x**2/((2*k)*(2*k+1)) a = a * R S = S + a print "a%d = %6.2f S%d = %6.2f"%(k,a,k,S) ...
cd88b4c54001ac8a0f77bd2b3caa6e1b0568a99d
sherry0812/simulation
/monty hall/montyhallproblem.py
1,397
3.890625
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 18 11:17:23 2020 @author: cherryb """ import random # Set number of boxes nBox = 50 # Set number of simulations n = 1000 scoreLoyal = 0 scoreSwap = 0 # Simulate n times for i in range(n): listBox = [] listBox = list(range(1, nBox+1)) # Randomly c...
6e664320073f16a115c3449ef1cf355b32a87dd3
san7ae/Ultimate_BLMannschaft
/merge.py
18,611
3.5625
4
import csv, os import pandas as pd # the file names f1 = "abgefangeneBaelle.csv" f2 = "abgewehrteElfmeter.csv" out_f = "1.csv" # read the files df1 = pd.read_csv(f1) df2 = pd.read_csv(f2) # get the keys keys1 = list(df1) keys2 = list(df2) # merge both files for idx, row in df2.iterrows(): data = df1[df1['Nam...
3f1932f41b556d700536b04f8f3f1bbed492cfe4
LaloValle/HOC5
/Recursos.py
2,886
3.890625
4
# -*- coding: utf-8 -*- #@author: Lalo Valle import math from Programa import * programa = Programa.programa() """ Lista de nombre de los tokens """ tokens = [ 'NUMERO', 'INDEFINIDA', 'VARIABLE', 'FUNCION', 'CONSTANTE', 'CADENA', 'PRINT', 'INCREMENTO', 'DECREMENTO', 'OR', # Operadores lógicos 'AND', 'M...
c2356498914228f94afda923c2040f34daa75a51
GODGANG4885/Algorithm_Solution_Git
/매일프로그래밍 by Python/question2.py
378
3.859375
4
# 매일프로그래밍 2 # 피보나치를 재귀함수 사용하지않고 짜보기 def evenFibSum(N): nextval = 0 sum = 0 plist = [0,1] while(nextval<N) : plist.append((plist[-2]+plist[-1])) nextval = plist[-1] if (nextval % 2 ==0) : sum += nextval return sum print(evenFibSum(100)) # for i in range(5): # print(pibona...
7fdea86df2ce81b2056dc8a6e1e379abffa5793d
wuxiaojiang/PCR_project
/服务器(远程socket)/gpio_tools.py
629
3.765625
4
#!/usr/bin/python #-*-coding:utf-8-*- #----------------------------------- #程序名:远程服务器gpio接口 #作 者:吴晓疆 #日 期:2015/4/7 #----------------------------------- import RPi.GPIO as GPIO class gpio(): def _init_(self): pass def init_gpio(self,num,flag): self.num=num GPIO.setmode(GPI...
3cac6f99f2466dc12e7f963faf1eb373c3cbaf29
anshulgera17/sunbeam_practise
/python/code-4/funcyieldargs.py
569
3.859375
4
#!/usr/bin/python def main(): print("this is the functions.py file ") for i in inclusive_range(): print(i) def inclusive_range(*args): numargs = len(args) if numargs < 1: raise TypeError('required atleast one argument') elif numargs == 1: stop = args[0] start = 0 step = 1 elif numargs == 2: (start, sto...
341e1ca7f5368ccf4d5b8e83c09eb6b43d3fb482
anshulgera17/sunbeam_practise
/python/code-1/forloop.py
156
3.90625
4
#!/usr/bin/python #read lines from the file fh = open('lines.txt') for line in fh.readlines(): # print(line,end=' ') this is not working print(line)
542cbb8e13c313e7f6daa855ccd5d0ca42e44c9d
yingl910/DataWrangling_Python
/extract_data_csv.py
1,112
3.65625
4
'''This is an example of processing file and using the csv module to extract data from it.''' # 1. the first line of the datafile is neither data entry, nor header. It is a line describing the data source. # extract the name of the station from it. # 2. the data is returned as a list of lists (not dictionaries). im...
52b494e80e7dd3209ad68124ce5814356441e4b3
padavkas/aaa
/python/Maioroumenor.py
108
3.9375
4
idade = int(input( "idade " )) if idade >= 18 : print "maior de idade" else: print "menor de idade"
e957a9165e271d3673ca6518e689f95bafc93e30
padavkas/aaa
/python/Nota.py
140
3.640625
4
# Pedir Nota nota = int(input("nota")) # Decisao se passa ou Reprova if nota<=9: print "reprovou" if nota>9: print "passou"
b4495190099c3dfc2cf859b1cc86a75dd270db94
rohanneps/sitemap
/robots_sitemap_exists_checker/sitemap_robots_exists_checker.py
2,102
3.5
4
import os import requests import argparse def getProperUrlFormat(sitename): if 'http://' not in sitename and 'https://' not in sitename: url = 'https://{}'.format(sitename) else: url = sitename url = url.replace('http://','https://') return url def check_if_robots_sitemap_exists(url): robots_url = '{}/robot...
a217734a3107375059883574e23eca091d35b02f
10arturoV/curso-programacionATS
/prueba4.py
918
3.796875
4
producto = int(input("cuantos articulos va a llevar ")) contador = 0 cuentaTo = 0 while contador < producto: contador = contador + 1 costo = int(input("ingrese el costo del producto ")) captura = costo * .16 total = captura + costo print("costo del articulo con iva " + str(tot...
b1c548cb19dbd3277e89d4f66e7c7b79ce11c2d4
Vigyrious/python_oop
/Testing-Lab/Car-Manager.py
8,284
3.8125
4
class Car: def __init__(self, make, model, fuel_consumption, fuel_capacity): self.make = make self.model = model self.fuel_consumption = fuel_consumption self.fuel_capacity = fuel_capacity self.fuel_amount = 0 @property def make(self): return self.__make ...
08a330c3317e901f7a72f651ccf1702265b3f5a8
Vigyrious/python_oop
/Defining-Classes-Exercise/OOP-project-TODO-List/section.py
1,038
3.71875
4
from Library.task import Task class Section: def __init__(self, name): self.name = name self.tasks = [] def add_task(self, task: Task): if task in self.tasks: return f"Task is already in the section {self.name}" self.tasks.append(task) return f"Task {task....
e3bd13a1f2265a4736130e0d35a7c7a4bfed29d6
WangXiaoyugg/python-journey
/demo/decorator.py
825
3.765625
4
# 装饰器 import time def decorator(func): def wrapper(*args,**kw): print(time.time()) func(*args,**kw) return wrapper # 装饰器没有改变函数原来的调用方式 # 装饰器利用可变参数,解决参数不一致的问题 # 不知道参数是什么,抽象用 *args,**kw @decorator def f1(func_name): print('this is a function ' + func_name) # f = decorator(f1) # f() ...
0d6192f6f6939bfde8508c9e504603ab1f728421
WangXiaoyugg/python-journey
/demo/fn.py
364
3.515625
4
''' 1. 参数列表可以没有 2. return value None ''' ''' import sys sys.setrecursionlimit(1000) ''' def add(x,y): result = x + y return result # 自己调用自己,递归默认最大 995 次,可以自己设置 # 避免和内置变量和函数名称相同 def print_code(code): print(code) a = add(1,2) b = print_code('python') print(a,b)
624dbeb023cabbbcc448a1b57c017aae6f194f1c
BenjaminMoreauAstro/Phsx815_Week5_
/HW6.py
1,223
3.625
4
#Ben Moreau #Integrate e^x from 0 to 1, which is e-1 from math import * print("The analytical integral of e^x from -1 to 1 is:", (exp(1)-exp(-1))) print("Input the max number of rectangles") N=int(input()) #Rectangles def eee(x): return exp(x) Areas=[] AreasE=[] for i in range(5,N): Area=0 for k in...
90c6a43a7190dc3f14042889c911cc1ce47f45fe
chennasivasankar/Lab-4
/movingsumavg.py
616
3.53125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Feb 8 20:18:20 2019 @author: chenna """ import numpy as np import matplotlib.pyplot as plt n=np.linspace(0,200,200) x=5*np.sin(2*np.pi*n) fig=plt.figure() ax1=fig.add_subplot(3,1,1) ax2=fig.add_subplot(3,1,2) ax3=fig.add_subplot(3,1,3) no=np.sin(2*np....
7930054150afc8a94a934b527339703f2d3ea139
yni58-ni/sentimentAnalysis
/test 3.py
4,354
3.578125
4
import string def move_punc (tweetsName): with open(tweetsName) as t: punct = string.punctuation New_tweet2 = [] for Line in t: m = Line.strip().split(" ", 5) # use maxsplit to get tweet contents new_tweet = m[-1] new_tweet = new_tweet.split() ...
29122834150f9fc6ec77de7754dde108ecc5e174
JoshuaKabo/Flight-Price-Predictor
/MultiFeatureLinearRegressor.py
5,141
3.578125
4
#Josh Kabo 2019 #Flight Pricing Predictor from __future__ import print_function import math import numpy as np import pandas as pd from sklearn import metrics from matplotlib import pyplot as plt import tensorflow as tf from tensorflow.python.data import Dataset from InputFunctions import multi_feature_input_fn from Pr...
af6607399d229f7f12cfb7a47d5d3cd7297e13b5
optionalg/PortScan
/PortScan-CLI.py
1,487
3.578125
4
import socket import sys import ipaddress def scan_host(ip_addr, start_port, end_port): print('[*] Starting TCP port scan on host %s' % ip_addr) # Begin TCP scan on host tcp_scan(ip_addr, start_port, end_port) print('[+] TCP scan on host %s complete' % ip_addr) def scan_range(network, st...
7500d23703b118e665502fffa219ba92cb806ca9
Virtual69/BSA
/bsa.py
157
3.578125
4
first_number = input('first name: ') secound_number = input('second name: ') bsa = first_number + secound_number print(f'welcome to our B.S.A {bsa} ')
abe952821d7619f1b854eb86169258ce398cc809
Martin208/Python
/minutes_counter.py
367
3.953125
4
import time import os count_mins = int(input('How much time do you need? ')) sec=0 mins=0 while sec<=60: os.system('clear') print(f'{mins} minutes {sec} seconds') time.sleep(1) sec+=1 if sec==60: mins+=1 sec=0 if mins == count_mins: print('Stop the clock!') ...