blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e98332712f89b688927a53228685b3e63cf7757c
wegfawefgawefg/GrokkingDRL_book
/stage 1/policyUtils.py
4,538
3.546875
4
import numpy as np import random from itertools import cycle import itertools def print_policy(pi, P, action_symbols=('<', 'v', '>', '^'), n_cols=4, title='Policy:'): print(title) arrs = {k:v for k,v in enumerate(action_symbols)} for s in range(len(P)): a = pi(s) print("| ", end="") ...
6a139d50895bb2ce12eee75de74f71df133ac49e
zhuangsen/python-learn
/com/beginner/7-6.py
1,504
4.3125
4
# -*- coding: utf-8 -*- # Python之定义默认参数 # # 定义函数的时候,还可以有默认参数。 # # 例如Python自带的 int() 函数,其实就有两个参数,我们既可以传一个参数,又可以传两个参数: # # >>> int('123') # 123 # >>> int('123', 8) # 83 # # int()函数的第二个参数是转换进制,如果不传,默认是十进制 (base=10),如果传了,就用传入的参数。 # # 可见,函数的默认参数的作用是简化调用,你只需要把必须的参数传进去。但是在需要的时候,又可以传入额外的参数来覆盖默认参数值。 # # 我们来定义一个计算 x 的N次方的函数: # #...
c7955ab772488638040b5925140d9f5d59ab8a31
JR1QQ4/python
/base/skill_59/py_04/py_31_property.py
2,815
3.515625
4
#!/usr/bin/python # -*- coding:utf-8 -*- # 第 31 条: 用描述符来改写需要符用 @property 方法 # 如果想复用 @property 方法及其验证机制,那么可以自己定义描述符类 # WeakKeyDictionary 可以保证描述符类不会泄露内存 # 通过描述符协议来实现属性得获取和设置操作时,不要纠结于 __getattribute__ 的方法具体运作细节 # WeakKeyDictionary: # 如果运行期系统发现这种字典所持有得引用,使整个程序里面指向 Exam 实例得最后一份引用,那么,系统就会自动将实例从字典得键中移除 class Homework(obje...
11d57782700a5fa690ec8d460bf44e68496281f2
kaczmarekkacper/ToxicSpanDetection
/painter/painter.py
509
3.5625
4
import matplotlib.pyplot as plt def draw_one_data_plot(data, title, xlabel, ylabel): x = range(1, len(data) + 1) plt.plot(x, data) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.show() def draw_two_data_plot(train, test, title, xlabel, ylabel, legend): x1 = range(1, len(train...
dd31cf52e49c0afa40e8464d8ccc5497cff7ece0
Akola-Mbey-Denis/Data-Structures-and-Algorithms-in-Python
/decimalToBinaryConverter.py
1,165
4.0625
4
class Stack: ''' This is an implemenation of stack data structure methods: pop: removes an element from the stack push: adds an element to the stack peek: returns the element at the top of the stack size: returns the number of elements in the stack ''' def __init__(self): ...
0a11537118199d9c61f80d79983a605bfb2e84e9
hitochan777/kata
/leetcode/python/maximum_subarray.py
280
3.515625
4
def max_sub_array(nums): dp = [0] * len(nums) dp[0] = nums[0] for i in range(1, len(nums)): if dp[i-1] < 0: dp[i] = nums[i] else: dp[i] = nums[i] + dp[i-1] return max(dp) print(max_sub_array([-2,1,-3,4,-1,2,1,-5,4]))
cd3ccfba0fbbd3a96c3da6c06d8a51b6e6f5fe0d
HarshaniDil/DataStructure
/Stack_using_deque.py
306
3.796875
4
from collections import deque stack = deque() #To push some elements in to the stack stack.append('P') stack.append('I') stack.append('N') stack.append('K') stack.append('I') print(stack) #POP print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack)
9082a581e81fe42701fd7a81e47709eabcbac32e
LouisYLWang/Algorithms
/Huffman_code/Binary_tree.py
724
3.515625
4
import Heap as hp import Node as nd class Binary_tree(): def __init__(self, heap): while heap._len != 2: self.merge_subtree(heap) assert heap._len == 2 self.root_node = self.merge_subtree(heap) def merge_subtree(self, heap): lf_node = heap.extract_value()...
df3ab7c03b63ade39d306a10d57f656d8153e0fb
0as1s/leetcode
/449_Serialize and Deserialize BST.py
1,409
3.71875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Codec: def serialize_helper(self, root): d = dict() d['v'] = root.val if root.left: d['left'] = self.serialize_he...
605bd4d7b19df3337632d82b64a170fede34ce0f
pleiades20/functions_and_classes_assignment
/question2.py
594
4.125
4
#########IMPORT LIBRARIES HERE IF NEEDED####### ################END IMPORTS#################### """ Write a function that takes a list of integers as input and returns the sum of the even numbers in the list minus the sum of the odd numbers in the list. The list may contain zeros and negative numbers. For example, f([...
1c9227724cb9aabe5d3144c679194df153311160
skybohannon/python
/w3resource/string/21.py
432
4.34375
4
# 1. Write a Python function to convert a given string to all uppercase if it contains at least 2 # uppercase characters in the first 4 characters. def conv_up(s): count = 0 for c in s[:4]: if c.isupper(): count += 1 if count >= 2: return s.upper() return s print(conv_up(...
786b9737f13c3b4079f4e723d3d46d8e2a7685a1
meghanamuthukumar/pythonCodes
/Assignment2.py
445
4.28125
4
''' Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking or ba...
d37fe5f24f58e969796c14e76632c6ecf19580d0
wiidi/CatchPMData
/PMData/readcityname.py
479
3.734375
4
# -*- coding: utf-8 -*- """ Created on Wed May 10 14:28:07 2017 @author: wudi1 """ def getCityName(filename='city.txt'): cityList=[] i=0 with open(filename,'r') as f: #读取每一行 lines=f.readlines() for line in lines: #通过逗号分词 list=str(line).split(',') ...
99327a9e8799d0a0f13b41f7f610a58b7a3d8cdb
suprviserpy632157/zdy
/ZDY/Jan_all/pythonbase/January0114/raise4.py
615
3.75
4
# 此实例示意用raise语句来传递信息给调用者 # 当用户输入的数字不是0~100之间的数字时,用异常方式通知调用者 def get_score(): """此函数强制用户输入0~100之间的数,如果输入的是 其它的数则直接触发异常来通知调用者""" score=int(input("请输入成绩:")) if score<0: raise ValueError if score>100: raise ValueError("成绩超出了最大值") return score try: score = 0 score = get_score(...
0bf4d223b9aa7248e68af15f0859e36ad9da6ead
dingcheng1204/python_test
/introducing_python_1.py
1,246
3.921875
4
a = 7 b = a b = 8+9 print(a) print(type(a)) print(9/5) print(9//5) print(0x25) print(int(True)) print(int(98.3)) print(int('99')) print(True + 5) print(True + 6.6) # print(int('99.3')) #error print(float('99.3')) print("this is first day" ",nice to meet u") print("ha"*4 + " oh") print(str(99)) print(str(True)) name...
95335f8b23e97f15341afbadcc4461391a0cc397
MaelsVilen/repo_github
/Basics/lesson_4/ex2.py
470
3.734375
4
"""Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента.""" input_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55] result_list = [el for el in input_list if input_list[input_list.index(el)] > input_list[(input_list.index(el)) - 1] and ...
1a7f97129c40da6128270dcfef3c3a00d98331a8
jasonrbriggs/python-for-kids
/ch7/silly-age-joke.py
243
3.734375
4
import sys def silly_age_joke(): print('How old are you?') age = int(sys.stdin.readline()) if age >= 10 and age <= 13: print('What is 13 + 49 + 84 + 155 + 97? A headache!') else: print('Huh?') silly_age_joke()
d57cc16179aab397c57afbef83a5ccb7dd9f5859
KylerF/pygame
/textbox_example.py
1,054
3.734375
4
import pygame from textbox import TextBox def process_input(id, text): print(text) white = (255, 255, 255) # This makes it so you can hold down keys KEY_REPEAT_SETTING = (200,70) pygame.init() screen = pygame.display.set_mode((800, 600)) screen.fill(white) # Set the key repeat setting pygame.key.set_repeat(*KE...
55707bb7be11060000307d1e1cce7c1f808a594f
ElliotConnell/Python
/bcp/Strings/oddpositions.py
199
4.125
4
#Strings & Lists 4 #Write a function that returns the elements on odd positions in a list.. set_list = [1, 2, 3, 4, 5, 6, 7 , 8, 9, 10] def odd_positions(): print(set_list[1::2]) odd_positions()
bf8e113b88d7672a78d07c5c8da4655835807992
BluePadge/exercism_source
/python/bank-account/bank_account.py
1,274
3.578125
4
import threading class BankAccount(object): def __init__(self): self.balance = 0 self.actived = True self._value_lock = threading.Lock() def get_balance(self): with self._value_lock: if self.actived: return self.balance else: ...
d46df966586124afdf36ce69ecc7f495f64ff170
mhidoart/pythonTrainingCode
/isPalandrome.py
465
3.921875
4
def is_palandrome(word): word = word.lower() return word[::-1] == word def is_anagram(w1,w2): w1 = w1 .lower() w2 = w2.lower() return sorted(w1) == sorted(w2) def dictionaryFill(string): dictionary = {} for c in string: if c in dictionary: dictionary[c]+= 1 else:...
795756fb2e57622772cbc214ec7c5d675644f9c8
Blast07/hackerrank
/interview-preparation-kit/Warm-up Challenges/repeatedString.py
460
3.671875
4
def counta(string, n): num_a =0 for i in range(n): if string[i]=='a':num_a+=1 return num_a def repeatedString(string, n): size = len(string) num_a = counta(string,size) if(size==n):return num_a elif(size>n): num_a = counta(string,n) return num_a; else: re...
12b8cc88cb90fcac08a112c8f18701289b3b55c7
yong0011/Research
/Python/GettingStart/StudentManagement/hs_student.py
326
3.625
4
from student import Student # inherit from Student class class HighSchoolStudent(Student): school_name = "Nash tech" def get_school_name(self): return "this is high scholl student" def get_name_capitalize(self): original_value = super().get_name_capitalize() return original_value ...
25ac920234f4b7c6262c5ba9e86b82bf215f6c99
mmcgov/pybites_exercises
/19/alt_simple_property.py
560
3.609375
4
from datetime import datetime, timedelta NOW = datetime.now() class Promo: def __init__(self, name, date): self.set_date(date) ## getter method to get the properties using an object def get_date(self): return self.expired ## setter method to change the value 'a' using...
8b1f4a180e17f2b08f1914ebce7ffada0d10e1a6
StefanRankovic/leetcode
/top_interview_questions/easy/design/min_stack.py
765
3.625
4
class MinStack: def __init__(self): self.backing = [] def push(self, x: int) -> None: top = self.util() if not top: self.backing.append((x, x)) else: self.backing.append((x, x if x < top[1] else top[1])) def pop(self) -> None: if sel...
1f01b26b26fc0e0de50605f9d7a94f98f7265be0
Burkow/Learning
/a.py
334
3.8125
4
def near_hundred(n): if n >= 90 and n <= 110 or n >= 190 and n <= 210: return True return False n = input("Give me a number") print(near_hundred(int(n))) game_over = False while not game_over: print("lol") is_game_over = input("is the game over? ") if is_game_over == "Yes": ga...
41c55c12530ff83a8859a8513e47de73d9b61023
ajilraju/python-practical-zone
/archives/Basic-Part-1/source-code/qn_3.py
145
3.828125
4
#!/usr/bin/env python3 from datetime import datetime now = datetime.now() print(" Current date and time :\n",now.strftime("%Y-%m-%d %H:%M:%S"))
88327a94489c91c474cca0d3e7df99c4156919d6
VladBaryliuk/my_start_tasks
/new/src/25.01.2020/HT.py
681
3.78125
4
from tkinter import * import random window = Tk() window.title('Greetings') window.geometry('400x300') def phrase_generator(): phrases = ["hello ","what's up ", "aloha ","hallo ","привет "] name = e1.get() greeting = phrases[random.randint(0,4)] + name t1.delete(0.0,END) t1.insert(END...
6b123f3b2c32cb759e03047dd6e17b39ea6f98c8
vadim-ivlev/STUDY
/coding/musor.py
180
3.65625
4
''' the user enters something >>> [1,2,3] [1, 2, 3] ''' def get_input(): a = input() b = input() print('{}-{}'.format(a,b)) print(a+b) # get_input() d=dict()
ebe53305798b1e69b8b887b75adb10763a90df30
CinatitBR/exercicios-phyton
/exercicios/ex077.py
362
3.90625
4
palavras = ('teste', 'programar', 'futuro', 'estudar', 'empresário', 'rico', 'brilhante', 'pensar', 'felicidade', 'computador') for p in palavras: # Verifica cada palavra print(f'A palavra {p.upper()} tem as vogais ', end='') for l in p: # Verifica cada letra da palavra if l in 'aeiou': ...
b87f506e5629bc98f7deaacff27c968ddcc38b47
lindo-zy/python-100
/python-097.py
270
3.8125
4
''' 题目:从键盘输入一些字符, 逐个把它们写到磁盘文件上,直到输入一个 # 为止。 ''' filename=input('请输入文件名:') f=open(filename,'w+') ch='' while '#' not in ch: f.write(ch) ch=input('输入写入内容:') f.close()
53059e3583ec53a488946ba0164f0c78479ef22f
Jonathan-aguilar/DAS_Sistemas
/Ago-Dic-2019/Luis Llanes/Practica1/ejercicio4-4.py
172
3.703125
4
#Hacer una lista del 1 al 1,000,000 listanumeros=[] for i in range(0,1000000): listanumeros.append(i+1) for i in range(0,len(listanumeros)): print(listanumeros[i])
76cc70e59fa13a98b3059dfe40aae4be686745ea
Ahmad-Magdy-Osman/JCoCo
/tests/test26.py
504
3.828125
4
import disassembler import sys def main(): zero = 0 def fib(n): i = zero current = 0 next = 1 while i < n: tmp = next + current current = next next = tmp i=i+1 return current ...
5de60fbe6f65da9dc61a88eea410da78efee9d89
boss2608-cmis/boss2608-cmis-cs2
/cs2quiz3.py
1,376
4.53125
5
#Section 1: Terminology +1 # 1) What is a recursive function? #A function that calls itself # # # 2) What happens if there is no base case defined in a recursive function? +1 #it will keep calling itself until it has reached a maximum about of times that it can call itself # # # 3) What is the first thing to consider w...
d3d6686b515667126a10571165234ecde85e8820
bssrdf/pyleet
/C/CountUnivalueSubtrees.py
2,344
3.984375
4
''' -Medium- 描述 Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of the subtree have the same value. 样例 Example1 Input: root = {5,1,5,5,5,#,5} Output: 4 Explanation: 5 / \ 1 5 / \ \ 5 5 5 Example2 I...
7d1ea2f545c24736e9dbc5a4784baacbe1363816
noob-art/tutorials
/prime checker.py
701
3.90625
4
#number = int(input("Kindly enter a number")) #def check_prime(): # for i in range(2, number): # if number % i == 0: # return False #return True #print(check_prime()) #number_list = [] #prime = [] #def list_prime(): # number = int(input("Enter Number")) # for x in range(1,number + 1):...
a4734ffa95e3fd699009356a1cf53db9595b3ad7
cody1991/learn
/finish-2016/python-learn/1-base/7-loop.py
125
3.75
4
names = ['body','cody','anna'] for name in names: print(name) sum = 0 for x in range(101): sum = sum + x print(sum)
3da4033130adc704e408a5ba1c19575ba5421a0c
Zedmor/EDX_6.00.1x
/usresident.py
397
3.609375
4
def general_poly (L): """ L, a list of numbers (n0, n1, n2, ... nk) Returns a function, which when applied to a value x, returns the value n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """ #YOUR CODE HERE def result(x): res = 0 for i in range(len(L)): res+=L[i]*x**(len(L)-i-1) ...
d19a77ef8677d512a4d33fc97f72033e28f3a331
himanshusuman555/Python-
/farahnite to celcious.py
91
3.5
4
f = input("Enter the temperature in farahnite") f =(int(f)) c = ((f-32)*5)/9 print(c)
61ec743f0093cf407d2ef3527bf6939c98d8ef29
RenegaDe1288/pythonProject
/lesson8/mission05.py
186
3.9375
4
number = int(input('Введите число: ')) summ = 0 for num in range(1, number + 1, 5): summ += num print('Номер стула ', num, 'сумма равна ', summ)
4349e81ae38b379ac3d989b1d2e9f9f76783665d
Erickfpc/AprendePython3
/Ejercicios/mislibrerias/entradas.py
584
3.890625
4
def get_int(hint): valid_answer = False while not valid_answer: try: answer = int(input(hint)) valid_answer = True except Exception as e: print("No has introducido un número:", e) return answer def get_str(hint): return input(hint) def get_bool(hint)...
9bca3bb266d05384e361aa44ec328e63fc6a1620
mikeselezniov/python-21v
/unit_08/generator/zip.py
923
3.609375
4
# -*- coding:utf-8 -*- def random(min_val=0, max_val=100): import random as rand rand.seed() while True: yield rand.randint(min_val, max_val) print [r for (r, i) in zip(random(), xrange(20))] # [42, 17, 35, 96, 31, 11, 18, 9, 81, 78, 35, 71, 14, 12, 28, 24, 62, 67, 61, 49] # Для list comprehensi...
5a4c17cabc72d613d55adb18fca01217759f0d2c
MerleLiuKun/python-demo-small
/data_structure/link_list/singly_linked_list.py
5,932
4.1875
4
# coding=utf-8 """ This is a link list demo with python 1.单向链表 """ # a simple Node for link list class Node(object): def __init__(self, x, nxt): self.val = x self.next = nxt # 单向链表 class SinglyLinkedList(object): def __init__(self): self.head = None # 判空只需要判断指向的下一个节点是否为...
0b2782a05af347075a720fe1780bc8f14afc6dab
rakeshsukla53/interview-preparation
/Rakesh/python-decorator/decorator1.py
508
3.890625
4
a_string ="this is a global variable" def foo(): print locals() print globals() foo() ''' The builtin globals function returns a dictionary containing all the variable names Python knows about. (For the sake of clarity I’ve omitted in the output a few variables Python automatically creates.) At point #2 I cal...
cac76dfc3cbe67b0d92ce1cf0999f450771caec9
das-jishu/data-structures-basics-leetcode
/Graph/implement-graph.py
1,452
3.78125
4
class Vertex(object): def __init__(self, key): self.id = key self.connectedTo = {} def addNeighbor(self, nbr, w): self.connectedTo[nbr] = w def getConnections(self): return self.connectedTo.keys() def getId(self): return self.id def getWeight(self, nbr): ...
48f08558cb4d1145a4d0b5466e622141bb4a69d0
proRamLOGO/gs-edu-outreach-9-python-dsa
/Day4-Factorial.py
240
3.875
4
def factorial(n) : if n==0 : return 1 return n * factorial(n-1) def main() : n = int(input()) ans = n for i in range(2,n) : ans *= i print(n,"! =",ans) print(n,"! =",factorial(n)) main()
cc87ba153471f08edbc17583a1dc509db502a89b
suman2826/Building_BLocks_of_Competitive
/Strings/sort_characters_by_frequency.py
200
3.734375
4
from collections import Counter def characters(s): sol = Counter(s) res = '' sol = sol.most_common() for letter,count in sol: res += letter*count print(res) a = "sumassaaaaaan" characters(a)
d6b723f6cb50d7d6b0a3008fcb0aa9d0d1ccc4de
gariciodaro/Automatic-Measurements-of-Fishes-physical-traits-V2
/Classes/DictionaryAuxiliar.py
680
3.65625
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 29 2019 @author: gari.ciodaro.guerra """ # Linear algebra library. import numpy as np def key_with_maxval(d): """Get the key with maximum value in a dictionary Paramerers: d (dictionary) """ try: v=list(d.values()) ...
a53084410f4be1995760e0edb5b3b1b890b443d3
gmontsell/Prac_3_IA
/prac_3.py
3,975
3.75
4
def printBoard(board): print(board[1] + '|' + board[2] + '|' + board[3]) print('-+-+-') print(board[4] + '|' + board[5] + '|' + board[6]) print('-+-+-') print(board[7] + '|' + board[8] + '|' + board[9]) print("\n") def spaceIsFree(position): if board[position] == ' ': return True ...
aa5ba248faa3154cccdc510c0af1453b594f8524
Eno-Gerguri/OCR-GCSE-Programming-Task-3-Second-Learning-Project
/Version 1 (Multiple Files)/Old Python Files (Not Working)/Authenticate_User.py
2,305
4.03125
4
import sqlite3 from Database_Manager import check_if_username_exists, username_exists, check_if_password_exists, password_exists from Database_Manager import create_account # ====================================================================================================================== # ======================...
123b5564f02eba187f18cc9af658be3496659f7f
agankur21/Algorithm
/LeetCode/3SumClosest.py
522
3.921875
4
# Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. # # For example, given array S = {-1 2 1 -4}, and target = 1. # # The sum that is closest to th...
f8f49bc048a99fa3121e85119e01409858cf3c7f
schiob/TestingSistemas
/ago-dic-2017/Cuauhtémoc Martínez/Práctica 2/practica2.py
486
3.609375
4
import sys def printFile(path): # Se abre archivo (default modo lectura) y se asigna a f. f = open(path) # f.read() lee todo lo restante del archivo, en este caso TODO el archivo. return f.read() def writeFile(path, str): # Se abre el archivo en modo escritura. f = open(path,'w') # write()...
d05ed50a69c75685d5a0cf5bb9e35b2708aa72a9
ZandbergenM/Week__6_Homwork
/Part 1 Exercise 12.1_Zandbergen.py
2,978
4.53125
5
#!/usr/bin/env python # coding: utf-8 # In[1]: #Write a function called most_frequent that takes a string and prints the letters decreasing order of frequency. # Sample String No man is an island Poem by John Donne English """No man is an island, Entire of itself, Every man is a piece of the continent, A part of th...
397e710be522e5436d2182a3890680d537250c74
mcgibbon/python-examples
/scripts/basic/for_loop.py
1,963
4.46875
4
# -*- coding: utf-8 -*- """ for_loop.py: this script shows examples of for loops. This code is released into the public domain. For full details, see UNLICENSE at the root of this project. In essence, you can copy and use this code for whatever purpose, with or without attribution. If you have any questions about the...
0721737b65fed19120821a9fbdec3c44e5210ea0
agustinPassetti/origin
/Practice/python_handon/condition and loop/2_dimensional_array.py
620
4.25
4
# ---------------------------------------------------------------\n", # python best courses https://courses.tanpham.org/\n", # ---------------------------------------------------------------\n", # Write a Python program which takes two digits m (row) and n (column) as input and generates a two-dimensional array. \n", ...
95a19e56262d19a0ab1a484554b80b2dcc600de4
epsilon-d/Python
/Practice/class of python.py
622
3.890625
4
class Calculator: def __init__(self): self.result = 0 def add(self, num): self.result += num return self.result def sub(self, num): self.result -= num return self.result cal1 = Calculator() cal2 = Calculator() cal3 = Calculator() print(cal1.add(3)) print(cal2.add...
a8e785f4a98baf46f87075501e04d585048f7747
ChrisFloresM/Coding-Python
/Python_Hackerrank/30 Days of Code/Day_1_Data_Types.py
575
3.796875
4
#Christian Flores 10/02/2020 i = 4 d = 4.0 s = 'HackerRank ' # Declare second integer, double, and String variables. intgr = 1 doub = 1.0 input_string = "hey" # Read and save an integer, double, and String to your variables. intgr = int(input()) doub = float(input()) input_string = input() # Print the sum of both inte...
3741448f534b01915d6df396162b21485ffc2071
jrbella/computer_science_icstars
/basic_functions/max_num.py
271
4
4
#Write your function here def max_num(nums): largest_num = nums[0] for number in nums: if number > largest_num: largest_num = number return largest_num #Uncomment the line below when your function is done print(max_num([50, -10, 0, 75, 20]))
01d163c03bd992d676d8f8d6672cc1020275f5d8
ParkinWu/leetcode
/python/leetcode/38.py
1,683
3.6875
4
# 报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: # # 1. 1 # 2. 11 # 3. 21 # 4. 1211 # 5. 111221 # 1 被读作  "one 1"  ("一个一") , 即 11。 # 11 被读作 "two 1s" ("两个一"), 即 21。 # 21 被读作 "one 2",  "one 1" ("一个二" ,  "一个一") , 即 1211。 # # 给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。 # # 注意:整数顺序将表示为一个字符串。 # #   # # 示例 1: # # 输入: 1 ...
045f5825a746da3b103a651cfd40200be93ad8ca
mmaithani/python-data
/gui(tkinter-1)/q1.py
386
4.28125
4
# Q1. Write a python program using tkinter interface to write Hello World and a exit button that closes the interface. import sys import tkinter from tkinter import * root=Tk() def show(): print("Hello World") def end(): sys.exit() b1=Button(root,text="hello world",width=20,command=show) b1.pack() b2=Button(...
aedc8a2cb8f56dc97f778799afc5b120602b98f5
DmitryPukhov/pyquiz
/test/leetcode/test_StringCompression2.py
2,781
3.921875
4
from unittest import TestCase from pyquiz.leetcode.StringCompression2 import Solution class TestSolution(TestCase): def test_get_length_of_optimal_compression_example1(self): """ Example 1: Input: s = "aaabcccd", k = 2 Output: 4 Explanation: Compressing s without deleting ...
44362b991f9a3a5e3a87d00028aaf401f1c0f6ba
xdc7/pythonworkout
/chapter-02/01-extra-03-piglatin-two-vowels.py
900
4.21875
4
""" Consider an alternative version of Pig Latin, in which we don't check to see if the first letter is a vowel, but rather we check to see if the word contains two different vowels. Thus, 'wine' would have 'way' added to the end, but 'wind' would be translated into 'indway'. How would you check for two different vowel...
04005c5b4fd191c5ea19a6112a3690d87a3b75c2
Ascarik/PythonLabs
/Ch06/Lab12.py
207
3.84375
4
def printChars(ch1, ch2, numberPerLine): for i in range(numberPerLine): for j in range(ord(ch1), ord(ch2)+1): print(chr(j), sep=" ", end="") print() printChars('A','z', 10)
c700b44e375da0c819c0d025d1ddb5987d6b37ac
shubhomedia/Learn_Python
/functions/recursive_function.py
449
4
4
# simple recursive function def factorial(n): if n == 1: return 1 else: return n* factorial(n-1) print(factorial(5)) # 120 output #simple recurtion def sum(n): if n == 1: return 1 else: return n + sum(n-1) #another recursive function def tail_sum(n,accumulator = 0): ...
51775a6e37838a27c50bd867f6720ce4d2c96356
mani5348/Python
/Day3/Odd_Occur.py
425
4
4
#Python Program to Find Element Occurring Odd Number of Times in a List list1=[] list2=[] n=int(input("how many no. you want to enter:")) for i in range(0,n): a=int(input("enter the no.: ")) list1.append(a) for i in range(0,n): c=0 for j in range(0,n): if(list1[i]==list1[j]): ...
1375ef835aeb842eba5b42cd61edd2688260e8b0
DaydreamerSiri/-bungsaufgaben
/src/aufgabe_4/game_of_life.py
14,123
3.578125
4
#-*- coding: UTF-8 -*- ''' Created on 15.08.2018 @author: Sehri Singh Dieses Python Programm soll von Conway das Spiel des Lebens simulieren in einem x * y Feld. ''' import time import random from copy import deepcopy from editable_extensions import Editable_extensions #■ █ class GameOfLife(object): """Klasse f...
2ec5b12c0f3bd75602386561aba205c840ddfc72
AasthaMehtaTech/LeetCodeProblems
/121_StockBuySell1Time.py
960
3.578125
4
''' Your input [7,1,5,3,6,4] stdout [6, 6, 6, 6, 4, 4] Output 5 Expected 5 ''' #simplest class Solution: def maxProfit(self, prices: List[int]) -> int: best = 0 buy = math.inf for p in prices: if p < buy: buy = p #min price to buy the share updated ...
6688599e19d28c9cb9fa6e6af362e3a331578aca
spoty/Py_builtins
/builtins/hasattr.py
1,039
3.828125
4
hasattr(object, name) The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.) hasattr internally and rapidly perfor...
5699423e1a637aa20d82ef6f200343de6bd35f26
anhdo93/WGU-C950
/Classes.py
1,819
3.984375
4
# Classes defined to be used class Package: """Define package class""" def __init__(self, id, address, city, state, zip, deadline, mass, notes, status, location_id): """initialize package object""" self.id = id self.address = address self.city = city self.state = state ...
a374259b6add9cb4af83b342896497560f70ead9
Bozorboyev-Bobur/Home_work_16.11.2021
/task3.py
96
4.0625
4
# num = int(input('Enter number:')) # if num >= 0: print (num ** 2) # else :print (num ** (1/3))
630d5456846f0947aca42b4b085064c4aaa05cb9
kazamari/Stepik
/course_568/2.5_difference-of-times.py
901
4.15625
4
''' Given the values of the two moments in time in the same day: hours, minutes and seconds for each of the time moments. It is known that the second moment in time happened not earlier than the first one. Find how many seconds passed between these two moments of time. Input data format The program gets the input ...
ab996639717344749d4350d5fddac8ed21a7247f
Zahidsqldba07/sandbox
/codewars/at-validate-args.py
1,399
3.859375
4
''' https://www.codewars.com/kata/at-validate-args Implement the validate_args decorator, which raises an error (InvalidArgument) when the decorated function is called with arguments of the wrong type. Validate_args takes in a sequence of argument types as a variable number of arguments. You do not have to check that ...
57438542535b13ae5777d2f53bc2623ec4d27d16
georgeredinger/CoffeeVision
/timestamp.py
411
3.5
4
#!/usr/bin/python import cv #Import functions from OpenCV import time cv.NamedWindow('a_window', cv.CV_WINDOW_AUTOSIZE) image=cv.LoadImage('coffee.jpeg', cv.CV_LOAD_IMAGE_COLOR) #Load the image font = cv.InitFont(cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 3, 8) #Creates a font x = 100 y = 100 t = time.asctime() cv.PutText(im...
c543b215914973f2ff5f85d9d5a1bf4b2bc97a2d
Anoopsmohan/Project-Euler-solutions-in-Python
/project_euler/pjt_euler_pbm_6.py
573
3.765625
4
'''The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640...
333756de4bf141973c016229dd419334f8f93dde
rootthirtytwo/sandbox
/OOP/Parent.py
1,727
4.21875
4
class Parent(): # Class attribute country = 'USA' # Initializer/Instance attribute def __init__(self, fname, lname): self.fname = fname self.lname = lname self.country = 'Canada' #class method def get_email(self): return self.fname+'.'+self.lname+'@company.com'...
ed58ad374152821e218eb98fac838769d64b2f7a
HassanDaja/assignment-2
/Q25_page299.py
393
3.859375
4
def digit_count(x): zeroes=0 even=0 odd=0 z=str(x).split(".") if len(z)>1: for x in z[1]: if x=="0": zeroes+=1 elif x=="1" or x=="3" or x=="5" or x=="7" or x=="9": odd+=1 elif x=="2" or x=="4" or x=="6" or x=="8...
0386d4d1692ada16559320111ae1b4a8c6f1d399
deusmax88/benchmark
/python/quick-sort.py
589
3.703125
4
import json import sys input = sys.stdin.read() input = input.rstrip('\n') a = json.loads(input) def quickSort(a, start, end) : if start < end : q = partition(a, start, end) quickSort(a, start, q - 1) quickSort(a, q + 1, end) def partition(a, low, high) : pivot = a[high] i = low -...
62aeadddc8d91708fc4741b678981b0e3056efaa
nabiharaza/pythonChallenges
/factorialZerosTail.py
973
3.71875
4
''' How many zeroes are at the end of the factorial of 10? 10! = 3628800, i.e. there are two zeroes. 16! in hexadecimal would be 0x130777758000, which results in three zeroes. Unfortunately machine integer numbers has not enough precision for larger values. Floats drops the tail we need. We can fall back to arbitrary-...
0e0207787c9873894f7c6d4f73caf4cf3b311a64
cpwood/Pico-Stub
/frozen/math.pyi
8,786
4.28125
4
# Stubs for math # See: http://docs.python.org/2/library/math.html from typing import Tuple e = ... # type: float pi = ... # type: float def acos(x: float) -> float: """ Return the arc cosine of ``x``, in radians. """ ... def acosh(x: float) -> float: """ Return the inverse hyperbolic co...
6da6ea2f39a466c21de7fb0c48915dc11b9fbcdf
tandatoua/PythonLearn
/src/Practice/1_Palindrome.py
101
4
4
'''回文数判断''' def is_palindrome(n:int)->int: n = str(n) m = n[::-1] return m == n
f39c1870bb5f23b4d4d3f1e522aa93140671d488
sshkim/PythonSkillUp
/algorithm/Time_Complexity/Primality.py
225
3.921875
4
p = int(input().strip()) def checkPrimality(num): return True for a0 in range(p): n = int(input().strip()) answer = checkPrimality(n) if answer: print("Prime") else: print("Not prime")
1578d8e3dcba2813c50b74e2abab8c90acd2d2c8
Plain-ST/python_practice_55knock
/37.py
402
4.5
4
""" 37. 型の確認 3つの変数に以下のように代入したコードがあります.各変数の型を出力してください.出力形式は問いません. data1 = {'A':1, 'B':2} data2 = "hoge" data3 = {1,2,3,4,5} 期待する出力:<class 'dict'> <class 'str'> <class 'set'> """ data1 = {'A':1, 'B':2} data2 = "hoge" data3 = {1,2,3,4,5} print(type(data1),type(data2),type(data3))
32667078cc5f6c7ca70a162a4125a3681d7847a0
vnejindal/vne_python
/thinkPython/11/Ex_11_1.py
1,884
4.15625
4
#!/usr/bin/python ''' Exercise 1 Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesnt matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary. If you did Exercise 11, you can compare the speed of this...
f3aa07b1ed3263cc6ed99c2f866b9d0d1cd2b9c9
amitraj08195/wordcount
/test.py
287
3.765625
4
import datetime x = int(input("Enter the age of yours")) y = input("Enter name of yours") now = datetime.datetime.now() net = now.year if x>=100: print("You are already a dinosaur") else: er = net - x ter = er + 100 (print ("Your age will be 100 years in %s" % ter))
0789cfbc2c3f7d57bd64b685131cac6fdbdd82f0
rafaelperazzo/programacao-web
/moodledata/vpl_data/7/usersdata/65/3659/submittedfiles/esferas.py
293
3.796875
4
# -*- coding: utf-8 -*- from __future__ import division A=('Digite o peso da primeira esfera: ') B=('Digite o peso da segunda esfera: ') C=('Digite o peso da terceira esfera: ') D=('Digite o peso da quarta esfera: ') if (A==B+C+D and B+C==D and B==C): print('S') else: print('N')
f6a14ccfd986c24e142d0190fd3040dc3fc0b09c
tsuryanto/UmbLearnAIWithPython
/hello.py
456
3.84375
4
from datetime import date, timedelta # tanggal mulai belajar begin_date = date(2019, 9, 12) # Mengambil tanggal hari ini today = date.today() # Cetak teks print("--------------------------------------------------------------") print("Hari ini adalah hari ke" , (begin_date - today).days ,"saya belajar python.") prin...
2a4118e5cccd89fcd9bd5ee3cd2619a2e3262b17
cminahan/CPE202
/Project3/min_pq.py
5,504
4.3125
4
""" Project 3 -- Minimum Priority Queue Name: Claire Minahan Course: CPE202-03 Instructor: Kuboi """ class MinPQ: """ Minimum Priority Queue Attributes: capacity(int): the capacity of the queue the default capacity is 2, but will be increased automatically num_...
f5aa0e129fccf78be07a43810cf1333f82e955ca
JaysM32/Jude_Exercise
/exercise4-PDM/PDM-no11.py
276
3.765625
4
def check(search): number = {} for x in search: number[x] = 0 for i in search: number[i] += 1 return number if __name__ == '__main__': searchstring = input("input word: ") result = check(searchstring) print(result)
eefef12abd15f0a2807d923e4b5cb25d80d704fe
denismwangi/python_roadmap
/branchA/counting.py
242
4.09375
4
count = 1 while count <= 3: print(count) count += 1 entry = 0 sum = 0 print("enter numbers to sum, negative numbers") while entry >= 0: entry = eval(input()) if entry >= 0: sum += entry print("sum =", sum)
b0a7d77d82775c2361efb074a9749a36057c3233
ramkishorem/pythonic
/session3_list_loop/06.py
768
4.21875
4
""" Insert and Delete You may insert and delete elements at any position. """ # Insert cars = ['Hyundai', 'Ford', 'Toyota', 'Skoda'] cars.insert(0,'Mercedes') print(cars) # Output: ['Mercedes', 'Hyundai', 'Ford', 'Toyota', 'Skoda'] cars.insert(2,'BMW') print(cars) # Output: ['Mercedes', 'Hyundai', 'BMW', 'Ford', 'Toy...
1d364d1c353bbabe8acf08582ad0310058742008
Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021
/answers/SIDTK365/Day 10/question2.py
314
3.75
4
s = input() count = 0 first = True t = "" for char in s: if(first==True): t+=char count+=1 first = False continue if(char.isupper()==False): t+=char else: print(t,end="\n") count+=1 t = "" t+=char print(t,end="\n") print(count)
3628c56f172f0d32b3bb407639cb2c9d662ef12f
airportyh/begin-to-code
/lessons/python/lesson-13/distance_formula.py
162
3.84375
4
import math def double(n): return n ** 2 def distance(x1, y1, x2, y2): return math.sqrt(double(x1 - x2) + double(y1 - y2)) print(distance(1, 1, 4, 3))
ad745cdbc7ab9548c5ee4dc223e28ab9ed9b29d2
luoluo19550418/python
/程序模块&包/读写文件/找文件.py
281
3.859375
4
#for循环找文件 #purpose:找某路径下的"*.txt"文件 import os def returndir(path): listdir=[] dirs=os.listdir(path) for i in dirs: if os.path.splitext(i)[1]=='.txt': #分开文件名和扩展名 listdir.append(i) return listdir listdir=returndir('2020.02')
1caadbb4c0a553611b7cc2196bc54f9240ad85b0
swapnilk02/Udemy_Python
/161 function_annotatio_and_type_hints.py
1,026
4.5
4
# function annotation make it clear what kind of the vslues ur functions can accept and what they return. def multiplication(x: float,y: float) -> float: # here we are providing the functional annotation and defining what will be our parameter types and what will be the return type our function result=x*y ...
fc75241c5d2f17f1c3fe9afe671fa59011e3be0c
Priyansh2906/cryptographic-algorithms
/Bruteforce-caesar-cipher.py
906
4.1875
4
str = input("Enter cipher text : ") key=0 for key in range(1,27): decrypted_text = '' for i in str: ascii_val = ord(i) temp_ascii = ascii_val-key #Checking if it is small alphabet or capital aplhabet if ascii_val>=65 and ascii_val<=90: #Capital...
9484a280113c5afabda29443dfac7563eab3e1f7
FernandaDR/Programaci-n
/CLASES/CLASE8/clase_virtual_1(ejemplopoo).py
919
3.8125
4
class Persona(): def __init__(self,nombre,estatura,peso,genero,edad): self.raza = "ser humano" self.nombre = nombre self.estatura = estatura self.peso = peso self.genero = genero self.edad = edad print("hola a todos soy un",self.raza, "mi nombre es",...
9e177985863e0d0d8940fc28bc801b57d87c4012
FAMarcus/Neural-Network-lab
/data_UCLA.py
947
3.671875
4
import numpy as np import pandas as pd admissions = pd.read_csv('data/UCLA_Admission.csv') # mesmo que student_data.csv # One-hot coding: Make dummy variables for rank data = pd.concat([admissions, pd.get_dummies(admissions['rank'], prefix='rank')], axis=1) # Adiciona à tabela de dados 4 colunas para os ranks data = ...
a63d63364056876b0fa2d6acaedff0d375af4f1c
lyoness1/interview-cake-2017
/6-rectangular-love.py
2,920
3.875
4
# INPUT: 2 dictx, rectangles # OUTPUT: dict, rectangular intersection # RUNTIME: O(1) def find_rectangular_intersection(rect_1, rect_2): """ >>> rect_1 = {'left_x': 1, 'bottom_y': 5, 'width': 10, 'height': 4} >>> rect_2 = {'left_x': 0, 'bottom_y': 4, 'width': 2, 'height': 2} >>> find_rectangular_intersection(re...
3462f0b0ca7a11fd78c73e769118c9d8ad7bae3b
pannekoekmetijsappelmoesenslagroom/AI
/week1/opgave4/uc_search.py
1,426
3.828125
4
import config as cf import model from tkinter import messagebox """ algorithm explanation found on: https://www.geeksforgeeks.org/uniform-cost-search-dijkstra-for-large-graphs/ """ def search(app, start, goal): queue = model.PriorityQueue() queue.put(start, 0) visited = [cf.SIZE*[False] for i in ran...
c48da8a0184b5b1bdae5173f53b295feceab75d9
gamishilbha/ps_data-cleaning
/data cleaning.py
2,065
3.9375
4
'''Python assignment Data Cleaning all 5 problems combined ''' import pandas as pd import numpy as np df = pd.DataFrame({'From_To': ['LoNDon_paris', 'MAdrid_miLAN', 'londON_StockhOlm', 'Budapest_PaRis', 'Brussels_londOn'], 'FlightNumber': [10045, np.nan, 10065, np.nan, 10085], 'RecentDelays': [[23, 47], [], ...