blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
6a29cb24698e9390ac9077d431d6f9001386ed84 | lakshay-saini-au8/PY_playground | /random/day26.py | 1,164 | 4.28125 | 4 |
# Write a program to find a triplet that sums to a given value with improved time complexity.
'''
Input: array = {12, 3, 4, 1, 6, 9}, sum = 24;
Output: 12, 3, 9
Explanation: There is a triplet (12, 3 and 9) present
in the array whose sum is 24.
'''
# brute force apporach
def triplet(arr, sums):
n = len(arr)
... | true |
fce872e76b3da0255f503a85d718dc36fd739dd6 | Niraj-Suryavanshi/Python-Basic-Program | /7.chapter/12_pr_03.py | 224 | 4.125 | 4 | num=int(input("Enter a number: "))
prime=True
for i in range(2,num):
if(num%i==0):
prime=False
break
if prime:
print("Number is prime")
else:
print("Number is not prime")
| true |
8d15cc01aa2db01da9ea285fc234cae188e5c0cf | Niraj-Suryavanshi/Python-Basic-Program | /3.chapter/06_pr_02.py | 210 | 4.40625 | 4 | letter='''Dear <|Name|>
you are selected
date: <|date|>'''
name=input("Enter your name:")
date=input("Enter a date:")
letter=letter.replace("<|Name|>",name)
letter=letter.replace("<|date|>",date)
print(letter) | false |
69f491abbf9b757d6dc5b7fe6d5e7cd925785389 | flerdacodeu/CodeU-2018-Group8 | /cliodhnaharrison/assignment1/question1.py | 896 | 4.25 | 4 | #Using Python 3
import string
#Input through command line
string_one = input()
string_two = input()
def anagram_finder(string_one, string_two, case_sensitive=False):
anagram = True
if len(string_one) != len(string_two):
return False
#Gets a list of ascii characters
alphabet = list(string.pr... | true |
c425fd70a75756fa84add2f21f7593b8e91b1203 | flerdacodeu/CodeU-2018-Group8 | /aliiae/assignment3/trie.py | 2,519 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Optional follow-up:
Implement a dictionary class that can be constructed from a list of words.
A dictionary class with these two methods:
* isWord(string): Returns whether the given string is a valid word.
* isPrefix(string): Returns whether the given string is a pr... | true |
6ddf930b444a33d37a4cc79308577c45cf45af96 | Saraabd7/Python-Eng-54 | /For_loops_107.py | 1,117 | 4.21875 | 4 | # For loops
# Syntax
# for item in iterable: mean something you can go over for e.g: list
# block of code:
import time
cool_cars = ['Skoda felicia fun', 'Fiat abarth the old one', 'toyota corola, Fiat panda 4x4', 'Fiat Multipla']
for car in cool_cars:
print(car)
for lunch_time in cool_cars:
print(car)
... | true |
933c9d74c3dee9ac64fefe649af9aba3dcffce02 | dmonzonis/advent-of-code-2017 | /day24/day24.py | 2,809 | 4.34375 | 4 | class Bridge:
"""Represents a bridge of magnetic pieces.
Holds information about available pieces to construct the bridge, current pieces used
in the bridge and the available port of the last piece in the bridge."""
def __init__(self, available, bridge=[], port=0):
"""Initialize bridge variabl... | true |
a68e2b0be94ba93bb4e9d123c55af80297ddc5d6 | dmonzonis/advent-of-code-2017 | /day19/day19.py | 1,866 | 4.34375 | 4 | def step(pos, direction):
"""Take a step in a given direction and return the new position."""
return [sum(x) for x in zip(pos, direction)]
def turn_left(direction):
"""Return a new direction resulting from turning 90 degrees left."""
return (direction[1], -direction[0])
def turn_right(direction):
... | true |
73521ec81d51bc78eeda2c636402f9be0e796776 | mahidhar93988/python-basics-nd-self | /difference_sum_even_odd_index.py | 539 | 4.125 | 4 | # difference_sum_even_odd_index
# You should name your function as difference_sum_even_odd_index
# It should take a list of integers
# Return an integer
def difference_sum_even_odd_index(arr):
e = 0
o = 0
for i in range(len(arr)):
if i % 2 == 0:
e += arr[i]
else:
... | false |
e140bd8915d97b4402d63d2572c056e61a0d9e5a | presstwice/Python- | /data_camp/simple_pendulum.py | 487 | 4.1875 | 4 | # Initialize offset
offset = -6
# Code the while loop
while offset != 0 :b # The goal is to get offset to always equal 0
print("correcting...") # Prints correcting to clearly state the loop point
if offset > 0: # You start the if statement by checking if the offset is positive
offset = offset - 1 # If... | true |
d22f5a9a6851525504cc7e4f1952a2bbb8ab27ae | BalaRajendran/guvi | /large.py | 336 | 4.21875 | 4 | print ("Find the largest number amoung three numbers");
num=list()
arry=int(3);
a=1;
for i in range(int(arry)):
print ('Num :',a);
a+=1;
n=input();
num.append(int(n))
if (num[0]>num[1] and num[0]>num[2]):
print (num[0]);
elif (num[1]>num[0] and num[1]>num[2]):
print (num[1]);
else:
prin... | true |
ca0409110b5846759427529b9a487ea95a84dadc | Sandhya-02/programming | /0 Python old/09_sandeep_milk_using_list.py | 504 | 4.15625 | 4 | """
mummy and sandeep went for shopping
sandeep trolley lo [eggs , meat,small milk packet, bread,jam,] teskocchadu
mummy said get big milk packet
sandeep small milk packet ni teesesi big milk packet bag lo pettukunnadu
"""
list = ["eggs","meat","small milk packet","bread","jam"]
print(list)
if "small milk packet" in... | false |
5e0c461e5b4d1f9e6c328dcc78d88b5c8a08d410 | UWPCE-PythonCert-ClassRepos/220-Advanced-Summer-2019 | /students/AndrewMiotke/lesson04/class_work/generators.py | 466 | 4.21875 | 4 | """
Generators are iterators that returns a value
"""
def y_range(start, stop, step=1):
""" Create a generator using yield """
i = start
while i < stop:
"""
yield, like next(), allows you to increment your flow control
e.g. inside a loop
"""
yield i
i += step... | true |
bb0828b74f6eb99c20ffc39e3cae82f0816ada65 | droidy12527/AlgorithmsInPythonandCpp | /anargrams.py | 409 | 4.125 | 4 |
def findAnargrams(arr):
answers = []
m = {}
for elements in arr:
make = ''.join(sorted(elements))
if make not in m:
m[make] = []
m[make].append(elements)
for hello in m.values():
answers.append(hello)
return answers
arr = [ "eat", "tea", "tan", "ate", ... | false |
2948bcec98743ca4b12feb2828c6337ce22673ae | ishmatov/GeekBrains-PythonBasics | /lesson03/task_03_03.py | 840 | 4.1875 | 4 | """
3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших
двух аргументов.
"""
def check_num(value):
try:
return True, int(value)
except ValueError:
print("Не число. Попробуйте ещё раз")
return False, -1
def sum_doble_max(num1, n... | false |
6c3c8bbae37317462a202481c0474008869186c5 | ishmatov/GeekBrains-PythonBasics | /lesson01/task_01_06.py | 1,914 | 4.1875 | 4 | """
6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, на который
общий результат спортсмена составить не менее b километров. Программа должна принимать значения п... | false |
603e12a667b8908776efbfef8d015c5e12b390c8 | Super1ZC/PyTricks | /PyTricks/use_dicts_to_emulate_switch_statements.py | 761 | 4.375 | 4 | def dispatch_if(operator,x,y):
"""This is similar to calculator"""
if operator == 'add':
return x+y
elif operator == 'sub':
return x-y
elif operator == 'mul':
return x*y
elif operator == 'div':
return x/y
else:
return None
def dispatch_dict(operat... | true |
1af51d9ed56217484ab6060fc2f36ee38e9523df | rgvsiva/Tasks_MajorCompanies | /long_palindrome.py | 560 | 4.21875 | 4 | #This was asked by AMAZON.
#Given a string, find the longest palindromic contiguous substring.
#if there are more than one, prompt the first one.
#EX: for 'aabcdcb'-->'bcdcb'
main_St=input("Enter the main string: ")
st=main_St
palindrome=[st[0]]
while len(st)>1:
sub=''
for ch in st:
sub+=ch
... | true |
78c17dc8b972e01ea7641e37fdcd4d35222ae513 | GandT/learning | /Python/season2/p015-016/p016.py | 987 | 4.28125 | 4 | # coding: UTF-8
"""
2018.4.13
指定された月の日数を返す(閏年を考慮)
"""
def day_of_month(year, month):
# 不正な月が指定された場合Noneを返す
if type(year) != int or type(month) != int or not(1 <= month <= 12):
return None
# 2月を除くハッシュテーブル(辞書)の作成
table = {
1: 31, 2: -1, 3: 31, 4: 30, 5: 31, 6: 30,
7: ... | false |
b6aca7b55b08724d2a922f3788cc2b15c4465f8e | webclinic017/davidgoliath | /Project/modelling/17_skewness.py | 1,280 | 4.125 | 4 | # skewness python
# https://www.google.com/search?q=skewness+python&oq=Skewness+python&aqs=chrome.0.0l4j0i22i30l6.3988j0j4&sourceid=chrome&ie=UTF-8
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html
# https://www.geeksforgeeks.org/scipy-stats-skew-python/
''' Statistical functions
In simple w... | true |
920fbc4957ec799af76035cbb258f2f41392f030 | Reskal/Struktur_data_E1E119011 | /R.2.4.py | 1,096 | 4.5625 | 5 | ''' R-2.4 Write a Python class, Flower, that has three instance variables of type str,
int, and float, that respectively represent the name of the flower, its number of petals, and its price. Your class must include a constructor method
that initializes each variable to an appropriate value, and your class should
in... | true |
de037860649e57eab88dc9fd8ae4cdab26fcb47a | sahilqur/python_projects | /Classes/inventory.py | 1,720 | 4.28125 | 4 | """
Simple python application for maintaining the product list in the inventory
"""
class product:
price, id, quantity = None, None, None
"""
constructor for product class
"""
def __init__(self, price, id, quantity):
self.price = price
self.id = id
self.quan... | true |
7279f2f62f5fab795ab14c5eaa8959fc8b1a1226 | gdgupta11/100dayCodingChallenge | /hr_nestedlist.py | 2,031 | 4.28125 | 4 | """
# 100daysCodingChallenge
Level: Easy
Goal:
Given the names and grades for each student in a Physics class of
students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
[["Gaurav",36], ["GG", 37.1], ["Rob", 42], ["Jack", 42]]
Note: If there are multiple students w... | true |
c93d362cfdbb5d7ff952181b68dda9d2b378d0c5 | Berucha/adventureland | /places.py | 2,813 | 4.375 | 4 | import time
class Places:
def __init__(self, life):
'''
returns print statements based on the user's input (car color)
and adds or takes away life points accordingly
'''
#testing purposes:
# print('''In this minigame, the user has been walking along to Adventurland.... | true |
d0d009499f6dd7f4194f560545d12f82f2b73db8 | starlinw5995/cti110 | /P4HW1_Expenses_WilliamStarling.py | 1,358 | 4.1875 | 4 | # CTI-110
# P4HW1 - Expenses
# William Starling
# 10/17/2019
#
# This program calculates the users expenses.
# Initialize a counter for the number of expenses entered.
number_of_expenses = 1
# Make a variable to control loop.
expenses = 'y'
# Enter the starting amount in your account.
account = float(i... | true |
3a0f1e27326226da336ceb45290f89e83bb1f781 | dosatos/LeetCode | /Easy/arr_single_number.py | 2,254 | 4.125 | 4 | """
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
Clarification ques... | true |
2fc808a248480a8840944c8e927ebdb2f23e854a | dosatos/LeetCode | /Easy/ll_merge_two_sorted_lists.py | 2,574 | 4.125 | 4 | """
Percentile: 97.38%
Problem:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Solution:
Change "pointers" as in merge sort algorithm.
Time Complexity = O(N+M)
Sp... | true |
066769bf25ea46c40333a8ddf2b87c35bfed4fae | arvindsankar/RockPaperScissors | /rockpaperscissors.py | 1,646 | 4.46875 | 4 | import random
def correct_input(choice):
while choice != "Rock" and choice != "Scissors" and choice != "Paper":
# corrects rock
if choice == "rock" or choice == "R" or choice == "r":
choice = "Rock"
# corrects scissors
elif choice == "scissors" or choice == "S" or choice == "s":
choice = "Scissors"
... | true |
fd2236eaf9f68b84c79bc5ea679231c8d1678210 | charuvashist/python-assignments | /assigment10.py | 2,992 | 4.34375 | 4 | '''Ques 1. Create a class Animal as a base class and define method animal_attribute. Create another class Tiger which is
inheriting Animal and access the base class method.'''
class Animal:
def animal_attribute(self):
print("This is an Animal Class")
class Tiger(Animal):
def display(self):
pr... | true |
a336d3cc2a6067b7716b502025456667631106d5 | joemmooney/search-text-for-words | /setup.py | 1,437 | 4.5625 | 5 | # This file is the main file for running this program.
import argparse
from fileReader import read_file
# The main function that is run when starting the program.
# It sets up argument parsing for the file name to read, the number of most common words to print,
# whether to return a json file, and the name for the js... | true |
cb8844bcac1c3fa02a35fbab9c6e8fd5c993cb74 | MysticSoul/Exceptional_Handling | /answer3.py | 444 | 4.21875 | 4 | # Program to depict Raising Exception
'''
try:
raise NameError("Hi there") # Raise Error
except NameError:
print "An exception"
raise # To determine whether the exception was raised or not
'''
'''Answer2.=> According to python 3.x
SyntaxError: Missing parentheses in call to print
... | true |
9aff241bff636fa31f64cc83cb35b3ecf379738a | devhelenacodes/python-coding | /pp_06.py | 621 | 4.125 | 4 | # String Lists
# Own Answer
string = input("Give me a word:\n")
start_count = 0
end_count = len(string) - 1
for letter in string:
if string[start_count] == string[end_count]:
start_count += 1
end_count -= 1
result = "This is a palindrome"
else:
result = "This is not a palindrome"
print(result)
# Learned... | true |
5ae27ed7ccb33a62bbb98ff56f51952d43eaaed6 | sergiofagundesb/PythonRandomStuff | /qualnome.py | 320 | 4.125 | 4 |
n1 = int(input('Digite um número'))
n2 = int(input('Digite mais um número'))
s=n1+n2
p=n1*n2
di=n1//n2
d=n1/n2
pot=n1**n2
mod=n1%n2
print('A soma é {},\n o produto é {},\n a divisão inteira é {},\n a divisão é {:.3f},\n a potência é {}\n e o resto {}'.format(s,p,di,d,pot,mod), end='====')
print('Cu é bom')
| false |
a176dbc8191e0cb82f1e2d93434a87327dfaaad6 | litojasonaprilio/CP1404-Practicals | /prac_01/extension_2.py | 520 | 4.125 | 4 | print("Electricity bill estimator 2.0", '\n')
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
tariff = int(input("Which tariff? 11 or 31: "))
while not (tariff == 11 or tariff == 31):
print("Invalid number!")
tariff = int(input("Which tariff? 11 or 31: "))
if tariff == 11:
price = TARIFF_11
else:
price = T... | false |
26fb03d7961e7a2d1c34fd0ef19b5ef2f6293061 | emeryberger/COMPSCI590S | /projects/project1/wordcount.py | 839 | 4.28125 | 4 | # Wordcount
# Prints words and frequencies in decreasing order of frequency.
# To invoke:
# python wordcount.py file1 file2 file3...
# Author: Emery Berger, www.emeryberger.com
import sys
import operator
# The map of words -> counts.
wordcount={}
# Read filenames off the argument list.
for filename in sys.argv[1:]... | true |
4cccd10c95689842e2fba8d256bd086bec47e32e | tkruteleff/Python | /6 - String Lists/string_lists.py | 295 | 4.125 | 4 | word = str(input("Type in a word "))
word_list = []
reverse_word_list = []
for a in word:
word_list.append(a)
print("One letter " + a)
reverse_word_list = word_list[::-1]
if(word_list == reverse_word_list):
print("Word is a palindrome")
else:
print("Word is not a palindrom")
| false |
84533ee76a2dc430ab5775fa00a4cc354dfc2238 | tkruteleff/Python | /16 - Password Generator/password_generator.py | 1,239 | 4.3125 | 4 | import random
#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 co... | true |
9777a2a85ad74c0cad75352fcded12ef838f3eb0 | echang19/Homework-9-25 | /GradeReport.py | 987 | 4.15625 | 4 | '''
Created on Mar 12, 2019
@author: Evan A. Chang
Grade Report
'''
def main():
studentList={'Cooper':['81','86', '90', '97'],'Jennie':['98', '79','99', '87', '82'], 'Julia':['87', '80','75', '10', '78']}
student=''
read=input("Would you like to access a student's grades?")
read.lower()
... | true |
2a1846f1de7daa7957dfbf272e16b185c344cfc2 | mittal-umang/Analytics | /Assignment-2/MultiplyMatrix.py | 1,194 | 4.3125 | 4 | # Chapter 11 Question 6
# Write a function to multiply two matrices
def multiply_matrix(left, right):
result = []
for i in range(len(left)):
innerMatrix = []
for j in range(len(left)):
sum = 0
for k in range(len(left)):
sum += left[i][k] * right[k][j]
... | false |
ed4293c4fcc473795705f555a305a4ee7c7a2701 | mittal-umang/Analytics | /Assignment-2/VowelCount.py | 977 | 4.25 | 4 | # Chapter 14 Question 11
# Write a program that prompts the user to enter a
# text filename and displays the number of vowels and consonants in the file. Use
# a set to store the vowels A, E, I, O, and U.
def main():
vowels = ('a', 'e', 'i', 'o', 'u')
fileName = input("Enter a FileName: ")
vowelCount = 0
... | true |
67593b7fcb04e87730e87066e587576fc3a88386 | mittal-umang/Analytics | /Assignment-1/PalindromicPrime.py | 1,189 | 4.25 | 4 | # Chapter 6 Question 24
# Write a program that displays the first 100 palindromic prime numbers. Display
# 10 numbers per line and align the numbers properly
import time
def isPrime(number):
i = 2
while i <= number / 2:
if number % i == 0:
return False
i += 1
return True
def... | true |
ab73985f340bdcafff532a601e84d268f849a7db | mittal-umang/Analytics | /Assignment-1/RegularPolygon.py | 1,258 | 4.25 | 4 | # Chapter 7 Question 5
import math
class RegularPolygon:
def __init__(self, numberOfSide=3, length=1, x=0, y=0):
self.__numberOfSide = numberOfSide
self.__length = length
self.__x = x
self.__y = y
def getNumberOfSides(self):
return self.__numberOfSide
def getLengt... | false |
cea462ca0b7bf4c088e1a2b035f26003052fcef2 | mittal-umang/Analytics | /Assignment-2/KeyWordOccurence.py | 1,328 | 4.40625 | 4 | # Chapter 14 Question 3
# Write a program that reads in a Python
# source code file and counts the occurrence of each keyword in the file. Your program
# should prompt the user to enter the Python source code filename.
def main():
keyWords = {"and": 0, "as": 0, "assert": 0, "break": 0, "class": 0,
... | true |
49837fed1d537650d55dd8d6c469e7c77bc3a4c6 | mittal-umang/Analytics | /Assignment-1/ReverseNumber.py | 502 | 4.28125 | 4 | # Chapter 3 Question 11
# Write a program that prompts the user to enter a four-digit integer
# and displays the number in reverse order.
def __reverse__(number):
reverseNumber = ""
while number > 0:
reverseNumber += str(number % 10)
number = number // 10
return reverseNumber
def main():... | true |
4bdeb3a2c137e5fa69998ca4503538302082cef0 | mittal-umang/Analytics | /Assignment-1/SineCosWave.py | 977 | 4.3125 | 4 | # Chapter 5 Question 53
# Write a program that plots the sine
# function in red and cosine in blue
import turtle
import math
def drawLine(x1, y1, x2, y2):
turtle.goto(x1, y1)
turtle.pendown()
turtle.goto(x2, y2)
turtle.penup()
def main():
drawLine(-360, 0, 360, 0)
drawLine(0, -150, 0, 150)
... | false |
c86efaf3ce656c67a47a6df3c036345d6e604001 | mittal-umang/Analytics | /Assignment-2/AccountClass.py | 1,428 | 4.1875 | 4 | # Chapter 12 Question 3
class Account:
def __init__(self, id=0, balance=100, annualinterestrate=0):
self.__id = id
self.__balance = balance
self.__annualInterestRate = annualinterestrate
def getMonthlyInterestRate(self):
return str(self.__annualInterestRate * 100) + "%"
def... | true |
692505ec86ff96fe6e96802c2b2cf6306e11e2e0 | mfnu/Python-Assignment | /Functions-repeatsinlist.py | 554 | 4.1875 | 4 | ''' Author: Madhulika
Program: Finding repeats in a list.
Output: The program returns the number of times the element is repeated in the list.
Date Created: 4/60/2015
Version : 1
'''
mylist=["one", "two","eleven", "one", "three", "two", "eleven", "three", "seven", "eleven"]
def count_frequency(myl... | true |
013cb916d56e94c09e5d0451ceff7c532c3a85cd | rustyhu/design_pattern | /python_patterns/builder.py | 1,028 | 4.125 | 4 | "Personal understanding: builder pattern emphasizes on the readability and user convenience, the code structure is not quite neat."
class BurgerBuilder:
cheese = False
pepperoni = False
lettuce = False
tomato = False
def __init__(self, size):
self.size = size
def addPepperoni(self):
... | true |
4cc5e4aa3463e07ce239339aac99d5821ec786a1 | ashok148/TWoC-Day1 | /program3.py | 423 | 4.34375 | 4 | #Program to swap two variable without using 3rd variable....
num1 = int(input("Enter 1st number : "))
num2 = int(input("Enter 2nd number : "))
print("Before swaping")
print("num1 = ",num1)
print("num2 = ",num2)
print("After swapping")
#LOGIC 1:- of swapping
# num1 = num1 + num2
# num2 = num1 - num2
# num1 = n... | true |
9878feed23238d5a152e08b2547b8db64d616a35 | send2manoo/All-Repo | /myDocs/pgm/python/ml/04-PythonMachineLearning/04-MatplotlibCrashCourse/01-LinePlot.py | 547 | 4.25 | 4 | '''
Matplotlib can be used for creating plots and charts.
The library is generally used as follows:
Call a plotting function with some data (e.g. plot()).
Call many functions to setup the properties of the plot (e.g. labels and colors).
Make the plot visible (e.g. show()).
'''
# The example below creat... | true |
849647385e43448924aa7108a5f4986015c0c88a | send2manoo/All-Repo | /myDocs/pgm/python/ml/03-MachineLearningAlgorithms/1-Baseline machine learning algorithms/2-Zero Rule Algorithm Classification.py | 1,166 | 4.125 | 4 | from random import seed
from random import randrange
# zero rule algorithm for classification
def zero_rule_algorithm_classification(train, test):
output_values = [row[-1] for row in train]
print 'output=',output_values
print "set=",set(output_values)
prediction = max(set(output_values), key=output_values.count)
... | true |
57a99993916020b5c5780236c8efb052974c51b0 | wuxu1019/1point3acres | /Google/test_246_Strobogrammatic_Number.py | 908 | 4.15625 | 4 | """
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Write a function to determine if a number is strobogrammatic. The number is represented as a string.
Example 1:
Input: "69"
Output: true
Example 2:
Input: "88"
Output: true
Example 3:
Input: "962"
Outp... | true |
a59fc3330c0cb851e43252c9f54c47f2ce2c175e | mennanov/problem-sets | /dynamic_programming/palindromic_subsequence.py | 2,379 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
A subsequence is palindromic if it is the same whether read left to right or right to left. For
instance, the sequence
A, C, G, T, G, T, C, A, A, A, A, T, C, G
has many palindromic subsequences, including A, C, G, C, A and A, A, A, A (on the other hand,
the subsequence A, C, T is not palin... | false |
bcb7788af7663d0e9c52057795c5f62acc349ba1 | mennanov/problem-sets | /other/strings/string_all_unique_chars.py | 1,371 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Implement an algorithm to determine if a string has all unique characters.
"""
def all_unique_set(string):
"""
Running time and space is O(N).
"""
return len(string) == len(set(string))
def all_unique_list(string):
"""
Running time is O(N), space is O(R) where R ... | true |
24a138a887902e511570cb744aae827d3b19409d | vatsaashwin/PreCourse_2 | /Exercise_4.py | 969 | 4.4375 | 4 | # Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) >1:
# find middle and divide the array into left and right
m = len(arr) //2
L = arr[:m]
R = arr[m:]
# print(L, R)
# recursively sort the left and right halves
mergeSort(L)
mergeSort(R)
i=j=k=0
... | false |
367e5bcdd755649dbedac19066b4f77e3a1293d7 | suminb/coding-exercise | /daily-interview/binary_tree_level_with_minimum_sum.py | 1,516 | 4.125 | 4 | # [Daily Problem] Binary Tree Level with Minimum Sum
#
# You are given the root of a binary tree. Find the level for the binary tree
# with the minimum sum, and return that value.
#
# For instance, in the example below, the sums of the trees are 10, 2 + 8 = 10,
# and 4 + 1 + 2 = 7. So, the answer here should be 7.
#
# ... | true |
7cd442736a1d68ef5e38bdb4927f7b02f2180c3f | zgaleday/UCSF-bootcamp | /Vector.py | 2,932 | 4.53125 | 5 | class Vector(object):
"""Naive implementation of vector operations using the python list interface"""
def __init__(self, v0):
"""
Takes as input the two vectors for which we will operate on.
:param v0: A 3D vector as either a python list of [x_0, y_0, z_0] or tuple of same format
... | true |
bf320a4a3eb4a61dbc1f485885196c0067208c94 | cs-fullstack-2019-fall/python-classobject-review-cw-LilPrice-Code-1 | /index.py | 1,852 | 4.28125 | 4 | def main():
pro1()
pro2()
# Problem 1:
#
# Create a Movie class with the following properties/attributes: movieName, rating, and yearReleased.
#
# Override the default str (to-String) method and implement the code that will print the value of all the properties/attributes of the Movie class
#
#
# Assign a value... | true |
1591a5a8e525549a24ed11f49346c6b207b2ef7c | Anthncara/MEMO | /python/coding-challenges/cc-001-convert-to-roman-numerals/Int To Roman V2.py | 896 | 4.28125 | 4 | print("### This program converts decimal numbers to Roman Numerals ###",'\nTo exit the program, please type "exit")')
def InttoRoman(number):
int_roman_map = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'),\
(50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1... | true |
f0eb2a695f110c0f81777d0d6c64b60a003fcc51 | chetan113/python | /moreprograms/rightangletriangle.py | 270 | 4.21875 | 4 | """" n = int(input("enter a number of rows:"))
for i in range(1,n+1):
for j in range(1,i+1):
print(" * ",end ="")
print()"""
"""one for loop statement"""
n =int(input("enter the number of rows:"))
for i in range(1,n+1):
print(" $ "*i)
| false |
eebd301ffac344f8fe7bdf16a8cf9677bb542d3a | G00398275/PandS | /Week 05 - Datastructures/prime.py | 566 | 4.28125 | 4 | # This program lists out the prime numbers between 2 and 100
# Week 05, Tutorial
# Author: Ross Downey
primes = []
upto = 100000
for candidate in range (2, upto):
isPrime = True # Required only to check if divisible by prime number
for divisor in primes: # If it is divisible by an integer it isn't a prime num... | true |
75a5d8161498d62cbdce415742715a9baac22543 | G00398275/PandS | /Week 02/hello3.py | 235 | 4.21875 | 4 | # Week 02 ; hello3.py, Lab 2.2 First Programs
# This program reads in a person's name and prints out that persons name using format
# Author: Ross Downey
name = input ("Enter your name")
print ('Hello {} \nNice to meet you'.format (name)) | true |
a0986698fa2430008eb4d33ebf02b50e933fc09c | G00398275/PandS | /Week 03/Lab 3.3.1-len.py | 270 | 4.15625 | 4 | # Week 03: Lab 3.3.1 Strings
# This program reads in a strings and outputs how long it is
# Author: Ross Downey
inputString = input ('Please enter a string: ')
lengthOfString = len(inputString)
print('The length of {} is {} characters' .format(inputString, lengthOfString)) | true |
8ff8959b62adcc0f3455ca00c1e9108a16fbf97e | G00398275/PandS | /Week 03/Lab 3.3.3 normalize.py | 575 | 4.46875 | 4 | # Week 03: Lab 3.3.2 Strings
# This program reads in a string and removes any leading or trailing spaces
# It also converts all letters to lower case
# This program also outputs the length of the original string
# Author: Ross Downey
rawString = input("Please enter a string: ")
normalisedString = rawString.strip().low... | true |
59fc57e8d10d9f71c59999d297edfaf310676efd | G00398275/PandS | /Week 04-flow/w3Schools-ifElse.py | 1,257 | 4.40625 | 4 | # Practicing ifElse loops, examples in https://www.w3schools.com/python/python_conditions.asp
# Author: Ross Downey
a = 33
b = 200
if b > a: # condition is IF b is greater than a
print("b is greater than a") # Ensure indentation is present for print, i.e. indent for condition code
a = 33
b = 33
if b > a:
print("b... | true |
2e60abd703a5013e8ee5f7d2ce30b066833a7872 | arnavgupta50/BinarySearchTree | /BinaryTreeTraversal.py | 1,155 | 4.3125 | 4 | #Thsi Program traverses the Binary Tree in 3 Ways: In/Post/Pre-Order
class Node:
def __init__ (self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
else:
if root.val==key:
retu... | true |
e6657c32a76d198d60ad812ef1fc5587e8a74465 | subham-paul/Python-Programming | /Swap_Value.py | 291 | 4.1875 | 4 | x = int(input("Enter value x="))
y = int(input("Enter value y="))
print("The value are",x,"and",y)
x = x^y
y = x^y
x = x^y
print("After the swapping value are",x,"and",y)
"""Enter value x=10
Enter value y=20
The value are 10 and 20
After the swapping value are 20 and 10
"""
| true |
eafda40ba1154d3f8d02c01d9b827f93f3d7edc6 | audflexbutok/Python-Lab-Source-Codes | /audrey_cooper_501_2.py | 1,788 | 4.3125 | 4 | # Programmer: Audrey Cooper
# Lab Section: 502
# Lab 3, assignment 2
# Purpose: To create a menu driven calculator
# set calc equal to true so it runs continuously
calc = True
while calc == True:
# adds two numbers
def add(x, y):
return x + y
# subtracts two numbers
def subtract... | true |
71c813eeaea12d9f0b3791bbbf7c2c92fcaf391f | dedx/PHYS200 | /Ch7-Ex7.4.py | 797 | 4.46875 | 4 | #################################
#
# ThinkPython Exercise 7.4
#
# J.L. Klay
# 30-Apr-2012
#
# Exercise 7.4 The built-in function eval takes a string and evaluates
# it using the Python interpreter. For example:
# >>> eval('1 + 2 * 3')
# 7
# >>> import math
# >>> eval('math.sqrt(5)')
# 2.2360679774997898
# >>> eval('t... | true |
2f319d09ef1183f75623fdc10fe226c371eba85f | stuffyUdaya/Python | /1-9-17/strings.py | 305 | 4.15625 | 4 | name = "hello world!"
lname = "This is Udaya"
print "Welcome",lname
print "Welcome"+lname
print "Hi {} {}".format(name,lname)
print name.capitalize()
print name.lower()
print name.upper()
print name.swapcase()
print name.find("l")
print lname.replace("Udaya","UdayaTummala")
print name.replace("o","0",1)
| false |
690805257154a3d610f72d0fa777a0196b9e07fb | sathishmepco/Python-Basics | /basic-concepts/for_loop.py | 1,005 | 4.28125 | 4 | #for loop
print('------Looping through string list')
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x,len(x))
print('------Looping through String')
str = 'Python'
for x in str:
print(x)
print('-----Range() function')
for x in range(10):
print(x)
print('-----Range() function with start and end valu... | false |
8617d6b008e47ed734b1ecaf568ae94dfc7db835 | sathishmepco/Python-Basics | /basic-concepts/collections/dequeue_demo.py | 1,329 | 4.34375 | 4 | from collections import deque
def main():
d = deque('abcd')
print('Queue of : abcd')
for e in d:
print(e)
print('Add a new entry to the right side')
d.append('e')
print(d)
print('Add a new entry to the left side')
d.appendleft('z')
print(d)
print('Return and remove the right side elt')
print(d.pop())
p... | true |
c5e31c20a1a55cec683250a8d64ebc8836c3f5b6 | JKodner/median | /median.py | 528 | 4.1875 | 4 | def median(lst):
"""Finds the median of a sequence of numbers."""
status = True
for i in lst:
if type(i) != int:
status = False
if status:
lst.sort()
if len(lst) % 2 == 0:
num = len(lst) / 2
num2 = (len(lst) / 2) + 1
avg = float(lst[num - 1] + lst[num2 - 1]) / 2
median = {"median": avg, "positi... | true |
33487b5cd6e069e72cbe686724143ba1eb16979e | Tayuba/AI_Engineering | /AI Study Note/List.py | 1,895 | 4.21875 | 4 | # original list
a = [1, 2, 3, 4, "m", 6]
b = ["a", "b", "c", "d", 2, 9, 10]
# append(), add an item to the end of already existing list
c = 8
a.append(c) # interger append
print(a) # [1, 2, 3, 4, 'm', 6, 8]
d = "Ayuba"
b.append(d)
print(b) # ['a', 'b', 'c', 'd', 2, 9, 10, 'Ayuba']
# extend(), add all items to the t... | true |
4f340717ec34d4d1ee5dc79b1bcac29c8be02600 | OliverMathias/University_Class_Assignments | /Python-Projects-master/Assignments/Celsius.py | 367 | 4.3125 | 4 | '''
A script that converts a user's celsius input into farenheight by using
the formula and prints out an temp in farenheight
'''
#gets user's temp Input
temp_c = float(input("Please enter the current temperature in celsius: "))
# turns it into farenheight
temp_f = temp_c*(9/5) + 32
#prints out farenheight
print("The... | true |
10ea306fedbee3cff2ce63c97add2561c9f2b54a | mbkhan721/PycharmProjects | /RecursionFolder/Practice6.py | 2,445 | 4.40625 | 4 | """ Muhammad Khan
1. Write a program that recursively counts down from n.
a) Create a recursive function named countdown that accepts an
integer n, and progressively decrements and outputs the value of n.
b) Test your function with a few values for n."""
def countdown(n): # def recursive_function(parameters)
if n... | true |
3a21120c6e8e9814b6dad06431ec73beaeee9ff2 | Roha123611/activity-sheet2 | /prog15.py | 366 | 4.1875 | 4 | #prog15
#t.taken
from fractions import Fraction
def addfraction(st_value,it_value):
sum=0
for i in range(st_value,it_value):
sum=sum+Fraction(1,i)
print('the sum of fractions is:',sum)
return
st_value=int(input('input starting value of series:'))
it_value=int(input('enter ending value ... | true |
4a917541eaf35c7e398ec8a4bb6acd1774541c9e | helgurd/Easy-solve-and-Learn-python- | /differBetw_ARR_LIST.py | 978 | 4.4375 | 4 | # first of all before we get into Python lists are not arrays, arrays are two separate things and it is a common mistakes that people think that lists are the same arrays.
#in array if we append different data type will return typeerror which that is not case in the list.
# ARRAY!=LIST
###example 1 python list
import... | true |
bfa347e6247121c5cd10b86b7769eb368d5ae487 | helgurd/Easy-solve-and-Learn-python- | /open_and_read _string.py | 1,310 | 4.6875 | 5 | #write a program in python to read from file and used more than method.
# read from file --------------------------------------------------------------------
#write a program in python to read from file and used more than method.
# method1
# f=open('str_print.txt','r')
# f.close()
#---------
# method2 called con... | true |
75964cfe90c20dbed87347908b79b899f45b593a | sachi-jain15/python-project-1 | /main.py | 1,206 | 4.1875 | 4 | # MAIN FILE
def output(): #Function to take user's choice
print "\nWhich script you want to run??\n Press 1 for students_to_teacher\n Press 2 for battleship\n Press 3 for exam_stats"
choice=int(raw_input('Your choice: ')) # To take users input of their choice
if (choice==1):
print "\n STUDENTS_... | true |
25246d0e0e2cb0ed366a2e778d1b3385fb1bd2db | Quetzalcoaltl/Cobra_2 | /OOP_P3.py | 2,735 | 4.53125 | 5 | """
aula 2 de orientação ao objeto,
Professor Corey Schafer
Tema Aula: Python OOP Tutorial 2: Class Variables
https://www.youtube.com/watch?v=BJ-VvGyQxho
"""
class Empregado:
aumento_salario= 1.04
numero_empregado=0
def __init__(self, primeiro_nome, ultimo_nome, pagamento):
sel... | false |
bb3f60122c2ecc63b78c98572cb05cffa6c4f72e | jaebradley/project_euler | /problems/pe44.py | 1,410 | 4.25 | 4 | """
Find the pair of pentagonal numbers for which their sum and difference are pentagonal
"""
import time
def is_pentagonal(number):
#inverse function for pentagonal number
return not (1 + (1 + 24 * number) ** 0.5)/6 % 1
def return_pentagonal(n):
return n * (3 * n - 1) / 2
def is_sum_and_difference_of... | false |
91e7da83b03fe16d65782809e07e397a41aabb72 | TheNathanHernandez/PythonStatements | /Unit 2 - Introductory Python/A1/Comments_Outputs_Errors.py | 1,379 | 4.65625 | 5 | print('Welcome to Python!')
# Output: Welcome to Python
# Why: String says "Welcome to Python
print(1+1)
# Output: 2
# Why: Math sum / 1 + 1 = 2
# print(This will produce an error)
# Output: This will produce an Error
# Why: The text doesn't have a string, it's invalid
print(5+5-2)
# Output: 8
# Why: 5 + 5 - 2
prin... | true |
bbed8da2e0837f77df6ae36a03ef73ac25e172fd | TheNathanHernandez/PythonStatements | /Unit 2 - Introductory Python/A4 - Conditional Expressions/programOne.py | 403 | 4.15625 | 4 | # Program One - Write a number that asks the user to enter a number between 1 and 5. The program should output the number in words.
# Code: Nathan Hernandez
from ess import ask
number = ask("Choose a number between 1 and 5.")
if number == 1:
print("One.")
if number == 2:
print("Two.")
if number == 3:
... | true |
5077815f19f7bd1d729650704069e64e448cd89c | Souravdg/Python.Session_4.Assignment-4.2 | /Vowel Check.py | 776 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
"""
Problem Statement 2:
Write a Python function which takes a character (i.e. a string of length 1) and returns
True if it is a vowel, False otherwise.
"""
def vowelChk(char):
if(char == 'a' or char == 'e' or char == 'i' or char == 'o' or char == 'u'):
ret... | true |
fb6ac747fcf5d0fc4fc360cdfbb7e146f9e099e4 | sharyar/design-patterns-linkedin | /visitor.py | 1,285 | 4.25 | 4 | class House(object):
def accept(self, visitor):
''' The interface to accept a visitor '''
# Triggers the visiting operation
visitor.visit(self)
def work_on_hvac(self, hvac_specialist):
print(self, 'worked on by', hvac_specialist)
# This creates a reference to the HVAC s... | true |
9dd9050ffca4e9c67628c713695472613b6ef5bd | mas254/tut | /String methods.py | 349 | 4.125 | 4 | course = "Python for Beginners"
print(len(course))
print(course.upper())
print(course.find("P"))
# You get 0 here as this is the position of P in the string
print(course.find("z"))
# Negative 1 is if not found
print(course.replace("Beginners", "Absolute Beginners"))
print(course)
print("Python" in course)
# All case se... | true |
132d54605b7b373f7d8494dce66665cf80cd9373 | mas254/tut | /creating_a_reusable_function.py | 935 | 4.28125 | 4 | message = input('>')
words = message.split(' ')
emojis = {
':)': 'smiley',
':(': 'frowney'
}
output = ''
for word in words:
output += emojis.get(word, word) + ' '
print(output)
def emojis(message):
words = message.split(' ')
emojis = {
':)': 'smiley',
':(': 'frowney'
}
outpu... | true |
cda3560dfafcb1c358ea0c6ff93477d6e868bb68 | sabach/restart | /script10.py | 540 | 4.375 | 4 | # Write a Python program to guess a number between 1 to 9.
#Note : User is prompted to enter a guess.
#If the user guesses wrong then the prompt appears again
#until the guess is correct, on successful guess,
#user will get a "Well guessed!" message,
#and the program will exit.
from numpy import random
randonly_sele... | true |
713773b1c5d7b50b23270a1ac5f7ca2aa62ac58b | VelizarMitrev/Python-Homework | /Homework1/venv/Exercise6.py | 343 | 4.34375 | 4 | nand = input("Choose a number ")
operator = input("Input + OR * for either computing a number or multiplying it ")
sum = 0
if operator == "+":
for x in range(1, int(nand) + 1):
sum = sum + x
if operator == "*":
sum = 1
for x in range(1, int(nand) + 1):
sum = sum * x
print("The final ... | true |
b44c3fcdf3aa99d88f9d5a03c7d12cb64e9715d6 | VelizarMitrev/Python-Homework | /Homework2/venv/Exercise10.py | 387 | 4.34375 | 4 | def fibonacci(num): # this is a recursive solution, in this case it's slower but the code is cleaner
if num <= 1:
return num
else:
return(fibonacci(num-1) + fibonacci(num-2))
numbers_sequence = input("Enter how many numbers from the fibonacci sequence you want to print: ")
print("Fibonacci sequenc... | true |
02d3f469da092a1222b12b48327c61da7fc1fea3 | mvargasvega/Learn_Python_Exercise | /ex6.py | 903 | 4.5 | 4 | types_of_people = 10
# a string with embeded variable of types_of_people
x = f"There are {types_of_people} types of people."
binary = "binary"
do_not = "don't"
# assigns a string to y with embeded variables
y = f"Those who know {binary} and those who {do_not}."
print(x)
print(y)
print(f"I said: {x}")
# printing a st... | true |
b13dd7edaf3c6269f3d3fa90682eeeb989d78571 | TigerAppsOrg/TigerHost | /deploy/deploy/utils/click_utils.py | 586 | 4.1875 | 4 | import click
def prompt_choices(choices):
"""Displays a prompt for the given choices
:param list choices: the choices for the user to choose from
:rtype: int
:returns: the index of the chosen choice
"""
assert len(choices) > 1
for i in range(len(choices)):
click.echo('{number}) {... | true |
702a6a7a507adab77dd080f235544229d6c219b6 | MrZhangzhg/nsd_2018 | /nsd1809/python2/day01/stack.py | 1,102 | 4.28125 | 4 | """
列表模拟栈结构
栈:是一个后进先出的结构
"""
stack = []
def push_it():
data = input('data to push: ').strip()
if data: # 如果字符串非空
stack.append(data)
def pop_it():
if stack: # 如果列表非空
print('from stack, popped \033[31;1m%s\033[0m' % stack.pop())
else:
print('\033[31;1mEmpty stack\033[0m')
... | false |
ea790c65632f47dd6d0e78d0f366b8b042d0b3ad | MrZhangzhg/nsd_2018 | /nsd1807/python1/day03/fibs_func.py | 819 | 4.15625 | 4 | # def generate_fib():
# fib = [0, 1]
#
# for i in range(8):
# fib.append(fib[-1] + fib[-2])
#
# print(fib)
#
# # generate_fib() # 调用函数,即将函数内的代码运行一遍
# # generate_fib()
# a = generate_fib()
# print(a) # 函数没有return语句,默认返回None
##############################
# def generate_fib():
# fib = [0, 1]
#... | false |
2609c2b1f06d647b086493c1294a1652787cefd8 | FranciscoValadez/Course-Work | /Python/CS119-PJ 6 - Simple Calculator/PJ 6 - Simple Calculator/PJ_6___Simple_Calculator.py | 1,900 | 4.5 | 4 | # Author: Francisco Valadez
# Date: 1/23/2021
# Purpose: A simple calculator that shows gives the user a result based on their input
#This function is executed when the user inputs a valid operator
def Results(num1, num2, operator):
if operator == '+':
print("Result:", num1, operator, num2, "=", (num1 ... | true |
f5617054ec164da96fe6c2d4b638c9889060bbf0 | hirani/pydec | /pydec/pydec/math/parity.py | 2,695 | 4.15625 | 4 | __all__ = ['relative_parity','permutation_parity']
def relative_parity(A,B):
"""Relative parity between two lists
Parameters
----------
A,B : lists of elements
Lists A and B must contain permutations of the same elements.
Returns
-------
parity : integer
... | true |
e3f3da252345a8e54f3e7bff4d6c695d379b5e42 | grupy-sanca/dojos | /039/2.py | 839 | 4.53125 | 5 | """
https://www.codewars.com/kata/55960bbb182094bc4800007b
Write a function insert_dash(num) / insertDash(num) / InsertDash(int num)
that will insert dashes ('-') between each two odd digits in num.
For example: if num is 454793 the output should be 4547-9-3.
Don't count zero as an odd digit.
Note that the number wil... | true |
4fd23931962dd3a22a5a168a9a49bc68fd8eadd6 | grupy-sanca/dojos | /028/ex2.py | 1,416 | 4.40625 | 4 | """
A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name.
They are now trying out various combinations of company names and logos based on this condition.
Given a string, which is the company name in lowercase letters, your task is to find the... | true |
f17e7bc0acc2e97393a392ffb15e96a3f9f805f2 | ayust/controlgroup | /examplemr.py | 645 | 4.28125 | 4 | # A mapper function takes one argument, and maps it to something else.
def mapper(item):
# This example mapper turns the input lines into integers
return int(item)
# A reducer function takes two arguments, and reduces them to one.
# The first argument is the current accumulated value, which starts
# out with t... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.