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
19e41d802893cecc1696d60f0bdba0f0b37fbe00
mshkdm/python_TheHardWay
/def_math.py
742
3.859375
4
def addition(a, b): print "%d plus %d:" % (a, b) return a + b def subtraction(a, b): print "%d minus %d" % (a, b) return a - b def multiplication(a, b): print "%d times %d" % (a, b) return a * b def division(a, b): print "%d devide %d" % (a, b) return a / b my_age = addition(20, 2) m...
2e717f7d0655c94d9418f5bbcbab06e52b9dd4ca
JuanGinesRamisV/prueba
/p5e7.py
225
3.828125
4
#juan gines ramis vivancos p5e7 print('introduce la altura de tu trianuglo') altura = int(input()) anchura = altura for i in range(altura): print() anchura = altura-(1*i) for i in range(anchura): print('*', end='')
2f641407953a4ac12554fa669db3d207ed84eeba
JuanGinesRamisV/prueba
/ejercicio 1 practica 3.py
108
3.765625
4
#juan gines ramis vivancos práctica 3 ej1 print('introduzca su nombre') nombre = str(input()) print ('su nombre es', nombre,)
e6d2083ca51095635b17398a2beaa08378f92293
TestowanieAutomatyczneUG/laboratorium-11-marekpolom
/tests/test_friendships.py
1,960
3.5625
4
import unittest from unittest.mock import * from sample.friendships import FriendShips class TestFriendships(unittest.TestCase): def test_make_friends(self): temp = FriendShips() temp.makeFriends("Kowalski", "Nowak") self.assertEqual(temp.data, {"Kowalski": ["Nowak"], "Nowak": ["Kowalsk...
91855199661a07b6d4c2c3c4a97791445d32cd91
37stu37/Hikurangi_mhzrd
/mhzrd_hikurangi.py
666
3.5625
4
import pandas as pd import numpy as np import os def Earthquake(): # select a source area to trigger an earthquake # sample the probability magnitude relationship log(N) = a-bMw # generate shaking from Openquake maps def Landslide(): # get the shaking at node location # get the landslide suscpetib...
de1515c2150e80505cca6fbec738b38bc896487f
KarenRdzHdz/Juego-Parabolico
/parabolico.py
2,756
4.34375
4
"""Cannon, hitting targets with projectiles. Exercises 1. Keep score by counting target hits. 2. Vary the effect of gravity. 3. Apply gravity to the targets. 4. Change the speed of the ball. Integrantes: Karen Lizette Rodríguez Hernández - A01197734 Jorge Eduardo Arias Arias - A01570549 Hernán Salinas Ibarra - A0157...
d32a35c007a710be6b852da523df21c8276a708d
ALai2/AWS-Flask-ML-App
/application/clean_info.py
1,337
3.546875
4
import keywords_dict as kd keywords = kd.get_keywords() def key_replace(x): if isinstance(x, str): for k in keywords: if str.lower(x).strip() in keywords[k]: return k return x else: return '' # Function to convert all strings to lower case and strip names o...
d304780068e23850918d3670e21b4119963533fa
PluxMinux/Boxes_method
/main.py
663
4.0625
4
import encryption e_key = input("Key: ").upper() e_msg = input("Messege: ").upper() print("\nPress 1 for Encryption.") print("Press 2 for Decryption.") e_d = input("\nSelect: ") if e_d == "1": print("\nEncrypted Message: ", encryption.encrypt(e_key,e_msg)) elif e_d == "2": print("\nDecrypted Messag...
9eabe314f17a7234abe20a782814d96d09d2580e
AakashSasikumar/StockMate
/DataStore/APIInterface.py
6,434
3.5
4
import yfinance as yf from lxml.html import fromstring import random import requests import os import pandas as pd class YFinance(): """A wrapper for the Yahoo Finance API This is actually a wrapper over a wrapper. This was done to implement some more specific behavior over the original. Attributes ...
02a01f7bc44fcdb31cef4c4ae58ea0b1ea573326
imruljubair/imruljubair.github.io
/_site/teaching/material/Functions_getting_started/16.py
235
4.15625
4
def main(): first_name = input('Enter First Name: ') last_name = input('Enter Last Name: ') print('Reverse: ') reverse_name(first_name, last_name) def reverse_name(first, last): print(last, first) main()
23e4678e79473596cb5d8742831ad45fe4e42b97
imruljubair/imruljubair.github.io
/_site/teaching/material/Dictionary/3.py
153
3.828125
4
# Adding list as values for keys..... card = {} for letter in ["A", "B", "C", "D", "E"]: card[letter] = [] # empty list print(card)
627a95962abed7b46f673bf813375562b3fa1cd2
imruljubair/imruljubair.github.io
/teaching/material/List/7.py
413
4.375
4
# append() # Example 7.1 def main(): name_list = [] again = 'y' while again == 'y': name = input("Enter a name : ") name_list.append(name) print('Do you want to add another name ?') again = input('y = yes, anything else = no: ') print() print(...
0c110fece3e121665c41b7f1c039c190ed1b7866
imruljubair/imruljubair.github.io
/teaching/material/List/5.py
268
4.28125
4
# Concating and slicing list # Example 5.1 list1 = [1,2,3] list2 = [4,5,6] list3 = list1 + list2 print(list3) # Example 5.2 days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Satureday'] mid_days = days[2:5] print(mid_days)
29a2a6bd2c367d30c883bfae9b2a8fa3deb5ceab
imruljubair/imruljubair.github.io
/teaching/material/Loop/2.py
115
4.09375
4
number = int(input("How long you want to add?: ")) sum = 0 for i in range(0,number+1): sum = sum + i print(sum)
6399bf8b03d1f6ef5a68bec3b6cc8baa26000edc
imruljubair/imruljubair.github.io
/_site/teaching/material/Functions_getting_started/17.py
266
4.4375
4
def main(): first_name = input('Enter First Name: ') last_name = input('Enter Last Name: ') N = reverse_name(first_name, last_name) print('Reverse: '+str(N)) def reverse_name(first, last): name = last+' '+ first return name main()
bd91c66c02435f8b47dea4f9275dc8a4f4e6c1ae
imruljubair/imruljubair.github.io
/_site/teaching/material/Functions_getting_started/5.py
217
3.703125
4
#Using variables from function to function def main(): get_name() print('Hi, ', name) # this will cause an error print('welcome') def get_name(): name = input('enter your name: ') main()
4cada66802a9817ec054ef1e6de12abcfff077fc
visitmsuresh/Python-Concepts
/task programs-formula7py.py
54
3.65625
4
r=int(input()) h=int(input()) pi=r**2*h print(pi)
82276c3aed35b68b4133264cd1ff40b7782dd0d2
MPTauber/Numpy
/MyArrays.py
1,674
3.875
4
## pip install numpy --user ## ctrl, SHIFT,P --> Python: Start REPL import numpy as np '''integers = np.array([x for x in range(2,21,2)]) ## gives even number (third values means steps of 2) print(integers) two_dim = np.array([[1,2,3],[4,5,6]]) ## dont forget inital [] around the two sets of bracketed lists print(two...
17f5b5f1d7d79dff3c1eed3ef569397d10fa43a4
kilicars/WheelOfFortune
/board.py
1,832
3.65625
4
import json import random import constants class Board: def __init__(self, file): self.file = file self.category = "" self.phrase = "" self.guessed_letters = [] def get_phrases(self): with open(self.file, "r") as f: phrases = json.loads(f.read()) ...
aea3ddf894c253cfe9bcdae7a3878f67bf76a5b7
softwaresaved/docandcover
/fileListGetter.py
1,118
4.375
4
import os def fileListGetter(directory): """ Function to get list of files and language types Inputs: directory: Stirng containing path to search for files in. Outputs: List of Lists. Lists are of format, [filename, language type] """ fileLists = [] for root, dirs, files in os.walk(dire...
83b8e37944e3615d2db07ad95aec4c4d7579992d
skyrocxp/python_study
/exercises3.py
2,192
4.03125
4
# ZYF-03-基础-猜字游戏 # 10 < cost < 50的等价表达式 cost = 40 (10 < cost) and (cost < 50) # 使用int()将小数转换成整数,结果是向上取整还是向下取整 print (int(3.6)) # 写一个程序,判断给定年份是否为闰年 # 闰年,能被4整除的年份 # 我的代码 year = int(input('请输入一个年份')) if year % 4 == 0: print('该年为闰年') else: print('该年不是闰年') # 老师的代码 year = input('请输入一个年份') if year.isdigit(): y...
b39e036c77f2a03507d5f3e48a48c59e15126785
supergonzo812/Data-Structures
/binary_search_tree/binary_search_tree.py
4,289
4.21875
4
""" Binary search trees are a data structure that enforce an ordering over the data they store. That ordering in turn makes it a lot more efficient at searching for a particular piece of data in the tree. This part of the project comprises two days: 1. Implement the methods `insert`, `contains`, `get_max`, and `for...
3870904959fddbed67492507ad40db196b53acfa
arashsaber/Displaying-filters-of-a-convolutional-layer
/displayer.py
4,434
3.609375
4
""" Displaying the filters of a convolutional layer Arash Saber Tehrani """ import numpy as np import tflearn import matplotlib.pyplot as plt # --------------------------------------- def filter_displayer(model, layer, padding=1): """ The function displays the filters of layer :param model: tflearn obj, ...
be446c4913f4788750712edd413343654e77b6c2
priyatiru/Problem-solving
/2dArray.py
420
3.53125
4
def hourglassSum(arr): count=0 for i in range(len(arr)-2): for j in range(len(arr)-2): sum= arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2] if sum>count: count = sum return count arr = [] for _ in range(6)...
7cf496c794995c44017e54c597422ac6d64e2d2a
mfbx9da4/neuron-astrocyte-networks
/backup/mypybrain/misc/stack_overflow.py
1,722
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 17 20:01:07 2013 @author: david """ #learn digit classification with a nerual network import pybrain from pybrain.datasets import * from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer from pybrain.structure.modules ...
fbd7f180535a42c13cc834b0a723d19454fbdf14
LeTond/DEV_PY110
/less04.py
10,299
3.890625
4
''' >>> import os.path >>> os.path.join("/tmp/1", "temp.file") # конкатенация путей '/tmp/1/temp.file' >>> os.path.dirname("/tmp/1/temp.file") # имя каталога по заданному полному пути '/tmp/1' >>> os.path.basename("/tmp/1/temp.file") # имя файла по заданному полному пути 'temp.file' >>> os.path.normpath("/tmp//2/../...
36b0c1000d57e2b1058477025476a4cd564c975d
DuskPiper/Code-Puzzle-Diary
/LeetCode 0103 Binary Tree Zigzag Level Order Traversal.py
1,272
3.796875
4
# 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): # 99% Time, 60% RAM def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[...
91b76a73d397f4820a23ff8aa6c0ddc3a00b204c
DuskPiper/Code-Puzzle-Diary
/LeetCode 1644 Lowest Common Ancestor of a Binary Tree II.py
1,111
3.609375
4
# 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): # 5 28 def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode ...
c911e5db782c6320a69349ec9dd00e5cbf2c6109
DuskPiper/Code-Puzzle-Diary
/LeetCode 0075 Sort Colors.py
1,003
3.703125
4
class Solution(object): # 100%, 0% def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ zero_boarder = 0 # 此下标之前的部分已经全是0 two_boarder = len(nums) - 1 # 此下标之后的部分已经全是2 i = 0 # iterator ...
26c107898fe41622d8abbc4c8b8d34f3116bc58d
DuskPiper/Code-Puzzle-Diary
/LeetCode 0490 The Maze.py
1,099
3.53125
4
class Solution: # 86 71 def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: rmax, cmax = len(maze), len(maze[0]) visited = set([]) q = [(start[0], start[1])] while q: r, c = q.pop() if r == destination[0] and c == destin...
a4b7855e174ee9ad620faf9b24ec1a8f938eadea
DuskPiper/Code-Puzzle-Diary
/LeetCode 0022 Generate Parentheses.py
803
3.5
4
class Solution: def generateParenthesis(self, n): """ :type n: int :rtype: List[str] 是一个递归的问题(但是可以用迭代代码实现 对于n的答案,其实是对n-1的答案的演绎,对n-1每个元素都进行以下两种操作之一: 1.在整个外面套一层() 2.在每个可能的slot(其实是所有length内所有下标)插入一个() 由此可以得到n的答案 以空string "" 为n=0的答案,由此可以递归演绎到n的答案 """ ans,i=set([""]),0...
273f5ce45b5bb1f787254540352893d4fad276eb
DuskPiper/Code-Puzzle-Diary
/LeetCode 1404 Number of Steps to Reduce a Number in Binary Representation to One.py
430
3.53125
4
class Solution: # 96 63 def numSteps(self, s: str) -> int: carry = 0 step = 0 for i in xrange(len(s) - 1, 0, -1): if int(s[i]) + carry == 1: # odd, +1÷2 => carry 1 to upper level, and remove current level (0) carry = 1 step += 2 else: #...
cbf78c124ce092e4d52d91baf052c9d79f7b07f7
lsDantas/Hacker-s-Guide-to-Neural-Networks-in-Python
/svm.py
5,096
3.703125
4
import math import random class Unit: def __init__(self, value, grad): # Value computed in the forward pass self.value = value # The derivative of circuit output w.r.t. this unit, computed in backward pass self.grad = grad class MultiplyGate(object): def __init__(self): ...
309345f381b0576b3057b747da65578024f62a02
fantashley/scrabble-api-python
/board_game.py
1,552
3.640625
4
from collections import namedtuple class BoardGame: # Board coordinates BOARD_X = None BOARD_Y = None SQUARE_TYPES = {} SQUARE_COORDS = {} TILES = {} Square = namedtuple("Square", "tile type") SquareMultiplier = namedtuple("SquareMultiplier", "letter word") Tile = namedtuple("Ti...
084744ae994df621efafbc7429b1ed971be533a4
J-woooo/acmicpc
/5585.py
334
3.84375
4
def greedyChange(coin, money): count = 0 i = 0 while(money != 0): if(coin[i] <= money): money -= coin[i] count += 1 else: i += 1 return count count = 0 coin = [500, 100, 50, 10, 5, 1] price = int(input("")) money = 1000-price print(greedyChange(...
6b6af3ba954b7dd15178eeb1fdb2abbe42c7284a
beenjammin/AssistantBrewer
/Scripts/probeTypes/Float_Switch.py
1,409
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Sep 12 11:23:08 2020 @author: pi """ try: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) except: pass from time import sleep class FloatSwitch(): """a class to handle the float switch pin, integer - the pin on the GPIO board that ...
185753e77b00d7d077ac46c7b099ed46a5e82203
waiteb15/py3forsci3day
/lamda_functions.py
649
3.875
4
#!/usr/bin/env python # Return Value # lambda param-list: expression # only use lambda's when you are passing functions def doit(func): result = func() print(result) def hello(): return "HELLO" #call back functions doit(hello) doit(lambda : "wombats!") fruits =...
f35afb7c52705c6067bdf0133df11358099ffaf4
waiteb15/py3forsci3day
/tuple_examples.py
1,055
3.703125
4
#!/usr/bin/env python person = 'Bill', 'Gates', 'Microsoft' junk1 = 'hello' # string junk2 = 'hello', # tuple print(person, len(person), person[0]) def greet(whom): print("Hello,", whom[0]) greet(person) first_name, last_name, product = person print(first_name, last_name, '\n') people = [...
efb473a71123b8e6b4c31555e37a9bd82f74ec09
waiteb15/py3forsci3day
/io_examples.py
1,070
4.03125
4
#!/usr/bin/env python import getpass name = 'Anne' color = 'red' value = 27 print(name, color, value) print(name, color, value, sep='/') print('name', end="=>") print(name) with open('DATA/mary.txt') as mary_in: for raw_line in mary_in: line = raw_line.rstrip() print(line) wit...
ac3d8240eb5970374d0a0bf3f10199b63434f7c0
waiteb15/py3forsci3day
/EXAMPLES/pandas_selecting.py
1,023
3.75
4
#!/usr/bin/env python """ @author: jstrick Created on Sun Jun 9 21:36:10 2013 """ from pandas.core.frame import DataFrame from printheader import print_header cols = ['alpha','beta','gamma','delta','epsilon'] index = ['a','b','c','d','e','f'] values = [ [100, 110, 120, 130, 140], [200, 210, 22...
aab502d04412167c2797bcbb7592221221966274
waiteb15/py3forsci3day
/ANSWERS/date_delta.py
473
4.09375
4
#!/usr/bin/python import sys import datetime if len(sys.argv) < 3: print("Please enter two dates in format YYYY-MM-DD") sys.exit(1) year, month, day = sys.argv[1].split("-") this_date = datetime.date(int(year), int(month), int(day)) year, month, day = sys.argv[2].split("-") that_date = datetime...
b713cfeb2d4ceb7eed21df67ffffefaaed03a1d9
waiteb15/py3forsci3day
/EXAMPLES/datetime_ex.py
821
3.734375
4
#!/usr/bin/python3 from datetime import datetime,date,time,timedelta print("date.today():",date.today()) now = datetime.now() print("now.day:",now.day) print("now.month:",now.month) print("now.year:",now.year) print("now.hour:",now.hour) print("now.minute:",now.minute) print("now.second:",now.second) ...
0020353624117615495ebdba328323478038dd34
waiteb15/py3forsci3day
/csv_examples.py
909
3.84375
4
#!/usr/bin/env python import csv with open('DATA/presidents.csv') as pres_in: rdr = csv.reader(pres_in) for row in rdr: term, first_name, last_name, birthplace, birth_state, party = row term = int(term) print(last_name, party) print('-' * 60) with open('DATA/presidents.tsv...
b519465696765d49dd7279157de55c47be275cfd
waiteb15/py3forsci3day
/EXAMPLES/generator_expression.py
797
3.8125
4
#!/usr/bin/python import re # sum the squares of a list of numbers # using list comprehension, entire list is stored in memory s1 = sum([x*x for x in range(10)]) # only one square is in memory at a time with generator expression s2 = sum(x*x for x in range(10)) print(s1,s2) print() # set constructor -- do...
7714e16790dbfe022f4a86f3639c306808b919f6
waiteb15/py3forsci3day
/EXAMPLES/time_ex.py
490
3.71875
4
#!/usr/bin/python3 import sys import time right_now = time.time() print("It is {0} seconds since 1/1/70".format(right_now)) time.sleep(5) now_asc = time.asctime() print("it is now",now_asc) now_ctime = time.ctime() print("it is now",now_ctime) time_str = "Jan 14, 1971" print('Time string:',time_s...
a2c4fea201b97fe3367cb0f2e4aab0cfc842bbe9
waiteb15/py3forsci3day
/EXAMPLES/slicing.py
950
3.875
4
#!/usr/bin/python fruits = ['watermelon', 'apple', 'kiwi', 'lime', 'orange', 'cherry', 'banana', 'raspberry', 'grape', 'lemon', 'durian', 'guava', 'mango', 'papaya', 'mangosteen', 'breadfruit'] s = slice(5) # first 5 print(fruits[s]) print() s = slice(-5,None) # last 5 print(fruits[s]) print() s = ...
f6bc859f0fe1d5d1b8a7075b37bfca3cd311362d
jihunparkme/Problem-Solving
/PS_Study/BOJ/1920.py
422
3.78125
4
def binarySearch(N, A, key): lt, rt = 0, N-1 while lt <= rt: mid = (lt + rt) / 2 if A[mid] == key: return 1 elif A[mid] > key: rt = mid - 1 else: lt = mid + 1 return 0 N = int(input()) A = list(map(int, input().split())) M = input() B =...
8d16160a858fd7f6ec6c66aec68388d5cd65f2b6
joshanstudent/DPWP
/Madlib/main.py
1,794
4.09375
4
# My MadLib Program by Joseph Handy # This a title print "Welcome to my game!" # Guess the number import random guesses = 0 first = raw_input("What is your first name? ") number = random.randint(1,5) # Print out results print first + ", I am thinging of a number between 1 and 5 " # loop while guesses < 3: gu...
ebac95e891d818f1127e20969b9797da5c96d33e
bhaveshbaranda/library
/library.py
395
3.5625
4
import argparse parser = argparse.ArgumentParser(description='Add two numbers') parser.add_argument('--a', type = int ,metavar = '',required=True, help = 'First Number') parser.add_argument('--b', type = int ,metavar = '',required=True, help = 'Second Number') args = parser.parse_args() def myAdd(a,b): re...
d9cd91999238b4f74e30c66145cb7cecd38b2de4
Floou/python-basics
/200914/01.lists.py
546
3.828125
4
#student_marks = [] #while True: # mark = input('введите оценку студента:\n') # if mark: # student_marks.append(mark) # else: # break # #print('ввод завершен') #print(student_marks) mock_student_mark = ['5', '4', '3', '2', '5'] student_marks = mock_student_mark i = 0 avg_mark = 0 while i < len(...
96b6fc9a3737846372715a16a7e96c5331bd2746
danny1000008/dec_to_roman
/tests.py
816
3.78125
4
import unittest from number import Number class decimalTestCase(unittest.TestCase): def test_1_is_roman_numeral_I(self): test_num = Number(1) self.assertTrue(test_num.convert_to_roman() == 'I') def test_2000_is_roman_numeral_MM(self): test_num = Number(2000) self.assertTrue(te...
64a76f29640cfc0e116a2870d5393ab355c1e9d1
luke-hta/learn2git
/one_random_number.py
123
3.578125
4
import random print('Here is one random number between 1 and 3!') print(1 + 2 * random.random()) print('You\'re welcome!')
29e2f29b85215ff541c096551b39f8a3c223cede
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/2 week(loops-if-else)/sum_square.py
88
3.5625
4
n = int(input()) sum_sq = 0 while n != 0: sum_sq += n ** 2 n -= 1 print(sum_sq)
a7bc9fe5aaa1a6e847e49d7bcf3abfae6dfbdf00
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/8 week (paradigma)/5.py
362
3.5
4
""" На вход подаётся последовательность натуральных чисел длины n ≤ 1000. Посчитайте произведение пятых степеней чисел в последовательности. """ from functools import reduce print(reduce((lambda x, y: (x * y)), map(int, input().split())) ** 5)
b2a23485ea9b7c0a0a9cce101c020ee580b25431
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/3 week(math-strings-slice)/3.4(replace-count)/1.py
207
3.5625
4
""" Дана строка, состоящая из слов, разделенных пробелами. Определите, сколько в ней слов. """ text = input() print(text.count(' ') + 1)
2a5d79386af0ae70441f607e383f3b7c61d7ef6e
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/5 week (list, set, for)/5.1(tuple, range)/3.py
316
3.59375
4
""" Дано натуральное число n. Напечатайте все n-значные нечетные натуральные числа в порядке убывания. """ n = int(input()) max_res = 10 ** n - 1 min_res = 10 ** (n - 1) for i in range(max_res, min_res - 1, -2): print(i, end=' ')
b71f08a1f51b10852a93f6ff23546806ba7472fe
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/7 week (set and dict)/7.2 (Dict)/5.py
509
3.859375
4
""" Дан текст. Выведите слово, которое в этом тексте встречается чаще всего. Если таких слов несколько, выведите то, которое меньше в лексикографическом порядке. """ file = open('input.txt') myDict = {} for word in file.read().split(): myDict[word] = myDict.get(word, 0) + 1 myList = sorted(myDict.items()) myList....
b27bccccc94b7c0ebf3620bcd4f0c67801c18315
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/6 week (sort)/1.py
1,063
3.90625
4
""" Даны два целочисленных списка A и B, упорядоченных по неубыванию. Объедините их в один упорядоченный список С (то есть он должен содержать len(A)+len(B) элементов). Решение оформите в виде функции merge(A, B), возвращающей новый список. Алгоритм должен иметь сложность O(len(A)+len(B)). Модифицировать исходные списк...
a5a247be32ad55eb47653a03a838578461345670
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/5 week (list, set, for)/5.1(tuple, range)/12.py
372
4
4
""" Даны два четырёхзначных числа A и B. Выведите все четырёхзначные числа на отрезке от A до B, запись которых является палиндромом. """ a, b = int(input()), int(input()) for i in range(a, b + 1): m = str(i) if m[0] == m[3] and m[1] == m[2]: print(i)
c571c4c36dbf81921bca4698ed33b166edef6480
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/4 week (fiunctions)/4.4(recursion)/9.py
334
3.921875
4
""" Дана последовательность чисел, завершающаяся числом 0. Найдите сумму всех этих чисел, не используя цикл. """ def my_sum(x): if x == 0: return x else: return x + my_sum(int(input())) n = int(input()) print(my_sum(n))
3c6ec8da3a07e7291823e088d450375f4d7f8280
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/3 week(math-strings-slice)/3.4(replace-count)/5.py
293
3.8125
4
""" Дана строка. Получите новую строку, вставив между каждыми двумя символами исходной строки символ *. Выведите полученную строку. """ text = input() print(text.replace('', '*')[1:-1])
d553e8d28badaa94b4592ac6ac3a033ec7bd0d81
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/3 week(math-strings-slice)/3.3(slice)/6.py
506
3.984375
4
""" Дана строка, состоящая ровно из двух слов, разделенных пробелом. Переставьте эти слова местами. Результат запишите в строку и выведите получившуюся строку. При решении этой задачи нельзя пользоваться циклами и инструкцией if. """ string = input() space = string.find(' ') print(string[space + 1:], string[:space])
06371106cc981aac3260a681d2868a4ccf24f5bf
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/3 week(math-strings-slice)/3.3(slice)/2.py
782
4.28125
4
""" Дана строка. Если в этой строке буква f встречается только один раз, выведите её индекс. Если она встречается два и более раз, выведите индекс её первого и последнего появления. Если буква f в данной строке не встречается, ничего не выводите. При решении этой задачи нельзя использовать метод count и циклы. """ str...
6b9179590f3a2bf82153a657064804ad0106a33b
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/2 week(loops-if-else)/num_polin.py
187
3.5625
4
n = int(input()) i = 1 counter = 0 while i <= n: int_to_str = str(i) reverse_num = (int_to_str[::-1]) if i == int(reverse_num): counter += 1 i += 1 print(counter)
407d7edba48b4a97c133ac7741ba6f1262cf3448
Sergey-Laznenko/Coursera
/Fundamentals of Python Programming/2 week(loops-if-else)/sum_follow.py
90
3.765625
4
n = int(input()) total = 0 while n != 0: total += n n = int(input()) print(total)
fe18a70582d9cd7d8d610b0b2a813a93fc9d3e5f
fantas1st0/network_scripts
/leetcode/top-interview-questions-easy/array/two_sum.py
730
4.0625
4
""" https://leetcode.com/explore/interview/card/top-interview-questions-easy/92/array/546/ Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice...
ee8d032bb86b8f69a9c1f37f76ad888fe3eb563f
Tracy219/pieCharts
/pieCharts.py
1,139
3.578125
4
#!/usr/bin/env python import matplotlib matplotlib.use("agg") # the code 'import matplotlib.pyplot as plt' must come out after # import matplotlib and matplotlib.use("agg") import matplotlib.pyplot as plt labels = 'Reading', 'Sleeping', 'Others', 'Chatting' # Labels of the parts of the pie chart sizes = [15, 30.0,...
707e6f8289e5fd9b8c7dea19a545e15aea587929
mostafaelgohry0/CSE-Courses
/AI/Robot_Emulator_final/Initial.py
1,787
3.671875
4
import Data import random class Initial: def __init__(self): self.chromosome = "" self.cost = 0 def set_height(self): h = random.randint(0, 3) self.chromosome = self.chromosome + Data.height[h][1] self.cost += Data.height[h][2] def set_width(self): w = ra...
777b1c54ca133bc9c82734c377f3b668bcf488ef
jaeheeLee17/BOJ_Algorithms
/Level3_ForStatements/11720.py
183
3.765625
4
def main(): N = int(input()) num_list = list(input()) total = 0 for num in num_list: total += int(num) print(total) if __name__ == "__main__": main()
203b06977b09e0d3c005a7797ff03fb4017a4973
jaeheeLee17/BOJ_Algorithms
/Level7_String/1316.py
607
3.953125
4
def groupword_checker(word): for i in range(len(word) - 1): if word[i] != word[i + 1]: if word[i] in word[i + 1:]: return False return True def count_group_words(word_list): groupword_cnt = 0 for word in word_list: if groupword_checker(word): grou...
a7b8ee727a6c139ff01d640a61d5aee451df1566
jaeheeLee17/BOJ_Algorithms
/Level7_String/2941.py
568
3.921875
4
def count_croatia_alpha(word): croatia_alpha_list = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z='] croatia_alpha_cnt = 0 idx = 0 while len(word) > idx: if word[idx : idx + 2] in croatia_alpha_list: idx += 2 elif word[idx : idx + 3] in croatia_alpha_list: idx +=...
6ede115cf6c103b9d518fa42aecbab018bb15062
gyubok-lee/algorithms
/week2/2_7.py
1,005
3.59375
4
# https://programmers.co.kr/learn/courses/30/lessons/42890 from itertools import combinations def solution(relation): rows = len(relation) cols = len(relation[0]) # 모든 조합 찾기 candidates = [] for i in range(1, cols + 1): candidates.extend(combinations(range(cols), i)) # 고유키 찾기 fina...
b8694f9b288a8904c59bb039cbcd1b29a9bc97c5
gyubok-lee/algorithms
/week7/7_2.py
1,987
3.5
4
# https://www.acmicpc.net/problem/16235 # 문제에서 주어진 조건을 빠짐없이 기록할것 def spring(): dead = [] for i in range(N): for j in range(N): if len(trees[i][j]) > 0: trees[i][j] = sorted(trees[i][j]) for k in range(len(trees[i][j])): if soil[i][j] < tre...
da75c16f3f3c9d1d6f2d5822f48d82908133b407
gyubok-lee/algorithms
/week3/3_8.py
753
3.671875
4
# https://www.acmicpc.net/problem/2630 def check(x,y,n): if n == 1: return True for i in range(n): for j in range(n): if board[x+i][y+j] != board[x][y]: return False return True def divide(node): global blue global white x,y,size = node if chec...
384785ebd3f0e57cc68ac0cd00389f4bcfd8b245
AffanIndo/python-script
/caesar.py
702
4.21875
4
#!usr/bin/env python """ caesar.py Encrypt or decrypt text based from caesar cipher Source: http://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python """ def caesar(plainText, shift): cipherText = "" for ch in plainText: if ch.isalpha(): stayInAlphabet = ord(ch) + shift ...
9f7de4fb5c580d257b47385f8342e126dba99b79
AffanIndo/python-script
/kasir.py
1,084
3.734375
4
""" kasir.py The user enters a cost and then the amount of money given. The program will figure out the change and the number of quarters, dimes, nickels, pennies needed for the change. """ from math import floor uang = int(input("Masukkan uang (Rp): ")) harga = int(input("Masukkan harga barang (Rp): ")) if (uang <...
afb0f6d0fdc125db455ac4b06330beacaf90e6fa
stoianmihail/EnsembleLearning
/classifiers/adaboost.py
9,074
3.53125
4
from classifiers.baseline import Classifier import numpy import math # The dataclass type and its features from dataclasses import dataclass from typing import List # The binary search for the performant prediction from bisect import bisect_left #### # A performant implementation with auto-tuning of AdaBoost ensembl...
02045de66eac587a4510f6a868a8a0fad0b1685c
anirudh99bot/Restaurant-Finder
/zomato.py
2,313
3.515625
4
import requests import json import random def SearchRestaurant() : params = { 'entity_id' : city_id, 'entity_type' : 'city', } response = requests.get('https://developers.zomato.com/api/v2.1/search', headers=headers, params=params) data = json.loads(r...
6889a03ce265b3569258d07818044ae768c5ccc7
Florian-Moreau/maison
/data_manager/utils/file_manager.py
246
3.625
4
import os def list_files(path): return [name for name in os.listdir(path) if (os.path.isfile("{}/{}".format(path,name)))] def list_folders(path): return [name for name in os.listdir(path) if (os.path.isdir("{}/{}".format(path,name)))]
81a80dd01d35084988abe7748a317e28d56f4735
yrsong15/shuffle
/shuffle.py
1,468
4.09375
4
from random import randint from queue import * def shuffle_with_queue(artists, num_of_songs, init_val): list_length = 0 for elem in num_of_songs: list_length += elem res = [init_val] * list_length q = init_queue(list_length) #maybe consider using PQueue? def init_queue(list_length): q = Queue(maxsize=list_le...
4ca600725e8a20b1710b0faba653edb55167d6ba
diego-d5000/algorithms
/sameStrings.py
208
3.6875
4
#Given 2 arrays of string, print an array of strings common in the two arrays def sameStrings(arg1, arg2): sameStrs = [] for i in arg1: for k in arg2: if k == i: sameStrs.append(k) print sameStrs
828d76bedb9a3ef460e719f6c589018c0c6b8f8b
foxcodenine/books
/Python 3 Object-Oriented Programming Third Edition/chapter-3/chapter3_1.py
3,144
4.21875
4
# Basic inheritance class Contact: all_contacts = [] def __init__(self, name, email): self.name = name self.email = email Contact.all_contacts.append(self) # The all_contacts list is shared by all inctances of the class because # it is part of the class definition. c...
fcaebb4eab29606515f3e80bc7d9a6d9b8c1b8a3
Jeremalloch/Project_Euler
/Python/In Progress/Problem 267/Problem 267.py
994
3.875
4
def finalMoney(numWins, fValue): ''' Returns the amount of money returned with a given number of wins and a specific fValue (proportion of money being gambled with each turn, as a decimal). ''' return ((1+2*fValue)**numWins)*((1-fValue)**(1000-numWins)) - (10**9) def fMDerivative(numWins, fVa...
ce7deae553575c90fdaf6bd9f1ab622841749202
Jeremalloch/Project_Euler
/Python/Completed Problems/Problem 2/Problem 2.py
237
3.546875
4
Fibonacci = [1,1,2] sum = 0 n=2 while Fibonacci[n] <= 4000000: Fibonacci.append(Fibonacci[n] + Fibonacci[n-1]) n+=1 for item in Fibonacci: if item <= 4000000 and item%2 == 0: sum+=item print(Fibonacci) print(sum)
2b0c73ae595c61e78780ace7d64021c54f47b702
ZCW-Data1dot2/scicalc-team-cocoa
/getValue.py
2,498
3.875
4
class Value: def getAddNum(self): global val_in_mem a = input("Enter the first number that you want to add: \n") if a == 'mrc': a = float(val_in_mem) else: a = float(a) b = input("Enter the second number that you want to add: \n") if b == 'mrc...
43a256e40b7956658e7ce928c469ea15c0e223ac
JuanRx19/ProyectoFinal
/Proyecto final - Juan Miguel Rojas.py
12,910
3.59375
4
import json #Carga de archivos. #Se hace la lectura del archivo donde se encuentran los usuarios con vehiculo registrado. Load = open("usuarios.json", "r", encoding="utf-8") usuarios = json.load(Load) #Se hace la lectura del archivo donde se encuentra la información acerca del parqueadero Load2 = open("tipo...
1a497b06e8a13ded103f6241b59e11eb2d919956
beccafeen/fromhomegroup
/Final Project/Number_guessing_game.py
697
3.96875
4
#Number guessing game def number_guessing(): import random play_again = True while play_again == True: while(True): guess = input('Guess a number between 1 to 100: ') ran = random.randint(1,101) if(guess==ran): print("You guessed the exact number\n...
20ffbd80d572fd4b75db8860c04c034cb6d87ab0
midephysco/midepython
/exercises2.py
250
4.125
4
#this is a program to enter 2 numbers and output the remainder n0 = input("enter a number ") n1 = input("enter another number") div = int(n0) / int(n1) remainder = int(n0) % int(n1) print("the answer is {0} remainder {1}".format(div, remainder))
cd99b934bb253952d9cd53a49b2d0e1f9965bd1e
midephysco/midepython
/forloop2.py
320
3.921875
4
def forExamples(): print('Example 1') #The varialble counter is a stpper variable. for counter in range (1,10): print(counter) print() print('Example 2') for counter in range (2,11,2): print(counter) print() print('Example 3') for counter in range(1,22): print(counter,end='') forExamples()
19665f62b7fa38f9cbc82e17e02dacd6de092714
midephysco/midepython
/whileloop2.py
452
4.21875
4
#continous loop print("Adding until rogue value") print() print("This program adds up values until a rogue values is entered ") print() print("it then displays the sum of the values entered ") print() Value = None Total = 0 while Value != 0: print("The total is: {0}.".format(Total)) print() Value = int(i...
3c306ab7b4a909a2f503e43f4d85d6383449daa7
ygma/INTRO_TO_COMPUTERS_INTERNET_THE_WEB
/prime_from_fibonaci.py
441
3.75
4
def is_prime(integer): i = integer - 1 while i > 1: if integer % i != 0: i -= 1 continue return False return True item1 = 1 item2 = 1 print(item1) print(item2) #i = 3 #while i <= 100: while True: nextItem = item1 + item2 if nextItem > 1000: ...
f40f6318bab35ea4da5fd874ee2b4d132448deb9
ygma/INTRO_TO_COMPUTERS_INTERNET_THE_WEB
/simple_calculator.py
186
4.03125
4
def cal(a, b, operator): return a + b if operator == '+' else a - b if operator == '-' else a * b if operator == '*' else a / b if operator == '/' else 'error' print(cal(1, 5, '/'))
9ab60290494f8f8d69dab08c20329a752d689c36
ygma/INTRO_TO_COMPUTERS_INTERNET_THE_WEB
/assignment_2/5_max_and_min.py
330
3.84375
4
import sys def get_max_and_min(a, b, c): # list = [a, b, c] # return (min(a, b, c), max(a, b, c)) if a < b: min, max = a, b else: min, max = b, a if c < min: min = c if c > max: max = c return (min, max) print(get_max_and_min(3,...
4d07bb6ee86d032dfc56c9065b20186808c9d01e
constans73/extructura
/ejercicio1.py
2,326
3.5
4
############################# EJERCICIOS 1 Y 2 ############################# """Dado un diccionario, el cual almacena las calificaciones de un alumno, siendo las llaves los nombres de las materia y los valores las calificación, mostrar en pantalla el promedio del alumno.""" #A partir del diccionario del...
d925de37c979f9c98a0fd58ca113683536e528e5
villoro/villoro_posts
/0006-singleton/4_mloader.py
880
3.875
4
""" Mixing both types of class instances """ class mloader: value = 0 def sync(self, new_value): """ This will only sync the current instance. If you use that one time the sync all won't work """ self.value = new_value @staticmethod def sync_all(n...
a5566b92a8ad36bddb0fc2a9b51bad72abc5ab10
zylianyao/PythonPPT
/运算符.py
4,764
3.953125
4
# coding=utf-8 # "+":两个对象相加 # 两个数字相加 a = 7 + 8 # $print a # 两个字符串相加 b = "GOOD" + " JOB!" # print b # "-":取一个数字的相反数或者实现两个数字相减 a = -7 # print a b = -(-8) # print b c = 19 - 1 # print c # "*":两个数相乘或者字符串重复 a = 4 * 7 # print a b = "hello" * 7 # print b # "/":两个数字相除 a = 7 / 2 # print a b = 7.0 / 2 c = 7 / 2.0 # prin...
77f574a1b2f43d54c6d348e762709d0d2454d431
0x0f0f/Practice
/Python/Pythonista/searchSubStr.py
314
3.65625
4
import string def search(s, sub): flag = True cnt = 0 index = -1 while(flag): index = string.find(s, sub, index +1) if index == -1: break cnt = cnt + 1 return cnt if __name__ == '__main__': s = raw_input() sub = raw_input() print search(s, sub)
9c047f21e5dddf8ea33e2012e46a9310a570760a
Witterone/cs-module-project-hash-tables
/applications/word_count/word_count.py
791
4.03125
4
def word_count(s): dic = {} words_raw = s.split() words = [] for x in words_raw: new = x.lower().strip('":;,.-+=/\\|[]{}()*^&') words.append(new) u_words = set(words) for i in u_words: count = 0 if i != "": for j in words:...
f5bbfa0d8559e6c8dce6a2d55edfe6f2622eee81
IamMarcIvanov/ImplementedAlgorithms
/dijkstra_algorithm.py
1,555
3.625
4
import typing import heapq import math def dijkstra(adjacency_list: typing.Dict[int, typing.Dict], source_vertex: int) -> typing.Tuple[typing.Dict[int, float], typing.Dict[int,int]]: # No negative edge weights allowed. Adj_list is of form {s_vertex: {t_vertex1: d1,...},...} # Returns a dictionary of shortest p...
67e167414717bdd471f5e373d224e5b111a1ed79
saipavans/pythonrepo
/lab3/3Task13.py
442
3.734375
4
def is_abcderian(word): word_len = len(word) result = True for iterator in range(len(word) - 1): if word[iterator] <= word[iterator+1]: iterator += 1 continue else: result = False break return result words_abcderian = 0 words_file_path = "../resources/words.txt" fin = open(words_file_path) for ...