blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
4e44d2e6cf93579aa38be0b342f3fdb2bd7cd0dd
AndreiSturzu/SORTING_ALGORITHMS
/count_sort.py
2,486
3.671875
4
import random import time import csv from test_sort import test_sort file = 'count_sort_tests.txt' # test file with (numbers of tests - first row, N - number of elements to be sorted, MAX - maximum value for elements) with open(file, "rt") as f: content = f.readlines() content = [line.strip('\n') fo...
04458888fd148e25220a7522d14dfbe05e8bc400
owidi-001/scripts
/tests/all.py
244
4.03125
4
fruits=['Mangoes','Apples','Oranges','Pineapples','Avocado','Lemon'] # print(all(fruits)) def all: for i in flruits: if i not fruits: return False return True if if __name__ == "__main__": all(fruits)
47c33748e247369ae2aef78e1d38fe13c32e95ac
tomyc/workshop-python
/_bin/podstawy-temperatura.py
550
3.828125
4
#!/usr/bin/env python3 def celsiusz_na_farenheit(celsiusze): """ Celsius to Fahrenheit: (°C * 1.8) + 32 = °F >>> celsiusz_na_farenheit(0) 32.0 >>> celsiusz_na_farenheit(1) 33.8 >>> celsiusz_na_farenheit(-1) 30.2 >>> celsiusz_na_farenheit(100) 212.0 """ return celsiusze ...
f4a1d0b9f4725cbb845088e97bf460d1931dc301
mdeakyne/IT150
/Blank Class Activities/0119Blank.py
2,694
4.90625
5
""" This assignment is worth 10 points and you should be able to answer the following questions after completing it: What is the difference between a variable and a literal? How do you assign variables in python? How do you deal with errors in python? What are different types of python variables? How do you make a mult...
2f6671f1a2720b8a45d15091803d5ed498e16601
AudaciousAxolotl/UltimateFishingChampionship
/vector.py
17,016
3.640625
4
# ETGG 1803 Lab08 - Rasterizer & Matrix Transformations # Joe McNally # Section 02 # 04/29/18 import math # Sin, Cos, Arctan all used for Vector2 calculations import matrix class Vector: """ This class represents a general-purpose vector class. We'll add more to this in later labs. For now, it repre...
2afa8bf2943ef1cefb29b2285fe0f5b7bf69a592
AdamZhouSE/pythonHomework
/Code/CodeRecords/2116/60870/260766.py
420
3.515625
4
order = int(input()) ugly_list = list(input().split(',')) for i in range(len(ugly_list)): ugly_list[i] = int(ugly_list[i]) count = 0 num = 1 while count < order: num_test = num for uglyNum in ugly_list: if num_test % uglyNum == 0: while num_test % uglyNum == 0: num_test =...
4f3ed206369d6b424cb4e508d6468f5cb175cb43
kamilck13/python_cwiczenia
/zestaw2/zadanie_8.py
152
3.78125
4
#3.8 t = [1,2,3,4] print(t) e = ['a', 'b','c', 1] print(e) lista = list(set(e + t)) print(lista) lista = list(set(t).intersection(set(e))) print(lista)
22f8442e418ff885f0ca76d935998eaabcdfa8da
thund3rstorm/python_solutions
/tcs-nqt/nqt4.py
1,130
3.828125
4
# Given a Maximim of four digit to the base 17, convert it into decimal # in base 17 (10 -A, 11 -B, 12-C, 13-D) # # Soln Copied from GFG # https://www.geeksforgeeks.org/convert-base-decimal-vice-versa/ def val(c): if c >= '0' and c <= '9': return ord(c) - ord('0') else: return o...
91002f298e8166d9b0b59e93733013e56ace41f5
tqpatil/Python-Games
/Python/FifteenPuzzle/fifteen.py
14,589
3.640625
4
#Name:Tanishq Patil #File: fifteen.py # Student ID:1961827 #Date:11/29/2022 # Sources:Professor Munishkina, UCSC, Sample Code on Canvas # create the logic for the game Fifteen import numpy as np from graph import Vertex from graph import Graph import random class Fifteen: # create a vector (ndarr...
9fde41702a44be038aec65fa7011ffac235aabe0
ProneToAdjust/Reminder-System
/reminder_system/utils.py
2,797
4.15625
4
import datetime def get_mins_between_now_and_event(event): """Returns the minutes between the current time and the start time of the inputted event Args: event (dict): an single event from the event list returned from google_calendar's GoogleCalendar class method get_events Returns: int: ...
2cb2d6170598703bb84f97aa54ec4d7dc5319f8e
vinodsubbanna/Python
/asmnt28.py
449
4.125
4
# 28)Define a function that can accept two strings as input and print the # string with maximum length in console. If two strings have the same # length, then the function should print al l strings line by line. # Hints: # Use len() function to get the length of a string def printmaxstr(a,b): if(len(a)>len(b)): ...
48c889295035479919df021eb4b84a28832c0b44
bronval/breakout_pygame
/brick.py
888
4.03125
4
##################################################### # # breakout game with pygame # for Python stage in Technofutur TIC (Belgium) # Authors : Bastien Wiaux and Benoit Ronval # ##################################################### from constants import * import pygame class Brick: def __i...
0edc4ed84dbe81929ff9d1256cf81dd1f389cac9
wuyunlei95/hat
/common/util/csv_file.py
1,204
4.03125
4
import csv class CSV_File(object): """读写csv文件""" def read_by_list(self, path): """ list(数组)形式读取csv里面的数据 过滤首行标题 @:param path(文件路径) @:return list """ file = open(path, 'r', encoding='utf8') data = csv.reader(file) list = [] flag = T...
c6a4b252e93757ee0cc8a5f78342e0e5e85de434
lifoxin/study
/rand_name/name.py
902
4.03125
4
#!/usr/bin/env python3 import random with open('firstname') as f1: firstname = f1.read() with open('boyname') as f2: boyname = f2.read() with open('girlname') as f3: girlname = f3.read() firstname = firstname.split() boyname = boyname.split() boyname = "".join(boyname) girlname = girlname.replace("\n",""...
919c4279af087faf7fddd4c55116a5399314be2b
lordbeerus0505/Logistic-Regression-and-SVM-from-Scratch
/lr_svm.py
11,580
3.546875
4
""" Please put your code for this question in a le called lr svm.py. This script should take three command-line-arguments as input as described below: 1. trainingDataFilename: the set of data that will be used to train your algorithms (e.g., train- ingSet.csv). 2. testDataFilename: the set of data that will be used t...
9b2b10fbf1349d8c965410b52f5b0cc21f524b93
ferdinandmudjialim/FNALGProjects
/Projects/Project01PolygonClasses/RectangleRoot.py
1,037
3.546875
4
from Rectangle import Rectangle myrectangle=Rectangle() print () print ("the four vertices of the 'hard-coded' myrectangle are ...") print(myrectangle) print ("the manually computed length of myrectangle is ... 6") print ("the manually computed width of myrectangle is ... 4") print () print ("translating ...
7119cb9a52c25d7f9adb47c3d1382e7e80f9c907
evelinasvarovskaya/evelina
/theme7/theme7.4.py
463
4.0625
4
print("Скорость первого автомобиля:") v1 = int(input()) print("Cкорость второго автомобиля:") v2 = int(input()) print("Расстояние между автомобилями равно:") s = int(input()) print("Время, которое прошло с момента старта:") t = int(input()) r = s+(v1+v2)*t print("Расстояние между автомобилями через t часов:", r)
5352200023389f39bf5d18dbfe4da68735580679
SgtSteiner/CursoPython
/src/anagram_db.py
1,070
3.859375
4
# -*- coding: utf-8 -*- ''' Created on 26 jun. 2017 @author: antonio.mendez ''' import shelve from anagram_sets import all_anagram, ord_cadena def store_anagrams(filename, anagram_map): """ Almacena un map de anagramas en database "shelf" filename = nombre de la base de datos anagram_m...
f6b1c4b72ebceb6debcd7e1a7c0aeb7a15c34212
oleksandrvarnytskyi/boot_camp
/data.py
1,188
3.875
4
class InvalidDate(Exception): pass class Date: def __init__(self, day=1, month=1, year=1970): self.day = day self.month = month self.year = year Date.date_validation(self) def date_validation(self): month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 3...
b09f0f73912b8ac731d1d1555393529cabc70bcc
DevKTak/inflearn-daily-algorithm-study
/week03-210704-210710/hyelimchoi1223/[프로그래머스]12903/solved.py
237
3.53125
4
def solution(s): answer = '' str_length = len(s) if str_length % 2 == 0: index = str_length//2 answer = s[index-1]+s[index] else: index = str_length//2 answer = s[index] return answer
8412c25f516b79c1e1aa0c2e1c09d62db97c7b85
CrimsoNx64/Python-Keylogger
/main.py
799
3.625
4
# _____ _ _ _ # / ____| (_) | \ | | # | | _ __ _ _ __ ___ ___ ___ | \| | # | | | '__| | '_ ` _ \/ __|/ _ \| . ` | # | |____| | | | | | | | \__ \ (_) | |\ | # \_____|_| |_|_| |_| |_|___/\___/|_| \_| ...
032cb6dc40a9e5294f77723af98623db3bb7cfac
Jainam2848/Coding
/Computational Physics/Chapter4/Exercise4.1.py
298
4.28125
4
n = int(input("Enter a Number to find its factorial :")) def factorial(n): fac = 1 if n<0: print("The factorial does not exists") elif n==0: print("The factorial is 1") for i in range(n,0,-1): fac*=i return fac print(factorial(n))
1e8fdd3aef74148e4fc5cd545d33a1b85c3b51f6
sekar5in/experiments
/LearnPython/httpfiledownload.py
504
3.578125
4
#!/usr/local/bin/python3 import urllib #import urllib2 #import requests url = 'https://www.nseindia.com/corporates/datafiles/BM_All_Forthcoming.csv' print("downloading with urllib") urllib.urlretrieve(url, "code.csv") ''' print "downloading with urllib2" f = urllib2.urlopen(url) data = f.read() with o...
86008b1aab51f138bb35e06bf6782dde22463599
georgeflanagin/trees
/rbtree.py
29,129
3.75
4
# -*- coding: utf-8 -*- """ A classic (not left-leaning) Red-Black Tree implementation, supporting addition and deletion. The code is by Stanislav Kozlovski, modified slightly by George Flanagin of University of Richmond, with the purpose of having it look somewhat more like the rest of the code at the university. The...
1c1c4b756978e75334501f72e58fb4575f13eaa2
sidharthpp/AwsCode
/NumPyTest.py
1,927
4.0625
4
import numpy as np import matplotlib.pyplot as plt a = np.array([(1,2,3),(3,4,5)]) #Dimension of array print(" Dimension of array ",a.ndim) #Byte SIze print(" Byte SIze ", a.itemsize) # Each element Occupies 4 bytes #Find DataType print(" DataType ",a.dtype) #Size of Array print(" Size of Array ",a.size) #Shape ...
3e1604b70791236c3a746e773510a49ce989d4c5
dinobobo/Leetcode
/17_letter_combination_phone_number.py
834
3.53125
4
from typing import List # Back tracking class Solution: def letterCombinations(self, digits: str) -> List[str]: letters = list(map(chr, range(97, 97 + 26))) num2let = {} for i in range(2, 7): num2let[str(i)] = letters[(i - 2) * 3: (i - 1)*3] num2let[str(7)] = letters[15...
050f63bf357b04667a999c78eaa14e5983bfac8c
pedrodib/machine-learning-study
/robot/robot.py
2,207
3.84375
4
# Robos # # A matriz vai de 0x0 ate 10x10 from random import randint class Point(object): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "<%s, %s>" % (self.x, self.y) class Robot(Point): def __init__(self, x, y): super(Robot, self).__init__(x, y) def move_up(self): if self....
88cc7e7a72a4975ae22c04bfe934d43b68b879eb
TheGhoul27/SuperTrend
/superTrend.py
4,771
3.578125
4
from urllib.request import Request, urlopen from urllib.error import URLError, HTTPError import json import pandas as pd url = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo" ATR = 7 MULTIPLIER = 3 class APIError(Exception): '''An API Error Except...
fd0e9b759f32e0d2e46f299a6da1da85f21b0c72
Abtaha/Google-CodeIn-2019
/Avengers Endgame/main.py
473
3.546875
4
import sys sys.setrecursionlimit(10**20) def subtractor(p, d): if p > 0: if d % 2 != 0: p = p - (d + 1) else: p = p - d else: return d d = d + 1 return subtractor(p, d) def algo(p): d = subtractor(p, 1) #d = 0 d -=...
519dc78d5bccebb807a46d5d9760cab74d81868c
dimkary/Python-tests
/Kattis/mixedfractions.py
429
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Dec 20 09:49:20 2018 @author: karips Solves the "Mixed Fractions" Kattis problem """ outputs=[] while True: x=input().split(' ') nums = [float(i) for i in x] if nums[0]==0 and nums[-1]==0: break fact = nums[0] // nums[1] enum = n...
ddf88fe3521a4f2a9a6ccdf52cb4460b98a9b019
AkashSabat/Machine_Learning
/Simple_Regression/Linear_Regression.py
1,365
4.0625
4
import numpy as npy import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('F:\Programming_Languages\Machine_Learning_Repo\Simple_Regression\Salary_DataSet.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:,1].values #divide data into training and testing data from sklearn.model_selec...
dab7a900ccde354861cd5631ec26d81e2d588a1b
lennonrar/courses
/coursera/python/week4/exe3.py
133
3.78125
4
a = str(input("Digite um numero inteiro: ")) s = len(a) i = 0 plus = 0 while i < s: j = 1+i plus += int(a[i:j]) i+=1 print(plus)
d047777ea5e257737e162f7099c4d3b304f1cf18
manbalboy/python-another-level
/python-basic-syntax/Chapter08/05.클래스 실습문제.py
1,164
3.75
4
class Item: def __init__(self, name, price, weight, isDropAble): self.name = name self.price = price self.weight = weight self.isDropAble = isDropAble def sale(self): print(f"{self.name} 판매 가격은 {self.price}") def discard(self): if self.isDropAble: ...
c8a9ea0be718bc2fd24fda61f72e3583f8f015e9
froginafog/data_analysis
/0005/main.py
3,869
3.75
4
def remove_repeated_data(data): num_elements_in_data = len(data) if(num_elements_in_data == 0): return data unique_data = [] unique_data.append(data[0]) for i in range(1, num_elements_in_data): num_elements_in_unique_data = len(unique_data) data_is_unique = True for j...
bac5581e840da13f254cc7dcc4b75121c66187b0
dhirajdkv/Guvi-Codekata
/proset2.py
304
3.5
4
name1,name2=input().split() count=0 count = abs(len(name2)-len(name1)) if(len(name1)<=len(name2)): ori = len(name1) else: ori = len(name2) for i in range(ori): if(len(name2)==1 and name2[i] in name1): break if (name1[i]!=name2[i]): count=count+1 print(count)
503b7abb7408f5a9b7b113f8aee844df8fda9bec
lanzhiwang/common_algorithm
/data_structures/01_binary_tree/03_avl_tree/01_avl_tree.py
1,768
3.875
4
# -*- coding: utf-8 -*- """ AVL 树的特性让二叉搜索树的节点实现平衡(balance),AVL树要求: 任一节点的左子树深度和右子树深度相差不超过1 avl 平衡二叉树使用到的相关辅助对象和函数 """ class MyQueue(): def __init__(self): self.data = [] self.head = 0 self.tail = 0 def push(self, data): self.data.append(data) self.tail += 1 def pop...
a7a5bdbc5495fc259c1be1ca484ae43faa036c8e
chaofan-zheng/tedu-python-demo
/month02/day10/udp_server.py
482
3.625
4
""" udp套接字服务端模型 重点代码!!! """ from socket import * # 创建udp套接字 udp_socket = socket(AF_INET,SOCK_DGRAM) # 绑定地址 udp_socket.bind(("0.0.0.0",8888)) while True: # 接收 发送消息 data-->bytes data,addr = udp_socket.recvfrom(1024) # if data == b"##": # break print("From",addr,":",data.decode()) n = udp_so...
fd0673853d3f402e08108ae06109887f9cfdb88f
adityabads/interview-practice
/08-linked-lists/4_kth_to_last_node.py
2,087
4.09375
4
# kth to last node # Write a function kth_to_last_node() that takes an integer k and the head_node # of a singly-linked list, and returns the kth to last node in the list. # # BONUS # Can we do better? What if we expect nn to be huge and k to be pretty small? # In this case, our target node will be close to the end of ...
7b13905fcc57e2863fcf5b7af5745db5b77b71cb
leiurus17/tp_python
/variables/python_tuple.py
414
4.3125
4
tuplez = ('abcd', 786, 2.23, 'john', 70.2) tinytuple = (123, 'daniel') print tuplez # Prints complete tuple print tuplez[0] # Prints first element of the tuple print tuplez[1:3] # Prints elements starting from 2nd till 3rd print tuplez[2:] # Prints elements starting from 3rd element print tin...
a8dc46e066bfe078b26393c7e7f84a8530512a2b
TheRealJenius/Udacity_AIPWP
/Scales_and_Transformations_Practice.py
1,575
3.875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # prerequisite package imports import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sb get_ipython().run_line_magic('matplotlib', 'inline') from solutions_univ import scales_solution_1, scales_solution_2 # Once again, we make use ...
c28bfa8d84c17d1596dad8e7c100a5f011ede3ed
ddatunashvili/lecture_src
/dicts/dict_ex.py
670
3.578125
4
# მოდელის სახელის ამოღება car = { "brand": "Ford", "model": "Mustang", "year": 1964 } print('???') # წელის მნიშვნელობის შეცვლა car = { "brand": "Ford", "model": "Mustang", "year": 1964 } print('???') # 'color' : "red" ის დამატება car = { "brand": "Ford", "model": "Mustang", "year": 1964 } print('?...
a929f8814a2c7cce7e42daf311c66604b0292c1f
OkabeRintarou/syl
/Python/程序员代码面试指南/Chapter08_数组和矩阵问题/14_Max_Product.py
534
3.9375
4
#!/usr/bin/python3 # -*- coding:utf-8 -*- def max_product(arr): if not arr or not len(arr): return 0 max_end, min_end, ans = arr[0], arr[0], arr[0] for v in arr[1:]: a, b, c = max_end * v, min_end * v, v max_end = max(a, b, c) min_end = min(a, b, c) ans = max(max_en...
f8fa33db2e4bb669224793e6836d4f764a3553b3
eclipse-ib/Software-University-Professional-Advanced-Module
/September 2020/02-Tuples-and-Sets/02-Average-Student-Grades.py
448
3.921875
4
n = int(input()) students = {} for i in range(n): student = input().split() name = student[0] grade = float(student[1]) if name not in students: students[name] = [grade] else: students[name].append(grade) for name, values in students.items(): average = sum(values) / len(valu...
3d16f7e20ca08fe00f871fd083cc8f1233291927
Israel1Nicolau/Python
/condAninhadas006.py
420
3.875
4
peso = float(input('Digite o seu peso: ')) altura = float(input('Digite sua altura: ')) imc = peso/(altura*altura) print('Seu IMC é {:.2f}'.format(imc)) if imc < 18.5: print('Está abaixo do peso') elif imc >= 18.5 and imc < 25: print('Peso ideal') elif imc >= 25 and imc < 30: print('Está com sobr...
01064d3f8d23c90365a10fe2ea24f1b698cb4db7
amitrajhello/PythonEmcTraining1
/Set1.py
209
3.796875
4
items = {'andy', 'eva', .98, 1.2, 3.8, 2.4, 'pat', 'kim'} items.add(22/7) items.add('elvis') items.remove(3.8) items.remove('andy') print(items) print() for element in items: print(element)
5c113f94ecbaff30c39a86073f03a6cc3eb40d75
JustDoPython/python-examples
/yeke/py-cflag/america_flag.py
1,685
4.0625
4
import turtle # 画条纹 def drawSquar(): turtle.color('black', 'red') turtle.begin_fill() for i in range(7): turtle.forward(600) turtle.left(90) turtle.forward(350 / 13) turtle.left(90) turtle.forward(600) turtle.right(90) turtle.forward(350 / 13) ...
95ef2bf61ad082eb270342a36b2f32a2ed5044b7
mihirkelkar/languageprojects
/python/check_anagram.py
692
4.125
4
#!/usr/bin/python def make_map(string): map = {} for ii in string: try: map[ii] += 1 except: map[ii] = 1 return map def check_anagram(string_one, string_two): map_one = make_map(string_one) map_two = make_map(string_two) if map_one == map_two: print "Confirmed anagrams" else: print "Not anag...
86723ec972801c95997661ba6ea180dd835199af
sunxianpeng123/python_common
/common_used_package/datetime_test/timedelta.py
914
3.5
4
# encoding: utf-8 """ @author: sunxianpeng @file: timedelta.py @time: 2019/12/1 17:27 """ from datetime import datetime from datetime import timedelta def datetime_add_or_minus(): dt = datetime.now() # 天数减一天 dt_minus_1 = dt + timedelta(days=-1) dt_minus_2 = dt - timedelta(days=1) #计算两个日期的差值 di...
3abc5640e3da4a5776b5cb849c38e557e3ff5609
npstar/HackBulgaria
/week0/1/iterations_of_nan_expand.py
412
3.96875
4
def iterations_of_nan_expand(expanded): expand = expanded.split() count = 0 for i in range(len(expand) - 2): if expand[i] != "Not" and expand[i + 1] != "a": return False if expand[-1] != "NaN": return False for i in range(0,len(expand)): if expand[i] == "N...
e3c07ad2462d8aae7fe92ac1b2da4f6a03b20cb5
AdemHodzic/python-learning
/Day #33/sentence.py
441
3.671875
4
def solution(string): current = 0 result = '' copy = string[:] for index, char in enumerate(string): if char.isupper(): result += (string[current:index]).lower() result += ' ' current = index if index == len(string) - 1: ...
34c0e24d8dc8befca9991337d819aab5805f7d59
omakasekim/python_algorithm
/02_leetcode/0404 sum of left leaves.py
864
3.828125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # my solution class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: if root is None: return...
9e4146c44eea977ec7ace65be58dcaa518ec8c2a
nikatov/tmo
/prog3.py
3,166
3.5
4
# -*- coding: utf-8 -*- # +-------------------------------+ # | Многоканальная СМО без | # | ограничений на длину очереди | # +-------------------------------+ from math import factorial import matplotlib.pyplot as plt # Приведенная интенсивность потока def p_f(Tc, Ts): l = 1 / Tc m = 1 / Ts ret...
205ccf69c18b5d88b91ee5d945c571ed9c66674e
karinleiva/ComputerElective
/Conditionals2.py
233
4.03125
4
age=input("What is the age of the customer?") if age >= 21: print "The customer is allowed to drink liquor" print "You may serve" else: print "The customer is not allowed to drink liquor" print "You may not serve"
8a1fe4823e785ee982f6e9487a2d91fa562d175a
juliazakharik/ML_algorithms
/algorithms/WEEK9/Swapping Nodes in a Linked List.py
1,158
3.65625
4
""" 1721. Swapping Nodes in a Linked List Medium Share You are given the head of a linked list, and an integer k. Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed). Input: head = [1,2,3,4,5], k = 2 Output: [1,4,3,2,5] ...
1326234374d3507a0ba9a63c1c1f531cc31b4c1d
EricWWright/PythonClassStuff
/stringMethods.py
146
3.765625
4
name = input("type in your first and last name ") x = name.find(" ") firstName = name[:x] lastName = name[x+1:] print(firstName) print(lastName)
cd79af8c315daf5c7b1ff71841f1eddcb671f2e7
sumergurjar/ComplexAlgorithm
/2WaterJugProblem.py
521
3.625
4
# 2 Water Jug Problem by Sumer def pour(jug1, jug2): max1, max2, fill = 3, 4, 2 #Change maximum capacity and final capacity print("%d\t%d" % (jug1, jug2)) if jug1 is fill: return elif jug1 != 0 and jug2 is 0: pour(0, jug1) elif jug1 < max1: pour(...
41d9dbe848cafc04efcc10fa8bc60263d15fffe0
mariogeneau/python
/for_loop.py
95
3.640625
4
friends = ['john', 'pat', 'gary', 'michael'] for name in friends: print (f'NAME : {name}')
99ba2a9f54fb3983d2905d0d9239ff9134a4520b
srqjan/python
/regexp.py
4,354
3.671875
4
import re """ . - any single charakter except new line + - 1 or More one or more time repeated * - 0 or More zero or more times repeated ? - 0 or One {3} - exact number {3,9} - range of numbers ( Minimum , Maximum ) ^ - begining of the line (string - matching pattern) $ - end of the line ( matching p...
c5b4e144009644b6cbcf13f037ea871c30075c26
sandeep9889/datastructure-and-algorithm
/problems/sorting/insertionsort.py
286
4.125
4
def insertionsort(arr): for i in range(1,len(arr)): store=arr[i] j=i-1 while j>=0 and store<arr[j]: arr[j+1]=arr[j] j-=1 arr[j+1]=store return arr arr=[12,6,5,14,3] sortedarr=insertionsort(arr) print(sortedarr)
eb59720634b21af4933819a6155fef7b01025423
mcastillo40/python-examples
/files_project/app.py
203
3.84375
4
my_file = open('data.txt', 'r') file_content = my_file.read() my_file.close() print(file_content) name = input('Enter your name: ') my_file = open('data.txt', 'w') my_file.write(name) my_file.close()
676903f9386b4d0757bc10438ccfbe87d35a8bb2
kannans89/Python_Machine_Learning
/Machine_Learning_algorithms_Python/first_model_build_python_da.py
1,004
4.0625
4
# Simple logistic regression model in Python # Below are the steps involved: # Import the required libraries # Read the data # Explore and clean the data # Build logistic regression model # Interpret the results # Using already cleaned dataset (Iris) as an example and build a model on this dataset and will look at w...
c7c9f07679198dd27816cec909ebcb3eb9e86fe8
TAKAKEYA/CPU
/tools/utils/expect.py
10,054
3.890625
4
"""A module for optional type checking of function calls and collections. Decorators are provided for function inputs and outputs, and collection keys and values. To check that the argument x is a positive integer each time f is called: @expect.input(int, lambda x: x > 0) def f(x): ... To check that...
e806800d04597d50743a644a8d9a8f655961c2c3
marduklev/repository.marduk
/_misc/learningpy/tkinter_test.py
1,187
4.3125
4
# -*- coding: utf-8 -*- # import 'module_name' # https://wiki.python.org/moin/TkInter # https://docs.python.org/3/library/tkinter.html from tkinter import * def main(): # Example (Hello, World): import tkinter #in python 3.x: tkinter wird kleingeschrieben tk = tkinter.Tk() frame = tkinter.Frame(tk, re...
c5184d6336c30760ba9ab8ab06cb15c7f56b51f4
kamaljohnson/funtions-exicution-with-multiple-threads
/test.py
1,013
3.953125
4
import threading from queue import Queue import time print_lock = threading.Lock() q = Queue() def examplejob(worker): #this is a basic funtion time.sleep(0.5) with print_lock: print(threading.current_thread().name, worker) for worker in range(20): #these are the wo...
e2ae619e73b05cdee3025434cbbbc409cef0b66c
snanapaneni/First-Pycharm-Project
/Resources/Keywords/stringpu.py
1,939
3.53125
4
# def should_be_x_than (number1, relation, number2): # ''' # This keyword makes relation between 2 numbers (it converts them to number) # Accepted relations: # < > <= => = # ''' # if relation =="<": # return float(number1) < float(number2) # if relation ==">": # return float(...
062c1dd5ae4de2d20a47858587e100e16919c2cf
anton1k/mfti-homework
/lesson_9/test_6.py
528
3.65625
4
'''Заданная цифра в числе Сколько раз цифра d входит в десятичную запись числа n? Входные данные Число 0≤d≤9. Пробел. Целое положительное число n в десятичной системе (0 ≤ n ≤ 3·10 6) . Выходные данные Сколько раз цифра d входит в запись числа n.''' s = input().split() res = 0 for i in s[1]: if i == s[0]: ...
7950dde666c0749c8b2a4e4c9d1b6cfaa584ab97
venkatadri123/Python_Programs
/Sample_programs/9swap.py
68
3.71875
4
#To swap a given numbers x=10 y=20 print(x,y) t=x x=y y=t print(x,y)
3e203ddee7f1e3f8a299f4f31077517b1f01b76d
jjc521/E-book-Collection
/Python/Python编程实践gwpy2-code/code/searchsort/binary_test.py
1,974
4
4
"""Test binary search.""" import unittest from binary_search import binary_search # The list to search with. VALUES = [1, 3, 4, 4, 5, 7, 9, 10] class TestBS(unittest.TestCase): def test_first(self): """Test a value at the beginning of the list.""" expected = 0 actual = binary_search(VAL...
326bbe3158c60ce9de574db4985bfd86f535d2a9
phillipn/coding_bootcamp_projects
/python_fundamentals/coin_tosses.py
407
3.640625
4
import random head_count = 0 tail_count = 0 for i in xrange(5000): toss = round(random.random()) if toss == 1: toss = 'head' head_count += 1 else: toss = 'tail' tail_count += 1 print "Attempt #{}: Throwing a coin... It's a {}! ... Got {} head(s) so far and {} tail(s) s...
a8fdaa6501865ab4ec8826e1239658dcac520d28
mtdargen/genrerator
/genrerator.py
5,689
3.65625
4
__author__ = "Matt Dargen" import random def main(): print("___-=/GENRERATOR\=-___") print(" by matt dargen ;)\n") print("Press ENTER to Genrerate!\n") while(True): raw_input() print(genrerate()) def genrerate(): r = random.Random() message = r.choice(messages) messa...
c71b9e3c7a002c1183e6857ad32fadbfa80785c1
yongdae/hello-prime-python
/ch3/PrintCurrentTime.py
340
3.546875
4
import time currentTime = time.time() totalSeconds = int(currentTime) currentSeconds = totalSeconds % 60 totalMinutes = totalSeconds // 60 currentMinute = totalMinutes % 60 totalHours = totalMinutes // 60 currentHours = totalHours % 24 print("현재 시간은 ", currentHours, ":", currentMinute, ":", currentSeconds, " 입니...
9d2dd76f17003ad9d440f986676f652936207115
BraydenRoyston/PracticeProblems
/List Ends, Function Practice.py
229
4.0625
4
# This function prints the first and last values in a list. # (made in a function for practice) a_list = [5, 10, 15, 20, 25] def get_end(a_list): return [a_list[0], a_list[len(a_list)-1]] print(get_end(a_list))
0c99371384440c416c0afd7e55822e78c14858e1
vivekpabani/projecteuler
/python/034/problem_034.py
833
3.9375
4
#!/usr/bin/env python """ Problem Definition : 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. """ __author__ = 'vivek' import time import math ...
8690046ac259e1fe71c8fdb5bb3185c828975cbb
positivevaib/nyu-archive
/undergrad/artificial-intelligence/programming-assignment-2/knapsack-HC.py
6,278
3.78125
4
# Import packages import copy import random import sys # Define Object class to reflect given objects class Object: # Define variables name = '' index = 0 weight = 0 value = 0 # Define constructor def __init__(self, name, index, weight, value): self.name = name self.index =...
0237b24bda1cf37e85147a2a1792fb233600ed99
Peter-Pater/Introduction-to-Computer-Science
/Exercises/Homework/problem_set _1/program 4.py
765
4.1875
4
second = int(input('Please input the seconds:')) time = {'days':0,'hours':0,'minutes':0,'seconds':0} if second < 60: time['days'] = 0 time['hours'] = 0 time['minutes'] = 0 time['seconds'] = second elif 60 <= second < 3600: time['days'] = 0 time['hours'] = 0 time['minutes'] = second//60 time['seconds'] = second%...
056e6a2d7ff3b32efb0b9fecc332d3489e07a38e
ihalseide/ttools
/charstat.py
3,271
3.578125
4
#!/usr/bin/env python3 import sys import argparse description = "Get statistics for characters of a text file." epilog = "Note: Occurence data in pretty printing is in the format 'row:col , index'" def escape(char: str): mapping = { '\n': r'\n', '\t': r'\t' } ...
b1c34dfcd2f1c0ccedc19b71f18f56d8868a6543
jeffclough/handy
/patch-cal
2,605
4.34375
4
#!/usr/bin/env python3 import argparse,os,sys from datetime import date,timedelta def month_bounds(year,month): """Return a tuple of two datetime.date instances whose values are the first and last days of the given month.""" first=date(year,month,1) if month==12: last=date(year+1,1,1) else: last=da...
129799a084eaa6aa0fdd74fd96c9fbf6116015f3
saphilli/Leetcode
/addTwoNumbers.py
1,238
3.921875
4
#60 ms, faster than 97.89% of Python3 online submissions for Add Two Numbers #14.2 MB, less than 99.99% of Python3 online submissions for Add Two Numbers. #You are given two non-empty linked lists representing two non-negative integers. #The digits are stored in reverse order, and each of their nodes contains a single ...
1d9539c653f5628ad4318de3e5b31a933d04369b
mtakayuki/machine-learning-ex-python
/ex6/readFile.py
272
3.6875
4
''' reads a file and returns its entire contents ''' def readFile(filename): ''' reads a file and returns its entire contents in file_contents ''' # Load File with open(filename, 'r') as f: file_contents = f.read() return file_contents
688b65209147377f90611b8f602d195d467e1399
mechanicalsea/pytorch-light
/pytorchlight/utils/log.py
2,881
3.671875
4
"""Application for log Features: 1. debug 2. info 3. warn 4. error 5. critical """ import os import logging class Log(object): """Define a log for record. """ def __init__(self, name): """Create a logger for record. Args: name (str) : the file name ...
8b699e52e09dfb12e8c1fbf0111e161583e23a25
lemepe/eemp2
/svms_ens_filled.py
5,692
3.5
4
""" SVMs and Ensemble Learning on the Default data set """ # Here we import all we will need import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns pd.set_option('display.max_columns', None) from sklearn.model_selection import train_test_split from sklearn.linear_mo...
0316a01cb918e0ee829293c1e094ebe26799ba6f
Salevo/German-Hangman-Game
/your-project/Hangman.py
5,040
4.125
4
#!/usr/bin/env python # coding: utf-8 # # The German Hangman Game # Here you will find my awesome code for the ultrahard German Hangman Game. # In[1]: # START GAME # user input "name" > all characters can be accepted # print "Hi "name", are you ready to get owned by German Hangman?" # wait 2 seconds, start game # ...
a2ac1bb9dfb3c6c61dfdd1affc00c0674eff4ab1
Nairi-IT/NI
/Lesson5.py
150
3.75
4
L = [21, 'sa', 2.25, 'qw'] """ print(L[1]) print(L[-1]) """ i = 0 while i < 2: print(L[i]) i += 1 #item[START:STOP:STEP] print(L[:])
7d92a6db545b8b0f7bdfad35c33b080a52ec700a
renchao7060/studynotebook
/基础学习/p1_数学计算-for.py
485
3.6875
4
''' 简述:这里有四个数字,分别是:1、2、3、4 提问:能组成多少个互不相同且无重复数字的三位数?各是多少? Python解题思路分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。 ''' #_*_coding:UTF-8_*_ sum=0 for i in range(1,5): for j in range(1,5): for k in range(1,5): if (i!=j)and(i!=k)and(j!=k): print(i,j,k) sum+=1 print(sum)
7e3117c9668fac1f59c34f7b1f4172dc8f2f0a7a
Orcha02/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-append_write.py
318
4.125
4
#!/usr/bin/python3 """Function appends string at end of text file, returns num of chars added""" def append_write(filename="", text=""): """ Append file""" with open(filename, 'a') as open_file: return open_file.write(text) # Return is .write instead of .append to return everything with the append
8972e91a2fe11d58cd27a043687626f264717288
cleverakash/Python-1
/AirwaysManagementSystem.py
7,193
3.671875
4
# Airways Management System ''' Make Sure you have installed two modules : 1. Python text-to-speech - pip install pyttsx3 2. Python My SQL Connector - pip install mysql-connector ''' import mysql.connector # it'll connect python to MySQL RDMS by which we can access our Databases. import pyttsx3 # this ...
95d2ec67161a6c6d738a223aee780fed8c0f665a
adithyaBellary/AI
/MP6/mp6-code/perceptron.py
4,584
3.65625
4
# perceptron.py # --------------- # Licensing Information: You are free to use or extend this projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to the University of Illinois at Urbana-Champaign # # Cre...
f7ee44305d053eaacdf9a275d293f25fe0f5cb6a
aKondratyuk/python_language
/homework_4.py
13,697
3.859375
4
# -*- coding: utf-8 -*- #task1------------------------------------------------------------ """ Задача «Список квадратов» По данному целому числу N распечатайте все квадраты натуральных чисел, не превосходящие N, в порядке возрастания. """ import math n = int(input()) limit = math.floor(math.sqrt(n)) for i ...
9d55ef20e23ded4599442310a9f3be7e132305d3
matheusm0ura/Python
/AluraProjects/Manipulação de strings/regularEx.py
1,171
3.859375
4
import re #{} - quantificadores: dizem quantas vezes um grupo aparece na str #[] - grupo: representa um conjunto de opções para o caractere. #() - correspondência exata. #? - pode existir ou não (pode ser substituído por {0, 1}) #Search() - usado para procurar o padrão dentro da string #Match() - usado para verificar ...
2e878a0923d1c88016c21c015460db51e9698d13
ivanilsonjunior/2018.1-Redes-PRC
/Sockets/Servidor.py
595
3.5625
4
# Retirado de https://docs.python.org/3/library/socket.html # Echo server program import socket HOST = '' # Abre em todos os IPs da maquina PORT = 50000 # Porta acima dos 1024 para garantir permissao with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((HOST, PORT)) ...
abce45a39219475f1c418b5f0f250f3ed1889d3b
bdespain/Codecademy-Orion
/Orion.py
1,005
3.71875
4
get_ipython().run_line_magic('matplotlib', 'notebook') from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np #Added this import not included in initial file to add random numbers for colors feature mentioned in the rubric. # Orion dimensions x = [-0.41, 0.57, 0.07, 0.00, -0.29,...
067192357e12ebf35226a049656954b648df4fbf
BigerWANG/geek_algorithm
/offer/twoStackToQueue.py
961
3.546875
4
# coding: utf-8 """ two stack to a queue """ class CQueue(object): def __init__(self): self.__append_stack = [] self.__delete_stack = [] def appendTail(self, value): """ :type value: int :rtype: None """ self.__append_stack.append(value) def del...
ce07c72f417785cf4abd44da236d5b0f515f366e
anubhav-shukla/Learnpyhton
/final_tuple.py
290
3.984375
4
# here we know more about tupe,list and str # python final_tuple.py num=tuple(range(1,11)) # print(num) number=str((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) print(number) print(type(number)) # show str number=list((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) print(number) print(type(number))#list
5eee5bc58d7d99cb273feabcfea52428652d4fd6
dwilson99/PiP
/Layout_test.py
1,092
4
4
import tkinter as tk import tkinter.ttk as ttk class Window(tk.Tk): def __init__(self): super().__init__() self.title("Hello Tkinter") self.label = tk.Label(self, text="Choose One") self.label.pack(fill=tk.BOTH, expand=1, padx=100, pady=30) hello_button =...
b236f90cf61d11b343c31e2c0ee3b0b900c98dfa
ezequielpilcsuk/Paradigmas
/python/atividade2/Organismo.py
1,420
3.796875
4
class Organismo: def __init__(self, position, size): self.position = position self.size = size class Parede_celular: def __init__(self, gram): self.gram = gram class Despesa: def __init__(self, upkeep): self.upkeep = upkeep class Cachorro(Organismo, Despesa): def __in...
1eda7b4cb20a7f1167f97769e1903ce8463f63c9
dhruv-aktiv/training_task_data
/Training_Work/Training_WORKSPACE/p31.py
167
3.75
4
no = 6 for row in range(no): for k in range(no - row + 1): print(" ", end=" ") for col in range(row + 1): print("*", end=" ") print("\n")
73dc62297f0e37802a890eacd5e7bc110c53da98
ludvi025/csci1133
/lib/runzip.py
1,626
3.578125
4
#!/usr/bin/python3 # Unzips all files in the directory its run and then unzips all zipped # files in files just unzipped. import zipfile as z, os, argparse def main(): zfile = getZipArg() # unzipAll(zfile) unzip(zfile) def getOutputDir(file_name): return '.'.join(file_name.split('.')[0:-1]) # def u...
3e6bca1c0eea8b9e2378cb08a3b1af248b257ef9
hana-zi/PythonTraining
/day0208/Code6_8.py
341
4.0625
4
def add_suffix(names): for i in range(len(names)): names[i] = names[i] + 'さん' return names before_names = ['松田','浅木','工藤'] """ copied_names = list() """ after_names = add_suffix(before_names) print('さん付け後:'+after_names[0]) print('さん付け前:'+ before_names[0])
75d1d29325cdb6b4809b02413517cd557dc9c7d9
TeamYotta/Yotta
/Alessandra.py
131
3.625
4
def foo(): output="bar" print output a=4 print a a="hello" print a foo() for i in range (10): if i %2 == 0: print i #hello
ee0296b341b58cf9061ba1c25ebeab7b0ad9c0bd
capy-larit/exercicios_python
/exer34.py
391
3.984375
4
''' Faça um programa em Python que solicite ao usuário um número inteiro e retorne se é múltiplo de 5 e de 10 ao mesmo tempo. ''' numero = int(input('Digite um número inteiro: ')) resultado = numero % 5 resultado_1 = numero % 10 if resultado == 0 and resultado_1 == 0: print('Esse número é múltiplo de 5 e de 10.') ...