blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
3e111383d987f4c5eeacb1eeb4e4c606d145d203
spencerwuwu/py-concolic
/traces/target/romanToInt.py
600
3.578125
4
#from symbolic.args import symbolic, concrete class TheClass: def __init__(self, value:str): self.value = value def __str__(self): return self.value def romanToInt(s:str) -> int: num = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000, 'E':0 } test_class = TheClass(s) fo...
ed806dfff84beebb01db23c679b98b688377f790
zuobing1995/tiantianguoyuan
/第一阶段/day08/exercise/sn2.py
323
3.625
4
# 2. 编写函数fun2,计算下列多项式的和 # Sn = 1/(1*2) + 1/(2*3) + 1/(3*4) + # ... + 1/(n*(n+1)) 的和 # print(fun2(3)) # 0.75 # print(fun2(1000)) def fun2(n): s = 0 for x in range(1, n + 1): s += 1 / (x * (x + 1)) return s print(fun2(3)) # 0.75 print(fun2(1000))
00ba685e9b4b8bdf76d0c3b699fa50650bc4100e
papasanimohansrinivas/c-language
/example2.py
247
3.984375
4
s=raw_input('enter a string ') def swapcase(s): s1=" " s2=" " for c in s: if(c<='z'and c>='a'): s1=s1+c print s1 elif(c<='Z'and c>='A'): s2=s2+c print s2 print s1,s2 return s1,s2 swapcase(s) #print s1,s2
3ab91f98a5b273dba943be505241515c3ec01cdd
rachelbates/coding-challenges
/leet/leet-add-two.py
439
3.75
4
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. # You may assume that each input would have exactly one solution, and you may not use the same element twice. # You can return the answer in any order. nums = [2,7,11,15] target = 9 class S...
5e49e2506247ceab8a5f0c890f995b83fc4e87c5
sysradium/hrank
/alphabet-rangoli.py
1,140
3.953125
4
""" Given a size N draw the rangoli alphabet N = 3 ----c---- 0 4 --c-b-c-- 1 2 4 6 c-b-a-b-c 2 0 2 4 6 8 --c-b-c-- 3 2 4 6 ----c---- 4 4 N = 5 --------e-------- ------e-d-e------ ----e-d-c-d-e---- --e-d-c-b-c-d-e-- e-d-c-b-a-b-c-d-e --e-d-c-b-c-d-e-- ----e-d-c-d-e---- ------e-d-e------ --------e----...
63f303325e485b03fc42bff136c23b6b484e618b
lt-scuolalavoro/python
/class_fix_me.py
375
3.78125
4
class phraseClass: phrase = "" def invert(self): return self.phrase[::-1] def wordCount(self): return len(self.phrase.split()) phrase1 = phraseClass() phrase1.phrase = "Hello World!" print(phrase1.invert()) print(phrase1.wordCount()) phrase2 = phraseClass() phrase2.phrase = "All good things come to an e...
dc2fb96e0487f30dea4fed78d090099aa6cadfaa
Galante97/CISC106-Projects
/November/program 2/intial/program2.py
2,337
4.125
4
#James Galante, Mike Malloy def delete(): print('Delete') def find_record(): print('Find Record') def insert_record(): print('Insert Record') def print_database(): print('Print Database') first_name = 0 last_name = 1 section = 2 grade = 3 list1 = [] list2 = [] def read_merge(): ''' This fun...
bb35ac55b0b5cda68a006e41c48777e452a90a2a
tomiam8/DRC-2019-team1
/test-code/polynomial-test.py
565
3.671875
4
import numpy as np import matplotlib.pyplot as plt coefficients = np.polynomial.polynomial.Polynomial.fit([1,2],[2,-3],1) coefficients = np.polyfit([1,2],[2,-3],1) print(coefficients) x_values = [] y_values = [] step = 10 lower = -1 upper = 3 for x in [p/step for p in range(lower*step, upper*step+1, 1)]: x_values....
335c8997788c32f56d77591f87b4babd7ba3bd35
blairDev/Python-Introduction
/chapter2/commenting.py
1,271
4.0625
4
#=============================================================== # # Name: David Blair # Date: 01/01/2018 # Course: CITC 1301 # Section: A70 # Description: This program outputs a simple hello message to # the console window. It also illustrates the use # of comments. All...
286ce33f86a6aacf9a4d16c746163542d70a77a9
Murillofilho86/PySparkRestAPI
/03_Infrastructure/Helpers/File.py
548
3.5625
4
import os class File: @property def fileName(self): return self._fileName @fileName.setter def fileName(self, value): self._fileName = value @property def file(self): return self._file @file.setter def file(self, value): self._file = value def __...
1a13585b2f51b226f1d86a5a21275da0029ffd34
github653224/GitProjects_PythonLearning
/PythonLearningFiles/小甲鱼Python基础课程笔记/python基础教程/05python的数据类型.py
488
3.84375
4
#整形、浮点型、布尔类型、e记法 # e记法 print(1.5e4) #1.5*10*10*10*10 #类型转换 a="520" print(a) b=int(a) print(b) print(int(5.99))#浮点型转换为整数型时,会把小数点后面的砍掉,不会四舍五入的 print(float(520)) print(str(5.99999999)) #获取类型的信息typeof print("\n") c="480" print(type(c)) print("\n") a="小甲鱼" b=100 print(isinstance(a,str)) print(isinstance(a,int)) print...
b85719f5d62dc7e84aaf56a97022447475d509ba
SsmallWinds/leetcode
/codes/7_revert_number.py
648
3.71875
4
''' 目描述:给定一个范围为 32 位 int 的整数,将其颠倒。 例1: 输入:132 输出:321 例2: 输入:-123 输出:-321 例3: 输入:120 输出:21 注意:假设我们的环境只能处理 32 位 int 范围内的整数。根据这个假设,如果颠倒后的结果超过这个范围,则返回 0。 ''' def calc(input:int)->int: positive=input > 0 input = input if positive else -input res = 0 while input != 0: res = input % 10 + res...
761acc1428d9e1296f072079497e1cb561872075
plgisele/python3-mundo1
/ex017.py
379
3.921875
4
# Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo, calcule e mostre o comprimento da hipotenusa. from math import hypot cat1 = float(input('Cateto oposto: ')) cat2 = float(input('Cateto adjacente: ')) hipo = hypot(cat1, cat2) print('A hipotenusa do triângulo c...
4ea84a868af2dd7b93091f33659034d0d4cab516
migueloyler/DailyCodingProblems
/kLengthApart.py
423
3.640625
4
'''Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False. ''' def kLengthApart(nums, k): i = 0 prev = -1 while i < len(nums): if nums[i] == 1: if prev != -1 and (i - (prev+1)) < k: ret...
6ed2c20e908b4fa98f7c524042bb8425db7a37ea
richbpark/Raspberry-Pi-Full-Stack-Revisited
/myDBquery.py
1,150
4.09375
4
####################################################### # myDBquery.py # # Rich Park February 09, 2019 # # A program to query the temperature and humidities # # from the RPiFSv2 Database # ########################################...
692f9c439c0c0c93b09036ab7555a588e76d5ea0
BeniyamL/alx-higher_level_programming
/0x04-python-more_data_structures/100-weight_average.py
399
4.40625
4
#!/usr/bin/python3 def weight_average(my_list=[]): """function that finds the weighted average of the list Arguments: my_list: the given list Returns: the weighted average """ if my_list is None or len(my_list) == 0: return 0 s = 0 weight = 0 for num in my_list:...
bda259c2b915baf5898e7a96d6e2b183ca094a5c
Zjianglin/Python_programming_demo
/chapter10/10-7.py
761
3.609375
4
""" 10–7. Exceptions. What is the difference between Python pseudocode snippets (a) and (b)? Answer in the context of statements A and B, which are part of both pieces of code. (Thanks to Guido for this teaser!) (a) try: statement_A except . . .: . . . else: statement_B (b) try: ...
9f745dc7c80df3916e67e2bdae87597dc543d802
16030IT028/Daily_coding_challenge
/Algoexpert-Solutions in Python/Group by Category/Strings/01_Palindrome_check.py
1,756
3.953125
4
"""Palindrome Check (Easy) ​ Write a function that takes in a non-empty string and that returns a boolean representing whether or not the string is a palindrome. A palindrome is defined as a string that is written the same forward and backward. ​ Sample input: "abcdcba" Sample output: True (it is a palindrome)""" # So...
fdbdaa54028d1878aa3d630a978d29a26e157b3c
jyeoniii/algorithm
/20201224/swap_nodes_in_pairs.py
423
3.515625
4
# https://leetcode.com/explore/challenge/card/december-leetcoding-challenge/572/week-4-december-22nd-december-28th/3579/ from common.common_data import ListNode class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head or not head.next: return head node_to_swap = head.next ...
14e2928254850eb748a3e745c665e7827c8f87c7
AdamZhouSE/pythonHomework
/Code/CodeRecords/2626/60774/315453.py
211
3.953125
4
s = input() if(s == '3,1,5,8'): print(167) elif(s == '1,4,8,0'): print(48) elif(s == '1,3,5,7'): print(140) elif(s == '5,4,3,2'): print(105) elif(s == '1,2,3,4'): print(40) else: print(s)
e75b77c1330e2a8cb24af754d550ac3679195c5f
nmessa/Python-2020
/Python Challenge/Starter Code/Problem20.py
259
3.546875
4
##Python Challenge Problem 20 ##Author: ##Date: def free_throws(percent, num): #Add code here #Test code print(free_throws("75%", 5)) print(free_throws("25%", 3)) print(free_throws("90%", 30)) ##Output ##24% ##2% ##4%
5e4bc144ed975463c9fe35cda9db677c7e4caf93
neurons4me/Time_Log
/task_logger/dates.py
1,012
3.5
4
from datetime import datetime, timedelta # Supplies a list of dates for the current week starting on Monday def latest_week_dates(formatted=False): today = datetime.today() monday = datetime.today() - timedelta(days=today.weekday()) tuesday = monday + timedelta(days=1) wednesday = monday + timedelta(...
d3b186b219e479151c923667ee8614c14f8abe44
msullivan/mypyc
/mypyc/ops.py
30,893
3.609375
4
"""Representation of low-level opcodes for compiler intermediate representation (IR). Opcodes operate on abstract registers in a register machine. Each register has a type and a name, specified in an environment. A register can hold various things: - local variables - intermediate values of expressions - condition fl...
d607bafcdce6086f5317b20b94e52b4ca4d4bea1
Nirmalselva/nirmal
/count the space.py
147
4.0625
4
a = input("Enter a string : ") count = 0 for c in a : if c.isspace() == True: count = count + 1 print("Total number of characters : ",count)
aeb31984dcb04eed49e26647893feebe036562df
nguiaSoren/Snake-game
/main.py
3,207
4.375
4
# # main.py # Snake game # # Created by OBOUNOU LEKOGO NGUIA Benaja Soren on 21/05/21. # Copyright © 2021 OBOUNOU LEKOGO NGUIA Benaja Soren. All rights reserved. # # We import the square root function from the math module because we need it to calculate # The distance between the snake head and the food from food...
83cea1a694b838fd833cdf67a776f10bf0ca2973
cherish6092/StanfordDeepNLP
/lecture1/pynp/numpy_array_broadcasting_reshape.py
178
3.5
4
#!python27 import numpy as np v = np.array([1,2,3]) w = np.array([4,5]) print np.reshape(v,(3,1)) * w x = np.array([[1,2,3],[4,5,6]]) print x+v print (x.T + w).T print x * 2
b5c965ecd9e55918a6aca782b4e289e2c4f172ff
mulongxinag/xuexi
/L3函数/9.递归.py
1,514
3.796875
4
#递归 recursion ##引题:计算机10的阶乘(1x2x3x4x5x6x7x8x9x10)(写出非递归解法或递归解法) #非递归写法 # total=1 # for i in range(1,11): # total=total*i # print(total) #换一种思路 #例如计算 5! #5!= (1*2*3*4)*5=4!*5 #4!=(1*2*3)*4=3!*4 #3!=(1*2)*3=2!*3 #2!=1!*2 #所以5!=(((1!*2)*3)*4)*5 #所以n!=(n-1)!*n n>=2 #结论:f(n)=f(n-1)*n n>=2 def factorial(n): ...
ccfabd4fcae07f48781843e02616aec62923ec50
fhca/python
/mas_funciones.py
998
4.09375
4
__author__ = 'fhca' def suma_hasta_v1(n): # esta linea se llama "encabezado" de la función """ Suma de los enteros 1, 2, 3,..., n. Versión recursiva. recursiva significa, que se llama a si misma en su cuerpo. """ # descripción de la función if n == 1: # caso para detenerse return 1 ...
a0a72010c130106c5d38c858ecd684b1f6be9a69
srinidhi-anand/Celebrity_database
/CelebrityScrape.py
2,477
3.578125
4
# Import Python Libraries for the url access and database import os import requests from bs4 import BeautifulSoup import sqlite3 from sqlite3 import DatabaseError import xlsxwriter def create_db_connection(db_filepath): # Function to Create a database connection to access the local file directory conn = None ...
0abd382ece73a9732f988cf13ec756d65005cf00
981377660LMT/algorithm-study
/6_tree/前缀树trie/1554. 只有一个不同字符的字符串.py
1,392
3.875
4
# !给定一个字符串列表 dict ,其中所有字符串的长度都`相同`。 # 当存在两个字符串在相同索引处只有一个字符不同时,返回 True ,否则返回 False 。 # dict 中的字符数小于或等于 10^5 。 # 你可以以 O(n*m) 的复杂度解决问题吗?其中 n 是列表 dict 的长度,m 是字符串的长度。 # 将单词插入前缀树之前判断是否可以满足只有一个字符不同的条件 from typing import List from Trie import Trie, TrieNode class Solution: def differByOne(self, dict: Li...
749d01fceb94be1504cfc393e09da60e895c3c73
youssefmamdouh/coursera_algorithms_course
/course1_toolbox/week3/dot_product.py
356
3.6875
4
#Uses python3 def max_dot_product(a, b): a = sorted(a, reverse=True) b = sorted(b, reverse=True) return sum([x*y for (x,y) in zip(a, b)]) if __name__ == '__main__': n = int(input()) a = [int(ai) for ai in input().split()] b = [int(bi) for bi in input().split()] assert len(a) == len(b) ==...
d5fabba9e4dcc7286dc35b44abecaef29c027aaf
huioo/byte_of_python
/main/base.py
4,852
4.5625
5
# 这里的文本,主要用作程序读者的注释 # 注释也可以使用 ''' 注释 ''' 或 """ 注释 """ """ 注释 """ ''' 注释 ''' # 例如:print是一个函数 print("help(len) 的结果信息:") # help方法,获取帮助信息 help('len') # print()函数参数:end表示结尾的字符,sep表示多个参数的中间连接字符 print('a', end='') print('b', end=', ') print('c', 'd', 'e', sep=' + ') print('*'*20) # 复制运算符(=)将常量5赋给变量i。称之为(陈述)语句,因为它陈述了需要完成的...
dea4f8dd32723d3cab3de803468d18810edbd2da
seismatica/guttag
/6.00.1x/OCW/2/ps2b.py
2,166
4.0625
4
def is_diophantine(x, a, b, c): """ Input: a non-negative integer Output: boolean on whether the integer is a diophantine """ diophantine_flag = False for k in range(x//c + 1): for j in range((x - k*c)//b + 1): remaining = x - k*c - j*b if remaining % a == 0: ...
012bce34f65c197a6604d809d4854f9176e1b223
stanman71/Python_Basics
/Machine Learning/Regression/Polynomiale Regression.py
1,916
3.75
4
""" Erweiterung der linearen Regression: y = a + bx + cx^2 """ ## ###################### ## Teil 0: Daten einlesen ## ###################### import pandas as pd df = pd.read_csv("./Python_Training/Machine Learning/Regression/CSV/fields.csv") ## ##################################### ## Modell 1: N...
093b6ffa0e3852a3720623d6b7154f03bdd08732
jisshub/python-django-training
/regex/Matching_with_start_and_plus.py
658
4.53125
5
import re pattern = re.compile('bat(wo)*man') match = pattern.search('batman') print(match.group()) # The * (called the star or asterisk) means “match zero or more”—the group # that precedes the star can occur any number of times in the text. It can be # completely absent or repeated over and over again. # Example-...
e49e44d64bacbdb171d09cd36903fa1e60a403c5
bhagyashrishitole/coding-challenges
/LeetCode31DaysChallenge/Week2/straight_line.py
1,786
4.09375
4
""" Problem Statement: Check If It Is a Straight Line You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Exa...
1fb38baea8d26a27ebc64c0f8b415738b7b0f2ed
mukeshbhoria/PythonClassData
/PythonClassData/Python_IMP/Link Codes/FileHandling/ExceptionDim.py
797
3.65625
4
def dimCheck(): try: print("st1") print("st1") #return 10 # '''(except only execute when try block have some error code)''' except TypeError : #( must be child of next excepts) print("st1") print("st1") return 21 except Exception : #( must be parent o...
69ee99dbc01c7b52a02b3756c4c24613e081d9c6
junbinding/algorithm-notes
/str.string-to-integer-atoi.py
1,787
3.515625
4
class Solution: """ 8. 字符串转换整数 (atoi) https://leetcode-cn.com/problems/string-to-integer-atoi 请你来实现一个 atoi 函数,使其能将字符串转换成整数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。接下来的转化规则如下: 如果第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字字符组合起来,形成一个有符号整数。 假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成一个整数。 该字符串在有效的整数部分之后也可...
61f5dec30eb20338d189e8568bb1aa764ea4cb77
dbgsprw/python-competitive-programming
/solutions/min_max_division.py
904
3.546875
4
def binary_search(start, end, array, value): mid = (start + end) // 2 if start == end: if mid >= len(array) or value == array[mid]: return start else: return start - 1 if value <= array[mid]: return binary_search(start, mid, array, value) else: re...
51ac158f55c15c1b158c543b1f8cfad527051570
DolglasMesquita/teste1
/desafio.py
1,227
3.515625
4
import csv with open("tabela.csv", 'w', newline='') as arquivo: escrever = csv.writer(arquivo) escrever.writerow(["id", "nome", "salario"]) escrever.writerow(["1", "fulano", "1000.00"]) escrever.writerow(["2", "beltrano", "2000.00"]) escrever.writerow(["3", "andre", "1500.00"]) escrever.write...
ff6fbd4f9cb152462121b57ed3bf6e3ffce386f6
wangzexin/ProblemEuler
/10001st prime.py
283
3.625
4
# Initialization primes = [2, 3] k = 4 # Calc the first 10001 prime numbers while len(primes) < 10001: f = True for prime in primes: if k % prime == 0: f = False break if f: primes.append(k) k += 1 # Output print(primes[-1])
aae3d7a73fdec85a6780c2a345a94f47097f13d0
srikanthpragada/python_18_jan_2021
/demo/assignments/06-FEB/even_first_odd_next.py
139
3.75
4
def odd_even(n): return 0 if n % 2 == 0 else 1 nums = [10, 29, 20, 40, 55, 33, 50] for n in sorted(nums, key=odd_even): print(n)
7340d0e3a03c4cb5e30921a5b2d4a2ed236c07ad
nazariinyzhnyk/sorting-algs
/sorters/insertion_sort.py
442
3.796875
4
from utils import register_sorter @register_sorter def insertion_sort(lst): for i in range(1, len(lst)): key = lst[i] j = i - 1 while j >= 0 and lst[j] > key: lst[j + 1] = lst[j] j -= 1 lst[j + 1] = key return lst if __name__ == '__main__': from ut...
08719a54c0227963b51f17d519b3bed4e17304bf
contactshadab/data-structure-algo-python
/data_structure/binary_tree/siblings_in_binary_tree.py
1,415
4.09375
4
from binary_search_tree_implementation import BinaryTree class MyBinaryTree(BinaryTree): def are_siblings(self, first, second): if self.root is None: raise Exception('Empty tree') if None in [first, second]: raise Exception('Illegal arguments') return self.__are_s...
aa63696b8ab13f9028fba208e632e921699d0f7e
andrewmeng810/python_algorithm
/fibonacci.py
340
4.125
4
def fibonacci(n): """ return a list of fibonacci sequence """ fib_list = [0,1] if n == 0: return [] elif n == 1: return [0] else: x = 2 a, b = fib_list[0],fib_list[1] while x < n: a, b = b , a + b fib_list.append(b) x += 1 ...
3fc750619f4c500e1f354d060302cd12481c2038
semydava/python-hw
/is_palindrome.py
84
3.65625
4
def is_palindrome(string): string = str(string) return string[::-1]== string
7d894b25c1abe93fc6bd6bf1070a58beb914ad35
yhtsai0916/Python200803
/Day1-5.py
396
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 3 14:26:51 2020 @author: USER """ x=input("請輸入成績:") x=int(x) if x>=0: print("你的等級是:") if x>100: print("!輸入錯誤!") elif x>=90: print("A") elif x>=80: print("B") elif x>=70: print("C") elif x>=60: ...
415f249b906aab416914916e212c53be2c0f60fa
alukinykh/python
/lesson5/3.py
803
3.875
4
# 3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. # Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. # Выполнить подсчет средней величины дохода сотрудников. with open('task_3.txt') as f_obj: employees = f_obj.readl...
20aed6b2c3088c4eeabbb620795ba3f45b426e60
Subaru3000/my_python
/dict_cinema_price.py
1,113
3.625
4
"Фильм «Паразиты», " "сеансы: 12 часов – 250 руб, 16 – 350 руб, 20 – 450 руб." "Фильм «1917»," "сеансы: 10 часов – 250 руб, 13 – 350 руб, 16 – 350 руб." "Фильм «Соник в кино», " "сеансы: 10 часов – 350 руб, 14 – 450 руб, 18 – 450 руб. " cinema = dict() cinema = {'Паразиты': {'сегодня': {12: 250, 16: 350, 20: 450}, 'з...
19dd2d1fce5d506ee4adb422ed78d5be51e3afaa
jsdiuf/leetcode
/src/Reverse String.py
642
4.28125
4
""" @version: python3.5 @author: jsdiuf @contact: weichun713@foxmail.com @time: 2018-9-4 17:28 Write a function that takes a string as input and returns the string reversed. Example 1: Input: "hello" Output: "olleh" Example 2: Input: "A man, a plan, a canal: Panama" Output: "amanaP :lanac a ,nalp a ,nam A" """ cla...
9822c6b25c80e8cdc24aaca1bd23b485978c448b
bb04265/PythonStudy
/BaekjoonSolving/for/8393.py
83
3.796875
4
num = int(input()) total = 0 for i in range(1, num+1): total += i print(total)
1de642152b89acfe2fbfd498a63985076856089e
viniTWL/Python-Projects
/funçoes/ex103.py
316
3.53125
4
def ficha(j, g): if not j: j = '<desconhecido>' if not g: g = 0 print(f'O jogador {j} fez {g} gols no total.') #Programa j = str(input('Qual o nome do seu jogador?')).strip() g = str(input(f'Quantos gols {j} fez?')).strip() if g.isnumeric(): g = int(g) else: g = 0 (ficha(j, g))
e6a83f2621681872cd86a0ab713fbb17c27ed1b0
Theskill19/sweetpotato
/les1.6.py
1,049
4.4375
4
#6. Спортсмен занимается ежедневными пробежками. # В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. # Программа должна принимать з...
eeb2a1f2e049286d1b8124dc4d5690cf40408b6a
hiratekatayama/math_puzzle
/leet/Reverse_String.py
339
3.8125
4
class Solution: def reverse_String(self, s): left, right = 0, len(s)-1 while left < right: s[left], s[right] = s[right], s[left] left = left + 1 right = right - 1 return s if __name__ == '__main__': test = Solution() lst_reverse = ["h","e", "l", "l" ,"o"] print(test.reverse_St...
0db13b1dbf0003a08f5b167544492f7aae48ab9b
helaahma/python
/conditions_task.py
807
4.1875
4
#Define 2 variables and one operator var1= input("Please enter 1st integer: \n") var2= input("Please enter 2nd integer: \n") oper=input("Please enter an operator (+,-,*,/): \n") #Conditions if (var1.isdigit()==True and var2.isdigit() == True) and oper== "+": print ("the result of %s %s %s=" %(var1,oper,var2), int(va...
df998b88731d7bd6021b2782d7ba0923cd1e74d5
yashgupta777/AllDataScienceProjects
/keepitup/pythonBasics/checkIfStringIsAValidKeyword.py
3,324
4.5
4
# Python code to demonstrate working of iskeyword() # In programming, a keyword is a "reserved word" by the language which convey a special meaning to the interpreter. # It may be a command or a parameter. Keywords cannot be used as a variable name in the program snippet. # Keywords in Python: Python language also ...
c0e261fc546da6261b884c46f0ccc4d709dac54a
953250587/leetcode-python
/TotalHammingDistance_MID_477.py
1,616
4.125
4
""" The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Now your job is to find the total Hamming distance between all pairs of the given numbers. Example: Input: 4, 14, 2 Output: 6 Explanation: In binary representation, the 4 is 0100, 14 is 1110, and...
37f3095f02e9c7b2539785f2c559a3eb7c612480
eroicaleo/LearningPython
/interview/leet/457_Circular_Array_Loop.py
1,179
3.578125
4
#!/usr/bin/env python3 class Solution: def circularArrayLoop(self, nums): l = len(nums) for i in range(l): print(f'i = {i}') head = slow = fast = i while True: slow = (slow+nums[slow])%l fast1 = (fast+nums[fast])%l ...
24bfddf06f7e90a9cb4f6617bb540cf20a76ea78
EldadZZipori/WoG-Devops_course_project
/GuessGame.py
914
3.84375
4
import Utils from random import randint # this module contains the function needed to run the Guess Game # generates a number between 1 and the games difficulty def generate_number(difficulty: int) -> int: return randint(1,difficulty) # asks the user for a guess between 1 to difficulty, returns the users gues...
ba5d8361fd1873acda1456f546ea2dd8583cf354
SmallConcern/python_leetcode
/25_reverse_nodes_in_k_group/reverse_nodes_in_k_group.py
909
3.953125
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def append(self, val): self.next = ListNode(val) def reverse_linked_list_in_k_group(head): pass class TestReverseNodesInKGroup(object): def string_to_linked_list(s...
f577efa63fa683f8a08703307a1e1090ee4a41bf
JeromeLefebvre/ProjectEuler
/Python/Problem197.py
737
3.921875
4
#!/usr/local/bin/python3.3 ''' http://projecteuler.net/problem=197() Investigating the behaviour of a recursively defined sequence Problem 197 Given is the function f(x) = ⌊230.403243784-x2⌋ × 10-9 ( ⌊ ⌋ is the floor-function), the sequence un is defined by u0 = -1 and un+1 = f(un). Find un + un+1 for n = 1012. Give ...
b7160f91633bc75bc9cdca7d5aebb8d894163cad
svnaumov1985/Python_alg_2
/less3_task1.py
377
3.53125
4
# В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9. dict = {i:0 for i in range(2,10)} for i in range(2, 100): for a in range(2, 10): dict[a] += 1 if i % a == 0 else 0 for a in dict: print(a, " - ", dict[a])
6b036d8879f329ee40aeace04a15863212f13763
vvaldes/ejemplo1
/baseDatosMysql.py
7,326
3.53125
4
#base datos #http://docs.peewee-orm.com/en/latest/peewee/installation.html #pip install peewee # o bien git clone https://github.com/coleifer/peewee.git # cd peewee # python setup.py install #python runtests.py #sudo pip3 install PyMySQL import pymysql import pymysql.cursors con = pymysql.connect('192.168.0.7', 'victo...
778a7d64d7426203ada920095c5c26122ae5fc7f
bpraggastis/Mac_Battleship
/battleship.py
21,765
4
4
###################################################### # # Battleship Game # started 8/3/14 # working version completed 8/13/14 # # ###################################################### import math import random import sys ######## Constants ############################## Ship = {'A' : ["...
6701472df3653b2b954c63a962a67ac1c99e9e12
shilpavijay/Algorithms-Problems-Techniques
/Python/dictFromList.py
305
3.6875
4
l = [1,2,3,3,5,1,2,3,4] d = {} for each in set(l): d.update({each:l.count(each)}) # OR # {d.update({each:l.count(each)}) for each in set(l)} print(d) OR from collections import Counter c=Counter(l) print(c) #DICT FROM TWO LISTS a=['a','b','c'] b=[1,2,3] lstDict = dict(zip(a,b)) print(lstDict)
4ff16ef8b0ccfe65512eabfdaf6f6e8180e8b587
PNeekeetah/Leetcode_Problems
/Same_Tree.py
1,681
3.953125
4
""" First time submission succesful. It beats 62% in terms of runtime and 0% in terms of memory. Admittedly, I was supposed to do this using an iterative version of inorder, postorder or preorder. I did it with a BFS. It took me about 1 hour to ditch trying to compare and write the iterative tree traversal. It t...
c2124b0dc7f0495e4eded0e261fc496d0edddb70
Siahnide/All_Projects
/Back-End Projects/Python/Python_OOP/hospital/hospital.py
595
3.609375
4
class hospital (object): def __init__(self,name,capacity,*patients): self.patients = list(patients) self.name = name self.capacity = capacity - len(self.patients) def info(self): print self.name names = "" for x in range(0,len(self.patients)): names +...
4ad0ec821a198bec6db30932374cd48592001009
hoang-ng/LeetCode
/Greedy/135.py
1,308
3.84375
4
# 135. Candy # There are N children standing in a line. Each child is assigned a rating value. # You are giving candies to these children subjected to the following requirements: # - Each child must have at least one candy. # - Children with a higher rating get more candies than their neighbors. # What is the minimum...
196b097cdad5b1fb306fdb05832d7bbee1573516
JackMGrundy/coding-challenges
/common-problems-leetcode/hard/basic-calculator-III.py
2,377
3.859375
4
""" Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . The expression string contains only non-negative integers, +, -, *, / ...
bf6033be9647c3599b3ff07160f5c4d2f704da06
rompe/adventofcode2020
/src/day16.py
3,430
3.625
4
#!/usr/bin/env python import collections import itertools import math import sys cache = dict(timestamp=0) def parse_input(input_file): """Parse input file and return rules, my ticket, nearby tickets.""" lines = open(input_file).read().split('\n\n') rules = {} for line in lines[0].splitlines(): ...
6c2e47052f4302fb4fd741608ed8bfb653491858
ZbigniewPowierza/pythonalx
/Kolekcje/zadanie_9.py
2,464
3.78125
4
""" OFERUJEMY NASTĘPUJĄCE PRODUKTY marchew: 2,35, ziemniaki: 2,20, cebula: 1,8, ogórki: 4,0 co chcesz kupić? marchew ile chcesz kupic [marchew]? 3 Za [marchew] płcisz 7,05 pPLN DODAJEMY obsluge magazynu po zakupie ilosc towaru sie zmniejsza jezeli ktos chce kupic wiecej niz w magazynie to mowie ze nie moze """ def ...
eed03c633e966eba5ecaed3708c6b975e28631fc
emmanuelbarturen/aprendiendo-python
/main.py
5,904
3.90625
4
import sys import copy print('Aprendiendo Python3') clients = 'ronny,renzo,paul' print(id(clients)) # puntero de memoria print('Valor de variable: ' + clients) print('*' * 25 + ' FUNCIONES ' + '*' * 25) def separator(title='', character='*'): """Esto es un texto de ayuda de como utilizar esta funcion. puede se...
9cb120b8d8376536a7a37502588eea468c0b98d4
castellanprime/ProgrammingChallenges
/minesweeper_challenge/minesweeper.py
3,460
3.90625
4
#!/usr/bin/env python """ ACM Minesweeper PC/UVa IDs: 110102/10189 """ def minesweeper(path_to_file): """ Play the minesweeper game Args: path_to_file:file path Returns: Nothing Raises: IOError: if it cannot open file """ gameboard = [] a...
c5f411fb61cb8e8c329af0c2f62d15b2be4bee69
UzaifAhmed/python-
/textutility.py
259
3.765625
4
def charCount(paragraph): """this func accepts a texting and returns an integr count of num of char in it""" char_count = len(paragraph) return char_count def word_count(paragraph): word_count = len(paragraph.split(" ")) return word_count
7c739be259cf7af3d84ea73aa577539d80a4553a
rampedro/Cracking-the-coding-interview-leetcode
/paint-fill.py
966
4.0625
4
def paint(A,i,j,color=3,p=None): if i<0 or i>len(A) or j<0 or j>len(A[0]): print("***") return A else: A[i][j] = 3 if A[i-1][j] == p: paint(A,i-1,j,color=3,p=p) if i+1 < len(A) and A[i+1][j] == p: paint(A,i+1,j,color=3,p=p) if A[i][j-1]...
3661a819a5a69541700fc59a55a38e06e7266876
CaduSantana/Data-Visualization-study
/Estudo matplotlib/Population growth/Brazil_population_growth.py
610
3.5
4
# Growth of Brazil's Population # Source: DataSus import matplotlib.pyplot as plt data = open("populacao_brasileira.csv").readlines() x = [] # Population qtd array y = [] # Year number array for i in range(len(data)): if i != 0: linha = data[i].split(";") x.append(int(linha[0])) y.append(...
3f09425de5769280530daafb32c77edf6a2f5f67
priscilamarques/pythonmundo1
/desafio6.py
267
4.03125
4
##Desafio 6 #Crie um algoritmo que leia um número que mostre seu dobro, trilo e raiz quadradra. n = int(input('Digite um número: ')) d = n * 2 t = n * 3 e = n ** (1/2) print('O número é {}. O dobro é {}, o triplo é {} e a raiz quadrada é {}.'.format(n,d,t,e))
40c7b4940ae9bca1260ff0ad47239e40b47ea0ba
VenkateshBisoyi/DSP-Lab-2
/perfect number.py
353
3.828125
4
#This is the program for Perfect number print ('''Venkatesh Bisoy 121910313056''') a = int(input("Enter the number: ")) # the factors of the number are found s= 0 for i in range(1,a): if (a % i==0): s = s + i # the Logic for perfect number if(a==s): print(a,'is a perfect number') else: ...
857f68baac8ad732a615d8b05aa074d81950f564
zhangchizju2012/LeetCode
/300.py
1,086
3.703125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat May 6 12:11:24 2017 @author: zhangchi """ #============================================================================== # example: # nums: [1, 3, 6, 7, 9, 4, 10, 5, 6] # result: [6, 5, 4, 3, 2, 3, 1, 2, 1] # result的每i项代表nums从第i个开始往后,含有nums[i]这个元素的Lo...
8230906264f21b36b0256cdb09938d1837e42de9
xiyiwang/leetcode-challenge-solutions
/2021-02/2021-02-16-letterCasePermutation.py
1,440
3.65625
4
# LeetCode Challenge: Letter Case Permutation (02/16/2021) # Given a string S, we can transform every letter individually # to be lowercase or uppercase to create another string. # # Constraints: # * S will be a string with length between 1 and 12. # * S will consist only of letters or digits. # Solution...
75158accae5dc815e1012f4c40286452b2268d46
abhijeetbhagat/dsa-python
/DSA/binary_search.py
576
3.859375
4
def binary_search_recursive(a : list, key : int, l : int, h : int): if l > h: return -1 m = (l + h) // 2 if a[m] == key: return m if a[m] > key: h = m - 1 else: l = m + 1 return binary_search_recursive(a, key, l, h) def binary_search(a, key): return binary_se...
993ddad7b3b9b282bfab82229801df2afe263bb6
TenzinJam/pythonPractice
/freeCodeCamp1/variables.py
598
4.34375
4
character_name = "John" character_age = "35" print("There once was a man named "+ character_name + ", ") print("he was " + character_age + " years old.") print("he really liked the name "+ character_name + ", ") print("but didnt like being "+ character_name + ".") print("Fullstack\nAcademy") print(character_name.lower...
7b2373b96d9a34f8c0009e19ef8e836a5cd1611a
Jashwanth-k/Data-Structures-and-Algorithms
/4.Linked Lists/Reverse the LL by using Tail T.C O[n] .py
1,148
3.71875
4
class Node: def __init__(self, data): self.data = data self.next = None def printLL(head): while head is not None: print(str(head.data) + '->', end='') head = head.next print('None') return def takeInput(): inputList = [int(ele) for ele in input().split...
a020246b2ca273f73bcffe86e0b196ad6ad6a5e2
flpsantos3/FProg-Project
/writeFiles.py
4,560
3.59375
4
# 2019-2020 Fundamentos de Programação # Grupo 20 # 55142 Filipe Santos # 28115 Lara Nunes import times import readFiles def writeHeaderD(fileName): """Uses the header info from a file of drones to write a new file, updating time and date (if needed) Requires: fileName is str, the name of a .txt...
b5490db37d86c866f2ed0102dee69bf890e225c8
itaouil/Daily-Coding-Problem
/6_is_happy.py
1,224
4.125
4
""" Write an algorithm to determine if a number n is "happy". Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which thi...
1bff13e307b98ee7e39b59101cca172fd48f3ad3
sguberman/pyku
/query.py
1,379
3.578125
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 25 15:29:20 2017 @author: Seth Guberman - sguberman@gmail.com """ from collections import defaultdict from parse import mhyph_dict_from_file, mpos_dict_from_file def words_by_syllable(): """ Build an index of all words with n syllables. """ print('Build...
5ac50982dd50b142c7c8b07c20482073b9733115
MATATAxD/untitled1
/8.14/递归函数.py
1,199
3.9375
4
# 递归函数的思想:把规模大的问题拆分成规模小的问题,然后把规模小的问题再拆分成规模更小的问题...一层层的拆分拆分到一定的程度 # 变成很小的问题,最后问题就解决了 import sys # count=0 # def f(count): # count+=1 # print(count) # # if count==10: # return count # # # f(count) # f(count) # return n + f(n-1) # # 1-100的和 #f(100) return 100+ f(9...
0c604dc4576c389c6e1423e30dd8afd7a22440e2
green-fox-academy/bauerjudit
/week-3/tuesday/list.py
927
3.734375
4
class Elem(object): _slots_ = ["value", "next"] def _repr_(self): return "({}, {})".format(self.value, self.next) def new_elem(value): elem = Elem() elem.value = value elem.next = None return elem def append(head, value): end = head while end.next is not None: end = en...
096de9431086031fefe85924814b2d0f8aafb865
Headmx/z59
/mytimer.py
517
3.859375
4
import datetime import time class Mydatetime: def __init__(self,s, h = None, m = None, ): self.h = h self.m = m self.s = s def timer(self): if 1<= self.m <60: self.s = self.s + self.m*60 elif 1<= self.h : self.s = self.s + self.h * 3600 f...
eb4104f22cc658efc7273e05ac451ee3959c7ed6
Giammi77/f3kcompetizioneDeploy
/packages/f3kp/lib/f3krules.py
12,625
3.515625
4
class task_base_one_validation: def __init__(self): self.maximum_flights=0 self.maximum_flight_time=0 def validate_flight(self,time,flyed=None): if time <= self.maximum_flight_time: return time else : return self.maximum_flight_time class A(task_base_on...
a7d1043fedfc101f7b7e00275c277935d601e56f
timvan/reddit-daily-programming-challenges
/route_planner.py
1,812
3.65625
4
# Google Maps Route Planner # Project 4 Python # 01-11-2015 import urllib import webbrowser place = () def place_request(): global route route = [] cont = True count = 0 print "Enter route" print "Press enter on black entry to route" while cont == True: if count ==0: place = raw_input("Starting Loc...
71d2c279fef11aad5b0bd5ddce70be5a8523665f
onlysingle007/labs
/Lab_5/4.py
238
4.0625
4
x = input("Enter a string.") count=0 for i in range(0,int(len(x)/2)): if(x[i]==x[len(x)-i-1]): count=count+1 if(count==int(len(x)/2)): print("String is a palindrome.") else: print("String is not a palindrome.")
2c52f8e1653a11cc93d37a144656cd7f5d8804f0
bus1029/HackerRank
/Interview Preparation Kit/Array/MinimumSwaps2.py
2,013
3.515625
4
#!/bin/python3 import math import os import random import re import sys # Complete the minimumSwaps function below. def minimumSwaps(arr): # Input Format:: # The first line contains an integer n, the size of arr. # The second line contains n space-separated integers arr[i]. # Constraints # 1 <= n...
da0c6825ea583680e399ca0affa5f55ea5dc9bf9
arjundha/COMP1510-Hackathon
/covid19_stats.py
1,769
3.59375
4
""" Handles retrieval of covid-19 statistics """ import requests import json import doctest def get(api_link: str) -> dict: """ Get response from api :param api_link: a valid api request link :preconditon: api_link must be a string :postcondition: return the response as a json dictionary :ret...
85aee223bbe358b44453fef2ca7b1e08ecdbc9fe
pranjay01/leetcode_python
/RecoverBinarySearchTree.py
2,077
3.671875
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def getTree(inputValues): #inputValues = [1,2,3] root = TreeNode(int(inputValues[0])) nodeQueue = [root] front = 0 index = 1 while index < len(inputVa...
109805fe8be49eaae5c73a56914ee82d983c6456
mammuth/Project-Euler-Solutions
/solutions/Problem056.py
270
3.65625
4
#!/usr/bin/python3 # Created by Max Muth on 05. December 2014 # kontakt@maxi-muth.de maxSum = 0 for a in range(2, 100): for b in range(2, 100): digitSum = sum(int(digit) for digit in str(a ** b)) if digitSum > maxSum: maxSum = digitSum print(maxSum)
3bd92f04eb1179c92fbbc4be89028aad9b8ba7e0
shawnwnha/PythonProjects
/Python OOP(day2)/day(2)/OOP(practice).py
253
3.609375
4
class monster(object): def __init__(self, name, height, weight): self.name = name self.height = height self.weight = weight self.intelligence = 0 class juka(monster): def __init__(self): super(juka,self).__init__() self.intelligence =10
133f82ef1da063822841a9cecbc0c1b7ed671048
Bushmangreen/my_world
/Season_2/Exercises/longest_increasing_subsequence.py
741
3.78125
4
def longest_increasing_subsequence(array): l = 0 r = 0 index = 0 my_max = 0 #find max min_value = min(array) min_index = array[array.index(min_value)] my_list = [] for runner in range(min_index, len(array)): my_list = [] my_list.append(min_value) for index in...
3bc7843fea00cf57fc58f223ca797f5dcb964ede
johnstantine/Python-Projects
/Percentage Calculator/Percentage Calculator.py
656
3.8125
4
print("How many documents did we get today? ") doc1 = int(input("EOB documents: ")) doc2 = int(input("EOBL documents: ")) doc3 = int(input("ERA documents: ")) total_docs = doc1 + doc2 + doc3 print(f'In total, we received {total_docs} documents.') print("What was the percentage of each? ") eob_docs = float(doc1/tota...
6791259c3dca001cc4a415119fa626f24fafe4be
helen5haha/pylee
/game/NQueens.py
1,437
3.90625
4
# The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. ''' Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where'Q' and '.' both indicate a queen ...