blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
62f12ec2379a89df04420b0b4c3edeb5f1eef7a7
daffuna91/Data-Structure-and-Algorithm-Quiz
/8_descending_order.py
1,257
3.921875
4
#Instructions: http://www.evernote.com/l/ACgUzetkv4tAfLDEkb0gNWe_sRjTjAyJm1w/ class maxMachine : def __init__(self) : self.myData = [] def addNumber(self, n) : self.myData.append(n) def removeNumber(self, n) : self.myData.remove(n) def getMax(self) : return max(self.m...
159bf8400f5bc72a860ef5afd16843dee4c41bdd
Bea-Nuri/PCC_Chapter_5_-_If_Statement
/exercise_5.8_Hello_Admin.py
253
3.953125
4
users = ['eric', 'thomas', 'faldo', 'rita', 'danny', 'admin'] for user in users: if user == 'admin': print("Hello Admin, would you like to see a status report?") else: print("Hello " + user + ", thank you for logging in again.")
9044884c979530ea12c75a50f20feb0dc0b26f6f
weina1117/Leetcode
/day4/409_Longest_Palindrom.py
1,350
4.0625
4
""" Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example "Aa" is not considered a palindrome here. Note: Assume the length of given string will not exceed 1,010. Example: Input: "abccccdd...
7282c9667d656058f0c81dfad296314b3620d57a
weina1117/Leetcode
/day6/441_Arranging_Coins.py
578
3.8125
4
""" You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. """ class Solution(object): def a...
1dd7b487b9c8609eba21a089db0027342d61ded2
weina1117/Leetcode
/day2/371_Sum_Two_Integers.py
752
3.71875
4
""" Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. """ class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ MAX_INT = 0x7FFFFFFF ...
2e7864398bb61d3b7544ff9aeb1f5eb0b7804bd7
kit-ai-club/ReiLa_intro
/python_intro_HW/class_intro.py
1,678
4.0625
4
class TestClass: # クラス名は大文字から def __init__(self, x): # initialize (初期化関数 1つ目のselfは必須のおまじない) self.x = x # クラス変数。クラスにxという値を保管しておく(登録した) def f(self): # クラス関数。クラスにfという関数を保管しておく print(self.x) testClass = TestClass("x1") # インスタンス(実体)の作成。クラスはただの概念。 # 「文字列()」という表記を使っていれば、クラスか関数のどちらか。 # self.xがx1に...
e9bfe88535c2b010ddbffba57c65ca4d2bdf3bbb
furkandv/Example
/rastgelezaratımı.py
638
3.578125
4
""" Bir zar atıldığı zaman toplamının iki gelme olasılığı Bir zar atıldığı zaman toplamının üç gelme olasılığı Bir zar atıldığı zaman toplamının dört gelme olasılığı Deneysel olasılık ile hesaplıyoruz. Bunun için 10 bin defa 2 adet zar atıp Gelen sonuçları bir listeye yazarak olasılığı hesaplayacağız. """ import r...
8af95df71b37693cec914877a43bca31f93fb6f4
furkandv/Example
/cumleleriayırma.py
605
3.609375
4
""" Cümleler nasıl ayrılır ? """ def ayir(cumle): kelimeler = [] kelime = " " for i in cumle: if i == " ": kelimeler.append(kelime) kelime = "" else: kelime += i kelimeler.append(kelime) return kelimeler metin = "Your registration is conf...
bb5e5b5ac9fa32a84e5d8141465bc3021cf458eb
handdole/PYTHON
/파이썬강의(입출력 및 간단한 계산)/mega1/사칙연산기.py
384
3.71875
4
#계산기 모듈을 여기에 사용하겠다는 표현 from other import Bull select = input("연산을 선택하세요 1.더하기2.곱하기3.나누기4.빼기 >> ") if select == "1": Bull.plus() elif select =="2": Bull.mul() elif select =="3": Bull.div() elif select == "4" : Bull.minus() else : print("잘못입력하셨습니다.")
1ac61080f7e7f65f87ca2a7c7478e18b53a29b53
handdole/PYTHON
/파이썬강의(collection)/mega/for4.py
931
3.875
4
list = [100,200,300,400,500,600,700,800,900] ''' for 문을 사용하세요. 1. 전체목록을 프린트 2. 홀수번째 있는 요소들을 프린트 3. 홀수번재 있는 요소들을 다 더해서 프린트 4. 짝수번째 있는 요소들을 프린트 for 문을 이용해서 풀어보세요 1. 1부터 1000까지 더해보세요 ''' for x in list : print(x,end=" ") print('---------------------------') for x in range(0,len(list),2) : ...
625bc9b7d55794d0a96823849ae21563c8609a0d
handdole/PYTHON
/파이썬강의(collection)/mega/for3.py
100
3.703125
4
target = [1,2,3,4,5] print(1 in target) for x in range(0,len(target),2) : print(target[x])
7e7ff05f560c36c4ced1e0d76401ce5e644fb485
handdole/PYTHON
/파이썬강의(연습문제)/연습문제/1.py
1,206
3.640625
4
# 2 7 14 / 5 8 11 /3 5 8 /5 10 11/2 7 11/4 7 9/6 9 11/4 7 13 /2 7 8 # 3 8 13 # 4 11 15 # 6 7 15 # 4 9 13 # 6 11 15 # 6 10 12 # 3 6 11 # 4 9 12 # 4 7 13 # 3 11 15 don = 0 sum = 5000 print('금액이 부족합니다.') print('총 금액은' + str(sum) + '원입니다.') print('부족한 금액은', str(sum - don1), '입...
888ffe5c2ebf3b3611e48b5e2490757f7bcca161
Joseph-Whiunui/Project-Euler
/largePal.py
402
3.796875
4
def main(): print(palindrome()) def palindrome(): for a in range(9,-1,-1): for b in range(9,-1,-1): for c in range(9,-1,-1): num = int(str(a)+str(b)+str(c)+str(c)+str(b)+str(a)) print(num) for i in range(999,100,-1): if (nu...
0662890b0515a61813ba4f95f82cd5e755262e14
prerakpanwar/Training-With-Acadview
/assignment8.py
3,623
4.3125
4
#Q1- Create a circle class and initialize it with radius. print("Make two methods getArea and getCircumference inside this class.\n") class Circle(): def __init__(self,radius): self.radius = radius def getArea(self): print("Area is : " + str(3.14*self.radius*self.radius)) ...
962d6843e1d648390ba46b6a2db88bce193158bc
prerakpanwar/Training-With-Acadview
/assignment16.py
1,573
4.46875
4
#Q1-Write a python program using tkinter interface to write Hello World and a exit button that closes the interface. from tkinter import * m = Tk() label = Label(m, text= "\nHello World\n") label.pack() #Q2-Write a python program to in the same interface as above and create a action when the button is click it wi...
dd9be21c48fb7f1bc05ac7f866f7c31b658f36af
bsavio/ProjectEuler
/Problem42.py
1,444
3.78125
4
""" Coded triangle numbers Problem 42 The nth term of the sequence of triangle numbers is given by, tn = 1/2n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values ...
052643c4617beb784e5c14985eaf071e8ac1c6bd
bsavio/ProjectEuler
/Problem3.py
393
3.65625
4
""" Largest prime factor Problem 3 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ from math import sqrt, ceil from lib import is_prime, iterate_odd number = 600851475143 limit = ceil(sqrt(number)) pf = [] for n in range(3, limit): if...
8c956346c061825430f3af1793d142cb31f370e7
bsavio/ProjectEuler
/Problem38.py
1,532
4.09375
4
""" Pandigital multiples Problem 38 Take the number 192 and multiply it by each of 1, 2, and 3: 192 × 1 = 192 192 × 2 = 384 192 × 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by s...
1dba40f50ddb0e77d308b198c5ac5087b887afe1
bsavio/ProjectEuler
/Problem23.py
1,431
3.78125
4
""" Non-abundant sums Problem 23 A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its prop...
6f4e1101495492bf56e6c56236f2d5656ecd985e
bsavio/ProjectEuler
/Problem34.py
968
3.78125
4
""" Digit factorials Problem 34 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. """ from math import factorial from timeit import default_t...
44800315f034f5e45990639ae8d45e66bb28a8f3
mwangi-njuguna/Project-Euler
/square_difference.py
545
3.625
4
def sum_of_square(limit): my_list = [] start = 1 while start<=limit: square = start*start my_list.append(square) start+=1 p = sum(my_list) if len(my_list)==limit: m = sum(my_list) return m def square_of_sum(limit): list = [] for a in range(1,l...
83519d7ccbabd9ba6a034b6f31e90cdbb261cbba
shendeguize/DeeCamp-2018-RobotArm
/Code-Python/Kinematics.py
1,496
3.609375
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 2 11:41:13 2018 @author: kk """ import math from math import pi def cos(theta): return math.cos(theta) def sin(theta): return math.sin(theta) d1 = 106.1 a = [13.2, 142, 158.8] deltaZ = -74 # 大致 deltaR = 56.65 def Angle2XYZ(Angle1=0, Angl...
3ff5b4048db46068e8af1ca6db68df4de51de974
nikitkokatsiaryna/Stepic_algorithms
/search_tree/traversing_binary_tree.py
1,372
3.859375
4
class BinaryTree: def __init__(self, tree): self.tree = tree self.result = list() def in_order(self, node): if node == -1: return self.in_order(self.tree[node]["left"]) self.result.append(self.tree[node]["key"]) self.in_order(self.tree[node]["right"])...
4d8e427d48265b415b791956466f244a434d9c9b
daniboyBr/decimal-to-bynari-converter
/main.py
425
3.765625
4
def main(): num_decimal = 1 binario = [] resto = 0 while (True): resultado = int(num_decimal / 2) resto = int(num_decimal % 2) num_decimal = resultado binario.insert(0, str(resto)) if (resultado == 1 or resultado == 0): binario.insert(0, str(resul...
8e720cea61458779a05d4c2220516863a13ba8f4
pmarlon/projeto-SGPJ
/models/banco.py
5,539
3.765625
4
from sqlite3 import * class Banco: """ Classe de criação do Banco de dados """ def __init__(self): self.conn = None self.cursor = None self.connected = False def connect(self): """ Realiza a conexão com o banco de dados""" self.conn = connect('banco.d...
0896d801151df5bd491b8d91e92398495c5e8ed2
kberwaldt/IntroToProgramming
/Project 4 Create a Movie Trailer Website/entertainment_center.py
1,339
4
4
# Lesson 3.4: Make Classes # Mini-Project: Movies Website # In this file, you will define instances of the class Movie defined # in media.py. After you follow along with Kunal, make some instances # of your own! # After you run this code, open the file fresh_tomatoes.html to # see your webpage! import media import f...
e04bd97461f56e8f944718eda5ff3b0d6ccc7615
GopalMule/python_basics
/list/sort_last_tuple.py
941
4.46875
4
#!/usr/bin/python # C. sort_last # Given a list of non-empty tuples, return a list sorted in increasing # order by the last element in each tuple. # e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields # [(2, 2), (1, 3), (3, 4, 5), (1, 7)] # Hint: use a custom key= function to extract the last element form each tuple. def...
b0e437cbc3cf030f452f73ff19d5668b4284e4cd
darkrazor99/assignment-one-
/main game with artficial intelegence.py
9,355
3.796875
4
list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] win=[] stop=1 turn=1 end=10 print("Welcome to the two squares game ") print("Do you want to see the rules?") print("") o=int(input("enter 1 to see the rules and 2 to skip the rules:\n")) rules=0 while rules==0: if o==1: print("Imagine a board of 4x4 squa...
460fedd0f8a5aeaeb8e8df421beb7e601c5bd983
Adam05443/WorkProgramming
/getlistofap.py
1,559
3.890625
4
""" A dumb script which gives a sorted list of items at element zero of a large text file """ import sys import os #open the file with the raw list of access points f = open(os.path.join('\MyDocuments\Python Scripts','list of access points'), "r") #opens a blank document - will write to it later. f2 = open(os.path...
6f7a141f43ce5c17851486e4fa6ae4bc4d435264
xerocrypt/Python
/Python-SQLite/CheckPassword.py
776
4.09375
4
#This program checks a username and password against an SQLite database #Michael, January 2014 #michael@ipv6secure.co.uk import sqlite3 import hashlib #Connect to database conn = sqlite3.connect('hashBase.db') c = conn.cursor() #Read entered password and generate hash currentUser = raw_input("Login: ") currentPass =...
fb6ac69ceb4ebd677638c7570619269a016de3b8
urluba/summer2018
/20180808/calculatrice.py
1,068
3.765625
4
''' 1 - Lire un fichier dont le format est: int;int;operation (+|-|*|/) exemple: 1;1;+ 2 - utiliser les informations fournies dans le fichier pour effectuer les operations arithmetiques définies 3 - Ecrire les résultats justes dans un fichier sous le format: L'addition de <premier nombre> avec <second nombre> est:...
26f6a7cdf918923594f07ee59275c32b841a4752
govind-shenoy/Python_Google_IT_Automation
/python_and_os/week3/valid_sentence.py
636
4.46875
4
#!/usr/bin/env python3 ''' Fill in the code to check if the text passed looks like a standard sentence, meaning that it starts with an uppercase letter, followed by at least some lowercase letters or a space, and ends with a period, question mark, or exclamation point. ''' import re def check_sentence(text): ...
30b7f97f57c7bb4bc13cd4a14b19375c7018fa48
dp1706/cloud-computing
/Assignment 8/lab_8/part_2/mapper.py
322
3.578125
4
#!/usr/bin/python import sys import re #from nltk import word_tokenize for line in sys.stdin: words=line.strip() words = re.findall("(?=[a-zA-z0-9])[\w']+",words) for word in words: #word = word.lower() #word = re.sub(r'[^\w]','',word) print '%s,%s' % (word.lower(), 1...
55c9c58863d79a64d39bacaa60a561690587a1a6
GabrielSilveiraDev/Lista-3-wiki-python
/Lista 3 wiki python.py
17,873
4.21875
4
#Lista 3 wiki python #Exercício 1: "" while True: nota = float(input('Digite uma nota entre 0 a 10: ')) if 0 <= nota <= 10: print(f'A nota digitada foi {nota}.') break "" #Exercício 2: while True: user = str(input('Digite seu nome de usuário: ')) senha = str(input('Digite sua se...
924bf6a0ef6fe209499be618ee76365abc902a0a
abailey509/Python-Program-2-Pong
/pong.py
4,826
3.890625
4
# Pong # Written by Andrew Bailey # CS 235 import pygame, sys import random pygame.init() clock = pygame.time.Clock() class moving_object: # moving object is used for both players and the ball velocityX = 5 # Adjusting velocity will increase or decrease difficulty velocityY = 5 score...
85c1b33bc75c0322b55ff7a2fc55bed37cd5e406
ztan-mines/csci534_final_project
/tetromino.py
327
3.515625
4
#!/usr/local/bin/python3 import numpy as np class Tetromino: def __init__(self, shape, row, col): self.shape = shape self.row = row self.col = col def rotate(self): """ Rotates tetromino clockwise by 90 deg. """ self.shape = np.rot90(self.shape, axes=(...
e5da1d976bea9f3865fa3b64083b86c4d47fada4
holysll/Leetcode
/0557_reverse-words-in-a-string-iii.py
1,205
3.9375
4
# !/usr/bin/env python # -*- coding:utf-8 -*- # some description # author: holysll # datetime: 2020-8-30 21:31 # software: PyCharm """ 题目:反转字符串中的单词 III 给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。 示例: 输入:"Let's take LeetCode contest" 输出:"s'teL ekat edoCteeL tsetnoc" 提示: 在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。 来源:力扣(Le...
b40a2b7967abe2cca6718bcfd760b111addd8b3b
holysll/Leetcode
/0099_recover-binary-search-tree.py
2,402
3.59375
4
# !/usr/bin/env python # -*- coding:utf-8 -*- # some description # author: holysll # datetime: 2020-8-9 21:37 # software: PyCharm """ 题目:恢复二叉搜索树 二叉搜索树中的两个节点被错误地交换。 请在不改变其结构的情况下,恢复这棵树。 示例 1: 输入: [1,3,null,null,2]   1   /  3   \   2 输出: [3,1,null,null,2]   3   /  1   \   2 示例 2: 输入: [3,1,4,null,null,2] 3 ...
7151ca8a6335148a37c17f0804e784ad7403a88c
holysll/Leetcode
/0144_binary-tree-preorder-traversal.py
4,579
3.796875
4
# !/usr/bin/env python # -*- coding:utf-8 -*- # some description # author: holysll # datetime: 2020-7-10 20:42 # software: PyCharm """ 题目:二叉树的前序遍历 给定一个二叉树,返回它的 前序 遍历。  示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,2,3] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-t...
c3200702c11e38855255404886ff76b75dfbd390
holysll/Leetcode
/0031_Next_Permutation.py
1,191
3.90625
4
# 下一个排列 # 题目: # 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 # 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 # 必须原地修改,只允许使用额外常数空间。 # 以下是一些例子,输入位于左侧列,其相应输出位于右侧列。 # 1,2,3 → 1,3,2 # 3,2,1 → 1,2,3 # 1,1,5 → 1,5,1 # Solution Code class Solution: def nextPermutation(self, nums): """ :type nums: List[int] ...
e04e243c8dd40a9f19242de13bb04865ce022afc
holysll/Leetcode
/0637_average-of-levels-in-binary-tree.py
2,277
3.875
4
# !/usr/bin/env python # -*- coding:utf-8 -*- # some description # author: holysll # datetime: 2020-9-12 21:36 # software: PyCharm """ 题目:二叉树的层平均值 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。 示例 1: 输入: 3 / \ 9 20 / \ 15 7 输出:[3, 14.5, 11] 解释: 第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。 提示: 节点值的范...
526ad9a4a91b909f42cf94be26161c4fb50b1abf
holysll/Leetcode
/1480_running-sum-of-1d-array.py
1,670
3.96875
4
# !/usr/bin/env python # -*- coding:utf-8 -*- # some description # author: holysll # datetime: 2020-8-3 15:47 # software: PyCharm """ 题目:一维数组的动态和 给你一个数组 nums 。数组「动态和」的计算公式为:runningSum[i] = sum(nums[0]…nums[i]) 。 请返回 nums 的动态和。 示例 1: 输入:nums = [1,2,3,4] 输出:[1,3,6,10] 解释:动态和计算过程为 [1, 1+2, 1+2+3, 1+2+3+4] 。 示例 2: 输入:...
0b766eeb886b6a850ebe1ad22ff5509fa7855762
holysll/Leetcode
/0079_word-search.py
2,256
3.859375
4
# !/usr/bin/env python # -*- coding:utf-8 -*- # some description # author: holysll # datetime: 2020-9-13 19:11 # software: PyCharm """ 题目:单词搜索 给定一个二维网格和一个单词,找出该单词是否存在于网格中。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。 示例: board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','...
44c1224d378baa2614ab4b6cf6ffd725b7507102
mirrorstage/100daysofcode-with-python-course
/days/07-09-data-structures/dataStructures.py
2,178
3.625
4
#!/usr/bin/env python3 import re import pprint cars = { 'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'], 'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'], 'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'], 'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'], 'Jeep': ['Grand Cherokee', 'Ch...
f52be270d36dfc79c72828f92b2e279e43e3e41d
erfantkerfan/python-examples
/33.py
110
3.90625
4
l = int(input("enter l:")) w = int(input("enter w:")) h = int(input("enter h:")) volume = l*w*h print(volume)
e2185b6528fb79f155ea8bc214707c067458d56e
erfantkerfan/python-examples
/16.py
77
3.71875
4
n = int(input('enter n:')) f = 1 for i in range(1, n+1): f *= i print(f)
7e60deb07f216ad01dd173caeed7f705ba92f76d
BurgeonGroup/capstone-frontend
/src/_error.py
1,050
3.828125
4
#!/usr/bin/python """ Objects of type Error are returned if there was an error loading bitlash code onto the Arduino. If you would like to add a new error add an entry in the error code table and add a handler in the __str__ method. """ ################################################################################ #...
d1e55ce91e8ec4fba02a89cfc66abe50bc32ff6d
feeglo/mython
/属性.py
569
3.625
4
class Programer(object): happy='play computer' def __init__(self, name, age, weight): self.name=name self._age=age self.__weight=weight @classmethod def get_happy(cls): return cls.happy @property def get_wight(self): return self.__weight def self_in(self): print 'My name is %s\nI am %s years old\n'%(...
d3ac1dea467ad680fc47c975e60df16e596a209e
nava99git/ELEMENTZ
/waste_segregations/yieldtest.py
419
3.78125
4
from time import sleep def nextSquare(): i = 0; # An Infinite loop to generate squares while True: print('nextSquare: %d' % (i)) yield i sleep(5) i += 1 # Next execution resumes # from this point # Driver code to test above generator # function for value in...
3a650709cf102b0fa24fa6b3f01e6898a996bee3
noelis/coding_challenges
/count_recursively.py
423
4.15625
4
def count_recursively(lst): """ Return number of items in a list, using recursion. >>> count_recursively([]) 0 >>> count_recursively(['a', 'b', 'c']) 3 """ if not lst: return 0 return 1 + count_recursively(lst[1:]) if __name__ == '__main__': import doctest print ...
ed43e5439b9d70fbdf168edfddb64482ad3803fd
patelrohan750/python_practicals
/Practicals/practical1_D.py
289
4
4
# D.write a python program to compute the GCD of two numbers num1 = int(input("Enter first Number: ")) num2 = int(input("Enter second Number: ")) i = 1 while i <= num1 and i <= num2: if num1 % i == 0 and num2 % i == 0: gcd = i i = i + 1 print(f"GCD is {gcd}")
3b35b7b47d66c8b1ec5d007de07be2aa01e5e47f
patelrohan750/python_practicals
/Practicals/practicals3_B.py
288
4.125
4
# To get a string from a given string where all occurrences of its first char have been # changed to '$', except the first char itself. # Sample String : 'restart' # Expected Result :' s=input("Enter String: ") ch=s[0] s=s.replace(ch,'$') s=ch+s[1:] print(f"The string is {s}")
8274a01726e147157ac0b2a0421e4e6c7e4f2cb1
patelrohan750/python_practicals
/Practicals/practical4_B.py
1,469
4.25
4
#B). to write a python program to change,delete,add,and remove elemnts in dictonary d = {26: "rohan", 24: "rahul"} user_choice = '' while user_choice != 'q': print("Enter Your Choice You Want To Do") print("1.Add") print("2.change") print("3.delete") print("4.remove") print("If You Want...
1c8f2ee29f7e77af8d20cad42cc420eebd4dd6f1
casey-rjones/Macronutrient-Calculator
/MacroCalculator.py
940
4
4
# This function adds two numbers def maintCalc(x, y): return (x * 10) * y print("Select operation.") print("1.Calculate Body Weight Maintenance") print("2.Calculate Macros") # Take input from the user choice = input("Enter choice(1 or 2): ") if choice == '1': bodyWeight = int(input("Enter Body Weight ...
7afaa3055db06ac9e43ff6acadeebc10e8236279
danra2/pythonOOP
/oop_chapter1.py
3,268
4.21875
4
class MyClass(object): var = 10 # pass this_obj = MyClass() that_obj = MyClass() print this_obj print this_obj.var print that_obj.var #This is an instance of MyClass. # class Joe(object): greeting = "hello, Joe" def callme(self): print('Calling call me method with instance:') thisjoe = Joe...
9b9d25703615db619515faead654b16b795cb2d6
yaolinxia/algorithm
/爱科赛尔/快速查找k的序列.py
445
3.71875
4
# 给出已排序整数数组,请写一个函数快速找出“k”在第几位。 """ 思路: 1. 蛮力法 2,二分查找 3. dict存储,k:index, v:num """ def find_k(l, k): d = {} for i, j in enumerate(l): d[i] = j new_d = {v:k for k,v in d.items()} if k in new_d: print(new_d[k]+1) else: print("k不存在!") if __name__ == '__main__': l = [1, 2, 5,...
f10cdb0b02ad36fea81aa496e899225cad2edd14
yaolinxia/algorithm
/数字字符/number_char.py
1,244
3.84375
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ 在十进制表示中,任意一个正整数都可以用字符’0’-‘9’表示出来。但是当’0’-‘9’ 这些字符每种字符的数量有限时,可能有些正整数就无法表示出来了。比如你有两个‘1’, 一个‘2’,那么你能表示出11,12,121等等,但是无法表示出10,122,200等数。 现在你手上拥有一些字符,它们都是’0’-‘9’的字符。你可以选出其中一些字符然后 将它们组合成一个数字,那么你所无法组成的最小的正整数是多少? """ def minInt(num): num_list = list(str(num)) # print(nu...
83f4b9d0db826ea7a2c16bcc166eb4c0a17133d7
yaolinxia/algorithm
/奇偶排序/isOddNumber.py
2,234
3.84375
4
""" 思路一: 蛮力法,依次扫描整个数组,每遇到一个偶数,就将该数放到最后 时间复杂度(O^2), 不符合题目要求 """ def isOddNumber(num): length = len(num) i = 0 while i < length: if num[i] % 2 == 0: num.append(num[i]) num.remove(num[i]) #print(num) i += 1 elif num[i] % 2 == 1: i += 1...
e14e62debf528140ffc6715aec88766f94a204f9
yaolinxia/algorithm
/快速排序/quick_sort.py
782
3.9375
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ def quick_sort(n): pivot = n[0] left = [] right = [] if len(n) == 1: return n for i in range(1, len(n)): if n[i] < pivot: left.append(n[i]) else: right.append(n[i]) return quick_sort(left) + [pivot] + ...
38ca967e93abab58f1e5d134df64dc98bb255a50
yaolinxia/algorithm
/baidu/6.py
951
3.5625
4
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # 挑选笔记,不能出现连续编号,需要点赞总数最多。两者都符合的时候,选择笔记总数最少的 # opt[i]表示前i篇文章获得的最多点赞数;arts[i]表示前总赞数最多时, 挑选的文章总数 def find_good(n, likes): opt = [0 for i in range(n)] arts = [0 for i in range(n)] opt[0], opt[1] = likes[0], likes[1] arts[0], arts[1] = 1, 1 for i in range(2, ...
23d7058ce66a99e81f9d8b539f3bee1e1f5897ce
wayne020311/random
/rand.py
211
3.8125
4
import random r = random.randint(1,30) while True : x = input("請輸入數字") x = int(x) if x == r : print('恭喜答對') break if x > r : print('比答案大') if x < r : print('比答案小')
0f3ef4daf330d50b39d12cd71f245f456bad3503
felipepatricioo/College-Assigments
/python1-college/assignment1-1.py
1,262
4.15625
4
#Code a program that receives a student name and final grade #Laço inifinito que só ira parar de cadastrar dados de alunos quando digitado "0" while True: start = int(input('Inserir dados do aluno? (1 = Sim, 0 = Não) ')) if start == 0: print('Encerrando Programa...') break name = i...
7ee3aed8a3fab6da1fe74ce577b756448537663f
sameerbakshi/SDET
/Python/Activity10.py
233
4.28125
4
num_tuple = tuple(input("Enter a tuple separated by commas: ").split(',')) print("You have entered: ",num_tuple) print("Element(s) that are divisible by 5: ") for num in num_tuple: if(int(num)%5==0): print(num)
95bfb84f4ae4a1885bec8eb9d41318c4d14c5593
baranee-18/Data-Structures-and-Algorithms
/reverse-nodes-in-k-group/reverse-nodes-in-k-group.py
761
3.578125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if not head: return L = [] while head: ...
d82dbaf50ed231fcea3699a6a5fc3be0e5328b39
baranee-18/Data-Structures-and-Algorithms
/Sorting/selection_sort.py
240
3.578125
4
nums = [5, 3, 7, 1, 20, 9] for i in range(len(nums)): min_index = i for j in range(i, len(nums)): if nums[j] < nums[min_index]: min_index = j nums[min_index], nums[i] = nums[i], nums[min_index] print(nums)
6414d0a6709724b6b56d89216ebd46424e855d92
baranee-18/Data-Structures-and-Algorithms
/binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.py
796
3.515625
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 class Solution:    def maxPathSum(self, root: TreeNode) -> int:                import sys        self.result = -sys.maxsize ...
db65c2492b3adc0d00c70250e693d01acea31073
baranee-18/Data-Structures-and-Algorithms
/clone-graph/clone-graph.py
671
3.546875
4
""" # Definition for a Node. class Node: def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] """ class Solution: def cloneGraph(self, node: 'Node') -> 'Node': cloned = {} def DFS(node): if not node...
3c4adff91c99f87729a59b9a17628cb3ba365302
baranee-18/Data-Structures-and-Algorithms
/car-pooling/car-pooling.py
480
3.609375
4
class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: stops = [] for passengers, start, stop in trips: stops.append([start, passengers]) stops.append([stop, -passengers]) stops.sort() ...
cbeb19e5e65d7685083ab6b6d0361d8a2d434bcf
baranee-18/Data-Structures-and-Algorithms
/find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.py
317
3.515625
4
class Solution:    def findDuplicates(self, nums: List[int]) -> List[int]:        hash_set = {}        res = []        for i in nums:            if i not in hash_set:                hash_set[i] = i            else:                res.append(i)        return res
efa39bd8e268bacefbc52a99143951838f1f313f
baranee-18/Data-Structures-and-Algorithms
/populating-next-right-pointers-in-each-node-ii/populating-next-right-pointers-in-each-node-ii.py
1,101
3.796875
4
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ class Solution: def connect(self, root: 'Node') -> 'Node': i...
5ee927b6f803607deb4bd2688da3ef72837d5933
baranee-18/Data-Structures-and-Algorithms
/find-median-from-data-stream/find-median-from-data-stream.py
667
3.59375
4
class MedianFinder: def __init__(self): """ initialize your data structure here. """ self.L = [] def addNum(self, num: int) -> None: self.L.append(num) self.L.sort() def findMedian(self) -> float: curr_len = len(self.L) if curr_len ...
cb51d4168d170bef628919cf53ffee8c9040adc0
baranee-18/Data-Structures-and-Algorithms
/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.py
759
3.796875
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 class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: return self.backTracking(...
be8c6771bf1c7790bd4e52163c150f1e9f90f103
AzitaDadresan/Restful
/Find.py
772
3.59375
4
# -*- coding: utf-8 -*- import json import pymongo import datetime from bson.objectid import ObjectId from pymongo import MongoClient from bson import json_util import os, sys connection = MongoClient('localhost', 27017) db = connection['market'] collection = db['stocks'] #find document method to find gt than small v...
bb07dba78ccdb78e82b96f4bfefd88726cbfea2d
binaryfaith/PythonCourse
/animal.py
1,505
3.953125
4
class animal(object): def __init__(self,name): self.name = name self.health = 20 def walk(self): if self.health > 0: self.health -= 1 return self def run(self): if self.health >= 5: self.health -= 5 return self def display...
7854b8ff70598c9fea57e9f3c71ba58169d9fbcb
MahmoudHadad/Hangman
/Hangman/hangman.py
3,462
3.578125
4
''' Created on Nov 17, 2015 @author: M-Hadad ''' import random ## functions def readFile(fileName): lis = [line.rstrip('\n') for line in open(fileName)] return list(map(lambda word:word.upper(),lis)) def printWord(w): for i in range(len(w)): print w[i]," ", print "" def isComplete(w): ...
cec346a7c000a3a8e49b385c09eadb6ac6001781
nyanyehtun-simon/CP1404Prac
/Prac_06/driving_simulator.py
1,476
4.25
4
from Prac_06.car import Car VALID_USER_CHOICES = ['d', 'r', 'q'] print("Let's drive!") name = input('Enter you car name: ') user_choice = None distance_in_km = -1 units_of_fuel = -1 car = Car(fuel=100, name=name) while user_choice != 'q': print(car) print(""" Menu: d) drive r) refuel q) qu...
5ae18253d215968e4192546ea6cd3aa1a441e605
nyanyehtun-simon/CP1404Prac
/Prac_02/files.py
471
3.9375
4
# name_file = open('name.txt', 'w') # # name = input('What is your name?: ') # # print(name, file=name_file) # name_file.close() # # name_file = open('name.txt', 'r') # # name_var = name_file.readline() # # print('Your name is {}'.format(name_var)) numbers_file = open('numbers.txt', 'r') number_list = numbers_file.rea...
973e49ab2607dd8c5859adfb96b44a0a33a4c9a4
nyanyehtun-simon/CP1404Prac
/Prac_05/electricity_bill_estimator.py
444
3.859375
4
print('Electricity Bill Estimator 2.0') TARIFF_DICT = { "TARIFF_11": 0.244618, "TARIFF_31": 0.136928 } tariff = input("Which tariff? {0} or {1}:".format(*TARIFF_DICT.keys())) daily_use_in_kWh = float(input('Enter daily use in kWh: ')) billing_days = float(input('Enter number of billing days: ')) estimated_bi...
2daefed5c5e8aec4e002a73f354d2535e0e09551
nyanyehtun-simon/CP1404Prac
/InClassDemo/formatDemo.py
1,031
3.671875
4
# name = 'Monty' # money = 73.6 # # #Output: Monty has $73.60 # print('{} has ${:.2f}'.format(name, money)) # var1 = 'Simon' # var2 = 2400 # # print('${1:<7,d} {0} {1}'.format(var1, var2)) # temp_file = open('tempfile.txt', 'w') # # print('first line', file=temp_file) # print('second line', file=temp_file) # temp_fi...
b1df5155f0cc2e8437f81f44a8d45957cfc2f1ae
panoczy/pano-2
/calculator.py
1,102
3.890625
4
#!/usr/bin/env python3 import sys def result(argv): for s in sys.argv[1:]: try : number,salary = s.split(':') salary = int(salary) except(IndexError,ValueError): print("Parameter Error") else: a = salary - 3500 - suf(salary) income...
3ae10a3ebd7804644a2463571bac9cdd23c59f0e
vishalmajumdar95/Python_logical_questions
/Recursion/recursion.py
3,138
3.96875
4
def pattern(number): if number == 1: return 1 else: return pattern(number-1) + 3 print(pattern(7)) def factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return (x * factorial(x-1)) num =int(input()) pr...
6aa2cdaee3ff9ad663dd3d294bce5fa68eff22c3
matthope1/cs50
/cs50/week7/pset7/houses/roster.py
668
3.890625
4
#houses # TODO from sys import argv, exit import csv from cs50 import SQL if len(argv) != 2: print("Missing command-line argument") exit(1) house = argv[1] db = SQL("sqlite:///students.db") rows = db.execute("SELECT first, middle, last, birth FROM students WHERE house=? ORDER BY last, first", house) for...
d0cc89c38785c2f4fc4b1485a55bffe9029a2bfe
alvinox/exercise
/python/multi.py
1,723
3.890625
4
from pprint import pprint #class base1(): # def __init__(self,value): # print('base1') # self.value = value # #class subbase1(base1): # def __init__(self,value1, value2): # print('subbase1', "value1=", value1, "value2=", value2) # value2 = 2 # super().__init__(value1,va...
0e61353150d02a0030005c48e091662c856ed081
Cybernetic1/python
/reinforcement_learning/Qlearn.py
5,828
3.859375
4
# -*- coding: utf-8 -*- ''' Notes from the book "AI - a modern approach" (3rd edition). Ch 21 talks about reinforcement learning. The aim of Q-learning is to learn Q values. Each Q value Q(S,A) is the utility of doing action A in state S. The update rule is: Q(S,A) += 𝞪 [ R(S) + 𝞬 max Q(S',A') - Q(S,A) ]. ...
466fc81a5a5c39c762c3637894cf05b0c4996c1c
Cybernetic1/python
/medical-terms/crawl-dic.py
1,569
3.515625
4
# crawl Wikipedia # 1. crawl Wikipedia purposefully, given English term # 2. locate said term in Wikipedia text or entry # 3. go to Chinese version of same page # 4. guess corresponding Chinese term based on textual location etc # 5. validate correspondence, by scoring, how? # 6. repeat actions # Scoring: # 1. if sam...
008760054bbb020ca44554c617f2ed162f525361
Cybernetic1/python
/fintech/genetic-programming.py
28,200
3.75
4
# -*- coding: utf8 -*- # This version focuses on next-day price prediction # Explanation: # Goal of learning is to learn 2 functions: # (1) the boolean condition C of whether to place a limit order or not # (2) the real function T of the target price of the limit order # C and T are dependent on 20 real-number variab...
0ffc3ed275446f333634b5d703b2aea90a2211bf
jfrichter4/Copy-of-Programming-Project
/Distance-function.py
269
4.28125
4
#Simon Phipps #2/26/21 #Distance Program x1 = float(input("Enter x1: ")) y1 = float(input("Enter y1: ")) x2 = float(input("Enter x2: ")) y2 = float(input("Enter y2: ")) #Input point values print("Your distance is",((y2-y1)**2+(x2-x1)**2))**.5 #This is the distance formula
4da265c9cdc6c3f7e5f7cf37cb8a3c25683572e7
TomSprules45/CS-coursework
/MachineClass.py
2,800
3.71875
4
class TuringMachine(): def __init__(self, tape_length, tape_values, head = 0, start = 0, final = 0, transition_rules = None): self.TapeData = {} self.head = head self.tape_length =...
9ad39ec3097f5985fb405e630df4edfec2d53faa
marthakhmil/python-tasks
/codewars-sum-count.py
462
3.84375
4
#count_positives_sum_negatives([1,2,3,4,5,6,-9,-6,-5]) def count_positives_sum_negatives(arr): my_list_pos=[] my_list_total=[] total=0 for i in arr: if i > 0: my_list_pos.append(i) a=len(my_list_pos) my_list_total.append(a) for i in arr: if i...
2cdc58214d3511d089e884ace9f09f3c0e8c5df2
marthakhmil/python-tasks
/classwork-3-(1-6).py
1,264
3.75
4
print('--------- task 1 ---------') my_list= [int(x) for x in input('enter 10 numbers:').split()] print(max(my_list)) print(min(my_list)) print('\n--------- task 2 ---------') interval=[x for x in range(1,10,1) if x%2==0] print(interval) interval_one=[x for x in range(1,10,1) if x%2==1 and x%3==0] print(interval_one) ...
d23b2f154e299b453eb76f3d947155a9fd0c1186
junjaytan/python-data-structures
/basic/concurrency/dining_philosophers.py
2,093
3.921875
4
import threading import random import time """ Dining philosophers: 5 philosophers with 5 forks. Philosopher must have 2 forks to eat. Deadlock is avoided by never waiting for a fork while holding a fork (locked). Procedure is to do block while waiting to get first fork, and a nonblocking acquire of second fork. If f...
ead8bda778050db83e12fb7753f30220f2cf2973
junjaytan/python-data-structures
/ICake/4_calendar.py
3,242
3.9375
4
# merge all overlapping intervals # assume values are all within the same day, and numbered in ascending order from 0 to 24 class Meeting(object): def __init__(self, starttime, endtime): self.starttime = starttime self.endtime = endtime def to_string(self): return "(%f, %f)" % (self.st...
b748594b682b6feecfeebd9e6848f3851aa344ab
junjaytan/python-data-structures
/basic/syntax/dict-examples.py
393
4.5625
5
# Dictionaries are basically hashes # initialize dictionary # ...directly mydict2 = {'john': 1, 'mary': 2} print mydict2 # ...via the dict() constructor, which takes sequences of key-value pairs mydict = dict([('john', 1), ('mary', 2)]) print mydict # loop through key-value pairs in dictionary print "looping throug...
5fff0d6154a98193733c44e9f5cf6f271257ce49
junjaytan/python-data-structures
/basic/syntax/lambda-examples.py
1,493
4.78125
5
# http://www.secnetix.de/olli/Python/lambda_functions.hawk """ One use of lambdas is to sort instances of a class by an attribute """ def lambdas_class_example(): class Meeting(object): def __init__(self, starttime, endtime): self.starttime = starttime self.endtime = endtime ...
d0e4b57c29cc1f7c56ac736945d59d87014dda79
keepmyfavor/yzu_python
/day06/LambdaDemo4.py
233
3.65625
4
# 利用 lambda 設計一個 bmi 函數式宣告 # 並"印出" 170, 60 的 "bmi" 值 h = 170 w = 60 bmiValue = lambda h, w : w / (h/100)**2 printBmiValue = lambda value : print("bmi = %.2f" % value) printBmiValue(bmiValue(h, w))
66ee52d95bb0a0f1809046c5113fe6b7fffc89e3
keepmyfavor/yzu_python
/day05/Set串列.py
285
3.65625
4
import random as r lotto = set() # 不重複元素的串列 lotto.add(10) lotto.add(10) lotto.add(20) print(len(lotto), lotto) # 今彩539電腦選號, 1~39取出任意5個不重複的號碼 lotto = set() while len(lotto) < 5: n = r.randint(1, 39) lotto.add(n) print(lotto)
542164b8b0a4c1aeb929dd192567500af1e50ede
Aryan220402/Python-Lab
/div.py
183
4.09375
4
n=int(input('Emter the Number')) for i in range(1,n+1): if i%5==0: if i%2==0: continue print('Numbers which are divisibe by 5 is :',i)
f1e1cf2bd0c57ad4b51075e808a997e28896a8a2
xsakurait/15fe
/15fepy.py
561
3.546875
4
~ジェネレータは何に使うか~ ジェネレータの一番の使い道はメモリ使用量を減らすことです 例 import sys a=[i for i in range(100000)] ジェネレータ使うとき def num(max): i=0 whike i<max yield i i++ for i in num(10): print(i) (配列でメモリ使用量多く使うのでジェネレータ使ったほうがいい) print(sys.getsizeof(a))#aのメモリ使用量(4000000) gen=num(100000) ...
8e5bf9037e7fd8114716a20e1533d81b25f0b785
satusky/ncdot-road-safety
/data_processing/extract_image_names.py
955
3.6875
4
# This script extracts image names from input data directory for mapping export image names to # real image names. # Command to run the script: python extract_image_names.py <input_data_dir> <output_image_name_file> # Command run example: python extract_image_names.py /projects/ncdot/2018/NC_2018_Images /projects/...
233d6b75629751ee6259d4e1296490a0fc5c0047
cristhoseby/CAS-Wales-2013
/1 - Variables/variable_error.py
72
3.765625
4
name = input("please enter your name: ") print("Hello {0}.format(Name))