blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
bbe05e7c59c9573d42918bdf7a5fd1f1447e1c95 | ablimit/cs130r | /solution/labs/lab5/palindrome.py | 465 | 4.15625 | 4 |
userInput= input("Please input a word or phrase of your choice:\n")
word = ""
# eliminate non alphabetic characters (space, !, ? , etc)
for letter in userInput:
if letter.isalpha():
word += letter.lower()
# print ("input",word)
length = len(word)
flag = True
for i in range(0,length):
if word[i] != word[le... | true |
348cb653794dd2b0775392036c38f9b6c5bd255a | mauerbac/hh-interview-prep | /general_algorithms/find_highest_product.py | 2,644 | 4.25 | 4 | #https://www.interviewcake.com/question/highest-product-of-3
'''Given an array_of_ints, find the highest_product you can get from three of the integers.
The input array_of_ints will always have at least three integers.
'''
#brute force solution
#create a dict {product: (int1,int2,int3)}
#sort dict to find highest
#run ... | true |
f351ff15ea73bf52c0cae75e6564ffdac3372306 | vaibhavg12/exercises | /python/exercises/arrays/dijkstra_national_flag.py | 813 | 4.21875 | 4 | """
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent,
with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
"""
def sort(arr):
left = 0
right = le... | true |
1f548569250c04acedd053ef3f4e73320a40983e | neilsharma2003/basic-bubble-sort-without-loops | /bubblesort.py | 560 | 4.28125 | 4 | '''
Insert 3 scrambled floats or integers and
get them sorted in ascending order where
x < y < z
'''
x = input("Insert first number")
y = input("Insert second number")
z = input("Insert third number")
temporary_var = max(x,y)
x = min(x,y)
y = temporary_var
temporary_var = max(y,z)
y = min(y,z)
z = temporary_var
t... | true |
182bd7ac74036a288116fc6418a514bfea262317 | Ashish1608/Rock-Paper-Scissor-Game | /main.py | 1,080 | 4.1875 | 4 | import random
from art import rock, paper, scissors
def result(user_option, computer_option):
if user_option == computer_option:
return "It's a draw!"
else:
if user_option == 2 and computer_option == 0:
return "You lose."
elif user_option == 0 and computer_option == 2:
... | true |
995ad076121e5c9fb5f3e99b7737804cd85dcb15 | YufeiCui/CSCA48 | /tutorials/t1/review.py | 991 | 4.4375 | 4 | # 1. let's say we have a matrix which is a list of lists
row = [0, 0]
matrix = [row, row]
print(matrix) # what's the output?
matrix[0][0] = 1
print(matrix) # what's the output?
row[1] = 3
print(matrix) # what's the output?
# 2. mutating lists
def append_to_list(array, item):
array = array + [item]
def ap... | true |
ba2f6bf63abbcdfb9d6d03cad9be7e1320081cac | lucasgarciabertaina/hackerrank-python3 | /strings/full_name.py | 304 | 4.1875 | 4 | def print_full_name(first, last):
text = 'Hello first last! You just delved into python.'
text = text.replace("first",first)
text = text.replace("last",last)
print(text)
if __name__ == '__main__':
first_name = input()
last_name = input()
print_full_name(first_name, last_name) | true |
4345f6601d08be66b47368f450854c28a6bc8061 | larrydanny/learning-python | /lists_method.py | 1,790 | 4.3125 | 4 | numbers = [3, 2, 7, 4, 5, 1]
print("Add new value 22 at the end on the list")
numbers.append(22)
print(numbers)
print("Add new value 10 at 2 index on the list")
numbers.insert(2, 22) # 2 is index and 10 is value
print(numbers)
print("Get index of given item 7")
print(numbers.index(7))
print("If given item not in l... | true |
594c5161b6fd9de2d840508cfb1a2f219a8fac81 | larrydanny/learning-python | /lists.py | 776 | 4.4375 | 4 | names = ["Larry", "Danny", "Python", "List", "Name"]
print("Full lists:")
print(names)
print("Get name using index of lists:")
print(names[2])
print("Update 3 index text lists:")
names[3] = "React"
print(names)
print("Using range operator [start:end]:")
print("Display 2 and 3 index value means less one from end inde... | true |
aa5ae5867e1103ef8f5292bce27d53d022b0b065 | nanako-chung/python-beginner | /Assignment 1/ChungNanako_assign1_problem2.py | 1,666 | 4.46875 | 4 | # Nanako Chung
# September 16th, 2016
# M/W Intro to Comp Sci
# Problem #2: Using the print function
# First, we must name the class by asking the user to store data into a variable. We use the input function to do this.
name1 = input("Please enter name #1: ")
name2 = input("Please enter name #2: ")
name3 = input("Ple... | true |
f329ca2ce2c101107f77409d0a0645c233ab2b95 | nanako-chung/python-beginner | /Assignment 5/ChungNanako_assign5_problem1.py | 1,970 | 4.3125 | 4 | #Nanako Chung
#Intro to Computer Programming M/W
#October 24th, 2016
#Problem #1: Pizza Party
#create counter for slices needed to get total amount of slices needed for order
slices_needed=0
#ask user for budget, cost of each slice, cost of each pie, and num of people
budget=float(input("Enter budget for your party: ... | true |
e64be02c858f43b52e83a034195af1176159b8b0 | carlosmaniero/ascii-engine | /ascii_engine/pixel.py | 1,393 | 4.125 | 4 | """
This module contains the a pixel representation
In this case a pixel is a character in the screen
"""
class Pixel:
"""
A pixel is the small part in the screen. It is represented by a
character with a foreground and background color.
"""
def __init__(self, char, foreground_color=None, backgrou... | true |
96057fafac5f7ed6ef5a7f48757d6ff954017122 | Pavankumar45k/Python | /Array Programs/Array rotation.py | 692 | 4.5 | 4 | #Array Rotation
from array import *
n=int(input("Enter a Number to shift arrays towards left:"))
a=array('i',{11,12,13,14,15})
print("Type of a is:",type(a))
#to print array before conversion
print("\n Array Before conversion:")
for i in range(len(a)):
print(a[i],end=' ')
# to move the array towards left by n times
... | true |
e1d6f5861ef558f55d25b36fa374db78e99c0ce9 | paramprashar1/PythonAurb | /py5g.py | 553 | 4.40625 | 4 | # Dictionaries
employee = {"eid": 101, "name": "John", "salary": 30000}
print(employee)
# eid is key and 101 is value
print(max(employee))
print(min(employee))
print(len(employee))
employee["eid"] = 222 # updating values of keys KEYS cant be changed but there values can be
print(employee["eid"])
print(list(employee.... | true |
bfcca2e9fe1fbd72974f1e1af21f8d33e08d4bce | paramprashar1/PythonAurb | /py4e.py | 524 | 4.15625 | 4 | #Cart is an empty list with len as 0
"""
cart=["Chicken"]
cart.append("Dal Makhni")
cart.append("Paneer Butter Masala")
print(cart)
cart.extend(["Noodles","Manchurian"])
print(cart)
cart.insert(1,"Soya Champ")
print(cart)
cart.pop(2)
print(cart)
print(cart[2])
"""
cart=[]
choice="yes"
while choice=="yes" or choice==... | true |
610597451753b96e327a6667da5ea037c5de63b2 | B-Rich/Python-Introduction | /Conjectures.py | 1,248 | 4.46875 | 4 | # Python 3.5.2
# TITLE: Conjectures
# 1. The Collatz Conjecture - Recursive
# Prints the Collatz Conjecture for integer n.
#
# Given any initial natural number, consider the sequence
# of numbers generated by repeatedly following the rule:
# - divide by two if the number is even or
# - multiply by 3 and add 1 if the ... | true |
e623d4524ddf421984209674ed104b63028cadee | dhanendraverma/Daily-Coding-Problem | /Day730.py | 1,800 | 4.28125 | 4 | '''
/***************************************************************************************************************************************
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
What will this code print out?
def make_functions():
flist = []
for i in [1... | true |
abc009f223364ec951d3ebe0a8f39e7263a7c786 | afaubion/Python-Tutorials | /Basic_Operators.py | 1,115 | 4.34375 | 4 | # basic order of operations
number = 1 + 2 * 3 / 4.0
print(number)
print("\n")
# modulo
remainder = 11 % 3
print(remainder)
print("\n")
# using two multiplication symbols creates power relationship
squared = 7 ** 2
cubed = 2 ** 3
print(squared)
print(cubed)
print("\n")
# using operators with strings
helloworld = "he... | true |
77ee5325d1f6a6f0a8a63f3b12e8f7168df9535f | afaubion/Python-Tutorials | /Multiple_Function_Arguments.py | 2,653 | 4.90625 | 5 | # Every function in Python receives a predefined number of arguments, if declared normally, like this:
# -----
def myfunction(first, second, third):
# do something with the 3 variables
...
# -----
# It is possible to declare functions which receive a variable number of arguments,
# using the following syntax:... | true |
20396ec6f593c24fa5e7ed56b51f435e228bae31 | afaubion/Python-Tutorials | /List_Comprehensions.py | 1,378 | 4.75 | 5 | # List Comprehensions is a very powerful tool,
# which creates a new list based on another list, in a single, readable line.
# For example, let's say we need to create a list of integers
# which specify the length of each word in a certain sentence,
# but only if the word is not the word "the".
# Ex: -----
sentence = ... | true |
a18e422bb8013ca18c3786ea758b633a03990b1a | chrishoerle6/Leetcode-Solutions | /Python/Easy/Sorting and Searching/First_Bad_Version.py | 1,429 | 4.25 | 4 | ## Author: Chris Hoerle
## Date: 08/20/2021
'''
You are a product manager and currently leading a team to develop
a new product. Unfortunately, the latest version of your product
fails the quality check. Since each version is developed based on
the previous version, all the versions after a bad version are also... | true |
b2a7820b20882ce1f52cc14c690d40088948f961 | chrishoerle6/Leetcode-Solutions | /Python/Easy/Math/Count_Primes.py | 775 | 4.1875 | 4 | ## Author: Chris Hoerle
## Date: 08/20/2021
'''
Count the number of prime numbers less than a non-negative number, n.
Examples:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Input: n = 0
Output: 0
Input: n = 1
Output: 0
Constraints:
0 <= n <= 5 * 106... | true |
5a8f02c10fbe40bdfd555d1b0d186b19ca38c7f1 | chrishoerle6/Leetcode-Solutions | /Python/Easy/Trees/Validate_Binary_Tree.py | 1,434 | 4.28125 | 4 | ## Author: Chris Hoerle
## Date: 08/12/2021
'''
Given the root of a binary tree, determine if it is a valid
binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less
than the node's key. The right subtree of a node contains only
nodes with keys ... | true |
7c265be4916796794f9bca60890936bbc0ade1d9 | chrishoerle6/Leetcode-Solutions | /Python/Easy/Trees/Convert_Sorted_Array_To_Binary_Search_Tree.py | 1,467 | 4.125 | 4 | ## Author: Chris Hoerle
## Date: 08/20/2021
'''
Given an integer array nums where the elements are sorted
in ascending order, convert it to a height-balanced binary
search tree. A height-balanced binary tree is a binary tree
in which the depth of the two subtrees of every node never
differs by more than one.
... | true |
2c1ac11465f615cb91c849da97e6a576598de69e | JacksonLeng/Computer-Science | /python_midterm_review 4/answers/16.py | 517 | 4.40625 | 4 | # 16. Movies You Want to See:
# Use a for-loop and sorted() to print your list in alphabetical order
# without modifying the actual list.
# Show that your list is still in its original order by printing it as well.
movies_i_want_to_see = ['Space Jam', 'Hidden Figures', 'The Pursuit of Happyness', 'Shrek', 'Independe... | true |
6e3ecec16a91fd3bb6160ce85b791a0c9a3e3237 | sb2rhan/PythonCodes | /ITStepTutorials/OOP/classes_intro.py | 2,948 | 4.15625 | 4 | class Car:
mark = 'Tesla'
model = 'P100D'
year = 2019
def start(self):
return f'Car {self.mark} {self.model} has been started'
def stop(self):
return f'Car {self.mark} {self.model} has been stopped'
"""
Difference between static method and class method:
1. Static ... | true |
5bc4e90a4ad1e45ae203c529b5533631ebb7269f | sb2rhan/PythonCodes | /ITStepTutorials/Collections_Functools/func_tools.py | 2,483 | 4.1875 | 4 | # Functools
# a module of high-level functions
# they are used to modify other low-level functions
# so they are decorators
import functools
# lru_cache for storing repetetive data
import requests
# # caches get_webpage function
# @functools.lru_cache(maxsize=24)
# def get_webpage(module):
# webpage = f'https:/... | true |
8c2a61c1c0d630b774bc4b0bcdcbe78b1e1311e7 | dunste123/cassidoo-rendezvous | /142_one_row/index.py | 855 | 4.15625 | 4 | # Given an array of words, return the words that can be typed using letters of only one row on a keyboard.
#
# Extra credit: Include the option for a user to pick the type of keyboard they are using (ANSI, ISO, etc)!
#
# Example:
#
# $ oneRow(['candy', 'doodle', 'pop', 'shield', 'lag', 'typewriter'])
# $ ['pop', 'lag',... | true |
317253748627559c6b607815d60d04a0c77792b5 | dunste123/cassidoo-rendezvous | /138_backspacing/index.py | 942 | 4.21875 | 4 | # Given two strings n and m, return true if they are equal when both are typed into empty text editors. The twist: #
# means a backspace character.
#
# Example:
#
# > compareWithBackspace("a##c", "#a#c")
# > true // both strings become "c"
#
# > compareWithBackspace("xy##", "z#w#")
# > true // both strings be... | true |
df3a99027d7b39c8f83a46ec18018d1231a5fb62 | shubhamjante/python-fundamental-questions | /Programming Fundamentals using Python - Part 01/Assignment Set - 03/Assignment on string - Level 2.py | 1,081 | 4.34375 | 4 | """
Given a string containing uppercase characters (A-Z), compress the string using Run Length encoding.
Repetition of character has to be replaced by storing the length of that run.
Write a python function which performs the run length encoding for a given String and returns the run
length encoded String.
Provide di... | true |
7f7bbd1e45f33fd18705e43ef2f2185d33103ef5 | shubhamjante/python-fundamental-questions | /Programming Fundamentals using Python - Part 01/Assignment Set - 02/Assignment on selection in python - Level 3.py | 2,127 | 4.125 | 4 | """
FoodCorner home delivers vegetarian and non-vegetarian combos to its customer based on order.
A vegetarian combo costs Rs.120 per plate and a non-vegetarian combo costs Rs.150 per plate.
Their non-veg combo is really famous that they get more orders for their non-vegetarian combo than the vegetarian combo.
Apart ... | true |
bc98f7142d565d2ae272698b052eb1c61016453d | shubhamjante/python-fundamental-questions | /Programming Fundamentals using Python - Part 02/Assignment Set - 07/Assignment on list APIs - Level 3 (puzzle).py | 1,726 | 4.1875 | 4 | """
Use Luhn algorithm to validate a credit card number.
A credit card number has 16 digits, the last digit being the check digit. A credit card number can be validated
using Luhn algorithm as follows:
Step 1a: From the second last digit (inclusive), double the value of every second digit.
Suppose the credit card num... | true |
f9264a548ddafcd40ffaa986e376baa7a219fbb5 | drsantos20/mars-rover | /rover.py | 2,640 | 4.21875 | 4 | """
INPUT AND OUTPUT
Test Input:
5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM
Expected Output:
1 3 N
5 1 E
"""
class rover:
def __init__(self):
"""All the variables are initialised here."""
self.x = 0
self.y = 0
self.direction = 'N'
self.left = 'L'
self.right = 'R'
self.move = 'M'
self.north = 'N'
sel... | true |
63be02823e11adf100f08cf09996b868a71f271e | saurav188/python_practice_projects | /square_root.py | 397 | 4.3125 | 4 | #Given a positive integer, find the square
#root of the integer without using any built
#in square root or power functions
#(math.sqrt or the ** operator).
#Give accuracy up to 3 decimal points.
def sqrt(x):
a=0
b=x
y=(a+b)/2
while round(a,3)!=round(b,3):
if y**2>x:
b=y
... | true |
19e32cd3149e716ad1449b5ecb461a1fcc30074d | nimbinatus/LPHW | /ex20.py | 1,642 | 4.46875 | 4 | # import argv function from sys module
from sys import argv
# set up argv
script, input_file = argv
# defines the function print_all, which prints a file passed in the function
# call
def print_all(f):
print f.read()
# defines a function rewind, which finds the beginning of a file using the
# seek file object an... | true |
c1a524d57adab1f93d3e7c7264e74e99238803f2 | najibelkihel/python-crash-course | /Chapter 4 Working with Lists - Lessons/magicians.py | 1,081 | 4.59375 | 5 | players = ['magic', 'lebron', 'kobe']
# use of for LOOP to apply printing to each player within player variable.
for player in players:
print(player)
# for LOOP has been defined, and each item from the 'players' loop has been
# stored in a new variable called 'player'.
# for every player in the players list
# ... | true |
5f85b795aa9102b6cc0b2ccb8a3c4711004cad78 | najibelkihel/python-crash-course | /Chapter 5 If Statements - Lessons/toppings.py | 1,763 | 4.3125 | 4 | # Chapter 5, 'Checking for inequality', p.78
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print('Hold the anchovies!')
# Above: the if statement is asking if requested_topping is NOT equal to
# 'anchovies', then the string 'Hold the anchovies!' should be printed.
# Because the requested_t... | true |
68554c29ec432067bca62a6c2913ce163e4c0d15 | najibelkihel/python-crash-course | /Chapter 5 If Statements - Lessons/toppings2.py | 1,770 | 4.4375 | 4 | # Using if statements with lists, p.89
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
print('Adding ' + requested_topping + '!')
print('\nFinished making your pizza!')
#
for requested_topping in requested_toppings:
if requested_topping == 'g... | true |
9e736ad8cc2847d518cd7afd9b0d170345e89df8 | najibelkihel/python-crash-course | /Chapter 8 Functions - Lessons/person.py | 981 | 4.25 | 4 | # Returning a dictionary p.144
def build_person(first_name, last_name, age=''):
"""return a dictionary of information about a person"""
person = {'first': first_name,
'last': last_name,
}
if age:
person['age'] = age
return person
athlete = build_person('lebron', '... | true |
a9700460ba4ae908e41039b424b0a9bd3c0635bb | najibelkihel/python-crash-course | /Chapter 8 Functions - Exercises/sandwiches.py | 1,499 | 4.15625 | 4 | # Exercises p.155
# 8-12
def make_sandwich(*items):
"""Creates a list of items to be included in a sandwich"""
print("Here are the ingredients that you've selected for your sandwich:")
for item in items:
print("\t- " + item.title().strip())
make_sandwich('tomato', 'cucumber', 'mayonnaise', 'chi... | true |
33841596590431b3ef442ced977d4c755d95dc08 | devopstasks/PythonScripting | /11-Loops - for and while loops with break, continue and pass/46-Practice-Read-a-path-and-check-if-given-path-is-a-file-or-a-directory.py | 422 | 4.28125 | 4 | '''
======================
Read a path and check if given path is a file or directory
=======================
'''
import os
path=input("Enter your path: ")
if os.path.exists(path):
print(f'Given path: {path} is a valid path')
if os.path.isfile(path):
print(" and it is a file path")
else:
pri... | true |
8426de85b92caa2223c5d5087aa1807a39b1577d | devopstasks/PythonScripting | /7-Conditional statements/32-Introduction-to-conditional-statements-simple-if-condition.py | 897 | 4.28125 | 4 | '''
==================================
if is called simple conditional statement.
Used to control the execution of set of lines or block of code or one line
if expression:
statement1
statement2
==================================
'''
'''
import os
t_w=os.get_terminal_size().columns
given_str=input("Enter your s... | true |
16f61816cb29366d110add2564d808c3c5a29fea | muthazhagu/simpleETL | /randomdates.py | 2,622 | 4.25 | 4 | from datetime import date
import random
def generate_random_dates(startyear = 1900, startmonth = 1, startday = 1,
endyear = 2013, endmonth = 12, endday = 31,
today = True,
numberofdates = 1):
"""
Method returns a list of n dates between a ... | true |
701de8c100f4b6f5efd602d8d68ea154af834f1d | SRSJA18/assignment-1-JaedynH99 | /Problem3/repeating_lyrics.py | 1,092 | 4.3125 | 4 | """Assignment 1: Problem 3 Extension: Repeating Lyrics"""
'''
Many songs use repetition. We can use variables to manage that repetition when printing out the lyrics.
Here is the chorus for Rick Astley's 'Never Gonna Give You Up'
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Ne... | true |
75b331ff1f7643e3ab7e3c6ce6a4fdc38d8c9c4d | ARaj771/Python-Data-Structure-Practice | /02_weekday_name/weekday_name.py | 597 | 4.375 | 4 | def weekday_name(day_of_week):
"""Return name of weekday.
>>> weekday_name(1)
'Sunday'
>>> weekday_name(7)
'Saturday'
For days not between 1 and 7, return None
>>> weekday_name(9)
>>> weekday_name(0)
"""
weekday_dict = {
... | true |
63026172deae959ec9d952658c4cbb199aaff0a1 | shaz13/PyScripts | /word_end_finder.py | 414 | 4.4375 | 4 | import re
# Replace this with your custom dictionary of words
file = open('Urdu_words.txt', 'r')
text = file.read().lower()
file.close()
text = re.sub('[^a-z\ \']+', " ", text)
words = list(text.split())
string = str(raw_input ("Enter the last ending letters: "))
def EndsWithWordFinder(string):
for word in words... | true |
b52e609ba07fca225b3bc37f21e33efdaf593662 | ivaylospasov/small-budget | /main.py | 1,912 | 4.15625 | 4 | #!/usr/bin/env python3
__author__ = 'ivaylo spasov'
from getBudget import currentBudget, path
def main():
endProgram = 'no'
totalBudget = currentBudget
while endProgram == 'no':
print('Welcome to the Personal Budget Program')
print('Menu Selections: ')
print('1-Add an Expense: ')
... | true |
36a0a0504f648c29f9bbd4c4b111cf7935508891 | prajakta401/UdemyTraining | /venv/Lect_23_Missing Data.py | 1,536 | 4.28125 | 4 | #Lecture 23 Missing Data
import numpy as np
from pandas import Series,DataFrame
import pandas as pd
data = Series(['one','two','np.nan','four'])
data.isnull() # returns True is particular index is null.
data.dropna()#drops the row which has NaN values
dataframe = DataFrame([[1,2,3],[np.nan,5,6],[7,np.nan,9],[np.nan,np.... | true |
6ff74e53b090bde4f3a66a99c13552724e1f053e | prajakta401/UdemyTraining | /venv/Lecture15_DataFrames.py | 1,877 | 4.125 | 4 | #Lecture 15: Data FRames
import numpy as np # array handling
import pandas as pd
from pandas import Series , DataFrame
import webbrowser # grab/scrape NFL data from website
website='http://en.wikipedia.org/wiki/NFL_win-loss_records'
webbrowser.open(website) #opens the url in nnew browser window
#copy few 10 rows and a... | true |
0e0f221bd037f809f317a88589bc0ee4804326a4 | deborabr21/Python | /PartI_Introduction_To_Programming/Assignment_2_Guess_a_number.py | 668 | 4.15625 | 4 | #Write a program with an infinite loop and a list of numbers.
#Each time through the loop the program#should ask the user to guess a number or type q to quit.
#If they type q the program should end. Otherwise it should tell them wether or not they successfully
#guessed a number in the list or not.
numbers = [1,3... | true |
ac66422ab45692bd991bf4fcbac5480fce015094 | Sahana012/Python-Code | /countwords.py | 320 | 4.1875 | 4 | introstring = input("Enter your introduction: ")
wordcount = 1
charcount = 0
for i in introstring:
charcount = charcount + 1
if(i == ' '):
wordcount = wordcount + 1
print("Number of word(s) in the string: ")
print(wordcount)
print("Number of characters(s) in the string: ")
print(charcount) | true |
318407d0b315c828efdd0c8b171b2a3a1106abb8 | Psingh12354/PythonNotes-Internshalla | /code/IF_ELSE.py | 343 | 4.125 | 4 | price=int(input("Enter the price : "))
quantity=int(input("Enter quantity : "))
amount=price*quantity
if amount>1000:
print("You got a discount of 10%")
discount=amount*10/100
amount-=discount
else:
print("You got a discount of 5%")
discount=amount*5/100
amount-=discount
print("Total ... | true |
814e5f1bcf0948ad96ca6acf2fb8191ed4193284 | matthewmckenna/advent2018 | /aoc_utils.py | 689 | 4.125 | 4 | """
utility functions for Advent of Code 2018.
"""
from typing import Iterator, List
def txt_to_numbers(fname: str) -> List[int]:
"""read `fname` and return a list of numbers"""
with open(fname, 'rt') as f:
data = [int(number) for number in f]
return data
def comma_separated_str_to_int_iterator... | true |
fc1336851b836312139a08eca6860207c1439b75 | kehkok/koodaus | /simple_tutorial_py/tut_01_factorial/factorial1.py | 2,319 | 4.125 | 4 | """
This module consists of basic factorial, exponential factorial and taylor
series of sin functions
"""
import math
def factorial(n):
"""Compute basic factorial function
Parameters
----------
n : integer
Specifies the number to be factorial
Returns
... | true |
7dc6191710fd5cb5fb54414ee212c4bb3946a3cc | camirmas/ctci | /ctci/p1_8.py | 1,940 | 4.125 | 4 | """
Write an algorithm such that if an element in an NxN matrix is 0, its entire
row and column are set to 0.
"""
# def zero_matrix(matrix: list):
# "Naive, takes O(N^2) space and O(N^3) time"
# zeroed = {}
# for r, row in enumerate(matrix):
# for c, value in enumerate(row):
# if (r, c) ... | true |
9a0a8174bcb51364c9d4e49b642d27e3b01e3e94 | claashk/python-startkladde | /pysk/utils/ascii.py | 655 | 4.3125 | 4 | # -*- coding: utf-8 -*-
REPLACEMENTS={ "ä" : "ae",
"Ä" : "Ae",
"ö" : "oe",
"Ö" : "Oe",
"ü" : "ue",
"Ü" : "Ue",
"'" : "" }
def toAscii(string):
"""Convert string to ASCII string
Replaces all non-ASCII charact... | true |
07eed30ca73ba360e51a4baf2188cccc44ffa2f6 | JayBee12/ITBadgePDT22021 | /Example4.py | 1,172 | 4.65625 | 5 | # We use def to define the structure of a function, functions can be created to expect 'arguments' which are data we provide to the function to do something with
# The examples below are 'pass by value' arguments in that the value is passed to the function rather than a reference or pointer to the variable itself
#Thi... | true |
0b2627d91942607f1d199c5b30c3a86f81a1a39e | adarsh-tyagi/codes | /Coding_Problem_Solution_21.py | 833 | 4.1875 | 4 | # asked by Google
# Given two singly linked lists that intersect at some point, find the intersecting node.
# The lists are non-cyclical.
# For example, given A = 3 -> 7 -> 8 -> 10 and B = 99 -> 1 -> 8 -> 10,
# return the node with value 8.
# In this example,assume nodes with the same value are the exact same no... | true |
0385f450453320dd2ce5204afa4df1896a2c0e52 | adarsh-tyagi/codes | /Coding_Problem_Solution_30.py | 1,054 | 4.375 | 4 | # asked by Facebook
# Given a string of round, curly, and square open and closing brackets,
# return whether the brackets are balanced (well-formed).
# For example, given the string "([])[]({})", you should return true.
# Given the string "([)]" or "((()", you should return false.
input_string="([])[]{()}"... | true |
2f65b8ab45a01075a6bfd5d96f82fac776e1cb23 | adarsh-tyagi/codes | /Coding_Problem_Solution_23.py | 992 | 4.1875 | 4 | # asked by Microsoft
# Given a dictionary of words and a string made up of those words (no spaces),
# return the original sentence in a list. If there is more than one possible reconstruction, return any of them.
# If there is no possible reconstruction, then return null.
# For example, given the set of words 'qu... | true |
246443dfb184b9d7536754b734117ab7880c15fd | adarsh-tyagi/codes | /Coding_Problem_Solution_16.py | 492 | 4.3125 | 4 | # asked by Google
# From a given string return the first recurring character of the string.
# for e.g. if string id "ABCDBA" then return "B"
# if string is "ABCD" return None because no character is recurring.
s=input("enter the string: ")
def First_Rec_Char(s):
char_list=[]
for i in s:
if i... | true |
5b570168559708075d967909b9d7130ac454da75 | emil45/computer-science-algorithms | /algorithmic-questions/majority_element.py | 553 | 4.15625 | 4 | from collections import defaultdict
def majority_element(l):
"""
Given an array of size n, find the majority element.
The majority element is the element that appears more than floor(n/2) times.
You may assume that the array is non-empty and the majority element always exist in the array.
"""
... | true |
5dc0333d3f75da76eb9d828521f6385335e311bb | venkyms/python-workspace | /scripts/Tag-counter.py | 621 | 4.3125 | 4 | """Write a function, `tag_count`, that takes as its argument a list
of strings. It should return a count of how many of those strings
are XML tags. You can tell if a string is an XML tag if it begins
with a left angle bracket "<" and ends with a right angle bracket ">".
"""
def tag_count(html_list):
count1 = 0
... | true |
88f8ee6fde8063fe4241094410a119c289207ab9 | venkyms/python-workspace | /scripts/Median.py | 698 | 4.125 | 4 | def median(numbers):
numbers.sort() #The sort method sorts a list directly, rather than returning a new sorted list
middle_index = int(len(numbers)/2)
if len(numbers) % 2 == 0:
return (numbers[middle_index] + numbers[middle_index - 1]) / 2
else:
return numbers[middle_index]
test1 = med... | true |
831487db53af4f9217a1f0a6e47ed45a184c003e | KimTanay7/py4e | /Excercise3_Conditional.py | 698 | 4.21875 | 4 | print ("**************************")
print ("* Activity 3-Conditional *")
print ("**************************")
name = input("Name:")
print ("Hello ",name, "!")
print ("This program will print a grade relevant to your score")
print (" Please enter score between 0.0 to 1.0")
print ("--------------------------------")
x=... | true |
611fdf2ab6ee60ea5d795455949c4be0bab5db63 | Maryam-ask/Python_Tutorial | /File/Delete_a_File/delete_a_file.py | 296 | 4.125 | 4 | # Delete a file
import os
if os.path.exists("D:\Python_Home\Files\myfile_create.txt"):
os.remove("D:\Python_Home\Files\myfile_create.txt")
else:
print("the file does not exist!")
# delete a folder:
os.rmdir("D:\Python_Home\Files\My new folder")
# !!! You can only remove empty folders. | true |
382d56ce419ead7862cccbbf16b420da26c17d65 | Maryam-ask/Python_Tutorial | /Function/Functions_Sololearn/Functional_Programming/Pure_functions.py | 1,339 | 4.5625 | 5 | """
Pure Functions:
Functional programming seeks to use pure functions. Pure functions have no side effects, and return a value that depends only on their arguments.
This is how functions in math work: for example, The cos(x) will, for the same value of x, always return the same result.
Below are examples of pure and ... | true |
7869e3b3f31dde7d7c1f7cff415a0dee1feb6b56 | Maryam-ask/Python_Tutorial | /Exercises/__init__.py | 465 | 4.1875 | 4 | """
Sum of Consecutive Numbers:
No one likes homework, but your math teacher has given you an assignment to find the sum of the first N numbers.
Let’s save some time by creating a program to do the calculation for you!
Take a number N as input and output the sum of all numbers from 1 to N (including N).
Sample Input
1... | true |
44cf49419a24a9838a0c42dfb1ef9478491cc7c8 | Maryam-ask/Python_Tutorial | /Collections/Dictionary/Accessing_Items.py | 1,044 | 4.25 | 4 | thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# halate 1:
x = thisdict["model"]
print(x)
# halate 2: estefade az methode get():
y = thisdict.get("model")
print(y)
# Get keys:
# The keys() method will return a list of all the keys in the dictionary.
key = thisdict.keys()
print("List of k... | true |
68329f8726017cbaac11286704ac41a23bc49740 | Maryam-ask/Python_Tutorial | /Exercises/SearchEngine.py | 581 | 4.28125 | 4 | """
Search Engine:
You’re working on a search engine. Watch your back Google!
The given code takes a text and a word as input and passes them to a function called search().
The search() function should return "Word found" if the word is present in the text, or "Word not found", if it’s not.
Sample Input
"This is awes... | true |
823453c64a30e699e33631d62187948c115ddc64 | Maryam-ask/Python_Tutorial | /Lambda/Lambda_SoloLearn/lambda_soloLearn.py | 567 | 4.5625 | 5 | def my_func(f, arg):
return f(arg)
my_func(lambda x: 2 * x * x, 5)
# *******************************************
# function:
def polynomial(x):
return x ** 2 + 5 * x + 4
print(polynomial(-4))
# lambda:
print((lambda x: x ** 2 + 5 * x + 4)(-4))
# *******************************************
# Lambda fu... | true |
e29a4847b55c2cd7195dcf6cb55daf4acbcb5144 | Maryam-ask/Python_Tutorial | /Boolean/BooleanPython.py | 1,142 | 4.3125 | 4 | # Boolean 2 meghdar ra barmigardanad -----> 1. True & 2. False
# When you run a condition in an if statement, Python returns ----> True or False
print(10 > 9)
print(10 == 9)
print(10 < 9)
# **************************************************
print()
a = 200
b = 33
if b > a:
print("b is greater than a")
else... | true |
792055dda42ef02fc484ef3414846a44d576bffc | CAEL01/learningpython | /variables.py | 1,235 | 4.28125 | 4 | """
Learning to code Variables in Python (via Pirple.com)
Using attributes such as Variables, Strings, Integers (positive numbers), Floats (decimals). These attributes define every
value of what is to be printed on the computer screen: A text, a positive numeric value, and a decimal
value. Using an artist with song ... | true |
cfa15a47f62c7539d79c2b10db2abd7e97ee48e3 | roorco/alphabetizer | /alphabetizer.py | 854 | 4.53125 | 5 | #!/usr/bin/env python2
#-*-coding:utf-8-*-
# modificare per eliminare accenti
def abcd():
print "\n-------------------"
print "THE ALPHABETIZER 2014"
print "by orobor"
print "This is a very small program that sorts"
print "the letter of your name in an alphabetical order."
print "It is supposed... | true |
193d1d993358ab8addd8de6cca80abbabcb51b2e | natmayak/lesson_2 | /if_age_hw_v.2.py | 1,005 | 4.125 | 4 | age = int(input("How old are you? "))
def ageist_function(age):
if age <= 0:
raise ValueError("You are in your parents' plans")
elif 0 < age <= 6:
print('Having fun at nursery')
elif 6 < age <= 16:
print('Wasting best years at school')
elif 16 < age <= 21:
print('Getting... | true |
fa47988f2a8ac4c0b0abdb52ebb239c7e5503fb8 | siriusgithub/dly | /easy/17/017/Should_I_say_this.py | 348 | 4.15625 | 4 | def triangle(height):
line = '@'
x= 1
if height == 0:
print('Triangle of height 0 not valid!')
while x <= height:
print(line)
line *= 2
x+=1
def reversetriangle(height):
line = '@'
x= height
if height == 0:
print('Triangle of height 0 not valid!')
while x > 0:
line = '@'*2**(x-1)
print('{:>... | true |
e213e5bea52460a93e747567b934984932d79800 | Aaron-Bird/leetcode | /Python/101 Symmetric Tree.py | 1,467 | 4.3125 | 4 | # Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
# For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
# 1
# / \
# 2 2
# / \ / \
# 3 4 4 3
# But the following [1,2,2,null,3,null,3] is not:
# 1
# / \
# 2 2
# \ \
# 3 3
# Note:
#... | true |
426b483ca5b06151e7d00bc317cecc8faa096147 | Mega-Barrel/10-days-statistics | /interquartile_range.py | 1,168 | 4.1875 | 4 | '''
Task
The interquartile range of an array is the difference between its first (Q1) and third (Q3) quartiles (i.e., Q3-Q1).
Given an array, X, of N integers and an array, F, representing the respective frequencies of X's elements, construct a data set, S, where each x1 occurs at frequency fi.
Then calculate an... | true |
df83ed57fddab1c66984ad0027cf12df22b4bd69 | RenukaDeshmukh23/Learn-Python-the-Hard-Way-Excercises | /ex33.py | 773 | 4.4375 | 4 | i = 0 #intialise to 0
numbers = [] #empty list numbers
while i<6: #while loop started
print(f"At the top i is {i}") #print the value of i
numbers.append(i) #append will add value of i to numbe... | true |
61cd552cd7cf0cb8e816f6c6d9054bc6ad6fbccd | jcjcarter/Daily-1-Easy-Python | /Daily 1 Easy Python/Daily_1_Easy_Python.py | 268 | 4.375 | 4 | # User's name.
name = input("What is your name? ")
# User's age.
age = input("How old are you? ")
# User's username.
username = input("What is your username? ")
print('Your name is {0}, you are {1} years old, and your username is {2}.'.format(name, age, username)) | true |
33103fb8b53fb56435e21c014a1fea4cc3d648a3 | rettka30/CUS1166_rettka30_Lab1 | /playground.py | 1,748 | 4.28125 | 4 | print("Basic program: ")
print("\nHello Word")
# Display a message
# Get user input and display a message.
myname = input("What is your name: ")
print("Hello " + str(myname))
# Alternative way to format a string
print("Hello %s" % myname)
print("Done Practicing The Basic Program")
print("\nVariables: ")
i = 120
print(... | true |
e24baf2bc6e4c75cabb9a650694c77a06cb409cf | nestorcolt/smartninja-july-2020 | /project/lesson_004/lesson_004.py | 2,086 | 4.65625 | 5 | # List and dictionaries - data structures
##############################################################################################
"""
Resources:
https://www.w3schools.com/python/python_ref_list.asp
"""
# Primitives data types
some_num = 4 # integer (whole number)
some_decimal = 3.14 # float (de... | true |
224ad99452a12881e5e51bafe17d37a74b003602 | Henrysyh2000/Assignment2 | /question1_merge.py | 1,125 | 4.34375 | 4 | def merge(I1, I2):
"""
takes two iterable objects and merges them alternately
required runtime: O(len(I1) + len(I2)).
:param I1: Iterable -- the first iterable object. Can be a string, tuple, etc
:param I2: Iterable -- the second iterable object. Can be a string, tuple, etc
:return: List -- ... | true |
6702c7ad5f3b4b1f11f09bb0e402f835909d7c53 | KoryHunter37/code-mastery | /python/leetcode/playground/built-in-functions/bin/bin.py | 758 | 4.375 | 4 | # bin(x)
# Convert an integer number to a binary string prefixed with "0b".
# The result is a valid Python expression.
# This method is reversed by using int() if the "0b" has been removed.
# Alternatives include format() and f-string, which do not contain "0b".
# > 0b1010
# The binary representation of 10, with 0b i... | true |
cd0a7956774aec6af702ed12f3aa0cee380a121a | bss233/CS126-SI-Practice | /Week 3/Monday.py | 2,002 | 4.25 | 4 | #Converts a number less than or equal to 10, to a roman numeral
#NOTE: You normally shouldn't manipulate your input, ie how I subtract from num,
# but it saves some extra checking. There is most certainly a cleaner way to do
# this function
def romanNumeral(num):
#define an empty string to add characters to
res... | true |
ca8ce04997f9d6fde7c2d45e0532bcf5e030693c | nishants17/Python3 | /dictionaries.py | 498 | 4.15625 | 4 | friend_ages = {"Nish" : 10 , "Adam" : 10}
print(friend_ages["Nish"])
friend_ages["Nish"] = 30
print(friend_ages["Nish"])
#Dictionaries have order kept in python 3.7 but cannot have duplicate keys
friends = ({"name" : "Rolf SMith", "age" : 24},
{"name" : "John", "age": 33})
print(friends[0]["name"]) #... | true |
15f5ca39b9bcab582fc777e42d4b38b997c82bb0 | unixtech/python | /150_py/2_Area_box.py | 308 | 4.5 | 4 | # Enter the width & Length of a box.
# The program should compute the area. Enter values as floating point numbers
# Enter the units of measurement used.
width = float(input("Enter the width: "))
length = float(input("Enter the length: "))
area = width*length
print('Area is:\t', area, 'Centimeters')
| true |
1d3f7b5029c39a9389268e180900869a38459ead | adamabarrow/Python | /comparisonOperators/comparisonOutline.py | 1,297 | 4.3125 | 4 | '''
This outline will help solidify concepts from the Comparison Operators lesson.
Fill in this outline as the instructor goes through the lesson.
'''
#1) Make two string variables. Compare them using the == operator and store
#that comparison in a new variable. Then print the variable.
a = "hi"
b = "hello"
c = (a ==... | true |
19c7fb4bb5b612ef584ea7faab4eb1117d08783c | oguzhanun/10_PythonProjects | /challange/repdigit.py | 553 | 4.4375 | 4 | # A repdigit is a positive number composed out of the same digit.
# Create a function that takes an integer and returns whether it's a repdigit or not.
# Examples
# is_repdigit(66) ➞ True
# is_repdigit(0) ➞ True
# is_repdigit(-11) ➞ False
# Notes
# The number 0 should return True (even though it's not a positive number... | true |
93eaade2a4ba280220cc021ff2837b6534d5ee17 | oguzhanun/10_PythonProjects | /challange/descending_order.py | 584 | 4.15625 | 4 | # Your task is to make a function that can take any non-negative integer as a argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
# Examples:
# Input: 21445 Output: 54421
# Input: 145263 Output: 654321
# Input: 123456789 Output: 9876543... | true |
d6af6d9581328120bc0a9130650caba6bb9ea818 | Ferihann/Encrypted-Chat | /rsa.py | 1,843 | 4.15625 | 4 | # This class make encryption using RSA algorithm
import random
large_prime = [] # Is array for storing the prime numbers then select into it randomly
class Rsa:
def generate_prime(self, lower, upper): # this function simply generate prime numbers
for num in range(lower, upper+1):
if num >... | true |
721e7a53934cff06f6b2dedca6224105f625e56e | marb61a/Course-Notes | /Artificial Intellingence/Python/Notebooks/PyImageSearch University/OpenCV 102/simple_thresholding.py | 2,216 | 4.3125 | 4 | # USAGE
# python simple_thresholding.py --image images/coins01.png
# The accompanying text tutorial is available at
# https://www.pyimagesearch.com/2021/04/28/opencv-thresholding-cv2-threshold/
# Thresholding is a basic image segmentation technique
# The goal is to segment an image into foreground and background pixel... | true |
21c4e3dc082242c5efe4e4ee022ab830b01c6488 | markk628/SortingAlgorithms | /IntegerSortingAlgorithm/bucket_sort.py | 2,911 | 4.25 | 4 | import time
def merge(items1, items2):
merged_list = []
left = 0
right = 0
while left < len(items1) and right < len(items2):
if items1[left] < items2[right]:
merged_list.append(items1[left])
left += 1
else:
merged_list.append(items2[right])
... | true |
7de66659c2cfe58e23c57090703c6a788eb1eb1c | Klauss-Preising/Weekly-Challenges | /Fall - 2018/Week 4/Week 4.py | 712 | 4.21875 | 4 | """
Make a function that takes a list and returns the list sorted using selection sor
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
"""
def ... | true |
661a13971faf750ec454dc6ce878c7bbf4bb1f92 | NatalyaDomnina/leetcode | /python/05. [31.08.17] Merge Two Binary Trees.py | 2,032 | 4.15625 | 4 | '''
Given two binary trees and imagine that when you put one of them to cover the
other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two
nodes overlap, then sum node values up as the new value of the merged node.
Otherw... | true |
42ae6ae0d309950914bdbc6350a180c24a1a5d92 | fancy0815/Hello-Hello | /Python/5_Functions/1_Map and Lambda Function.Py | 436 | 4.21875 | 4 | cube = lambda x: x**3 # complete the lambda function
def fibonacci(n):
# return a list of fibonacci numbers
if n==1:
return [0]
if n==0:
return []
fib = [0,1]
for i in range (2,n):
fib += [sum(fib[i-2:i])]
return fib
# return fib[0:n]
# return[sum(fib[i-2:i]) fo... | true |
fe6bb27b70808ee72441d9aba87040d52d09b6a1 | skybohannon/python | /w3resource/basic/4.py | 378 | 4.59375 | 5 | # 4. Write a Python program which accepts the radius of a circle from the user and compute the area.
# The area of circle is pi times the square of its radius.
# Sample Output :
# r = 1.1
# Area = 3.8013271108436504
from math import pi
radius = float(input("Please enter the radius of your circle: "))
area = pi * (rad... | true |
334fb0bde5f0c2fddee9b27d104aa54a233f45d8 | skybohannon/python | /w3resource/string/11.py | 323 | 4.15625 | 4 | # 11. Write a Python program to remove the characters which have odd index values of a given string.
def remove_odds(str):
new_str = ""
for i in range(len(str)):
if i % 2 == 0:
new_str = new_str + str[i]
return new_str
print(remove_odds("The quick brown fox jumped over the lazy dog"... | true |
6612b6f86f022b90b5e41f4aff4586aacf41e1ce | skybohannon/python | /w3resource/25.py | 333 | 4.25 | 4 | # 25. Write a Python program to check whether a specified value is contained in a group of values.
# Test Data :
# 3 -> [1, 5, 8, 3] : True
# -1 -> [1, 5, 8, 3] : False
def in_values(i, lst):
if i in lst:
return True
else:
return False
print(in_values(3, [1, 5, 8, 3]))
print(in_values(-1, [1... | true |
d31125e3528c4ce3fbde12349bacfcc20d4fd5d9 | skybohannon/python | /w3resource/string/32.py | 256 | 4.125 | 4 | # 32. Write a Python program to print the following floating numbers with no decimal places.
x = 3.1415926
y = -12.9999
print("Original number: {}\nFormatted number: {:.0f}".format(x, x))
print("Original number: {}\nFormatted number: {:.0f}".format(y, y)) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.