blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
827a75178963d0b672460e8b7f01a566fd1a0177 | thiagorangeldasilva/Exercicios-de-Python | /pythonBrasil/02.Estrutura de Decisão/15. triangulo.py | 1,090 | 4.28125 | 4 | #coding: utf-8
"""
Faça um Programa que peça os 3 lados de um triângulo.
O programa deverá informar se os valores podem ser
um triângulo. Indique, caso os lados formem um triângulo,
se o mesmo é: equilátero, isósceles ou escaleno.
Dicas:
Três lados formam um triângulo quando a soma de
quaisquer dois lados for... | false |
359ae83a4c2f4184a35587ab2dca1c2840629e5d | Gokulancv10/CodeBytes | /2-Week_Array/Spot The Difference.py | 1,723 | 4.125 | 4 | """
This question is asked by Google. You are given two strings, s and t which only consist of lowercase letters.
t is generated by shuffling the letters in s as well as potentially adding an additional random character.
Return the letter that was randomly added to t if it exists, otherwise, return ''.
Note: You may... | true |
0a601544eea489d94afbcedd7b5bc054c43459bb | greencodespace/code_data | /py_scipy/엔지니어를위한_파이썬/chapter05/class1.py | 789 | 4.40625 | 4 | # 클래스 정의
class MyClass(object): # (1) 상속하는 클래스 없음
""" (2) 클래스의 닥스트링 """
# (3) 변수 x, y의 정의
x = 0
y = 0
def my_print(self):
self.x += 1 # x를 인스턴스마다 별도로 존재하는 변수로 다룸
MyClass.y += 1 # y를 클래스마다 존재하는 변수로 다룸
print('(x, y) = ({}, {})'.format(self.x, self.y))
# 클래스의 인스턴스를 생성
f = ... | false |
612234d53d3d28701fdb0d4992a6b9be51fdc0c3 | Raymond-P/Github-Dojo | /Python_200_Problems/arrays/array_rotate.py | 405 | 4.15625 | 4 | # Rotate an array of n elements to the right by k steps.
# For example, with n = 7 and k = 3,
# the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
# Note:
# Try to come up as many solutions as you can,
# there are at least 3 different ways to solve this problem.
def rotate1(array, steps):
if len(array) > st... | true |
62d903677f5a006144cf2f01530863cfca8c3bde | PAVISH2002/my-captain | /fibonocii.py | 281 | 4.1875 | 4 | #code for fibonacci numbers
n1=0
n2=1
count = 0
nterms=int(input("Enter how many terms :"))
if nterms<=0:
print("Enter a positive interger :")
else:
while(count<nterms):
print(n1)
nth=n1+n2
n1=n2
n2=nth
count+=1
| false |
1a646975d309c839d68874299c25d90b118e6108 | Icarus-150/KMCSSI19 | /Welearn/M3-PYTHON/LABS/lab1-pluralizeit/pluralize.py | 618 | 4.15625 | 4 |
def pluralize(word,num):
if num > 1:
if word [-3:]== "ife" :
return( word[:-3] + "ives")
elif word[-2:] == "sh" or word[-2:] == "ch" :
return( word + "es")
elif word[-2:] == "us":
return(word[:-2] + "i")
elif word[-2:] == "ay" or word[-2:] == "oy"... | false |
3991269b55ef51fd1e75c2e56d21d36c6960080a | yuvan11/python_basic_practice | /python_class/operators.py | 1,288 | 4.21875 | 4 | x = 15
y = 4
# Arithmetic
# Addition
print('5 + 5 =',x+y)
#
# subtraction
print('6- 3 =',x-y)
#
# Multiplication
print('7* 7 =',x*y)
# Division
print('50/ 5 =',x/y)
#
# floor division // quotient
print('x // y =',x//y)
# Exponent
print('x ** y =',x**y)
#
# #Modulus // remainder
print('x % y =... | false |
7da8c3be50b482c5e40d2e94b7dda7650ea0bfa3 | Mariakhan58/simple-calculator | /calculator.py | 1,343 | 4.25 | 4 | # Program to make a simple calculator
# This function adds two numbers
def Calculate():
def add(a, b):
return a+b
# This function subtracts two numbers
def subt(a, b):
return a-b
# This function multiplies two numbers
def mult(a, b):
return a*b
#This function divides... | true |
f304dca7c8c76a0be1fab0a06e1087a5d31089e1 | AnaLeonor/labs | /lab2.py | 1,140 | 4.15625 | 4 | #LAB2
#Exercicio1
shoppingList = ['potatoes', 'carrots', 'cod', 'sprouts']
#Exercicio2
scnElem = shoppingList[1]
print(scnElem)
lastElem = shoppingList[-1]
print(lastElem)
#Exercicio3
for i in shoppingList:
print(i)
#Exercicio4
studentList = []
#Exercicio5
shoppingList.append('orange')
shoppingList.append('lime... | false |
416bce7ea5543c5d05b52d9cfb0e26d1d3cbd510 | Reece323/coding_solutions | /coding_solutions/alphabeticShift.py | 467 | 4.15625 | 4 | """
Given a string, your task is to replace each of its characters by the
next one in the English alphabet; i.e. replace a with b, replace b with c,
etc (z would be replaced by a).
"""
def alphabeticShift(inputString):
#97(a) - 122(z)
to_list = list(inputString)
for i in range(len(to_list)):
... | true |
25916d96dec4108171537a9ac039b2110ee31bc4 | Reece323/coding_solutions | /coding_solutions/first_not_repeating_character.py | 843 | 4.21875 | 4 | """
Given a string s consisting of small English letters, find and return the
first instance of a non-repeating character in it. If there is no such character,
return '_'.
Example
For s = "abacabad", the output should be
first_not_repeating_character(s) = 'c'.
There are 2 non-repeating characters in the string:... | true |
d869fc6cf5f3cdf029c4d8ea4439fb6a62c4cd28 | Digikids/Fundamentals-of-Python | /if statements.py | 477 | 4.21875 | 4 |
number_1 = int(input("Input a number: "))
number_2 = int(input("Input a second number: "))
operation = input("What do you want to do with the two numbers: ")
output = ""
if operation == "+":
output = number_1 + number_2
elif operation == "-":
output = number_1 - number_2
elif operation == "*":
output = n... | true |
e5bd64932169fa7beed4c6f919d07d97d2b02dab | shaokangtan/python_sandbox | /reverse_linked_list.py | 662 | 4.21875 | 4 | class Node:
def __init__(self, value):
self.value = value
self.nextnode = None
def reverse_linked_list(node):
current = node
prev = None
next = None
while current:
next = current.nextnode
current.nextnode = prev
prev = current
curr... | true |
d49d6a35fe93577fecb7810aa0e151160d02ae06 | shaokangtan/python_sandbox | /hello_world.py | 994 | 4.125 | 4 | print("hello world %c" % '!')
class Dog():
"""Represent a dog."""
def __init__(self, name):
"""Initialize dog object."""
self.name = name
def sit(self):
"""Simulate sitting."""
print(self.name + " is sitting.")
class SARDog(Dog):
"""Represent a searc... | false |
e14bb95ae0b24e82ed8f92fcfa17bc7d6e339cf8 | JianFengY/codewars | /codes/bit_counting.py | 627 | 4.15625 | 4 | # -*- coding: utf-8 -*-
'''
Created on 2018年2月2日
@author: Jeff Yang
'''
'''
Write a function that takes an (unsigned) integer as input, and returns the number
of bits that are equal to one in the binary representation of that number.
Example: The binary representation of 1234 is 10011010010, so the functio... | true |
48780254b9319513472ab29b52c1074f34b439db | JianFengY/codewars | /codes/format_a_string_of_names.py | 1,372 | 4.1875 | 4 | # -*- coding: utf-8 -*-
'''
Created on 2018年2月2日
@author: Jeff Yang
'''
'''
Given: an array containing hashes of names
Return: a string formatted as a list of names separated by commas except for the
last two names, which should be separated by an ampersand.
Example:
namelist([ {'name': 'Bart'}, {'name':... | false |
65260f9763e0ebeb995c3a7c5260c2b8420206c7 | JianFengY/codewars | /codes/binary_addition.py | 486 | 4.21875 | 4 | # -*- coding: utf-8 -*-
'''
Created on 2018年2月1日
@author: Jeff Yang
'''
'''
Implement a function that adds two numbers together and returns their sum in binary.
The conversion can be done before, or after the addition.
The binary number returned should be a string.
'''
def add_binary(a, b):
"""a... | true |
98638499b765de5668015c9425b882f5721ede52 | afrazn/Projects | /MemoizationDynamicProgramming.py | 1,144 | 4.1875 | 4 | '''This program uses memoization dynamic programming to find the optimal items to loot based on weight capacity and item value'''
from util import Loot
def knapsack(loot, weight_limit):
grid = [[0 for col in range(weight_limit + 1)] for row in range(len(loot) + 1)]
for row, item in enumerate(loot):
row = row ... | true |
8437ae1338934cdf4937ab1e97967a097731e77c | srirachanaachyuthuni/object_detection | /evaluation.py | 2,508 | 4.1875 | 4 | "This program gives the Evaluation Metrics - Accuracy, Precision and Recall"
def accuracy(tp, tn, total):
"""
Method to calculate accuracy
@param tp: True Positive
@param tn: True Negative
@param total: Total
@return: Calculated accuracy in float
"""
return (tp + tn ) / total
def pre... | true |
3f15cde13c1183324a580bac67c3f2ffcee42c73 | simplifies/Coding-Interview-Questions | /hackerrank/noDocumentation/countingValleys.py | 1,393 | 4.125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
# so instantly i'm thinking switch the DD UU to 1 and -1
# so [DDUUUU] would become [-1, -1, 1, 1, 1, 1]
# So a valley is determined when he goes below sea leve... | true |
c1904c47cfe04e5bacb7261cf7a1d2501dfc3332 | viththiananth/My-Python-Practise | /11. Check Primality Functions.py | 1,713 | 4.1875 | 4 | #Ask the user for a number and determine whether the number
# is prime or not. (For those who have forgotten,
# a prime number is a number that has no divisors.).
# You can (and should!) use your answer to Exercise 4 to
# help you. Take this opportunity to practice using functions,
# described below.
#num=int(input("P... | true |
8b3bfb58367bd57f4e474a7dc475b983214b3bcd | viththiananth/My-Python-Practise | /16. Password Generator.py | 1,118 | 4.1875 | 4 | #Write a password generator in Python. Be creative with how you generate passwords - strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The passwords should be random, generating a new password every time the user asks for a new password. Include your run-time code in a main meth... | true |
57e8501523b862c44d87e29d8577bfd759a54da8 | oldman1991/learning_python_from_zero | /work/work_demo05.py | 1,671 | 4.21875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# create by oldman
# Date: 2019/1/10
# 1,编程实现9*9乘法表
# 2. 用函数实现一个判断,用户输入一个年份,判断是否是闰年
# 3. 用函数实现输入某年某月某日,判断一下这一天是这一年的第几天,需要考虑闰年
import datetime
def multiplication_table():
for i in range(1, 10):
for j in range(1, i + 1):
print(str(j) + "*" + str(i)... | false |
197c33c4b87a081269f3223c5a5828e728f34bbe | Aswin-Sureshumar/Python-Programs | /bubble.py | 227 | 4.21875 | 4 | def bubble_sort(list):
for i in range(len(list)-1,0,-1):
for j in range(i):
if list[j]>list[j+1]:
list[j],list[j+1]=list[j+1],list[j]
list=[9,8,7,5,1,11]
bubble_sort(list)
print(" The sorted list is : ",list) | false |
9bf1d0dd74c501be2fcba420a3c4e9fa4d9b25b0 | ziyingye/python_intro | /HW/HW3/HW3.py | 2,472 | 4.15625 | 4 | from math import pi
from pprint import pprint
from icecream import ic
# 120%
def compute_rect(top_left, bottom_right):
"""
compute the area of square
:param top_left: vertices of top left corner
:type top_left: tuple
:param : vertices of bottom right corner
:type bottom_right: tuple
:retur... | false |
946deb8b75fb2f6aa256423df749acd46b53af28 | lroolle/CodingInPython | /leetcode/336_palindrome_pairs.py | 1,150 | 4.1875 | 4 | #!usr/bin/env python3
"""LeetCode 336. Palindrome Pairs
> Given a list of unique words. Find all pairs of distinct
indices (i, j) in the given list, so that the concatenation
of the two words, i.e. words[i] + words[j] is a palindrome.
- Example 1:
Given words = ["bat", "tab", "cat"]
Return [[0,... | true |
4197a945fa1cea1dfd132bb21a12340640d50c69 | Virjanand/LearnPython | /005_stringFormatting.py | 474 | 4.3125 | 4 | # String formatting with argument specifiers
name = "John"
print("Hello, %s!" % name)
# Use two or more argument specifiers
name = "Jane"
age = 23
print("%s is %d years old." % (name, age))
# objects have "repr" method to format it as string
mylist = [1, 2, 3]
print("A list: %s" % mylist)
# Exercise: write Hello John... | true |
cdfc3b31fed2480004ec70e5e03cfb0ff491716b | Virjanand/LearnPython | /009_functions.py | 1,455 | 4.40625 | 4 | # Functions are blocks of code
#block_head:
# 1st block line
# 2nd block line
# Functions are defined using def func_name
def my_function():
print("Hello from my function!")
# Arguments
def my_function_with_args(username, greeting):
print("Hello, %s, from my function! I wish you %s" %
(username, gree... | true |
0d23ff1b5d66a7d90d77af0a6d30ae3c6bac8118 | herereadthis/timballisto | /tutorials/abstract/abstract_04.py | 808 | 4.4375 | 4 | """More on abstract classes."""
"""
AbstractClass isn't an abstract class because you can create an instance of it.
Subclass must implement the (abstract) methods of the parent abstract class.
MyClass does not show an implementation of do_something()
"""
from abc import ABC, abstractmethod
class AbstractClass(ABC):... | true |
a3fa46c6ae0d0316e11dba1e8a556ac65e80fc8c | priyeshkolte/EDUYEAR-PYTHON---20 | /Day 3.py | 959 | 4.1875 | 4 | # Day 3 Assignments
#age year calculator
print("welcome to age in years calculator")
a=input("please enter the year of bitth and press enter " )
age = int(a)
result = 2021-age
print("YOUR AGE IS"+" " + str (result) + " years \n")
##simple calculator
print(" \n welcome to simple arithmatic clacul... | false |
abc124c578327b3e4b9a4ee3ce9e5300d6374af9 | amaurya9/Python_code | /fileReverseOrder.py | 762 | 4.375 | 4 | #Write a program to accept a filename from user & display it in reverse order
import argparse
items=[]
def push(item):
items.append(item)
def pop():
return items.pop()
def is_empty():
return (items == [])
def ReadFile(i):
fd=open(i)
char1=fd.read(1)
while char1:
push(cha... | true |
29877f7706f9b95ae71fd344bfd4ec031e481b35 | Shaners/Python | /collatzSeq.py | 424 | 4.25 | 4 | def collatz(num):
if num % 2 == 0:
return num // 2
else:
return 3 * num + 1
while True:
try:
print("Please provide a number.")
num = int(input('> '))
except ValueError:
print("Error: Invalid argument. You did not provide a number.")
continue
else:
... | true |
0e7d16c28f81bd3a89965e28314437257da5bf72 | Shaners/Python | /weightHeightConverter.py | 354 | 4.15625 | 4 | # Height and Weight Converter
# Set height variable to height in inches
# Set weight variable to weight in lbs
# This will print to console height in centimeters and weight in Kilograms
height = 74 # inches
weight = 180 # lbs
print(f"{height} inches is {height * 2.54} centimeters tall.")
print(f"{weight} lbs is {weig... | true |
2276cbfff7abb897c84bfba8b32999689da9890e | juliagarant/LearningPython | /COMP2057/Assignment3_104987469.py | 657 | 4.21875 | 4 | """
Assignment 3 for Programming for Beginners
Julia Garant
104987469
Mar 29 2020
"""
def main():
user_num = int(input("Enter an integer greater than 1: "))
numbers = []
for count in range(2, user_num + 1): # range is (inclusive,exclusive) which is why I need +1
numbers.append(count)
for i... | true |
87e55d48afe12116907a2c60c8639a3312e34568 | RodrigoTXRA/Python | /If.Statement.py | 527 | 4.40625 | 4 | # If statements are either true or false
# If condition is true it will action something otherwise it action sth else
# boolean variable below
is_male = True
is_tall = True
# Using OR one of the condition can be true
# Using AND both conditions must be true
if is_male and is_tall:
print("You are a male or t... | true |
a677bbd4b38851ef90af67fc9be48af051c29cec | EllaT/pickShape | /pickShape.py | 573 | 4.1875 | 4 | from turtle import *
from random import randint
shapes = int(input("How many shapes?"))
for i in range(shapes):
length_of_side = int(input("How many sides?"))
size = int(input("How many forward steps?"))
color = (input("What color?"))
number = (randint (20, 90))
for i in range(length_of_side):
pencolor(color)
... | true |
e94c488be437105918c000ac79a3551ab7841b84 | limanmana/python- | /pycharm_wenjian/L10-数据库基础和sqlite/2-sqlite示例1.py | 1,706 | 4.25 | 4 | # (重点)sqlite示例 创建表,写数据
import sqlite3
connect = sqlite3.connect("testsqlite.db")
cursor = connect.cursor()
# cursor.execute("""CREATE TABLE student(
# id INT PRIMARY KEY,
# name VARCHAR(10)
# ); """)
cursor.execute("""
INSERT INTO student (id, name)... | false |
832c2e39b074233947a2783eaeba6f4f7ce44114 | mehakgarg911/Basics_of_Python_Programming_1 | /question7.py | 246 | 4.125 | 4 | def factorial(num1):
fact =1
for x in range(2,num1+1):
fact*=x
return fact
def rec_factorial(num1):
if num1==0 or num1==1:
return 1;
else:
return num1*rec_factorial(num1-1);
print(factorial(6))
print(rec_factorial(6)) | true |
87eb176f50ef2a325f6bb8408fd4e4e3bfce1a01 | feminas-k/MITx---6.00.1x | /problemset6/applycoder.py | 396 | 4.15625 | 4 | def applyCoder(text, coder):
"""
Applies the coder to the text. Returns the encoded text.
text: string
coder: dict with mappings of characters to shifted characters
returns: text after mapping coder chars to original text
"""
r = ''
for char in text:
if char in coder:
... | true |
fe8f96cff7baa842c2397a7a4d0750ee8a7aa292 | AJsenpai/codewars | /titleCase.py | 1,295 | 4.25 | 4 | """
Write a function that will convert a string into title case, given an optional list of exceptions (minor words).
The list of minor words will be given as a string with each word separated by a space. Your function should ignore the case
of the minor words string -- it should behave in the same way even if the cas... | true |
16f4933df1f63e9e92a5f136e4d61802f376bb16 | AJsenpai/codewars | /isSquare.py | 1,028 | 4.21875 | 4 | # Kyu 7
"""
Given an integral number, determine if it's a square number:
In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words,
it is the product of some integer with itself.
The tests will always use some integral number, so don't worry about that in dynami... | true |
e0fc750cd3c4a2260e6cc12a364d9d2efbdf4c64 | mepky/verzeo-project | /verzeo minor project/prime_or_not.py | 378 | 4.125 | 4 | n=int(input('Enter the number:'))
def checkprime(n):
if n<=1:
return False
for i in range(2,n):
if (n%i==0):
return False
return True
if checkprime(n):
print(n,"is prime number")
else:
print(n,'is not a prime ... | true |
9093342f336ee965a5c0ac03f783477b571d217a | SmurfikComunist/light_it_calculator | /calculator/calculator.py | 972 | 4.1875 | 4 | """ Calculator module """
from math import sqrt
class Calculator:
""" Calculator implementation """
def add(self, x: int, y: int) -> int:
""" Add to attributes to each other """
return x + y
def subtract(self, x: int, y: int) -> int:
""" Subtract one attribute from another """
... | false |
b1c3e745d09b7a1ce161a41b5bf1ec70d6f33353 | 953250587/leetcode-python | /LargestTriangleArea_812.py | 1,748 | 4.1875 | 4 | """
You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.
Example:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2
Explanation:
The five points are show in the figure below. The red triangle is the largest.
Notes:
3 <= points.length <... | true |
ae33090f151b891fe79a8e2286e13745ff2f3900 | 953250587/leetcode-python | /KdiffPairsInAnArray_532.py | 2,322 | 4.125 | 4 | """
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: Th... | true |
3cea738e3ba2ed6322d0ca1c5beaf65379977b69 | 953250587/leetcode-python | /DifferentWaysToAddParentheses_MID_241.py | 2,744 | 4.15625 | 4 | """
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*... | true |
738e8c67cba389fb6720beb1e5872f7713a20275 | 953250587/leetcode-python | /ShortestPalindrome_HARD_214.py | 2,620 | 4.21875 | 4 | """
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
"""
class Solution(object):
def shor... | true |
4b17f1f4bd5fd6067b3fe78acd92cd4a76c6bfff | cvelezca/Practica_uso_git | /modulo_json.py | 2,040 | 4.15625 | 4 | """ Probar la libreria json de forma basica"""
import json
#json= string (cadena de caracteres). a continuacion se crea una variable tipo json con f (fstring)
#f (fstring)= tipo de codificacion de python que permite meter variables dentro de cadenas de strings se ponen
#tres comillas para indicar que se debe hacer sa... | false |
07f2ab307ebc2804f0ff99df449cb7b358b5ef12 | David-sqrtpi/python | /returning-functions.py | 463 | 4.375 | 4 | def calculate_recursive_sequence(number):
print(number)
if number == 0:
return number
return calculate_recursive_sequence(number-1)
def calculate_iterative_sequence(number):
for i in range(number, -1, -1):
print(i)
number = int(input("Write a number to calculate its descending sequenc... | true |
b9985aff1e6ae6d0fb2d695d54f167b9dc4eb97c | artmur0202/AaDS_1_184_2021 | /zad1.№7.py | 585 | 4.21875 | 4 | from math import*
x = int(input("Введите переменную x: "))
y = int(input("Введите переменную y: "))
z = int(input("Введите переменную z: "))
def funct(x, y, z):
D = y**2 - 4*x*z
if D<0:
print("Корней нет")
elif D==0:
f1=(-1*y/2*x)
print("Единственный корень = ",f1)
els... | false |
322465c7512f10bcaa51192c186995ef1af0f6c1 | Dzhevizov/SoftUni-Python-Fundamentals-course | /Programming Fundamentals Final Exam - 14 August 2021/01. Problem.py | 1,250 | 4.34375 | 4 | username = input()
command = input()
while not command == "Sign up":
command = command.split()
action = command[0]
if action == "Case":
case = command[1]
if case == "lower":
username = username.lower()
else:
username = username.upper()
print(us... | true |
02cb52724d606e22f5c6f4dad9b8550247d2f99a | Ssellu/python_tutorials | /ch06_operators/test06_멤버쉡연산자.py | 423 | 4.15625 | 4 | """
< 멤버쉽 연산자 >
- 원소의 구성 여부를 확인하는 연산자
- 결과값의 자료형은 bool형 (True 혹은 False)
in : a in iterables (iterables 에 a가 있으면 True)
not in : a not in iterables (iterables 에 a가 없으면 True)
"""
num1 = 3
num2 = 10
lst = [1, 2, 3, 4, 5]
print(num1 in lst) # True
print(num2 in lst) # False
print(num1 no... | false |
e5d9e9b8bbebea5b78b1ba4eb97cf9ca27021337 | ZTatman/Daily-Programming-Problems | /Day 3/problem3.py | 2,180 | 4.25 | 4 | # Author: Zach Tatman
# Date: 5/26/21
'''
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
... | true |
c3eadb1541b822fcad2aee32bd7700639f765f15 | soccergame/mincepie | /mincepie/demo/wordcount.py | 2,197 | 4.125 | 4 | """
Wordcount demo
This demo code shows how to perform word count from a set of files. we show how
to implement a simple mapper and reducer, and launch the mapreduce process.
To run the demo, run:
python wordcount.py --input=zen.txt
This will execute the server and the client both locally.
Optionally, you can
ru... | true |
dde50d7e399e4d3e9414fa3a92492d5edbfdcc81 | rwu8/MIT-6.00.2x | /Week 1/Lecture 2 - Decision Trees/Exercise1.py | 751 | 4.21875 | 4 | def yieldAllCombos(items):
"""
Generates all combinations of N items into two bags, whereby each
item is in one or zero bags.
Yields a tuple, (bag1, bag2), where each bag is represented as a list
of which item(s) are in each bag.
"""
# Your code here
N = len(items)
#... | true |
fc1863c9d52aeb479680be82aa4201694b9a0e21 | rmoore2738/CS303e | /assignment4_rrm2738.py | 1,599 | 4.28125 | 4 | #Rebecca Moore RRM2738
#Question 1
print("I’m thinking of a number from 1 to 10000. Try to guess my \nnumber! (Enter 0 to stop playing.)")
guess = input("Please enter your guess:")
guess = int(guess)
number = 1458
if guess == number:
print("That's correct! You win! You guessed my number in X guesses.")
while guess... | true |
ad7f18c17fb1757033f7647597c12a8187f1e824 | rohitx/DataSciencePrep | /PythonProblems/coderbyte/Second_Great_Low.py | 790 | 4.15625 | 4 | '''
Using the Python language, have the function SecondGreatLow(arr) take the array of numbers stored in arr and return the second lowest and second greatest numbers, respectively, separated by a space. For example: if arr contains [7, 7, 12, 98, 106] the output should be 12 98. The array will not be empty and will con... | true |
318f7d8acb098cd424025e2dd8bb9e085e8e3c58 | rohitx/DataSciencePrep | /PythonProblems/precourse/problem9.py | 499 | 4.25 | 4 | def word_lengths2(phrase):
'''
INPUT: string
OUTPUT: list of integers
Use map to find the length of each word in the phrase
(broken by spaces) and return the values in a list.
'''
# I will make use of the lambda function to compute the
# length of the words
# first I will break the s... | true |
699f4acd1a878494f7294565e6cafde8296398bc | rohitx/DataSciencePrep | /PythonProblems/precourse/problem6.py | 1,121 | 4.4375 | 4 | import numpy as np
def average_rows1(mat):
'''
INPUT: 2 dimensional list of integers (matrix)
OUTPUT: list of floats
Use list comprehension to take the average of each row in the matrix and
return it as a list.
Example:
>>> average_rows1([[4, 5, 2, 8], [3, 9, 6, 7]])
[4.75, 6.25]
'''... | true |
b2860e5741a5196f5cfded6bc2a8c8e7d1cd41e5 | rohitx/DataSciencePrep | /PythonProblems/coderbyte/longest_word.py | 780 | 4.46875 | 4 | '''
Using the Python language, have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty.
'''
def L... | true |
5bbca24e796907dd70f15221aa58438e860f97c0 | rohitx/DataSciencePrep | /PythonProblems/coderbyte/Ex_Oh.py | 761 | 4.3125 | 4 | '''
Using the Python language, have the function ExOh(str) take the str parameter being passed and return the string true if there is an equal number of x's and o's, otherwise return the string false. Only these two letters will be entered in the string, no punctuation or numbers. For example: if str is "xooxxxxooxo" t... | true |
16f44df0d5b4db85c87ec8bc0e7d4415802f14eb | elad-allot/Udemy | /cake/is_binary_search_tree.py | 1,496 | 4.125 | 4 | class BinaryTreeNode(object):
def __init__(self, value):
self.value = value
self.right = None
self.left = None
def insert_left(self, value):
self.left = BinaryTreeNode(value)
return self.left
def insert_right(self, value):
self.right = BinaryTreeNode(value)... | true |
caee4a4b0415440b3d790033e791762a8542fe5c | syeluru/MIS304 | /basic.py | 696 | 4.125 | 4 | # Program to demonstrate basic python statements
print("Welcome to Python Programming")
message = "Welcome to Python Programming!!!"
print (message)
print(type(message))
# message is a variable of type str
number = 25
print (number)
print (type(number))
# number is a variable of type num
price = 12.99
print (price)... | true |
93842a724512bb1c706efd214c07bde85f43809d | syeluru/MIS304 | /ComputeArea.py | 1,693 | 4.40625 | 4 | #program to compute area
"""
length = 20
width = 5
area = length * width
print (type(length))
print (type(width))
print (area)
print (type(area))
length = 12.8
width = 5.6
area = length * width
print (type(area))
print (area)
#f is format specifier for floating numbers
#.2 is two decimal places
print ("Area = %.3f... | true |
9abd36a53d1ac0e7ce8192da50de38e489016ab4 | yurifarias/CursoEmVideoPython | /ex059.py | 1,187 | 4.34375 | 4 | # Crie um programa que leia dois
# valores e mostre um menu como o
# ao lado na tela:
# Seu programa deverá realizar a
# operação solicitada em casa caso.
#
# [1] somar
# [2] multiplicar
# [3] maior
# [4] novos números
# [5] sair do programa
num1 = float(input('Digite o primeiro número: '))
num2 = float(input('Digite ... | false |
c879dfea0085fb99c3e0b55adcb2c91d5767e7ed | yurifarias/CursoEmVideoPython | /ex016.py | 405 | 4.1875 | 4 | from math import floor, trunc
número = float(input('Digite um número decimal: '))
'''# Convertendo para int
print('A porção inteira do número {} é {}'.format(número, int(número)))'''
# Usando math.floor()
print('A porção inteira do número {} é {}'.format(número, floor(número)))
'''# Usando math.trunc()
print('A por... | false |
d3f8cad90b395b080a6317319d6b9e8837f1e5ff | yurifarias/CursoEmVideoPython | /ex060.py | 266 | 4.1875 | 4 | # Faça um programa que leia um número
# qualquer e mostre o seu fatorial.
#
# Ex:
# 5! = 5 * 4 * 3 * 2 * 1 = 120
fatorial = 1
num = int(input('Digite um número para se calcular o seu fatorial: '))
while num > 0:
fatorial *= num
num -= 1
print(fatorial)
| false |
363096b85d7fec25acae5e64105c09c2b4fd8b1d | Will-Fahie/stack-implementation | /stack.py | 1,713 | 4.125 | 4 | class Stack(object):
def __init__(self, max_size):
self.__items = []
self.__reverse_stack = []
self.__max_size = max_size
def is_full(self):
return len(self.__items) == self.__max_size
def is_empty(self):
return len(self.__items) == 0
def print_stack(self):
... | false |
a7301fbb2f49e5c3d6bfcba808ee87687797796b | spencerf2/coding_temple_task3_answers | /question3.py | 426 | 4.34375 | 4 | # Question 3
# ----------------------------------------------------------------------
# Please write a Python function, max_num_in_list to return the max
# number of a given list. The first line of the code has been defined
# as below.
# ----------------------------------------------------------------------
# def ma... | true |
93de2ea8bac4cc7070de874a254ff6668c284cb9 | jeffreytzeng/HackerRank | /Algorithms/Sorting/Insertion Sort - Part 1/my_solution.py | 569 | 4.21875 | 4 | def PrintArray(arr):
"""Printing each array elements."""
for i in range(len(arr)):
print(str(arr[i]) + ' ' if i != len(arr)-1 else str(arr[i]), end='')
def Sort(arr):
"""Sorting array by ascending."""
for i in reversed(range(len(arr))):
key = arr[i]
j = i-1
whi... | false |
393c9787c87ac3ec229da96a87d394fd681b744b | laxos90/MITx-6.00.1x | /Problem Set 2/using_bisection_search.py | 1,425 | 4.46875 | 4 | __author__ = 'm'
"""
This program uses bisection search to find out the smallest monthly payment such that
we can pay off the entire balance within a year.
"""
from paying_debt_off_in_a_year import compute_balance_after_a_year
def compute_initial_lower_and_upper_bounds(balance, annual_interest_rate):
monthly_in... | true |
5a23a290af8452c425a290c8201146b14cc7081f | badladpancho/Python_103 | /While_loop.py | 204 | 4.34375 | 4 | # This is the basic to a while loop
# will loop through until it is false
# This is like it is done in C programing
i = 0
while i <= 10:
print(i);
i += 1;
print("Done with this loop") | true |
ccaca618954119e58e0d107e36cd5ce48be68e0c | badladpancho/Python_103 | /Guessing_Game.py | 692 | 4.25 | 4 | # This is going to be a simple game in order to guess
# We are going to be using if statments while loops and other things that i have
# learned.
# MADE BY BADLADPANCHO
print("Player 1 enter the secret word\n");
secret_word = input("");
print("OK lets play!");
guess = ""
i = 0;
chance_limit = 3;
w... | true |
df294dbacb1c93363b2c3e7a2b5a4a5b1470a116 | reddevil7291/Python | /Program to find the sum of n natural 2.py | 302 | 4.125 | 4 | print("Program to Find the sum of n Natural Numbers")
n = eval(input("\nEnter the value of n:"))
sum = float
if(not isinstance(n,int)):
print("\nWRONG INPUT")
else:
if(n<=0):
print("\nERROR")
else:
sum1 = (n*(n+1))/2
print("The sum is ",sum1)
| true |
93ceca59795a7577174652ea4ef9e81ffc46d7a4 | Mark24Code/python_data_structures_and_algorithms | /剑指offer/37_FirstCommonNodesInLists(两个链表的第一个公共结点).py | 2,598 | 4.3125 | 4 | """
面试题37:两个链表的第一个公共结点
题目:输入两个链表,找出它们的第一个公共结点。链表结点定义如下:
https://leetcode.com/problems/intersection-of-two-linked-lists/
思路:
两个链表连接以后,之后的节点都是一样的了。
1. 使用两个栈push 所有节点,然后比较栈顶元素,如果一样就 都 pop继续比较。如果栈顶不一样,结果就是上一次 pop 的值。
2. 先分别遍历两个链表,找到各自长度,然后让一个链表先走 diff(len1-len2)步骤,之后一起往前走,找到的第一个就是。
"""
# Definition for singly-linked... | false |
d135fd7ec20c5ad900a18256337f55c4272b4bb5 | Galyopa/SoftServe_Marathon | /Sprint_05/question04.py | 1,879 | 4.5625 | 5 | """
Question text
Write the function check_number_group(number) whose input parameter is a number.
The function checks whether the set number is more than number 10:
in case the number is more than 10 the function should be displayed the corresponding message -
"Number of your group input parameter of function is v... | true |
f01841425d4f7d890e3f170bfb7cdefcf53c28bf | Galyopa/SoftServe_Marathon | /Sprint_03/question3.py | 2,039 | 4.3125 | 4 | """
Create function create_account(user_name: string, password: string, secret_words: list).
This function should return inner function check.
The function check compares the values of its arguments with password and secret_words:
the password must match completely, secret_words may be misspelled (just one element).
... | true |
4fa8cd4350ce3c53c4c3b861463a461962633197 | dkhroad/fuzzy-barnacle | /prob2/string_validator.py | 2,026 | 4.40625 | 4 | class StringValidator(object):
'''validate a string with brackes and numbers'''
def validate_brackets(self,s):
''' ensures that string s is valid
:type s: str
:rtype: bool
valiation criteria:
- the string only contains the followin characters
... | true |
554b090af2ba3bc3040e9e9acccf883928375c9c | dariclim/python_problem_exercises | /Directions_Reduction.py | 2,372 | 4.1875 | 4 | """
Once upon a time, on a way through the old wild west, a man was given directions
to go from one point to another.
The directions were "NORTH", "SOUTH", "WEST", "EAST".
Clearly "NORTH" and "SOUTH" are opposite, "WEST" and "EAST" too.
Going to one direction and coming back the opposite direction is a needless eff... | true |
8bf7fbff0e0776f7af28af9627c2ebf9dbd6a32d | sohaib-93/SOIS_Assingment | /Embedded_Linux/Part_A/prog9.py | 833 | 4.40625 | 4 | # !/usr/bin/python3
# Python Assignment
# Program 9: Implement a python code to count a) number of characters b) numbers of words c) number of lines from an input file to output file.
f = open("finput.txt", "r+")
text = f.read().splitlines()
lines = len(text) # length of the list = number of lines
words = sum(len(li... | true |
211d6ce07287364d6800a059625419ac93e88e12 | sohaib-93/SOIS_Assingment | /Embedded_Linux/Part_A/prog3.py | 769 | 4.53125 | 5 | # !/usr/bin/python3
# Python Assignment
# Program 3: Implement a python code to find the distance between two points.(Euclidian distance)
# Formula for Euclidian distance, Distance = sqrt((x2-x1)^2 + (y2-y1)^2)
def edist(x1,y1,x2,y2):
dist1 = (x2-x1)**2 + (y2-y1)**2
dist = dist1**0.5
return dist
x1 = float(input("... | true |
7d95ce35091a63117f24f34c936b485f9af5917e | sohaib-93/SOIS_Assingment | /Embedded_Linux/Part_A/prog8.py | 497 | 4.28125 | 4 | # !/usr/bin/python3
# Python Assignment
# Program 8: Implement a python code to solve quadratic equation.
# Quadratic Equation Formula: x = b^2 + (sqrt(b^2 - 4ac) / 2a) or b^2 - (sqrt(b^2 - 4ac) / 2a)
print ("ax^(2)+bx+c")
a = int(input("Enter the value of a:"))
b = int(input("Enter the value of b:"))
c = int(input("E... | true |
b9b98dc058b1f05f3833d3af575f9cea85292539 | lxwc/python_start | /if_else.py | 633 | 4.28125 | 4 | age = 12
if age >= 18:
print('your age is',age)
print('adult')
else:
print('your age is',age)
print('teenager')
if age >= 18:
print('adult')
elif age >= 6: #elif is else if abbreviation
print('teenager')
else:
print('kid')
height = input("Please input your height:")
if int(height) >= 180:
print('ta... | false |
9d0a50a37674344e868b687f47b9f4eeef8748fe | jtwray/cs-module-project-hash-tables | /applications/crack_caesar/sortingdicts-kinda.py | 2,932 | 4.59375 | 5 | # Can you sort a hash table?
## No!
## the hash function puts keys at random indices
# Do hash tables preserve order?
## NO
## [2, 3, 4, 5]
# my_arr.append(1)
# my_arr.append(2)
# my_arr.append(3)
# [1, 2, 3]
# my_hash_table.put(1)
# my_hash_table.put(2)
# my_hash_table.put(3)
## *Dictionary
### Yes
### Since Pyt... | true |
9bb8498290f491440011fda2ab93b2f20570d4df | petercripps/learning-python | /code/time_check.py | 368 | 4.25 | 4 | # Use date and time to check if within working hours.
from datetime import datetime as dt
start_hour = 8
end_hour = 22
def working_hours(now_hour):
if start_hour < now_hour < end_hour:
return True
else:
return False
if working_hours(dt.now().hour):
print("It is during work hou... | true |
ea9084b8b4da109d9d364e0c7fc44f961e8ceedc | emmagordon/python-bee | /group/reverse_words_in_a_string.py | 602 | 4.28125 | 4 | #!/usr/bin/env python
"""Write a function, f, which takes a string as input and reverses the
order of the words within it.
The character order within the words should remain unchanged.
Any punctuation should be removed.
>>> f('')
''
>>> f('Hello')
'Hello'
>>> f('Hello EuroPython!')
'EuroPython Hello'
>>> f('The cat s... | true |
49ce4c0bc77b3f0eca3a3f93435b108cedd1e3c8 | xuanngo2001/python-examples | /is_py.py | 255 | 4.15625 | 4 | #!/bin/python3
obj = 1
if type(obj) == int:
print("Integer")
obj = 12.2312
if type(obj) == float:
print("Float")
obj = 12.3213
if type(obj) == int or type(obj) == float:
print("It is a number")
else:
print("It is NOT a number") | false |
8d142982d667457fcf063bef95064599a5d51fe0 | Mujeeb-Shaik/Python_Assignment_DS-AIML | /13_problem.py | 1,966 | 4.1875 | 4 | """
You found two items in a treasure chest! The first item weighs weight1 and is worth value1,
and the second item weighs weight2 and is worth value2. What is the total maximum value
of the items you can take with you, assuming that your max weight capacity is maxW and
you can't come back for the items later?
Not... | true |
c20cfc1512539c2a887b763369e0e1d64211e839 | mani5348/Python | /Day3/Exits_key.py | 270 | 4.3125 | 4 | #write a Program to Check if a Given Key Exists in a Dictionary or Not
dict1={'Manish':1,'Kartik':2,'Shubham':3,'Yash':3,'Aman':4}
key=input("enter the key values what we want to check:")
if key in dict1.keys():
print("Exists")
else:
print("Not Exists")
| false |
be1bb2b7b2fa490f0a1c170ad281088047576532 | mani5348/Python | /Day3/Sum_Of_Values.py | 288 | 4.25 | 4 | #write a Program to Sum All the Items in a Dictionary
n=int(input("Enter the no. of keys :"))
dict1={}
for i in range(1,n+1):
key=input("enter key values:")
value=int(input("enter the values of keys:"))
dict1.update({key:value})
sum1=sum(dict1.values())
print(sum1)
| true |
bbd4be4c2712c6e488b9a70a809032560e1f35d9 | mani5348/Python | /Day3/Bubble_sort.py | 353 | 4.28125 | 4 | #write a program to Find the Second Largest Number in a List Using Bubble Sort
list1=[9,3,6,7,4,5,8]
length=len(list1)
for i in range(0,length):
for j in range(0,length-i-1):
if(list1[j]>list1[j+1]):
temp=list1[j]
list1[j]=list1[j+1]
list1[j+1]=temp
print("Second... | true |
287ca547d96ce97e69e1f4d78a8647cdb9b11ffc | bishalpokharel325/python7am | /sixth day to 9th day/codewithharry decorators.py | 2,253 | 4.5 | 4 | """Decorators modify functionality of function."""
"""1. function can be assigned into another variable which itself act as a function"""
def funct1(x,y):
print(x+y)
funct2=funct1
funct2(5,6)
"""2. function lai assigned garisakexi org funct lai delete garda will funct2 also get deleted?"""
def funct3(x,y):
pr... | true |
93ca28d208ff5af73eb00b39535a17cc97092572 | mubar003/bcb_adavnced_2018 | /bcb.advanced.python.2018-master/review/functions.py | 727 | 4.25 | 4 | '''
Paul Villanueva
BCBGSO 2018 Advanced Python Workshop
'''
# The function below squares a number. Run this code and call it on a
# couple different numbers.
def square(n):
return n * n
# Write a function named cube that cubes the input number.
# Define a function square_area that takes the width... | true |
5f5163b99870b9fac1d95f483fb9b64f346e7db2 | VinneyJ/alx-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 645 | 4.1875 | 4 | #!/usr/bin/python3
"""Contains definition of text_indentation() function"""
def text_indentation(text):
"""Print given text with 2 new lines after '.', '?', and ':' characters.
Args:
text (str): Text to be formatted.
"""
if not isinstance(text, str):
raise TypeError("text must be a st... | true |
9443bf14f31969ad00955eacf6b01164fd37f39d | the-code-matrix/python | /unit6/practice/Unit6_Dictionaries_practice.py | 1,679 | 4.5 | 4 | #!/usr/bin/python
# 1. Write a program to map given fruit name to its cost per pound.
#Solution:
item_cost={ 'banana': 0.69,
'apple' : 1.29,
'pear' : 1.99,
'grapes' : 2.49,
'cherries' : 3.99 }
print("Cost of apple per lb is: ",item_cost['apple'])
print("Cost of grapes ... | true |
8aef5e8d21ab0f028466b88aa7c7c24ed85b5501 | the-code-matrix/python | /unit1/practice/echo.py | 320 | 4.5625 | 5 | # Create a program that prompts the
# user to enter a message and echoes
# the message back (by printing it).
# Your program should do this 3 times.
message_1 = input("Enter message 1: ")
print(message_1)
message_2 = input("Enter message 2: ")
print(message_2)
message_3 = input("Enter message 3: ")
print(message_3) | true |
5a3eb2642017b2adf55a16bd1aa2d939ea65c3f3 | raptogit/python_simplified | /Programs/06_operators.py | 1,196 | 4.46875 | 4 | # #Arithmetic Operators ::
a=5 #Addition operator
b=3
c=a+b
print(c)
s=8-5 #Substraction operator
print(s)
print(9*2) #Multiplication Operator
print(6/3) #division Operator
print(13%3) #Modulus operat... | true |
de9529d4f66915a08b636c0c112185a455119c9d | jabc1/ProgramLearning | /python/python-Michael/ErrorPdbTest/debug.py | 2,448 | 4.25 | 4 | # -*- coding: utf-8 -*-
# 调试
# 1.简单粗暴:print()把可能有问题的变量打印出来
def fn(s):
n = int(s)
print('>>> n = %d' % n)
return 10 / n
def main():
fn('0')
main()
# 用print()最大的坏处是将来还得删掉它,想想程序里到处都是print(),运行结果也会包含很多垃圾信息
# 2.断言(assert)
# 用断言(assert)替代print()辅助查看的地方
def fn(s):
n = int(s)
assert n != 0, 'n is zero!'
return ... | false |
dbc534f073b45146d9be6f04d243320051cad014 | jabc1/ProgramLearning | /python/python-Michael/functionProgramming/higherfunction.py | 1,469 | 4.125 | 4 | # 函数式编程
#函数式编程就是一种抽象程度很高的编程范式,纯粹的函数式编程语言编写的函数没有变量,因此,任意一个函数,只要输入是确定的,输出就是确定的,这种纯函数我们称之为没有副作用
#允许使用变量的程序设计语言,由于函数内部的变量状态不确定,同样的输入,可能得到不同的输出,因此,这种函数是有副作用的。
# 函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数!
#Python对函数式编程提供部分支持。由于Python允许使用变量,因此,Python不是纯函数式编程语言。
# 高阶函数英文叫Higher-order function
abs(-10) #abs(-10)是函数调用,而abs是函... | false |
8f931bb230cddf47e94a2cf3be03a41501ae6090 | aash-beg/CoderApprentice | /Exercises/Chapter 01-09/Ex 5.3.py | 318 | 4.28125 | 4 | num1 = float(input('1st number: '))
num2 = float(input('2nd number: '))
num3 = float(input('3rd number: '))
large = max(num1, num2, num3)
small = min(num1, num2, num3)
avg = (num1 + num2 + num3)/3
print('Largest number is {0}\n'
'Smallest number is {1}\n'
'Average is {2:.2f}'.format(large, small, avg))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.