blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
1c0357c5d25156eb2b9024fa411639ad0ff2aec9 | Atrociou/Saved-Things | /todo.py | 619 | 4.1875 | 4 | print("Welcome to the To Do List")
todoList = ["Homework", "Read", "Practice" ]
while True:
print("Enter a to add an item")
print("Enter r to remove an item")
print("Enter p to print the list")
print("Enter q to quit")
choice = input("Make your choice: ")
if choice == "q":
exit()
break
elif choi... | true |
7ca8bdfb4b5f89ec06fb494a75413184f153401d | NISHU-KUMARI809/python--codes | /abbreviation.py | 522 | 4.25 | 4 | # python program to print initials of a name
def name(s):
# split the string into a list
l = s.split()
new = ""
# traverse in the list
for i in range(len(l) - 1):
s = l[i]
# adds the capital first character
new += (s[0].upper() + '.')
# l[-1] gives last it... | true |
6c8e860f0ac34f6199c71ba0b528622dc980e61a | xdc7/pythonworkout | /chapter-03/01-extra-02-sum-plus-minus.py | 1,155 | 4.15625 | 4 | """
Write a function that takes a list or tuple of numbers. Return the result of alternately adding and subtracting numbers from each other. So calling the function as plus_minus([10, 20, 30, 40, 50, 60]) , you’ll get back the result of 10+20-30+40-50+60 , or 50 .
"""
import unittest
def plus_minus(sequence):
sum... | true |
182bc373458a808387825084a7927ff50288e270 | xdc7/pythonworkout | /chapter-02/05-stringsort.py | 984 | 4.25 | 4 | """
In this exercise, you’ll explore this idea by writing a function, strsort, that takes a single string as its input, and returns a string. The returned string should contain the same characters as the input, except that its characters should be sorted in order, from smallest Unicode value to highest Unicode value.
... | true |
92188bb3349159b96640692939e9b784426ee41d | xdc7/pythonworkout | /chapter-04/03-restaurant.py | 1,383 | 4.28125 | 4 | """
create a new dictionary, called menu, representing the possible
items you can order at a restaurant. The keys will be strings, and the values will be prices (i.e.,
integers). The program will then ask the user to enter an order:
If the user enters the name of a dish on the menu, then the program prints the price a... | true |
a265236d9b35352de75c292cd30b2b66301aae55 | xdc7/pythonworkout | /chapter-02/01-pig-latin.py | 987 | 4.25 | 4 | """write a Python program that asks the user to enter an English word. Your program should then print the word, translated into Pig Latin. You may assume that the word contains no capital letters or punctuation.
# How to translate a word to pig latin:
* If the word begins with a vowel (a, e, i, o, or u), then add way... | true |
476c3f377be42a32630992fd0fbbc18bce1c9288 | xdc7/pythonworkout | /chapter-05/5.2.2-factors.py | 1,054 | 4.28125 | 4 | """
Ask the user to enter integers, separated by spaces. From this input, create a dictionary whose keys are the factors for each number, and the values are lists containing those of the users' integers that are multiples of those factors.
"""
def calculateFactors(num):
factors = []
for i in range (1, num + 1... | true |
bfdc1168bf7bbbf621d41de4efb479b1bf4a11fe | xdc7/pythonworkout | /chapter-01/05-extra-01-hex-to-dec.py | 1,737 | 4.25 | 4 | """
Write a program that takes a hex number and returns the decimal equivalent. That is, if the user enters 50, then we will assume that it is a hex number (equal to 0x50), and will print the value 80 on the screen. Implement the above program such that it doesn’t use the int function at all, but rather uses the builti... | true |
38a591219f2e390385353788fa8c1eb969e4d253 | maurice-gallagher/exercises | /chapter-5/ex-5-6.py | 2,004 | 4.5 | 4 | # Programming Exercise 5-6
#
# Program to compute calories from fat and carbohydrate.
# This program accepts fat grams and carbohydrate grams consumed from a user,
# uses global constants to calculate the fat calories and carb calories,
# then passes them to a function for formatted display on the screen.
# Glo... | true |
667c668af92cafa7af07828df395d4d43b948b75 | nazariyv/leetcode | /solutions/medium/bitwise_and_of_numbers_range/main.py | 554 | 4.3125 | 4 | #!/usr/bin/env python
# Although there is a loop in the algorithm, the number of iterations is bounded by the number of bits that an integer has, which is fixed.
def bit_shift(m: int, n: int) -> int:
shifts = 0
while m != n:
m >>= 1
n >>= 1
shifts += 1
return 1 << shifts
# if n... | true |
e305999659409116a695be650da868d41cad775c | sandeepbaldawa/Programming-Concepts-Python | /recursion/regex_matching_1.py | 1,453 | 4.28125 | 4 | '''
Implement a regular expression function isMatch that supports the '.' and '*' symbols.
The function receives two strings - text and pattern - and should return true if the text
matches the pattern as a regular expression. For simplicity, assume that the actual symbols '.'
and '*' do not appear in the text string... | true |
96a0bc369ee2198c2bc03d5d555d6449a4339693 | sandeepbaldawa/Programming-Concepts-Python | /recursion/cryptarithm.py | 2,093 | 4.28125 | 4 | Cryptarithm Overview
The general idea of a cryptarithm is to assign integers to letters.
For example, SEND + MORE = MONEY is “9567 + 1085 = 10652”
Q. How to attack this problem?
-Need list of unique letters
-Try all possible assignments of single digits
-Different arrangemen... | true |
d39cf9c6a416f7678bf3b98e36ab52b6ac17997a | sandeepbaldawa/Programming-Concepts-Python | /recursion/crypto_game.py | 2,243 | 4.34375 | 4 | '''
Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it.
Input formula is a string; output is a digit-filled-in string or None.
Where are we spending more time?
if we run CProfile on CProfile.run('test()')
we see maximum time is spent inside valid function,
so how do we optimize the same?
In valid ... | true |
16494f0438fe6af0cfc369187fa8c8708bda7925 | sandeepbaldawa/Programming-Concepts-Python | /lcode/amazon/medium_sort_chars_by_freq.py | 504 | 4.25 | 4 | '''
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"
Output:
"eert"
'''
from collections import defaultdict
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
res = defaultdict(int... | true |
4fcf4d2382a0222c93bcd328383399ea292ea031 | isrishtisingh/python-codes | /URI-manipulation/uri_manipulation.py | 1,173 | 4.125 | 4 | # code using the uriModule
# the module contains 2 functions: uriManipulation & uriManipulation2
import uriModule
# choice variable is for choosing which function to use for manipulating the URL/URI
choice = -1
try:
choice = int(input(" \n Enter 1 to parse given URL/URIs \n Enter 2 to enter your own URI/U... | true |
89ea463ab59b1aa03b14db54ec8d86a8a4168fcf | iriabc/python_exercises | /exercise3.py | 2,082 | 4.46875 | 4 | from collections import deque
def minimum_route_to_treasure(start, the_map):
"""
Calculates the minimum route to one of the treasures for a given map.
The route starts from one of the S points and can move one block up,
down, left or right at a time.
Parameters
----------
the_map: list of... | true |
19d10ffc36a71b8e662857b9f83cbdecdb47114e | TnCodemaniac/Pycharmed | /hjjj.py | 567 | 4.125 | 4 |
import turtle
num_str = input("Enter the side number of the shape you want to draw: ")
if num_str.isdigit():
s= int(num_str)
angle = 180 - 180*(10-2)/10
turtle.up
x = 0
y = 0
turtle.setpos(x,y)
numshapes = 8
for x in range(numshapes):
turtle.color("red")
x += 5
y += 5
turtle.forward(x)
tur... | true |
2d5a337a4cef68a85705c164d5dcdfbd4edb5e17 | nembangallen/Python-Assignments | /Functions/qn10.py | 384 | 4.15625 | 4 | """
10. Write a Python program to print the even numbers from a given list.
Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result : [2, 4, 6, 8]
"""
def get_even(my_list):
even_list = []
for item in my_list:
if (item % 2 == 0):
even_list.append(item)
else:
pass
... | true |
8a872760535ef1b17100bdd9faee4ff6609c1b8d | nembangallen/Python-Assignments | /Functions/qn13.py | 395 | 4.21875 | 4 | """
13. Write a Python program to sort a list of tuples using Lambda.
"""
def sort_tuple(total_student):
print('Original List of tuples: ')
print(total_student)
total_student.sort(key=lambda x: x[1])
print('\nSorted:')
print(total_student)
total_student = [('Class I', 60), ('Class II', 53),
... | true |
040902675356f5d842d290c5b0570546bc83c9cb | nembangallen/Python-Assignments | /Functions/qn8.py | 387 | 4.28125 | 4 | """
8. Write a Python function that takes a list and returns a new list with unique
elements of the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
"""
def unique_list(my_list):
unique_list = []
for x in my_list:
if x not in unique_list:
unique_list.append(x)
... | true |
ecedcca7da6cd799acc1bce8c0e2b4361c9652a4 | BlaiseMarvin/pandas-forDataAnalysis | /sortingAndRanking.py | 1,820 | 4.34375 | 4 | #sorting and ranking
# to sort lexicographically, we use the sort_index method which returns a new object
import pandas as pd
import numpy as np
obj=pd.Series(range(4),index=['d','a','b','c'])
print(obj)
print("\n")
print(obj.sort_index()) #this sorts the indices
#with a dataframe, you can sort by index on either ... | true |
7d44b3978280fed567e2422c24f0d2488c28d89d | vandent6/basic-stuff | /elem_search.py | 893 | 4.15625 | 4 |
def basic_binary_search(item, itemList):
"""
(str, sequence) -> (bool)
Uses binary search to split a list and find if the item is in the list.
Examples:
basic_binary_search(7,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90, 100, 600]) -> True
basic_binary_search(99,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90... | true |
2817f68fa0dc08ba61921f04a3c4ea5eccc31b38 | ltrii/Intro-Python-I | /src/cal.py | 1,702 | 4.6875 | 5 | # """
# The Python standard library's 'calendar' module allows you to
# render a calendar to your terminal.
# https://docs.python.org/3.6/library/calendar.html
# Write a program that accepts user input of the form
# `calendar.py month [year]`
# and does the following:
# - If the user doesn't specify any input, you... | true |
4d726618926c5e8d18a6f6a1f6b69fe670c46ad5 | JayVer2/Python_intro_week2 | /7_dictionaries.py | 469 | 4.125 | 4 |
#Initialize the two dictionaries
meaningDictionary = {}
sizeDictionary = {}
meaningDictionary["orange"] = "A Fruit"
sizeDictionary["orange"] = 5
meaningDictionary["cabbage"] = "A vegetable"
sizeDictionary["cabbage"] = 10
meaningDictionary["tomato"] = "Widely contested"
sizeDictionary["tomato"] = 5
print("What defi... | true |
4207246674a228f5ab87bf29c41ef6677a1165fc | jaclynchorton/Python-MathReview | /Factorial-SqRt-GCD-DegreeAndRadians.py | 556 | 4.15625 | 4 | #------------------From Learning the Python 3 Standard Library------------------
#importing math functions
import math
#---------------------------Factorial and Square Root---------------------------
# Factorial of 3 = 3 * 2* 1
print(math.factorial(3))
# Squareroot of 64
print(math.sqrt(64))
# GCD-Greatest Common Den... | true |
0eacae023b58e7727bcfcec37684d47ab49ddfbb | Jabed27/Data-Structure-Algorithms-in-Python | /Algorithm/Graph/BFS/bfs.py | 1,508 | 4.25 | 4 | # https://www.educative.io/edpresso/how-to-implement-a-breadth-first-search-in-python
from collections import defaultdict
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
#initializing a default dictionary with list
graph=defaultdict(list)
parent=[]
dist=[]
def init(n):
for ... | true |
a4a2e639b8c672ebfdb7f8b67f1f567c1ebc704e | Programmer7129/Python-Basics | /Functions.py | 444 | 4.25 | 4 | # For unknown arguments in a function
def myfunc(**name):
print(name["fname"]+" "+name["lname"])
myfunc(fname="Emily", lname="Scott")
def func(*kids):
print("His name is: "+ kids[1])
func("Mark", "Harvey", "Louis")
# Recursion
def recu(k):
if(k > 0):
result = k + recu(k-1)
... | true |
79072e55960b5de9f56486db34748bfaa55c08b9 | FayazGokhool/University-Projects | /Python Tests/General Programming 2.py | 2,320 | 4.125 | 4 | def simplify(list1, list2):
list1_counter,list2_counter = 0,0 #This represents the integer in each array that the loop below is currently on
list3 = [] #Initialise the list
list1_length, list2_length = len(list1), len(list2) #Gets the length of both lists and stores them as varibales so they don't have to be called... | true |
39fdd0263563f932f80ce91303ba69e74bf67259 | leilii/com404 | /1-basics/3-decision/4-modul0-operator/bot.py | 214 | 4.375 | 4 | #Read whole number UserWarning.
#work out if the number is even.
print("Please enter a number.")
wholenumber=int(input())
if (wholenumber%2 == 0):
print("The number is even")
else:
print("The number is odd")
| true |
b7d81a61e20219298907d2217469d74539b10ac4 | fwparkercode/Programming2_SP2019 | /Notes/RecursionB.py | 806 | 4.375 | 4 | # Recursion - function calling itself
def f():
print("f")
g()
def g():
print("g")
# functions can call other functions
f()
def f():
print("f")
f()
g()
def g():
print("g")
# functions can also call themselves
#f() # this causes a recursion error
# Controlling recursion with depth
def c... | true |
21f141bbd269f85b302c1950cc0f2c8705f97854 | tejasgondaliya5/advance-python-for-me | /class_variable.py | 615 | 4.125 | 4 | class Selfdetail:
fname = "tejas" # this is class variable
def __init__(self):
self.lname = "Gondaliya"
def printdetail(self):
print("name is :", obj.fname, self.lname) # access class variable without decorator
@classmethod # access class va... | true |
298c5f852cc317067c7dfcceb529273bbc89ec66 | tejasgondaliya5/advance-python-for-me | /Method_Overloding.py | 682 | 4.25 | 4 | '''
- Method overloding concept is does not work in python.
- But Method ovrloding in diffrent types.
- EX:- koi ek method ma different different task perform thay tene method overloading kehvay 6.
'''
class Math:
# def Sum(self, a, b, c):
def Sum(self, a = None, b=None, c=None): # this one method b... | true |
08421cdc822d1ee9fb6a906927bb4836f1bc691f | YuanchengWu/coding-practice | /problems/1.4.py | 605 | 4.1875 | 4 | # Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palin drome.
# A palindrome is a word or phrase that is the same forwards and backwards.
# A permutation is a rearrangement of letters.
# The palindrome does not need to be limited to just dictionary words.
def palindrome_... | true |
767b3239ad235c29906cc7f903713ac0c67712c7 | laboyd001/python-crash-course-ch7 | /pizza_toppings.py | 476 | 4.34375 | 4 | #write a loop that prompts the user to enter a series of pizza toppings until they enter a 'quit' value. As they enter each topping, print a message saying you'll add that to their pizza.
prompt = "\nPlease enter the name of a topping you'd like on your pizza:"
prompt += "\n(Enter 'quit' when you are finished.) "
... | true |
77a0cf7be579cd67bf2f9a449d8615c682924d6f | dipeshdc/PythonNotes | /loops/for.py | 782 | 4.125 | 4 | """
For Loop
"""
sentence = "the cat sat on the mat with"# the rat cat and rat were playing in the mat and the cat was happy with rat on the mat"
'''
print("Sentence is: ",sentence)
print("Length of sentence:", len(sentence))
print("Number of Occurrences of 'cat': ", sentence.count('t')) #3
'''
count=0
for char in s... | true |
014db87928669d171b65f3c43c09aca9345843bc | MrLVS/PyRep | /HW5.py | 621 | 4.15625 | 4 | print("Введите неотрицательные целые числа, через пробел: ")
answer = input("--> ")
def find_min_int_out_of_string(some_string):
""" A function to find the minimum number outside the list. """
int_list = list(map(int, some_string.split()))
for i in range(1, max(int_list)+1):
if i not in int_list:
... | true |
35d0fce23734caccf4dc22ddec7175a2230b3c5d | MrLVS/PyRep | /HW10.py | 496 | 4.21875 | 4 | # Solution of the Collatz Hypothesis
def сollatz(number):
""" A function that divides a number by two if the number is even,
divides by three if the number is not even, and starts a new loop.
Counts the number of cycles until the number is exactly 1. """
i = 0
while number > 1:
if numbe... | true |
4dc8fcf6c516ca8bf19c652eef0ab235aa0dc1c4 | frederatic/Python-Practice-Projects | /palindrome.py | 509 | 4.3125 | 4 | # Define a procedure is_palindrome, that takes as input a string, and returns a
# Boolean indicating if the input string is a palindrome.
def is_palindrome(s):
if s == "": # base case
return True
else:
if s[0] == s[-1]: # check if first and last letter match
return is_palin... | true |
9185f60dee9625d663bcecea816da0255507f7a3 | ukrduino/PythonElementary | /Lesson02/Exercise2_1.py | 724 | 4.65625 | 5 | # Write a recursive function that computes factorial
# In mathematics, the factorial of a non-negative integer n, denoted by n!,
# is the product of all positive integers less than or equal to n. For example,
# 5! = 5 * 4 * 3 * 2 * 1 = 120.
def factorial_rec(n):
"""
Computing factorial using recursio... | true |
ec90fa2fe745ef77be5573534260e1261f3a0d87 | Anku-0101/Python_Complete | /String/03_StringFunction.py | 329 | 4.15625 | 4 | story = "once upon a time there lived a guy named ABC he was very intelliget and motivated, he has plenty of things to do"
# String Function
print(len(story))
print(story.endswith("Notes"))
print(story.count("he"))
print(story.count('a'))
print(story.capitalize())
print(story.find("ABC"))
print(story.replace("ABC", ... | true |
1d8479254cbe4a936f1b7c21715fc58638f61f84 | Anku-0101/Python_Complete | /DataTypes/02_Operators.py | 591 | 4.15625 | 4 | a = 3
b = 4
print("The value of a + b is", a + b)
print("The value of a*b is", a * b)
print("The value of a - b is", a - b)
print("The value of a / b is", a / b)
print("The value of a % b is", a % b)
print("The value of a > b is", a > b)
print("The value of a == b is", a == b)
print("The value of a != b is", a != b)
p... | true |
05f486e4dac5d903bd5ec01c15c0835caa59a8b2 | Weenz/software-QA-hw2 | /bmiCalc.py | 1,631 | 4.3125 | 4 | import math
#BMI Calculator function
def bmiCalc():
print ("")
print ("BMI Calculator")
print ("------------------")
#Loop to verify integer as input for feet
while True:
try:
feet = int(input("Enter your feet part of your height: "))
except ValueError:
... | true |
12491cc31c5021a38cb40799492171c2d5b6b978 | muneel/url_redirector | /redirector.py | 2,194 | 4.25 | 4 | """
URL Redirection
Summary:
Sends the HTTP header response based on the code received.
Converts the URL received into Location in the response.
Example:
$ curl -i http://127.0.0.1:5000/301/http://www.google.com
HTTP/1.0 301 Moved Permanently
Server: BaseHTTP/0.3 Python/2.7.5
Date: Wed, 19 Apr 2017 20:06:11 GMT
Locat... | true |
94c39abb57532962ca90b9df933800cfa6d1b3b3 | AswinT22/Code | /Daily/Vowel Recognition.py | 522 | 4.1875 | 4 |
# https://www.hackerearth.com/practice/basic-programming/complexity-analysis/time-and-space-complexity/practice-problems/algorithm/vowel-game-f1a1047c/
def count_vowel(string,):
vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
count = 0
length=len(string)
for i in range(0, length):
i... | true |
d9816ac73df50f5676313824859a15b10485a7c4 | affreen/Python | /pyt-14.py | 511 | 4.28125 | 4 | """demo - script that converts a number into an alphabet and then
determines whether it is an uppercase or lowercase vowel or consonant"""
print("Enter a digit:")
var=input()
var=int(var)
new_var=chr(var)
#if(new_var>=97 and new_var<=122):
if (new_var in ['a','e','i','o','u']):
print("You have entered a... | true |
f33786d90ed22092a69a7114e274fd8610c4d278 | admcghee23/RoboticsFall2019GSU | /multiCpuTest.py | 2,198 | 4.3125 | 4 | #!/usr/bin/env python
'''
multiCpuTest.py - Application to demonstrate the use of a processor's multiple CPUs.
This capability is very handy when a robot needs more processor power, and has processing elements
that can be cleaved off to another CPU, and work in parallel with the main application.
... | true |
7fb846cef384bf05421502c4602add3a30f2c889 | mahespunshi/Juniper-Fundamentals | /Comprehensions.py | 1,006 | 4.53125 | 5 | # List comprehension example below. notes [] parenthesis. Comprehensions can't be used for tuple.
x =[x for x in range(10)]
print(x)
# create comprehension and it can creates for us, but in dict we need to create it first and then modify it.
# so, we can't create auto-dict, we can just modify dict, unlike list.
# Dict... | true |
19e0975c0f0f0df045b2c1a1e6ff13ad97a3aee6 | BaDMaN90/COM404 | /Assessment_1/Q7functions.py | 1,429 | 4.3125 | 4 | #file function have 4 functions that will do a cool print play
#this function will print piramids on the left of the face
def left(emoji):
print("/\/\/\\",emoji)
#this function will print piramids on the right of the face
def right(emoji):
print(emoji,"/\/\/\\")
#this function will print face between piramid... | true |
3f7d577aacbb73da5406b3676fb12d9947c98e51 | BaDMaN90/COM404 | /Basic/4-repetition/1-while-loop/2-count/bot.py | 684 | 4.125 | 4 | #-- importing the time will allow the time delay in the code
#-- progtram will print out the message and ask for input
#-- 2 variables are created to run in the while loop to count down the avoided live cables and count up how many have avoided
import time
print("Oh no, you are tangle up in these cables :(, how many li... | true |
5996714a292cf5902cefb2830c497c7d81959b54 | RPadilla3/python-practice | /python-practice/py-practice/greeter.py | 407 | 4.1875 | 4 | prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name?"
name = input(prompt)
print("\n Hello, " + name + "!")
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print("\nThe number " + ... | true |
5d10bf344a26b484e373e93cd734b9c405d3076c | rexrony/Python-Assignment | /Assignment 4.py | 2,548 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#Question 1
firstname = input("Your First Name Please ");
lastname = input("Your Last Name Please ");
age = int(input("Your Age Please "));
city = input("Your City Please ");
userdata = {
'first_name': firstname,
'last_name': lastname,
'age': age,
'... | true |
8536c9d42de73a7e2b426c38df271740c51f79e2 | HarshHC/DataStructures | /Stack.py | 1,819 | 4.28125 | 4 | # Implementing stack using a linked list
# Node Class
class Node(object):
# Initialize node with value
def __init__(self, value):
self.value = value
self.next = None
# Stack Class
class Stack(object):
# Initializing stack with head value and setting default size to 1
def __init__(self, ... | true |
dec63d4f99825d1934be4b81836d5a3728b8038e | DKanyana/Code-Practice | /ZerosAndOnes.py | 372 | 4.25 | 4 | """
Given an array of one's and zero's convert the equivalent binary value to an integer.
Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
"""
def binary_array_to_number(arr):
binNum = 0
for cnt,num in enumerate(arr):
binNum += num * (2 ** (len(arr)-1-cnt))
return bin... | true |
67588905fa64b3e7efa93541b569769688d1600f | krrish12/pythonCourse | /Day-4/DecisionMaking.py | 1,578 | 4.125 | 4 | var,var1 = 100,110
if ( var == 100 ) : print("Value of expression is 100 by Comparison operator")
#output: Value of expression is 100
if ( var == 10 ): print("Value of expression is 10 by Comparison operator")
elif(var1 == 50): print("Value of expression is 50 by Comparison operator")
else:print("Value of expression i... | true |
56af4680b7f68a43096c0c8d8a9d81a318b3ceea | Tom0497/BCS_fuzzy | /src/FuzzyFact.py | 2,097 | 4.46875 | 4 | class FuzzyFact:
"""
A class to represent a fuzzy fact, i.e. a fact or statement with a value of certainty in the range [-1, 1],
where -1 means that the fact is a 100% not true, whereas a value of 1 means that the fact is a 100% true,
finally, a value of 0 means ignorance or lack of knowledge in terms o... | true |
6048b803d984e8837f31aaa7c31667e396f4b0b0 | yogesh1234567890/insight_python_assignment | /completed/Data3.py | 384 | 4.21875 | 4 | '''3. Write a Python program to get a string from a given string where all
occurrences of its first char have been changed to '$', except the first char itself.
Sample String : 'restart'
Expected Result : 'resta$t' '''
user=input("Enter a word: ")
def replace_fun(val):
char=val[0]
val=val.replace(char,'$')
... | true |
12d6c22a4cdacef7609f965d1f682213f06d25d1 | yogesh1234567890/insight_python_assignment | /completed/Data22.py | 267 | 4.1875 | 4 | #22. Write a Python program to remove duplicates from a list.
mylist=[1,2,3,4,5,4,3,2]
mylist = list(dict.fromkeys(mylist))
print(mylist)
##here the list is converted into dictionaries by which all duplicates are removed and its well again converted back to list | true |
c0874441b6ae538e3be713d71015ec626f04272f | yogesh1234567890/insight_python_assignment | /functions/Func14.py | 498 | 4.4375 | 4 | #14. Write a Python program to sort a list of dictionaries using Lambda.
models = [{'name':'yogesh', 'age':19, 'sex':'male'},{'name':'Rahsit', 'age':70, 'sex':'male'}, {'name':'Kim', 'age':29, 'sex':'female'},]
print("Original list:")
print(models)
sorted_models = sorted(models, key = lambda x: x['name'])
print("\nSo... | true |
93705ba1b2d202737fa5f9f9852ed9814f768eb4 | yogesh1234567890/insight_python_assignment | /functions/Func5.py | 313 | 4.40625 | 4 | """ 5. Write a Python function to calculate the factorial of a number (a non-negative
integer). The function accepts the number as an argument. """
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
n=int(input("Insert a number to calculate the factiorial : "))
print(fact(n)) | true |
7d701dbeb4a04cda556c0bc2da03de589a1d26e9 | yogesh1234567890/insight_python_assignment | /completed/Data39.py | 206 | 4.1875 | 4 | #39. Write a Python program to unpack a tuple in several variables.
a = ("hello", 5000, "insight")
#here unpacking is done
(greet, number, academy) = a
print(greet)
print(number)
print(academy)
| true |
93d2d0026b5d737c60049229091c9c01faedf0f0 | yogesh1234567890/insight_python_assignment | /functions/Func7.py | 666 | 4.25 | 4 | """ 7. Write a Python function that accepts a string and calculate the number of
upper case letters and lower case letters.Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12 """
string="The quick Brow Fox"
def check(string):
upper=0
l... | true |
45c4e66f0dba9851ea5539d2c98e6076ed1ad8fd | sk-ip/coding_challenges | /December_2018/stopwatch.py | 734 | 4.125 | 4 | # program for stopwatch in python
from datetime import date, datetime
def stopwatch():
ch=0
while True:
print('stopwatch')
print('1. start')
print('2. stop')
print('3. show time')
print('4. exit')
ch=input('enter your choice:')
if ch=='1':
sta... | true |
9f34a088a4d0a61f2af65fa911222eb2d3372dd8 | mbramson/Euler | /python/problem016/problem016.py | 488 | 4.125 | 4 | # -*- coding: utf-8 -*-
## Power Sums
## 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
## What is the sum of the digits of the number 2**1000?
## This is actually a very simple problem in python, because Python automatically deals with large numbers.
## Returns the Power Sum of n. As in it sum... | true |
a4382447caa1d2c2e4bfd9ddedef88a7063bf943 | valerienierenberg/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 1,421 | 4.1875 | 4 | #!/usr/bin/python3
"""This module contains a function island_perimeter that returns
the perimeter of the island described in grid
"""
def island_perimeter(grid):
"""island_perimeter function
Args:
grid ([list of a list of ints]):
0 represents a water zone
1 represents a la... | true |
74a62d228dbd2ce456d09211bea6f15d822ca3f7 | James-E-Sullivan/BU-MET-CS300 | /sullivan_james_lab3.py | 2,052 | 4.25 | 4 | # Eliza300
# Intent: A list of helpful actions that a troubled person could take. Build 1
possible_actions = ['taking up yoga.', 'sleeping eight hours a night.',
'relaxing.', 'not working on weekends.',
'spending two hours a day with friends.']
'''
Precondition: possibl... | true |
91e5fa35bc4ea64c7cc65e096d10ed0d91d8d88b | bperard/PDX-Code-Guild | /python/lab04-grading.py | 320 | 4.125 | 4 | score = int(input('On a scale of 0-100, how well did you?'))
grade = ''
if score > 100:
grade = 'Overachiever'
elif score > 89:
grade = 'A'
elif score > 79:
grade = 'B'
elif score > 69:
grade = 'C'
elif score > 59:
grade = 'D'
elif score >= 0:
grade = 'F'
else:
grade = 'Leave'
print(grade)
| true |
21ab8c793589afe2c8f984db02ca2b5650be962b | bperard/PDX-Code-Guild | /python/lab08-roshambo.py | 1,309 | 4.25 | 4 | '''
Rock, paper, scissors against the computer
'''
import random
throws = ['rock', 'paper', 'scissors'] #comp choices
comp = random.choice(throws)
player = input('Think you can beat me in a game of Roshambo? I doubt it, but let\'s give it a shot.\n Choose your weapon: paper, rock, scissor.').lower() #player prompt
... | true |
75566c13a5e09874a1ea4ff64c7f198b7f4218fc | bperard/PDX-Code-Guild | /python/lab31-atm.py | 2,865 | 4.21875 | 4 | '''
lab 31 - automatic teller machine machine
'''
transactions = [] # list of deposit/withdraw transactions
class ATM: # atm class with rate and balance attribute defaults set
def __init__(self, balance = 0, rate = 0.1):
self.bal = balance
self.rat = rate
def __str__(self): # format w... | true |
e5a8eae58dc45a0259309b867eeac974b3dc7d62 | bperard/PDX-Code-Guild | /python/lab09-change.py | 838 | 4.25 | 4 | '''
Making change
'''
# declaring coin values
quarters = 25
dimes = 10
nickles = 5
pennies = 1
# user input, converted to float
change = float(input('Giving proper change is key to getting ahead in this crazy world.\n'
'How much money do you have? (for accurate results, use #.## format)'))
# conv... | true |
07de036683eeaf643caaa7e140c8959af82703e7 | RobertCochran/connect4 | /user_input.py | 1,148 | 4.25 | 4 | import random
def user_input():
""" This function allows the user to choose where their red piece goes. """
print "We're going to play Connect Four."
print " I'll be black and you'll be red. "
print "You go first and choose where you want to put your piece. There are seven columns in total."
... | true |
eb7cb4ffdec2e4c5790db0c1d1b407ed5b8a2930 | galgodon/astr-119-hw-1 | /operators.py | 1,641 | 4.5 | 4 | #!/usr/bin/env python3 # makes the terminal know this is in python
x = 9 #Set variables
y = 3
#Arithmetic Operators
print(x+y) # Addition
print(x-y) # Subtraction
print(x*y) # Multiplication
print(x/y) # Division
print(x%y) # Modulus (remainder)
print(x**y) # Exponentiation ... | true |
9bdfa82561a8638beb7caa171e52f717cc3bb89e | galgodon/astr-119-hw-1 | /functions.py | 1,209 | 4.1875 | 4 | #!/usr/bin/env python3
import numpy as np # import numpy and sys
import sys
def expo(x): # define a function named expo that needs one input x
return np.exp(x) # the function will return e^x
def show_expo(n): # define a subroutine (does not return ... | true |
3ad1a7fcb0a7b6d2c7ba0e1f639d396c6adf6fe7 | Peter-Moldenhauer/Python-For-Fun | /If Statements/main.py | 502 | 4.3125 | 4 | # Name: Peter Moldenhauer
# Date: 1/12/17
# Description: This program demonstrates if statements in Python - if, elif, else
# Example 1:
age = 12
if age < 21:
print("Too young to buy beer!")
# Example 2:
name = "Rachel"
if name is "Peter": # you can use the keword is to compare strings (and also numbers), it... | true |
26cdf3876507195bf2db3deb50b2bee7eb316483 | JatinBumbra/neural-networks | /2_neuron_layer.py | 1,059 | 4.15625 | 4 | '''
SIMPLE NEURON LAYER:
This example is a demonstration of a single neuron layer composed of 3 neurons. Each neuron has it's own weights that it
assigns to its inputs, and the neuron itself has a bias. Based on these values, each neuron operates on the input vector
and produces the output.
The be... | true |
d8fb565e7a39ebb7a200514407b2ffb49e07b19d | adharmad/project-euler | /python/commonutils.py | 2,794 | 4.34375 | 4 | import functools
from math import sqrt
@functools.lru_cache(maxsize=128, typed=False)
def isPrime(n):
"""
Checks if the number is prime
"""
# Return false if numbers are less than 2
if n < 2:
return False
# 2 is smallest prime
if n == 2:
return True
# All even numbers ... | true |
779d06833f0b30281c71242196a77f9ff08ce094 | abhay-rana/python-tutorials. | /DATA STRUCTURE AND ALGORITHMS/INSERRTION_ SORT.py | 397 | 4.15625 | 4 | #INSERTION SORT IS SIMILAR TO E WE PLAYING CARDS
# THE WAY WE SORT THE CARDS
def insertion_sort(arr):
for e in range(1,len(arr)):
temp=arr[e]
j=e-1
while j>=0 and temp<arr[j]:
arr[j+1]=arr[j] # we are forwarding the elements
j=j-1
else:
arr[j... | true |
6cc03c6e49891cacfa4ff2824caf9718994e1811 | Avinint/Python_musicfiles | /timeitchallenge.py | 1,006 | 4.375 | 4 | # In the section on Functions, we looked at 2 different ways to calculate the factorial
# of a number. We used an iterative approach, and also used a recursive function.
#
# This challenge is to use the timeit module to see which performs better.
#
# The two functions appear below.
#
# Hint: change the number of itera... | true |
f348334cc86f5d86e66be05fa2aaaab5da2460c6 | cyrus-raitava/SOFTENG_364 | /ASSIGNMENT_2/SOLUTIONS/checksum.py | 1,406 | 4.125 | 4 | # -*- coding: utf-8 -*-
def hextet_complement(num):
'''
Internet Checksum of a bytes array.
Further reading:
1. https://tools.ietf.org/html/rfc1071
2. http://www.netfor2.com/checksum.html
'''
# Create bitmask to help calculate one's complement
mask = 0xffff
# Use th... | true |
82b50126fd52145f1d863a61ca57c592bf13b297 | carlosflrslpfi/CS2-A | /class-08/scope.py | 1,521 | 4.21875 | 4 | # Global and local scope
# The place where the binding of a variable is valid.
# Global variable that can be seen and used everywhere in your program
# Local variable that is only seen/used locally.
# Local analogous to within a function.
# we define a global variable x
x = 5
def some_function():
x = 10 # local v... | true |
1f561cbd24991690d041d444eae5cc96a110e06d | bronyamcgrory1998/Variables | /Class Excercises 5.py | 724 | 4.21875 | 4 | #Bronya McGrory
#22/09/2014
#Both a fridge and a lift have heights, widths and depths. Work out how much space is left in the lift once the fridge
fridgeheight= int (input("fridge height"))
fridgewidth= int (input("fridge width"))
fridgedepth= int (input("fridge depth"))
volume_of_fridge_answer= fridgeheigh... | true |
2d8881cef624299204688eee1fbe091c8f32fab0 | mariia-iureva/code_in_place | /group_coding_sections/Section2/8ball.py | 991 | 4.375 | 4 | """
Simulates a magic eight ball.
Prompts the user to type a yes or no question and gives
a random answer from a set of prefabricated responses.
"""
import random
# make a bunch of random answers
ANSWER_1 = "Ask again later."
ANSWER_2 = "No way."
ANSWER_3 = "Without a doubt."
ANSWER_4 = "Yes."
ANSWER_5 = "Possibly."
d... | true |
a57612a005864e361ebf18274fc62a76f97618d1 | duonglong/practice | /magicalRoom.py | 2,880 | 4.15625 | 4 | # --*-- coding: utf-8 --*--
"""
You're an adventurer, and today you're exploring a big castle.
When you came in, you found a note on the wall of the room.
The note said that the castle contains n rooms, all of which are magical.
The ith room contains exactly one door which leads to another room roomsi.
Because the room... | true |
1cd204b6f3b4a171e9625b8d2a3db9c04e472b84 | duonglong/practice | /acode.py | 2,098 | 4.25 | 4 | """
Alice and Bob need to send secret messages to each other and are discussing ways to encode their messages:
Alice: 'Let's just use a very simple code: We'll assign 'A' the code word 1, 'B' will be 2, and so on down to 'Z' being assigned 26.'
Bob: 'That's a stupid code, Alice. Suppose I send you the word 'BEAN' enco... | true |
b3fbacf8e7c5a5fd61a833c04a2b4e87899dc127 | KRiteshchowdary/myfiles | /Calculator.py | 394 | 4.15625 | 4 | a = float(input('number 1 is '))
function = input('desired function is ')
b = float(input('number 2 is '))
if (function == '+'):
print(a + b)
elif (function == '-'):
print(a - b)
elif (function == '*'):
print(a*b)
elif (function == '/' and b != 0):
print(a/b)
elif (function == '/' and b==0):
print... | true |
0ee672d520f8a915f269215ac12d78738e46ed33 | bilun167/FunProjects | /CreditCardValidator/credit_card_validator.py | 1,036 | 4.1875 | 4 | """
This program uses Luhn Algorithm (http://en.wikipedia.org/wiki/Luhn_algorithm) and works with most credit card numbers.
1. From the rightmost digit, which is the check digit, moving left, double the value of every second digit.
2. If the result is greater than 9 (e.g., 7 * 2 = 14), then sum the digits of it (e.g... | true |
8153b4cfc2169b781bc16d1ad06e2ca4233b3ea9 | osagieomigie/foodWebs | /formatList.py | 1,572 | 4.21875 | 4 | ## Format a list of items so that they are comma separated and "and" appears
# before the last item.
# Parameters:
# data: the list of items to format
# Returns: A string containing the items from data with nice formatting
def formatList(data):
# Handle the case where the list is empty
if len(data) == ... | true |
d87ae28da2b3a113e2891241fddd47595525417f | margueriteblair/Intro-To-Python | /more-loops.py | 1,001 | 4.125 | 4 | #counting in a loop,
zork = 0
print('Before', zork)
for thing in [9, 42,12, 3, 74, 15]:
zork = zork+1
print(zork, thing)
print('After', zork)
count = 0
sum = 0
print('Before', count, sum)
for value in [9, 42,12, 3, 74, 15]:
count = count + 1
sum = sum + value
print(count, sum, value)
print('After... | true |
c3bce9a9f83075deeb2e20c609676b26e669840e | murffious/pythonclass-cornell | /coursework/working-with-data-file/samples/unit4/convert.py | 956 | 4.15625 | 4 | """
Module showing the (primitive) way to convert types in a CSV files.
When reading a CSV file, all entries of the 2d list will be strings, even if you
originally entered them as numbers in Excel. That is because CSV files (unlike
JSON) do not contain type information.
Author: Walker M. White
Date: June 7, 2019
"... | true |
30be17d0390482768e1351980180136f55087a9e | murffious/pythonclass-cornell | /coursework/programming-with-objects/exercise2/funcs.py | 1,793 | 4.15625 | 4 | """
Module demonstrating how to write functions with objects.
This module contains two versions of the same function. One version returns a new
value, while other modifies one of the arguments to contain the new value.
Author: Paul Murff
Date: Feb 6 2020
"""
import clock
def add_time1(time1, time2):
"""
Re... | true |
5aa45d78764eb9ca62abc1f4d6bfd82b7056d90d | ellafrimer/shecodes | /lists/helper.py | 549 | 4.46875 | 4 | print("Accessing just the elements")
for letter in ['a', 'b', 'c']:
print(letter)
print("Accessing the elements and their position in the collection")
for (index, letter) in enumerate(['a', 'b', 'c']):
print("[%d] %s" % (index, letter))
print("A string is also a collection...")
for (index, letter) in enumerat... | true |
6276c03f5933147d623376818f96cfa35f07f8e8 | shahamran/intro2cs-2015 | /ex3/findLargest.py | 410 | 4.46875 | 4 | #a range for the loop
riders=range(int(input("Enter the number of riders:")))
high_hat=0
gandalf_pos=0
#This is the loop that goes through every hat size and
#checks which is the largest.
for rider in riders:
height=float(input("How tall is the hat?"))
if height>high_hat:
high_hat=height
ganda... | true |
8552969c9e3f4e2764951ac3914572d1b9744a36 | Lumexralph/python-algorithm-datastructures | /trees/binary_tree.py | 1,471 | 4.28125 | 4 | from tree import Tree
class BinaryTree(Tree):
"""Abstract base class representing a binary tree structure."""
# additional abstract methods
def left_child(self, p):
"""Return a Position representing p's left child.
Return None if p does not have a left child
"""
raise Not... | true |
bf12f927c2d684699f41b48c1191ea956205a41c | km-aero/eng-54-python-basics | /exercise_103.py | 433 | 4.3125 | 4 | # Define the following variables
# name, last_name, species, eye_color, hair_color
# name = 'Lana'
name = 'Kevin'
last_name = 'Monteiro'
species = 'Alien'
eye_colour = 'blue'
hair_colour = 'brown'
# Prompt user for input and Re-assign these
name = input('What new name would you like?')
# Print them back to the user ... | true |
1736fa54bb0aa30ff931ced7e8fc61c104a3aa5d | CheshireCat12/hackerrank | /eulerproject/problem006.py | 544 | 4.21875 | 4 | #!/bin/python3
def square_of_sum(n):
"""Compute the square of the sum of the n first natural numbers."""
return (n*(n+1)//2)**2
def sum_of_squares(n):
"""Compute the sum of squares of the n first natural numbers."""
return n*(n+1)*(2*n+1)//6
def absolute_diff(n):
"""
Compute the absolute d... | true |
99e02fa63b997cb3156d5427da3833584a99d3c3 | stogaja/python-by-mosh | /12logicalOperators.py | 534 | 4.15625 | 4 | # logical and operator
has_high_income = True
has_good_credit = True
if has_high_income and has_good_credit:
print('Eligible for loan.')
# logical or operator
high_income = False
good_credit = True
if high_income or good_credit:
print('Eligible for a loan.')
# logical NOT operator
is_good_credit = True
c... | true |
fa537f900f5a5f23c8573e1965895df2dd3b3706 | jhreinholdt/caesar-cipher | /ceasar_cipher.py | 1,693 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 21 15:33:33 2017
@author: jhreinholdt
Caesar cipher - Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th nex... | true |
58185c8ed1fbceae5dbb44fc547712f101f17e21 | Meenal-goel/assignment_7 | /fun.py | 2,238 | 4.28125 | 4 | #FUNCTIONS AND RECURSION IN PYTHON
#1.Create a function to calculate the area of a circle by taking radius from user.
rad = float(input("enter the radius:"))
def area_circle (r):
res = (3.14*pow(r,2))
print("the area of the circle is %0.2f"%(res) )
area_circle(rad)
print("\n")
#Write a function “perfect()” t... | true |
833994a2e77655b22525d4cf4e8d3d3a6ab93cc4 | JustineRobert/TITech-Africa | /Program to Calculate the Average of Numbers in a Given List.py | 284 | 4.15625 | 4 | n = int(input("Enter the number of elements to be inserted: "))
a =[]
for i in range(0,n):
elem = int(input("Enter the element: "))
a.append(elem)
avg = sum(a)/n
print("The average of the elements in the list", round(avg, 2))
input("Press Enter to Exit!")
| true |
5f5106c85c99ffa303151c793d5d490844b92977 | rajatsachdeva/Python_Programming | /UpandRunningwithPython/Working with files/OS_path_utilities.py | 1,241 | 4.125 | 4 | #
# Python provides utilities to find if a path is file or directory
# whether a file exists or not
#
# Import OS module
import os
from os import path
from datetime import date, time , datetime
import time
def main():
# print the name of os
print "Os name is " + os.name
# Check for item existence ... | true |
f848e3d507aaad9c30b0042a17542dc6225e5945 | rajatsachdeva/Python_Programming | /Python 3 Essential Training/04 Syntax/object.py | 921 | 4.25 | 4 | #!/bin/python3
# python is fundamentally an object oriented language
# In python 3 everything is an object
# class is a blueprint of an object
# encapsulation of variables and methods
class Egg:
# define a constructor
# with special name __init__
# All methods within classes have first argument as self
... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.