blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3865e404fdf198c9b8a6cb674783aa58af2c8539 | rehul29/QuestionOfTheDay | /Question8.py | 561 | 4.125 | 4 | # minimum number of steps to move in a 2D grid.
class Grid:
def __init__(self, arr):
self.arr = arr
def find_minimum_steps(self):
res = 0
for i in range(0, len(self.arr)-1):
res = res + self.min_of_two(self.arr[i], self.arr[i+1])
print("Min Steps: {}".format(res))
... | true |
b24b8cb5a6a7200c99bc112b9d5812eb9726bc60 | ywtail/leetcode | /35_58.py | 616 | 4.125 | 4 | # coding:utf-8
# Length of Last WordLength of Last Word 最后一个词的长度
s=raw_input()
def lengthOfLastWord(s):
"""
:type s: str
:rtype: int
"""
t=s.split()
if len(t)==0:
return 0
else:
return len(t[-1])
print lengthOfLastWord(s)
"""
题目:
给定一个字符串s由大写/小写字母和空格字符''组成,返回字符串中最后一个字的长度。
如果最后一个字不存在,返回0。
注意:单词定义为仅由非空格字符组成... | false |
5b13b24acbbc286305aa9cda7adc9afd7709104f | sjNT/checkio | /Elementary/Fizz Buzz.py | 1,288 | 4.15625 | 4 | """
"Fizz buzz" это игра со словами, с помощью которой мы будем учить наших роботов делению. Давайте обучим компьютер.
Вы должны написать функцию, которая принимает положительное целое число и возвращает:
"Fizz Buzz", если число делится на 3 и 5;
"Fizz", если число делится на 3;
"Buzz", если число делится на 5;
"""
... | false |
1e30e88c79c0941f93ce4239a74eb38d4dcd02f5 | dtekluva/first_repo | /datastructures/ato_text.py | 1,616 | 4.125 | 4 | # sentence = input("Please enter your sentence \nWith dashes denoting blank points :\n ")
# replacements = input("Please enter your replacements in order\nseperated by commas :\n ")
# ## SPLIT SENTENCE INTO WORDS
# sentence_words = sentence.split(" ")
# print(sentence_words)
# ## GET CORRESPONDING REPLACEMENTS
# rep... | true |
b9a6f5dfa9f184d24f941addd3aa219dcc16a1bd | harrylb/anagram | /anagram_runner.py | 2,436 | 4.3125 | 4 | #!/usr/bin/env python3
"""
anagram_runner.py
This program uses a module "anagram.py" with a boolean function
areAnagrams(word1, word2)
and times how long it takes that function to correctly identify
two words as anagrams.
A series of tests with increasingly long anagrams are performed,
with the word length and ... | true |
7008f73c39d0cffbb93e317e2e4371b16e4a1152 | ozgecangumusbas/I2DL-exercises | /exercise_01/exercise_code/networks/dummy.py | 2,265 | 4.21875 | 4 | """Network base class"""
import os
import pickle
from abc import ABC, abstractmethod
"""In Pytorch you would usually define the `forward` function which performs all the interesting computations"""
class Network(ABC):
"""
Abstract Dataset Base Class
All subclasses must define forward() method
"""
... | true |
a477f9345fcd496943a6543eba007b5a883bc1d0 | Ayaz-75/Prime-checker-program | /pime_checker.py | 267 | 4.125 | 4 | # welcome to the prime number checker
def prime_checker(number):
for i in range(2, number):
if number % i == 0:
return "not prime"
else:
return "prime"
num = int(input("Enter number: "))
print(prime_checker(number=num))
| true |
52230fa21f292174d6bca6c86ebcc35cc860cb69 | kisyular/StringDecompression | /proj04.py | 2,900 | 4.625 | 5 | #############################################
#Algorithm
#initiate the variable "decompressed_string" to an empty string
#initiate a while True Loop
#prompt the user to enter a string tocompress
#Quit the program if the user enters an empty string
#Initiate a while loop if user enters string
#find the first bracket and... | true |
e3e8af1efd0adbca06cba83b769bc93d10c13d69 | jalalk97/math | /vec.py | 1,262 | 4.125 | 4 | from copy import deepcopy
from fractions import Fraction
from utils import to_fraction
class Vector(list):
def __init__(self, arg=None):
"""
Creates a new Vector from the argument
Usage:
>> Vector(), Vector(None) Vector([]) creates empty vector
>> Vector([5, 6, 6.7, Fracti... | true |
a84f6776548484ef96ab81e0107bdd36385e416e | DasVisual/projects | /temperatureCheck/tempCheck2.py | 338 | 4.125 | 4 | #! python 3
# another version of temperature checker, hopefully no none result
print('What is the current temperature of the chicken?')
def checkTemp(Temp):
if Temp > 260:
return 'It is probably cooked'
elif Temp < 260:
return 'More heat more time'
Temp = int(input())
Result = checkTemp(Tem... | true |
2d8d833c7ef4ea7411848251e673088c3ea18c88 | GauravKTri/-All-Python-programs | /calculator.py | 334 | 4.28125 | 4 | num1=float(input("Enter the first number"))
num2=float(input("Enter the second number"))
num3=input("input your operation")
if num3=='+':
print(num1+num2)
if num3=='+':
print(num1+num2)
if num3=='-':
print(num1-num2)
if num3=='/':
print(num1/num2)
if num3=='*':
print(num1*num2)
if num3=='%':
pri... | false |
cd3b288dc03da30a69439727191cb18e429d943a | olympiawoj/Algorithms | /stock_prices/stock_prices.py | 1,934 | 4.3125 | 4 | #!/usr/bin/python
"""
1) Understand -
Functions
- find_max_profit should receive a list of stock prices as an input, return the max profit that can be made from a single buy and sell. You must buy first before selling, no shorting
- prices is an array of integers which represent stock prices and we need to find the ... | true |
0affe2658592fab3415002287c348ef24ae372bb | Swaraajain/learnPython | /learn.python.loops/calc.py | 384 | 4.1875 | 4 | a= int(input("provide first number : "))
b= int(input("provide second number : "))
sign= input("the operation : ")
def calc(a,b):
if sign == '+':
c= a+b
elif sign== '-':
c= a-b
elif sign=='*':
c= a*b
elif sign=='/':
c= a/b
else:
print("This option is not ... | false |
17209e6ac514e763706e801ef0fb80a88ffb56b7 | Swaraajain/learnPython | /learn.python.loops/stringQuestions.py | 457 | 4.1875 | 4 | # we have string - result must be the first and the last 2 character of the string
name = "My Name is Sahil Nagpal and I love Programming"
first2index = name[:2]
last2index = name[len(name)-2:len(name)]
print(first2index + last2index)
#print(last2index)
#string.replace(old, new, count)
print(name.replace('e','r',2))... | true |
8d895964bd49c9b70d02da96c01d1fa5e935caa3 | Swaraajain/learnPython | /learn.python.loops/lisOperations.py | 729 | 4.125 | 4 | # list1, list2 = [123, 'xyz'], [456, 'abc', 'ade', 'rwd', 'ghhg']
#
# print(list1[1])
# print(list2[2:4])
# list2[2]=123
# print(list2)
# #del list2[2]
# print(list2)
# print(len(list2))
# print(list1+list2)
# print(456 in list2)
# for x in list2:
# print(x)
# def cmp(a,b):
# return (a > b) - (a < b)
#
# list1 ... | false |
fbc2b174ff0abcb78531105634d19c6ec9022184 | 40309/Files | /R&R/Task 5.py | 557 | 4.28125 | 4 | checker = False
while checker == False:
try:
user_input = int(input("Please enter a number between 1-100: "))
except ValueError:
print("The value entered was not a number")
if user_input < 1:
print("The number you entered is too low, Try again")
elif user_input > 100:
... | true |
aad05d66c26fa07d7b9ea7b59ca719af4f456248 | Marinagansi/PythonLabPractice | /practiceq/pythonProject1/fucntion/q1.py | 225 | 4.1875 | 4 | ''' to print multipliacation table of a given number by using fuction'''
def multi(a):
product=1
for i in range(11):
product=a*i
print (f"{a}*{i}={product}")
a=int(input("enter the nnumber"))
multi(a)
| false |
707681af05d6cb4521bf4f729290e96e6c347287 | Dirac26/ProjectEuler | /problem004/main.py | 877 | 4.28125 | 4 | def is_palindromic(num):
"""Return true if the number is palindromic and false otehrwise"""
return str(num) == str(num)[::-1]
def dividable_with_indigits(num, digits):
"""Returns true if num is a product of two integers within the digits range"""
within = range(10 ** digits - 1)
for n in within[1:]... | true |
774edd572b1497b9a8bc9e1c0f6107147626f276 | max-moazzam/pythonCoderbyte | /FirstFactorial.py | 541 | 4.1875 | 4 | #Function takes in a number as a parameter and returns the factorial of that number
def FirstFactorial(num):
#Converts parameter into an integer
num = int(num)
#Creates a factorial variable that will be returned
factorial = 1
#While loop will keep multipying a number to the number 1 less than it until 1 is ... | true |
4fdd9b3423f94460b3faad5262229e374ca3518c | indeyo/PythonStudy | /algorithm/insertion_sort.py | 720 | 4.125 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Author : indeyo_lin
# @Time : 2020/5/28 4:20 下午
# @File : insertion_sort.py
"""
def insertion_sort(arr):
if not arr:
return -1
for i in range(1, len(arr)):
current = arr[i]
# 有序区的索引
pre_index = i - 1
while pre_i... | false |
1f29fed056ccc1691b630acc4ffbc33526a29276 | lcantillo00/python-exercises | /2-SimplePythonData/ex11.py | 227 | 4.40625 | 4 | deg_f = int(input("What is the temperature in farengeigth? "))
# formula to convert C to F is: (degrees Celcius) times (9/5) plus (32)
deg_c = (deg_f -32)*5/9
print(deg_f, " degrees Celsius is", deg_c, " degrees Farenheit.")
| false |
681ec03bc494256d93fd8e6482a2aea210cf94d2 | lcantillo00/python-exercises | /4-ModuleTurtle/ex5.py | 772 | 4.15625 | 4 | # draw an equilateral triangle
import turtle
wn = turtle.Screen()
norvig = turtle.Turtle()
for i in range(3):
norvig.forward(100)
# the angle of each vertice of a regular polygon
# is 360 divided by the number of sides
norvig.left(360/3)
wn.exitonclick()
# draw a square
import turtle
wn = turtle.Sc... | false |
d9fbdc7310218e85b562a1beca25abe48e72ee8b | lcantillo00/python-exercises | /randy_guessnum.py | 305 | 4.15625 | 4 | from random import randint
num = randint(1, 6)
print ("Guess a number between 1 and 6")
answer = int(raw_input())
if answer==num:
print ("you guess the number")
elif num<answer:
print ("your number is less than the random #")
elif num>answer:
print("your number is bigger than the random #")
| true |
7b692f7ea4d8718261e528d07222061dc3e35de8 | michelmora/python3Tutorial | /BegginersVenv/dateAndTime.py | 757 | 4.375 | 4 | # Computers handle time using ticks. All computers keep track of time since 12:00am, January 1, 1970, known as epoch
# time. To get the date or time in Python we need to use the standard time module.
import time
ticks = time.time()
print("Ticks since epoch:", ticks)
# To get the current time on the machine, you can ... | true |
4dd9a591648531943ccd60b984e1d3f0b72a800c | michelmora/python3Tutorial | /BegginersVenv/switch(HowToSimulate).py | 2,519 | 4.21875 | 4 | # An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.
# OPTION No.1
def dog_sound():
return 'hau hau'
def cat_sound():
return 'Me au'
def horse_sound():
return 'R R R R'
def cow_sound():
return 'M U U U'
def no_sound():
return "T... | true |
8dee8c987a27474de2b12a4a783dddc7aa142260 | darrengidado/portfolio | /Project 3 - Wrangle and Analyze Data/Update_Zipcode.py | 1,333 | 4.21875 | 4 | '''
This code will update non 5-digit zipcode.
If it is 8/9-digit, only the first 5 digits are kept.
If it has the state name in front, only the 5 digits are kept.
If it is something else, will not change anything as it might result in error when validating the csv file.
'''
def update_zipcode(zipcode):
"""C... | true |
3177bc787712977e88acaa93324b7b43c25016f9 | sudharsan004/fun-python | /FizzBuzz/play-with-python.py | 377 | 4.1875 | 4 | #Enter a number to find if the number is fizz,buzz or normal number
n=int(input("Enter a number-I"))
def fizzbuzz(n):
if (n%3==0 and n%5==0):
print(str(n)+"=Fizz Buzz")
elif (n%3==0):
print(str(n)+"=Fizz")
elif (n%5==0):
print(str(n)+"=Buzz")
else:
print(str(n)+... | true |
bf90882a0af31c4272a9fee19aa2716760847bbc | krishna-kumar456/Code-Every-Single-Day | /solutions/piglatin.py | 1,060 | 4.375 | 4 | """ Pig Lating Conversion
"""
def convert_to_pig_latin(word):
""" Returns the converted string based on the
rules defined for Pig Latin.
"""
vowels = ['a', 'e', 'i', 'o', 'u']
char_list = list(word)
""" Vowel Rule.
"""
if char_list[0] in vowels:
resultant_word = word + 'way'
""" Consonant Rule.
"""
... | false |
da04ab784745cdce5c77c0b6159e17d802011129 | sclayton1006/devasc-folder | /python/def.py | 561 | 4.40625 | 4 | # Python3.8
# The whole point of this exercise is to demnstrate the capabilities of
# a function. The code is simple to make the point of the lesson simpler
# to understand.
# Simon Clayton - 13th November 2020
def subnet_binary(s):
""" Takes a slash notation subnet and calculates the
number of host addresse... | true |
bbfa62e0a73aa476ff8c7a2abd98c021c956d20e | Zeonho/LeetCode_Python | /archives/535_Encode_and_Decode_TinyURL.py | 1,708 | 4.125 | 4 | """
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it
returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your
encode/decode algorithm should work. You j... | true |
4af8683399a7344690ba6e7a3ba749d10852c993 | aparecidapires/Python | /Python para Zumbis/3 - Atacando os tipos basicos/Comentarios e Resolucao de Exercicios/Lista III/1.py | 398 | 4.375 | 4 | '''
Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido.
'''
nota = float(input("Digite uma nota entre '0' e '10': "))
while nota < 0 or nota > 10:
print ('Digite uma nota válida!')
nota = float(inp... | false |
ad6c9704c7f09a5fa1d1faab38eb5d43967026a4 | fagan2888/leetcode-6 | /solutions/374-guess-number-higher-or-lower/guess-number-higher-or-lower.py | 1,199 | 4.4375 | 4 | # -*- coding:utf-8 -*-
# We are playing the Guess Game. The game is as follows:
#
# I pick a number from 1 to n. You have to guess which number I picked.
#
# Every time you guess wrong, I'll tell you whether the number is higher or lower.
#
# You call a pre-defined API guess(int num) which returns 3 possible resul... | true |
6a097f9f7027419ba0649e5017bc2e17e7f822d3 | fagan2888/leetcode-6 | /solutions/557-reverse-words-in-a-string-iii/reverse-words-in-a-string-iii.py | 773 | 4.1875 | 4 | # -*- coding:utf-8 -*-
# Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
#
# Example 1:
#
# Input: "Let's take LeetCode contest"
# Output: "s'teL ekat edoCteeL tsetnoc"
#
#
#
# Note:
# In the string, each word is... | true |
6f4b3f90db0be1ccc197aacca9b625642c498aee | Raziel10/AlgorithmsAndMore | /Probability/PowerSet.py | 267 | 4.34375 | 4 | #Python program to find powerset
from itertools import combinations
def print_powerset(string):
for i in range(0,len(string)+1):
for element in combinations(string,i):
print(''.join(element))
string=['a','b','c']
print_powerset(string) | true |
da7bd9d5abbdd838c1110515dde30c459ed8390c | Smita1990Jadhav/GitBranchPracticeRepo | /condition&loops/factorial.py | 278 | 4.25 | 4 | num=int(input("Enter Number: "))
factorial=1
if num<1:
print("Factorial is not available for negative number:")
elif num==0:
print("factorial of 1 is zero: ")
else:
for i in range(1,num+1):
factorial=factorial*i
print("factorial of",num,"is",factorial) | true |
9f0b7ec7c45ed53ae0c7141eb88d50e04c62a868 | silasbispo01/todosOsDias | /Todos os dias/dia41/Exércicio3.py | 832 | 4.1875 | 4 | # Importação do random
import random
# Criação da lista de sorteios vazia
listaSorteio = []
# For para cadastro de 3 pessoas
for p in range(3):
# Inputs para nome da pessoa e quantia doada.
nome = input('Insira seu nome: ')
valorDoado = int(input('Insira o valor doado: R$'))
# Calculo de quantas vez... | false |
a3e1eadfdf24f44dc353726180eee97269844c45 | jjspetz/digitalcrafts | /py-exercises3/hello2.py | 517 | 4.34375 | 4 | #!/usr/bin/env python3
# This is a simple function that says hello using a command-line argument
import argparse
# formats the arguments for argparse
parser = argparse.ArgumentParser()
# requires at least one string as name
parser.add_argument('username', metavar='name', type=str, nargs='*',
help... | true |
c46f2637edea6f94adff6a8e93f78bd858d94fc1 | jjspetz/digitalcrafts | /py-exercises2/make-a-box.py | 327 | 4.15625 | 4 | # makes a box of user inputed hieght and width
# gets user input
height = int(input("Enter a height: "))
width = int(input("Enter a width: "))
# calculate helper variables
space = width - 2
for j in range(height):
if j == 0 or j == height - 1:
print("*" * width)
else:
print("*" + (" "*space) ... | true |
5c9ff36d6710c334e72abc5b9b58abc8a94758bd | jjspetz/digitalcrafts | /dict-exe/error_test.py | 343 | 4.125 | 4 | #!/usr/bin/env python3
def catch_error():
while 1:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Enter an integer!")
except x == 3:
raise myError("This is not an integer!")
else:
x += 13
if __name__ == "__main... | true |
4bdd9011b451281cdd9b3c8d4c3abbe730f9358f | kusaurabh/CodeSamples | /python_samples/check_duplicates.py | 672 | 4.25 | 4 | #!/usr/bin/python3
import sys
def check_duplicates(items):
list_items = items[:]
list_items.sort()
prev_item = None
for item in list_items:
if prev_item == item:
return True
else:
prev_item = item
return False
def create_unique_list(items)... | true |
a5a46c8dbaaf4c4ceee25803e0cca585d74eb883 | pseudomuto/sudoku-solver | /Python/model/notifyer.py | 1,164 | 4.125 | 4 | class Notifyer(object):
"""A simple class for handling event notifications"""
def __init__(self):
self.listeners = {}
def fireEvent(self, eventName, data = None):
"""Notifies all registered listeners that the specified event has occurred
eventName: The name of the event being fired
data: An optional param... | true |
3e925a8f0736eec9688f3597502d77f249c05e08 | annapaula20/python-practice | /functions_basic2.py | 2,510 | 4.4375 | 4 | # Countdown - Create a function that accepts a number as an input.
# Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countdown(num):
nums_list = []
for val in range(num, -1, -1):
nums... | true |
607e0ba035eaa2dc9216f0884c1562036797ba79 | Jagadeesh-Cha/datamining | /comparision.py | 487 | 4.28125 | 4 | # importing the required module
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3,4,5,6,7,8,9,10]
# corresponding y axis values
y = [35,32,20,14,3,30,6,20,2,30]
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('busiest places in descending-order')
# naming th... | true |
b4816526ef6cc323464ac3e9f787a6032e32072f | lilimonroy/CrashCourseOnPython-Loops | /q1LoopFinal.py | 507 | 4.125 | 4 | #Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits.
# Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left.
def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
cou... | true |
0ca00b26b0774c6e0d1891fca4567889cc657a01 | Mmingo28/Week-3 | /Python Area and Radius.py | 263 | 4.28125 | 4 |
#MontellMingo
#1/30/2020
#The program asks if the user can compute the area of an circle and the radius.
radius = int(input("what is the radius"))
#print("what is the number of the radius"+ )
print("what is the answer")
print(3.14*radius*radius)
| true |
8fbfcc3bcd13f2db5c6178cd7ed40f9eade923fc | xywgo/Learn | /LearnPython/Chapter 10/addition.py | 372 | 4.1875 | 4 |
while True:
try:
number1 = input("Please enter a number:(enter 'q' to quit) ")
if number1 == 'q':
break
number1 = int(number1)
number2 = input("Please enter another number:(enter 'q' to quit) ")
if number2 == 'q':
break
number2 = int(number2)
except ValueError:
print("You must enter a number")
... | true |
d025ef9b5f54fb004dc8ed67b652469566c92754 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/has_zero_triplets.py | 1,089 | 4.1875 | 4 | """
Given an array of integers that do not contain duplicate values,
determine if there exists any triplets that sum up to zero.
For example,
L = [-3, 2, -5, 8, -9, -2, 0, 1]
e = {-3, 2, 1}
return true since e exists
This solution uses a hash table to cut the time complexity down by n.
Time complexity: O(n^2)
Spac... | true |
31966a029427f2de3759a8af889481c05e30339a | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/three_sum_closest.py | 1,284 | 4.34375 | 4 | """
Given an array "nums" of n integers and an integer "target", find three integers in nums such that the sum is closest
to "target". Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closes... | true |
a7ad18871194654ee4d1cf04e1264b670df3d204 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/toeplitz_matrix.py | 1,212 | 4.46875 | 4 | """
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given an MxN matrix,
return True if and only if the matrix is Toeplitz.
Example 1:
Input: matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Output: True
Explanation:
1234
5123
9512
In the above grid, the diagonals ar... | true |
895e80acf9eed3e1b580a9ac4dec51eb295e7319 | davidadamojr/diary_of_programming_puzzles | /sorting_and_searching/find_in_rotated_array.py | 1,653 | 4.21875 | 4 | """
Given a sorted array of n integers that has been rotated an unknown number of times,
write code to find an element in the array. You may assume that the array was originally
sorted in increasing order.
"""
def find_in_rotated(key, rotated_lst, start, end):
"""
fundamentally binary search...
Either t... | true |
46a081380aa96ceaf062d72e0101881f8d57a08c | davidadamojr/diary_of_programming_puzzles | /bit_manipulation/hamming_distance.py | 1,025 | 4.3125 | 4 | """
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers num1 and num2, calculate the Hamming distance.
https://leetcode.com/problems/hamming-distance/
"""
# @param num1 integer
# @param num2 integer
def hamming_distance(num1, num2):
... | true |
1ebdbdafcc3dadabe48676ca0dbda76cdb3181d8 | davidadamojr/diary_of_programming_puzzles | /misc/convert_to_hexadecimal.py | 1,658 | 4.75 | 5 | """
Given an integer, write an algorithm to convert it to hexadecimal. For negative integers, two's complement method is
used.
Note:
1. All letters in hexadecimal (a-f) must be in lowercase.
2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero
character... | true |
a6673418628269bdac32de4aaa469fc9ea6b8239 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/integer_to_string.py | 952 | 4.6875 | 5 | """
Write a routine to convert a signed integer into a string.
"""
def integer_to_string(integer):
"""
Writes the string backward and reverses it
"""
if integer < 0:
is_negative = True
integer = -integer # for negative integers, make them positive
else:
is_negative = False... | true |
e114ca362bb69f5298c5137696ee4aaffec569ad | davidadamojr/diary_of_programming_puzzles | /mathematics_and_probability/intersect.py | 931 | 4.125 | 4 | """
Given two lines on a Cartesian plane, determine whether the two lines would
intersect.
"""
class Line:
def __init__(self, slope, yIntercept):
self.slope = slope
self.yIntercept = yIntercept
def intersect(line1, line2):
"""
If two different lines are not parallel, then they intersect... | true |
76e8af6b3ef66bce39724bd917d84150361c139e | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/excel_sheet_column_title.py | 662 | 4.15625 | 4 | """
Given a positive integer, return its corresponding column title as it appears
in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
"""
def convert_to_title(num):
integer_map = {}
characters = "ZABCDEFGHIJKLMNOPQRSTUVWXY"
for i in range(0, 26):
integer_map[i] = c... | true |
e6d847fbca7e196b13b3da94080a760656626497 | CindyWei/Python | /ex41.py | 1,295 | 4.15625 | 4 | #coding=utf-8
'''
2014-2-11
习题41:类
'''
class TheThing(object):
def __init__(self):
self.number = 0
def some_function(self):
print "I got called"
def add_me_up(self, more):
self.number += more
return self.number
a = TheThing()
b = TheThing()
a.some_function()
b.some_function()
print a.add_me_up(20)
prin... | false |
332acd1b09be1ad4bdea876a5f3f82633319c7bc | cryojack/python-programs | /charword.py | 402 | 4.34375 | 4 | # program to count words, characters
def countWord():
c_str,c_char = "",""
c_str = raw_input("Enter a string : ")
c_char = c_str.split()
print "Word count : ", len(c_char)
def countChar():
c_str,c_char = "",""
charcount_int = 0
c_str = raw_input("Enter a string : ")
for c_char in c_str:
if c_char is not " "... | true |
28d38ddd8f5cf86011e785037ef891a338810b23 | Daywison11/Python-exercicios- | /ex014.py | 252 | 4.25 | 4 | # Escreva um programa que converta uma temperatura digitando
# em graus Celsius e converta para graus Fahrenheit.
gc = float(input('infoeme a temperatra em °C :'))
fr = ((9*gc)/5) + 32
print('a temeratura de {}°C conrresponde a {}° F'.format(gc,fr)) | false |
c08e6a357ee5cd58f4a171dc81b001df5a8f487a | rPuH4/pythonintask | /INBa/2015/Serdehnaya_A_M/task_5_25.py | 1,494 | 4.25 | 4 | # Задача 5. Вариант 28.
# Напишите программу, которая бы при запуске случайным образом отображала название одной из пятнадцати республик, входящих в состав СССР.
# Serdehnaya A.M.
# 25.04.2016
import random
print ("Программа случчайным образом отображает название одной из пятнадцати республик, входящих в состав СС... | false |
bbaf1dec6b370ba832181e6b33f6e0f18a8490fb | ElianEstrada/Cursos_Programacion | /Python/Ejercicios/ej-while/ej-14.py | 476 | 4.21875 | 4 | #continuar = input("Desea continuar? [S/N]: ")
continuar = "S"
while(continuar == "S"):
continuar = input("Desea continuar? [S/N]: ")
print("Gracias por usar mi sistema :)")
'''
con ciclo while
pedir al usuario una cantidad númerica a ahorrar
y luego que le pregunten a al usuario si desea agregar otra canti... | false |
2c12b700e72b2cd155a8dca90a3e2389106eed3f | koenigscode/python-introduction | /content/partials/comprehensions/list_comp_tern.py | 311 | 4.25 | 4 | # if the character is not a blank, add it to the list
# if it already is an uppercase character, leave it that way,
# otherwise make it one
l = [c if c.isupper() else c.upper()
for c in "This is some Text" if not c == " "]
print(l)
# join the list and put "" (nothing) between each item
print("".join(l))
| true |
22e20f3364f8498766caf17e4dc8b967ef217f5b | BMariscal/MITx-6.00.1x | /MidtermExam/Problem_6.py | 815 | 4.28125 | 4 | # Problem 6
# 15.0/15.0 points (graded)
# Implement a function that meets the specifications below.
# def deep_reverse(L):
# """ assumes L is a list of lists whose elements are ints
# Mutates L such that it reverses its elements and also
# reverses the order of the int elements in every element of L.
#... | true |
73e4c51440c5d6da38f297556843c0173f0153ee | alexhong33/PythonDemo | /PythonDemo/Day01/01print.py | 1,140 | 4.375 | 4 | #book ex1-3
print ('Hello World')
print ("Hello Again")
print ('I like typing this.')
print ('This is fun.')
print ('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')
print ('你好!')
#print ('#1')
# A comment, this is so you can read your program later.
# A... | true |
41af103a812a599e376b79251c7f1c76a01fe914 | KevinOluoch/Andela-Labs | /missing_number_lab.py | 787 | 4.4375 | 4 | def find_missing( list1, list2 ):
"""When presented with two arrays, all containing positive integers,
with one of the arrays having one extra number, it returns the extra number
as shown in examples below:
[1,2,3] and [1,2,3,4] will return 4
[4,66,7] and [66,77,7,4] will return 77
"""
... | true |
b2875d7737c5fd6cc06a5299f9f8c888c93bebb8 | byhay1/Practice-Python | /Repl.it-Practice/forloops.py | 1,856 | 4.71875 | 5 | #--------
#Lets do for loops
#used to iterate through an object, list, etc.
# syntax
# my_iterable = [1,2,3]
# for item_name in my_iterable
# print(item_name)
# KEY WORDS: for, in
#--------
#first for loop example
mylist = [1,2,3,4,5,6,7,8,9,10]
#for then variable, you chose the variable
print('\n')
for num in m... | true |
29d08b7acb73e2baeb8a2daf67be103e1ad302fc | byhay1/Practice-Python | /Repl.it-Practice/tuples.py | 828 | 4.1875 | 4 | #------------
#tuples are immutable and similar to list
#FORMAT of a tuple == (1,2,3)
#------------
# create a tuple similar to a list but use '()' instead of '[]'
#define tuple
t = (1,2,3)
t2 = ('a','a','b')
mylist = [1,2,3]
#want to find the class type use the typle function type(PUTinVAR)
print('',"Find the type o... | true |
4f3e7af26400a2f4c309cffa69d5a6f874819731 | byhay1/Practice-Python | /Repl.it-Practice/OOPattributeClass.py | 2,069 | 4.5 | 4 | #----------
# Introduction to OOP:
# Attributes and Class Keywords
#
#----------
import math
mylist = [1,2,3]
myset = set()
#built in objects
type(myset)
type(list)
#######
#define a user defined object
#Classes follow CamelCasing
#######
#Do nothing sample class
class Sample():
pass
#set variable to class
my_sa... | true |
eef86cb4c54bf7d0b38ced84acff83220b0304e3 | jongwlee17/teampak | /Python Assignment/Assignment 5.py | 988 | 4.34375 | 4 | """ Exercise 5: Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
Make sure your program works on two lists... | true |
3061d9515b321d746e69674f44b9550ae0e6f151 | ankitoct/Core-Python-Code | /40. List/6. AppendMethod.py | 222 | 4.125 | 4 | # Append Method
a = [10, 20, -50, 21.3, 'Geekyshows']
print("Before Appending:")
for element in a:
print (element)
# Appending an element
a.append(100)
print()
print("After Appending")
for element in a:
print (element) | true |
0a064e70245373690e15b0a00b36ee1f2ba76c8d | ankitoct/Core-Python-Code | /45. Tuple/6. tupleModification.py | 585 | 4.125 | 4 | # Modifying Tuple
a = (10, 20, -50, 21.3, 'GeekyShows')
print(a)
print()
# Not Possible to Modify like below line
#a[1] = 40 # Show TypeError
# It is not possible to modify a tuple but we can concate or slice
# to achieve desired tuple
# By concatenation
print("Modification by Concatenation")
b = (40, 50)
tup1 = a... | true |
a673f44d42f7a6ee67fa74814afac52099634358 | ankitoct/Core-Python-Code | /38. Function/28. TwoDecoratorFunction.py | 642 | 4.1875 | 4 | # Two Decorator Function to same function
# Example 1
def decor(fun):
def inner():
a = fun()
add = a + 5
return add
return inner
def decor1(fun):
def inner():
b = fun()
multi = b * 5
return multi
return inner
def num():
return 10
result_fun = decor(decor1(num))
print(result_fun())
# Example 2
de... | false |
74b872c0cdaec66aa6e378aed100b87079b91f6d | ankitoct/Core-Python-Code | /54. Nested Dictionary/3. AccessNestedDict1.py | 375 | 4.40625 | 4 | # Accessing Nested Dictionary using For loop
a = {1: {'course': 'Python', 'fees':15000},
2: {'course': 'JavaScript', 'fees': 10000 } }
# Accessing ID
print("ID:")
for id in a:
print(id)
print()
# Accessing each id keys
for id in a:
for k in a[id]:
print(k)
print()
# Accessing each id keys -- value
for id in... | false |
bbf0d85066f85fae9f77a1a91d43237aaa3a1f57 | ankitoct/Core-Python-Code | /9. if elif else Statement/1. ifelifelseStatement.py | 472 | 4.40625 | 4 | # If elif else Statement
day = "Tuesday"
if (day == "Monday"):
print("Today is Monday")
elif (day == "Tuesday"):
print("Today is Tuesday")
elif (day == "Wednesday"):
print("Today is Wednesday")
else:
print("Today is Holiday")
# If elif else with User Input
day = input("Enter Day: ")
if day == "Monday":
print("To... | false |
7457008cab91ec66f819dcaec3f2b4bd4e69c627 | ankitoct/Core-Python-Code | /36. Formatting String/7. FStringExample3.py | 897 | 4.125 | 4 | # Thousand Separator
price = 1234567890
print(f"{price:,}")
print(f"{price:_}")
#Variable
name = "Rahul"
age= 62
print(f"My name is {name} and age {age}")
# Expression
print(f"{10*8}")
# Expressing a Percentage
a = 50
b = 3
print(f"{a/b:.2%}")
# Accessing arguments items
value = (10, 20)
print(f"{value[0]} {value[1... | false |
a60165af0986981ea6097e34278a844d9b9b2f70 | MirandaTowne/Python-Projects | /grade_list.py | 754 | 4.46875 | 4 | # Name: Miranda Towne
# Description: Creating a menu that gives user 3 choices
# Empty list
grade = []
done = False
new_grade = ''
# Menu options
menu = """
Grade Book
0: Exit
1: Display a sorted list of grades
2: Add a grade to the list
"""
# Display menu at start of a while loop
while not done:
... | true |
ec40f68419b2a7c639bb9614cf1447f02927f529 | kimalaacer/Head-First-Learn-to-Code | /chapter 12/dog4.py | 1,205 | 4.34375 | 4 | # this is an introduction to object oriented programming OOP
# dog class has some attributes (state) such as name, age, weight,and behavior ( or method) bark
class Dog:
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def bark(self):
... | false |
bffb8076b777e4962c687e0f9c790b5fafc93041 | Silentsoul04/2020-02-24-full-stack-night | /1 Python/solutions/unit_converter.py | 697 | 4.25 | 4 | def convert_units(data):
conversion_factors = {
'ft': 0.3048,
'mi': 1609.34,
'm': 1,
'km': 1000,
'yd': 0.9144,
'in': 0.0254,
}
value, unit_from, unit_to = data
converted_m = conversion_factors[unit_from] * value
return round(converted_m / conversi... | true |
63756dbda9070dd378118718383a7dbebcc469d9 | haaks1998/Python-Simple | /07. function.py | 1,011 | 4.1875 | 4 | # A function is a set of statements that take inputs, do some specific computation and returns output.
# We can call function any number of times through its name. The inputs of the function are known as parameters or arguments.
# First we have to define function. Then we call it using its name.
# format:
# def ... | true |
3dd22a089fd49714b6cd36abbd3e5a6a3c6a4d2b | rakipov/py-base-home-work | /py-home-work/tasks/horoscope.py | 1,961 | 4.1875 | 4 | # Простая задача из первых лекий для определения знака зодиака
day = int(input('Введите день: '))
month = (input('Введите месяц: ')).lower()
if day <= 31:
if (21 <= day <= 31 and month == 'март') or (1 <= day <= 20 and month == 'апрель'):
zodiac = 'Овен'
elif (21 <= day <= 30 and month == 'апрель') or ... | false |
2d95625294be5907d014ea1c2c0a5c7c30640d34 | feixuanwo/py_bulidinfunc | /myreverse_reversed.py | 241 | 4.15625 | 4 | #!:coding:utf-8
#reversed与reverse不同。前者是内置函数,后者是列表、字典的方法。前者返回一个新列表。
i = [x for x in range(-5,6)]
for x in reversed(i):
print x,
print
print i
print i.reverse()
print i
| false |
1520b9faa5b957da64ea48e158adacc0e5987adf | pixeltk623/python | /Core Python/Datatypes/string.py | 478 | 4.28125 | 4 | # Strings
# Strings in python are surrounded by either single quotation marks, or double quotation marks.
# 'hello' is the same as "hello".
# You can display a string literal with the print() function:
# print("Hello")
# print('Hello')
# a = "hello"
# print(a)
# a = """cdsa
# asdasdas
# asdasdassdasd
# asdasdsa""... | true |
4b3f9e149707817aefa696ce2d336453cd93f34a | undergraver/PythonPresentation | /05_financial/increase.py | 766 | 4.125 | 4 | #!/usr/bin/env python
import sys
# raise in percent
raise_applied=6
raise_desired=40
# we compute:
#
# NOTE: the raise is computed annually
#
# 1. the number of years to reach the desired raise with the applied raise
# 2. money lost if the desired raise is applied instantly and no other raise is done
salary_now=100... | true |
6a293c64aabc496cc4e1669935d1659dc1042c39 | Kjartanl/TestingPython | /TestingPython/Logic/basic_logic.py | 368 | 4.21875 | 4 |
stmt = True
contradiction = False
if(stmt):
print("Indeed!")
if(contradiction):
print("Still true, but shouldn't be! Wtf?")
else:
print("I'm afraid I'm obliged to protest!")
print("------- WHILE LOOP ---------")
number = 0
while(number < 5):
print("Nr is %s" %number)
number = num... | true |
f4f9ba1982577f908487115093736c315f4a2c8c | aanantt/Sorting-Algorithms | /InsertionSort.py | 253 | 4.21875 | 4 | def insertionSort(array):
for i in range(len(array)):
j=i-1
while array[j] > array[j+1] and j >=0:
array[j], array[j+1] = array[j+1], array[j]
j -= 1
return array
print(insertionSort([1,5,8,2,9,0])) | false |
db4b2589fced75a64c6b55331dd7bbec12836441 | Cary19900111/G7Cary | /Learn/crdataStrcuture/Array/dict/copycr.py | 1,696 | 4.15625 | 4 | from copy import copy,deepcopy
def copy_tutorial():
'''
第一层的id不一样,但是第二层的id是一样的,指向的是同一块地址
修改copy1,就会修改copy2
'''
dict_in = {"name":"Cary","favor":["tabletennis","basketball"]}
dict_copy1 = copy(dict_in)
dict_copy2 = copy(dict_in)
print("Before copy1:{}".format(dict_copy1))
print("Befor... | false |
fc2e497f6a4df5ed6002bb92dbcf4c5b3af8b393 | 2292527883/Learn-python-3-to-hard-way | /ex39/ex39.py | 1,962 | 4.1875 | 4 | # 字典
# create a mapping of state to abbreviation
statse = { # 定义字典
'Oregon': 'OR',
'Floida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some citise in them
cites = {
'CA': 'san Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
... | false |
134bf3bc84a1f0b67781d6f27656f24b81eef683 | simonvantulder/Python_OOP | /python_Fundamentals/numberTwo.py | 979 | 4.28125 | 4 |
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'},
{'first_name': 'Mark', 'last_name': 'Guillen'},
{'first_name': 'KB', 'last_name': 'Tonel'}
]
#iterateDictionary(students)
# should output: (it's okay if each key-value p... | false |
dd9dca4f015cb790227af5eb427850a1c8823202 | PramodSuthar/pythonSnippets | /generator.py | 670 | 4.15625 | 4 | """
def squence_num(nums):
result = []
for i in nums:
result.append(i*i)
return result
squared_list = squence_num([1,2,3,4,5])
print(squared_list)
"""
def squence_num(nums):
for i in nums:
yield(i*i)
##squared_list = squence_num([1,2,3,4,5])
"""
print(squa... | false |
0e07914cfa997c6ee2bef28123972e089f49b454 | montaro/algorithms-course | /P0/Task4.py | 1,234 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to i... | true |
d3eb57ca3377dcb7462afd86e43997a1f220e940 | shivanshutyagi/python-works | /primeFactors.py | 566 | 4.3125 | 4 | def printPrimeFactors(num):
'''
prints primeFactors of num
:argument: number whose prime factors need to be printed
:return:
'''
for i in range(2, num+1):
if isPrime(i) and num%i==0:
print(i)
def isPrime(num):
'''
Checks if num is prime or not
:param num:
:r... | true |
a89ba3ea381c392845379d369981fca1a0a16d1b | roberg11/is-206-2013 | /Assignment 2/ex13.py | 1,150 | 4.4375 | 4 |
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
## Combine raw_input with argv to make a script that gets more input
## from a user.
fruit = raw_inpu... | true |
c232410e848da610102a0a08b4077aa2295847b0 | roberg11/is-206-2013 | /Assignment 2/ex20.py | 1,803 | 4.53125 | 5 | from sys import argv
script, input_file = argv
# Definition that reads a file given to the parameter
def print_all(f):
print f.read()
# Definition that 'seeks' to the start of the file (in bytes) given to parameter
# The method seek() sets the file's current position at the
# offset. The whence argument is optio... | true |
676817b23e15e5368746b750f48e518427c937ae | onerbs/w2 | /structures/w2.py | 1,914 | 4.28125 | 4 | from abc import ABC, abstractmethod
from typing import Iterable
from structures.linked_list_extra import LinkedList
class _Linear(ABC):
"""Abstract linear data structure."""
def __init__(self, items: Iterable = None):
self._items = LinkedList(items)
def push(self, item):
"""Adds one item... | true |
7f7b411883c7f6985a354f163a11da1a879b0cac | nishaagrawal16/Datastructure | /Python/decorator_for_even_odd.py | 1,363 | 4.21875 | 4 | # Write a decorator for a function which returns a number between 1 to 100
# check whether the returned number is even or odd in decorator function.
import random
def decoCheckNumber(func):
print ('Inside the decorator')
def xyz():
print('*************** Inside xyz *********************')
num =... | true |
aa5bc400ed332b046f45db6233975294afa48494 | nishaagrawal16/Datastructure | /Linklist/partition_a_link_list_by_a_given_number.py | 2,555 | 4.125 | 4 | #!/usr/bin/python
# Date: 2018-09-17
#
# Description:
# There is a linked list given and a value x, partition a linked list such that
# all element less x appear before all elements greater than x.
# X should be on right partition.
#
# Like, if linked list is:
# 3->5->8->5->10->2->1 and x = 5
#
# Resultant linked list... | true |
bf13df5bf072797b535624bca57f87f5f5c7b39c | nishaagrawal16/Datastructure | /sorting/bubble_sort.py | 1,314 | 4.6875 | 5 | # Date: 20-Jan-2020
# https://www.geeksforgeeks.org/python-program-for-bubble-sort/
# Bubble Sort is the simplest sorting algorithm that works by
# repeatedly swapping the adjacent elements if they are in wrong order.
# Once the first pass completed last element will be sorted.
# On next pass, we need to compare till l... | true |
da785b4c17fbed0a35787f7db82ee578ffaf07bf | nishaagrawal16/Datastructure | /Python/overriding.py | 2,643 | 4.46875 | 4 | # Python program to demonstrate error if we
# forget to invoke __init__() of parent.
class A(object):
a = 1
def __init__(self, n = 'Rahul'):
print('A')
self.name = n
class B(A):
def __init__(self, roll):
print('B')
self.roll = roll
... | true |
fee51facfda5df96e5aa73eaf6f7d3962df39c2c | cherkesky/urbanplanner | /city.py | 762 | 4.59375 | 5 | '''
In the previous Urban Planner exercise, you practices defining custom types to represent buildings. Now you need to create a type to represent your city. Here are the requirements for the class. You define the properties and methods.
Name of the city.
The mayor of the city.
Year the city was established.
A collect... | true |
8da1b3e55c7d3c0f941d28d2395c1e1d353be217 | spikeyball/MITx---6.00.1x | /Week 1 - Problem 3.py | 1,002 | 4.125 | 4 | # Problem 3
# 15.0/15.0 points (graded)
# Assume s is a string of lower case characters.
#
# Write a program that prints the longest substring of s in which the letters
# occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your
# program should print
#
# Longest substring in alphabetical order is: ... | true |
776a2822e9a89368babe21c0289fa93e4f1b6e55 | CaptainMich/Python_Project | /StartWithPython/StartWithPython/Theory/OOP/Class.py | 2,994 | 4.25 | 4 | # -------------------------------------------------------------------------------------------------
# CLASS
# -------------------------------------------------------------------------------------------------
print('\n\t\tCLASS\n')
class Enemy: # define a class;
... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.