blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ce2e9a4fce24333c40aab5c06c2b83d16c5ae9c0 | booherbg/ken | /ppt/magic/functions_examples.py | 2,601 | 4.125 | 4 | '''
Working with functions
'''
# one parameter, required
def person1(name):
print "My name is %s" % name
#one parameter, optional w/ default argument
def person2(name='ken'):
print "My name is %s" % name
#three parameters, two optional
def person3(name, city='cincinnati', work='library'):
pri... | true |
9c73b01299eeb325f8035f6c3307aab051fd804d | ShehrozeEhsan086/ICT | /Python_Basics/replace_find.py | 689 | 4.28125 | 4 | # replace() method
string = "she is beautiful and she is a good dancer"
print(string.replace(" ","_")) # replaces space with underscore
print(string.replace("is","was")) # replaces is with was
print(string.replace("is","was",1)) #replaces the first is with was
print(string.replace("is","was",2)) #replaces both is... | true |
508877d679b9c33911f6c9823045770931d7c0f0 | CallumRai/Radium-Tech | /radium/helpers/_truncate.py | 855 | 4.375 | 4 | import math
def _truncate(number, decimals=0):
"""
Truncates a number to a certain number of decimal places
Parameters
----------
number : numeric
Number to truncate
decimals : int
Decimal places to truncate to, must be non-negative
Returns
-------
ret : numeric
... | true |
541985ab340362d1e210695e949cea874923687e | Somu96/Basic_Python | /FileHandling/student_dict.py | 880 | 4.28125 | 4 | #student nested dictionary
student = {'Std_1': {'name': 'Som', 'math': 35, 'science': 35},
'Std_2': {'name': 'Vanitha', 'math': 99, 'science': 99}
'Std_3': {'name': 'Divya', 'math': 100, 'science': 100}
}
add_std = True
def get_stu_info():
stu_id = input('Enter the ID for student ... | false |
6bbaf096406780be38dceedcf04602b1d48210d0 | AliSalman86/Learning-The-Complete-Python-Course | /10Oct2019/list_comprehension.py | 1,678 | 4.75 | 5 | # list comprehension is a python feature that allows us to create lists very
# succinctly but being very powerful.
# doubling a list of numbers without list comprehension:
numbers = [0, 1, 2, 3, 4, 5]
doubled_numbers = list()
# use for loop to iterate the numbers in the list and multiply it by 2
for number in numbers... | true |
a6ff0a523770dff757aecf156646ae5ad1ef9687 | AliSalman86/Learning-The-Complete-Python-Course | /07Oct2019/basic_while_exercise.py | 738 | 4.40625 | 4 | # you can input any letter but it will actually do something only if p entered to
# print hello or entered q to quit the program
user_input = input("Please input your choice p to start the prgram or q to terminate: ")
# Then, begin a while loop that runs for as long as the user doesn't type 'q', if q
# entered then ... | true |
2e21af9e8646ab019caf79da570e11bb0f2d7a44 | AliSalman86/Learning-The-Complete-Python-Course | /16Oct2019/lambda_func_python.py | 1,634 | 4.46875 | 4 | # lambda functions get inputs, do a small amount of processing then return outputs
# functions can do 2 things:
# 1- perform an action (not a lambda function):
print("I am a function that perform an action, showing people a print, without changing the data")
# 2- return an output(can be used as lambda function):
def d... | true |
e55dfe9f427f2175b7b376ebec07ebfece9a3413 | AliSalman86/Learning-The-Complete-Python-Course | /13Oct2019/list_comprehension_with_conditions.py | 1,744 | 4.5625 | 5 | # we can use conditions with list comprehension to make it more flexible.
# Info: we have 2 lists, a list of friend names and a list of event's guest names
# Problem: we want to find list of friends who attended the party.
# there is to solutions:
# Solution 1: using sets and intersection() without list comprehension,... | true |
c11ceb526f159f47b92a781ed5fd8fad6d372247 | skulshreshtha/Data-Structures-and-Algorithms | /DS/queue_implementation_using_two_lists.py | 1,189 | 4.28125 | 4 | class MyQueue(object):
def __init__(self):
""" Creates two empty stacks for implementing the queue (FIFO)."""
self._front_stack = []
self._back_stack = []
def peek(self):
""" Returns (without removing) the element at front of the queue."""
self._prepare_stacks()
... | true |
7218ec87313889d8b40deed9b8e620279a667d04 | Psyconne/python-examples | /ex39_init.py | 611 | 4.4375 | 4 | #you can only use numbers to index into lists
print 'this is a list'
things = ['a', 'b', 'c', 'd']
print 'things: ', things
print things[1]
things[1] = 'r'
print things[1]
print 'things: ', things
#a dict associates one thing to another, no matter what it is
print 'this is dicts'
stuff = {'name': 'El Idrissi', 'age'... | false |
07379dcf89e6ee2650643c049ff6a457c9089df0 | ingwplanchez/Python | /Program_48_FuncionesExternas/Modulos.py | 1,849 | 4.21875 | 4 |
def Bienvenidos(): # def se utiliza para definir una funcion
print("Bienvenido a la agenda telefonica.\n")
print("1.- Agregar un elemento a la agenda")
print("2.- Listar los elementos de la agenda")
print("3.- Buscar por nombres\n")
def Escribir():
print("Has elegido agregar un elemento ... | false |
a27c424b39d298263ab0d41bf10ad186a0dacec4 | kopchik/itasks | /round2/fb_k-nearest.py | 430 | 4.125 | 4 | #!/usr/bin/env python3
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
def nearest(loc, points, k):
def distance(point):
return (loc.x-point.x)**2 \
+ (loc.y-point.y)**2
points.sort(key=distance, reverse=True)
return points[-k:]
if __name__ == '__main__':
points ... | true |
2221d7ed1b60b7649e28e66ae9d30596ed3abc5c | kopchik/itasks | /round5/rot13.py | 983 | 4.21875 | 4 | #!/usr/bin/env python3
def rot13(s, base=13):
"""
Encodes and decodes strings with ROT-13 (https://en.wikipedia.org/wiki/ROT13).
Arguments:
s -- string to encode/decode.
base -- number of shifts to perform
Returns:
string representing encoded/decoded data.
"""
decoded = []
... | true |
68eedc593ebe156fa80d85279b3dab4b955d3e52 | jingxuanyang/BFS_Sequences | /halton.py | 2,008 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# Write a computer code for the Halton sequence. The input should be the
# dimension s and n, and the output should be the nth Halton vector where
# the bases are the first s prime numbers.
# About Halton Sequence
#
# Reference https://en.wikipedia.org/wiki/Halton_sequence
# imp... | true |
a92f00bdd7408a9bc210c991f0108448019bf0a2 | Sangavi-123/Data-Structures-and-Algorithms | /BubbleSort.py | 1,235 | 4.59375 | 5 | # Bubble sort implementation
# create a list
l = [6,8,1,4,10,7,8,9,3,2,5]
# Algorithm
"""
The algorithms has two loops
Inner for loop takes each element and compares it with neighboring elements
If the element is bigger than neighbor the element is swapped. This is done
for each element in the list. But... | true |
da0709770e89c51aa2636d04f580e41c7c102e56 | Sangavi-123/Data-Structures-and-Algorithms | /InsertionSort.py | 815 | 4.3125 | 4 | import numpy as np
l = [6,1,8,4,10]
l1 = [2,6,11,90,3,2,4]
l3 = [17,2,9,3,7]
# Algorithm
"""
the algorithm iterated from the first element and not the zeroth element.
it compare each element with previous elements and if the other element is large,
it is swappped. Now the element [identity - just a n... | true |
3b2c1da384a2abf780f1ad906cfb6f13d12835be | groulet/checkio-code | /scientific-expedition/conversion-from-camelcase/solve.py | 1,542 | 4.5625 | 5 | '''
https://py.checkio.org/en/mission/conversion-from-camelcase/
Your mission is to convert the name of a function (a string) from CamelCase ("MyFunctionName") into the Python format ("my_function_name") where all chars are in lowercase and all words are concatenated with an intervening underscore symbol "_".
Input: ... | true |
51b287c0ad340098350a847c3a489ae1814eb81f | groulet/checkio-code | /home/digits-multiplication/solve.py | 1,328 | 4.5625 | 5 | '''
https://py.checkio.org/en/mission/digits-multiplication/
You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes.
For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes).
Input: A positive integer.
Output:... | true |
a84806404994be5321900302c8c6f12a0e83d498 | tahmid-tanzim/problem-solving | /Arrays_and_Strings/__Waterfall-Streams.py | 2,850 | 4.1875 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Waterfall%20Streams
"""
You're given a two-dimensional array that represents the structure of an
indoor waterfall and a positive integer that represents the column that the
waterfall's water source will start at. More specifically, the water source
will s... | true |
6fe09d0536e033edf229e0d7e9f3be559deeb540 | tahmid-tanzim/problem-solving | /Linked_Lists/__Zip-Linked-List.py | 1,189 | 4.5 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Zip%20Linked%20List
"""
You're given the head of a Singly Linked List of arbitrary length
k. Write a function that zips the Linked List in place (i.e.,
doesn't create a brand new list) and returns its head.
A Linked List is zipped if its nodes are in the... | true |
78346fb924bee1aedf9291633904599970d52a52 | tahmid-tanzim/problem-solving | /Arrays_and_Strings/Generate-Document.py | 1,524 | 4.46875 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Generate%20Document
"""
You're given a string of available characters and a string representing a
document that you need to generate. Write a function that determines if you
can generate the document using the available characters. If you can generate
the... | true |
391f27573f012bac2679959c171562cf27d68121 | tahmid-tanzim/problem-solving | /Sorting/Bubble-Sort.py | 603 | 4.28125 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Bubble%20Sort
# Best Time Complexity - O(n), Space Complexity - O(1)
# Avg. & Worst Time Complexity - O(n^2), Space Complexity - O(1)
def bubbleSort(array):
isSorted = False
n = len(array)
while not isSorted:
isSorted = True
i = 0
... | false |
caf12586797ad108848b25770645b7bb36dfd2c0 | tahmid-tanzim/problem-solving | /Heap/__Continuous-Median.py | 1,423 | 4.15625 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Continuous%20Median
"""
Write a ContinuousMedianHandler class that supports:
1. The continuous insertion of numbers with the insert method.
2. The instant (O(1) time) retrieval of the median of the numbers that have
been inserted thus far with th... | true |
c4621e516b2b3c5f053085912110f31cde5a09d1 | tahmid-tanzim/problem-solving | /Trees_and_Graphs/Binary Search Trees/__Right-Smaller-Than.py | 1,137 | 4.15625 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Right%20Smaller%20Than
"""
Write a function that takes in an array of integers and returns an array of
the same length, where each element in the output array corresponds to the
number of integers in the input array that are to the right of the relevant
i... | true |
e1e70a36206e3958e422cf061a398739b185aad8 | tahmid-tanzim/problem-solving | /Trees_and_Graphs/Min-Height-BST.py | 2,514 | 4.28125 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Min%20Height%20BST
"""
Write a function that takes in a non-empty sorted array of distinct integers,
constructs a BST from the integers, and returns the root of the BST.
The function should minimize the height of the BST.
You've been provided with a BST... | true |
254ff9b1dc2888bfba0f9a72e3f9f1f37bcd0e90 | tahmid-tanzim/problem-solving | /Arrays_and_Strings/Smallest-Difference.py | 1,642 | 4.25 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Smallest%20Difference
"""
Write a function that takes in two non-empty arrays of integers, finds the
pair of numbers (one from each array) whose absolute difference is closest to
zero, and returns an array containing these two numbers, with the number from
... | true |
ca20a33dbf1d50c3c4b915e463c019906d05020a | tahmid-tanzim/problem-solving | /Searching/Search-In-Sorted-Matrix.py | 1,360 | 4.34375 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix
"""
You're given a two-dimensional array (a matrix) of distinct integers and a
target integer. Each row in the matrix is sorted, and each column is also sorted; the
matrix doesn't necessarily have the same height and width.
... | true |
1afe66ec741a4890d9bb8f695d129957a81814e8 | tahmid-tanzim/problem-solving | /Dynamic_Programming/triple-step.py | 1,261 | 4.34375 | 4 | #!/usr/bin/python3
# Cracking the Coding Interview - 8.1
# Dynamic Programming
# Time complexity - O(3 ^ n)
def tripleStep(n):
if n < 0:
return 0
if n == 0:
return 1
return tripleStep(n - 1) + tripleStep(n - 2) + tripleStep(n - 3)
# Dynamic Programming with Tabulation
# BottomUp Approac... | false |
a1bc7035f2da69f3b360a3596cdce78baae0bdf0 | tahmid-tanzim/problem-solving | /Searching/Shifted-Binary-Search.py | 2,977 | 4.375 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Shifted%20Binary%20Search
"""
Write a function that takes in a sorted array of distinct integers as well as a target
integer. The caveat is that the integers in the array have been shifted by
some amount; in other words, they've been moved to the left or to... | true |
89f98bd8a53b8a5466b576f2eabba8dec0d76d2e | tahmid-tanzim/problem-solving | /Arrays_and_Strings/First-Duplicate-Value.py | 1,320 | 4.3125 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/First%20Duplicate%20Value
"""
Given an array of integers between 1 and n,
inclusive, where n is the length of the array, write a function
that returns the first integer that appears more than once (when the array is
read from left to right).
In other w... | true |
0457984ce7a77d93fcad90843c19ef4c219c91be | tahmid-tanzim/problem-solving | /Arrays_and_Strings/Longest-Peak.py | 1,675 | 4.46875 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Longest%20Peak
"""
Write a function that takes in an array of integers and returns the length of
the longest peak in the array.
A peak is defined as adjacent integers in the array that are strictly
increasing until they reach a tip (the highest value in ... | true |
9900be549d5d606590669361432c07b16bfed919 | tahmid-tanzim/problem-solving | /Stacks_and_Queues/__Sort-Stack.py | 1,584 | 4.125 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Sort%20Stack
"""
Write a function that takes in an array of integers representing a stack,
recursively sorts the stack in place (i.e., doesn't create a brand new array), and returns it.
The array must be treated as a stack, with the end of the array as the... | true |
454704723c91aaa38436e984d0a865a2c976bf16 | tahmid-tanzim/problem-solving | /Trees_and_Graphs/Binary Trees/__Right-Sibling-Tree.py | 1,842 | 4.1875 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Right%20Sibling%20Tree
"""
Write a function that takes in a Binary Tree, transforms it into a Right Sibling Tree, and returns its root.
A Right Sibling Tree is obtained by making every node in a Binary Tree have
its right property point to its right siblin... | true |
b7f4391572eab18178ed397bc1b8ea51ea9ed7d7 | tahmid-tanzim/problem-solving | /Linked_Lists/__Node-Swap.py | 1,057 | 4.21875 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Node%20Swap
"""
Write a function that takes in the head of a Singly Linked List, swaps every
pair of adjacent nodes in place (i.e., doesn't create a brand new list), and
returns its new head.
If the input Linked List has an odd number of nodes, its final... | true |
a4962f58924124af332458eac342123774a77ba2 | tahmid-tanzim/problem-solving | /Trees_and_Graphs/Graphs/__Detect-Arbitrage.py | 1,826 | 4.53125 | 5 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Detect%20Arbitrage
"""
You're given a two-dimensional array (a matrix) of equal height and width that
represents the exchange rates of arbitrary currencies. The length of the array
is the number of currencies, and every currency can be converted to every
... | true |
cd8f888f235ddf31bf6b8dcd869221dd07d72b4c | tahmid-tanzim/problem-solving | /Sorting/Merge-Sort.py | 2,132 | 4.4375 | 4 | #!/usr/bin/python3
# https://www.algoexpert.io/questions/Merge%20Sort
"""
Write a function that takes in an array of integers and returns a sorted
version of that array. Use the Merge Sort algorithm to sort the array.
If you're unfamiliar with Merge Sort, we recommend watching the Conceptual
Overview section o... | true |
125c1a7bd7101bab95075dd25ff88ede5b144faf | dgoon/ExercisesForProgrammers | /Chapter-2/2/count.py | 227 | 4.15625 | 4 | #! /usr/bin/env python3
import sys
print('What is the input string? ', end='')
sys.stdout.flush()
s = sys.stdin.readline().strip()
if len(s) == 0:
print('Empty string!')
else:
print('%s has %d characters.' % (s, len(s)))
| true |
18cf159378beeda3b07ae556acbaa45921672afd | ivan-ops/progAvanzada | /Ejercicio_85.py | 1,309 | 4.25 | 4 | #Ejercicio 85
#convertir un entero a un numero cardinal.
#las palabras como primero segundo tercero y cuarto, son llamados tambien como numeros cardinales
#en este ejercicio debe describir una funcion que tome un numero entero como su unico parametro y regrese una cadena de caracteres.
#con la palabra cardinal del... | false |
9c7728063cd8feefc5c9105f2f3826f5c3f19170 | im876/Python-Codes | /Codes/occurance_of_digit.py | 393 | 4.25 | 4 | #take user inputs
Number = int(input('Enter the Number :'))
Digit = (int(input('Enter the digit :')))
#initialize Strings
String1 = str()
String2 = str()
#typecast int to str
String1 = str(Number)
String2 = str(Digit)
#count and print the occurrence
#Count function will return int value
#so change it's type to string ... | true |
7b862c422c3649116c6aa3cf2d168661b2f47c57 | NurlybekOrynbekov/python-projects | /etc/tableView.py | 686 | 4.1875 | 4 | #! python3
# tableView.py - Форматирует переданный список, и выводит его в табличном виде
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(list):
widht = []
for row in list:
maxWid... | false |
817311e1832e80358d0055866cda4d9974a638c6 | shortdistance/workdir | /python 内置序列处理函数/testZip.py | 271 | 4.28125 | 4 | # -*-coding:utf-8-*-
'''
zip() in conjunction with the * operator can be used to unzip a list:
zip(x,y) 压缩, zip(*list) 带型号表示解压
'''
x = [1, 2, 3]
y = [4, 5, 6]
z = [5, 6, 7]
zipped = zip(x, y, z)
print zipped
x2, y2, z2 = zip(*zipped)
print x2, y2, z2
| false |
c012c84ecadc853a90bd9608d7e9eb2e12205ea8 | malladi2610/Python_programs | /Dictionaries/interchange_keys_elements.py | 1,118 | 4.25 | 4 | d = {} #The input Dictionary
d_ic = {} #Dictionary obtained after interchange
def dict_generate(x):
for i in range(x): #The loop used to create the input dictionary
d_keys = input("Enter the key value for the dictionary : ")
d_values = input("Ente... | true |
4bb3a680db9def453f45c2a2ae88b0b0adf5133a | malladi2610/Python_programs | /Assignment_programs/Assignment_1/Assignment2.4.py | 304 | 4.3125 | 4 | """
Write a program to print a pattern of numbers. The input should be the number of rows.
Example: Input:4
Output:
1
1 2
1 2 3
1 2 3 4
"""
input = int(input("Enter the number to generate the pattern : "))
for i in range(1,input+1):
for j in range(1,i+1):
print(j," ",end = "")
print() | true |
7804b927c81293aa67afcdfd9c49009994ff8f02 | malladi2610/Python_programs | /Strings/displayinglast10char.py | 236 | 4.3125 | 4 | """
Write the program to display the last 10 characters of the string
“Python Application Programming” on the console.
"""
x = input('Enter a string: ')
n = len(x)
y = x[-1:-10:-1]
print("The last 10 char of the string are : ",y) | true |
14203b17746f5858660083ed7924636ac0995591 | malladi2610/Python_programs | /Lists/frequency_of_elements.py | 423 | 4.4375 | 4 | """
Program to count the frequency of a given element in a list of numbers
"""
list = []
i = 0
count = 0
n = int(input("Enter the number of elements of the list"))
while i < n:
list.append(int(input("Enter the elements of the list :")))
i += 1
x = int(input("Enter the elements to get its frequency : "))
for... | true |
e36544d6aaa97846fb062aa4dd4dfa13e6e40e4a | fahimahammed/problem-solving-with-python | /32-reverse-string-function.py | 313 | 4.4375 | 4 | # 32. Write a function to reverse a string.
def rev_string(text):
rev_str = ""
if len(text) > 0:
for i in range(len(text)-1, -1, -1):
rev_str += text[i]
return rev_str
else:
return "This is empty string."
str1 = input("Enter a string: ")
print(rev_string(str1))
| true |
1ac888ad20e87c6e29c18ff9c25099b2e05f2120 | fahimahammed/problem-solving-with-python | /11-rectangle-area-perimeter.py | 414 | 4.625 | 5 | # 11. Write a python program that prints the perimeter of a rectangle to take its height and width as input.
width = float(input("Enter the width of the rectangle: "))
height = float(input("Enter the height of the rectangle: "))
area = width * height
perimeter = 2 * (width + height)
print("The area of the rectangle:... | true |
7c410cc1e0820b7b65c6b1726bbdef55a719a003 | fahimahammed/problem-solving-with-python | /9-triangle-area.py | 287 | 4.28125 | 4 | # 9. Write a python program that will accept the base and height of a triangle and compute the area.
base = float(input("Enter the base of the triangle:"))
height = float(input("Enter the height of the triangle:"))
area = 0.5 * base * height
print(f"The area of the triangle: {area}") | true |
1aa7edf4aec48c3ecc01543641c619b6ee4c19d9 | fahimahammed/problem-solving-with-python | /24-2D-array2.py | 490 | 4.3125 | 4 | # 24. Write a program which takes two digits m (row) and n (column) as input and generates a two-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. Note: i = 0, 1, ....., m-1 and j = 0, 1, ......, n-1
m = int(input("Input number of row: "))
n = int(input("Number of column... | true |
9ac53ddb3db9ef9fe046fb833eb6807fa3518ce0 | fahimahammed/problem-solving-with-python | /15-string-reverse.py | 273 | 4.40625 | 4 | # 15. Write a program that accepts a word the user and reverse it.
word = input("Enter a string/word: ")
for i in range(len(word)-1, -1, -1):
print (word[i], end="")
# alternative
# word = input("Enter a string/word: ")
# rev_word = word[::-1]
# print (rev_word)
| true |
4276c42b834688b91429c1cbdbfa11507ccb56d1 | nirmalit/DATA-STRUCTURE-python | /SingleLinkedList.py | 1,552 | 4.15625 | 4 | class Node:
def __init__(self,val):
self.value = val
self.next = None
class Single:
def __init__(self,val):
self.head = val
def printlist(self):
self.l = self.head
while self.l is not None:
print(self.l.value)
self.l=self.l.next
def inser... | false |
c7d26e9968dcb66683bb5d48617a34fd1f49fb34 | natalia-sitek/udemy-python-tutorial2 | /Methods_and_Functions/excersises.py | 1,162 | 4.21875 | 4 | def function():
print("Hello World")
function()
def myfunc(name):
print('Hello ' + name)
myfunc("Jose")
def is_greater(x, y):
return x > y
print(is_greater(2, 3))
def myfunction(a):
if a == True:
return "Hello"
elif a == False:
return "Goodbye"
print(myfunction(True))
... | true |
eb8394ddadc6edc22066ff17cce16489ac770b15 | guilhermepirani/think-python-2e | /exercises/cap04/mypolygon.py | 2,853 | 4.65625 | 5 | # Page 31: 4.3 Exercises
''' final code at 4.3.5
Make a more general version of circle called arc that takes an additional
parameter angle, which determines what fraction of a circle to draw.
The parameter angle is in units of degrees,
so when angle=360, arc should draw a complete circle.
'''
import math
impo... | true |
63ae1c501ff338b576bc3ed70ee1b2b123e6f231 | guilhermepirani/think-python-2e | /exercises/cap05/ex-5-2.py | 1,458 | 4.46875 | 4 | '''Code for 5.14.2
Fermat’s Last Theorem says that there are no positive integers a, b,
and c such that:
a**n + b**n = c**n
for any values of n greater than 2.
Write a function named check_fermat that takes four parameters—a, b, c and n
—and checks to see if Fermat’s theorem holds.
If n is greater than 2 and... | true |
5fb2d3114328cf17562d0cf581219c502318b4e4 | paige0701/algorithms-and-more | /projects/leetCode/easy/flipAndInvertImage.py | 664 | 4.125 | 4 | """
Input: [[1,1,0],[1,0,1],[0,0,0]]
Output: [[1,0,0],[0,1,0],[1,1,1]]
Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].
Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]
"""
class Solution:
def flipAndInvertImage(self, A):
# for i in A:
# i.reverse()
# print(i)
... | false |
b094776c0a3d6bccb6a5f08896d3cd8d390f78b9 | muthoni12/python_dictionary | /dictionarytask.py | 1,791 | 4.21875 | 4 | '''
Given a list of dictionaries containing data such as productNmae, exclprice
passed to a function as a parameter, together with the tax rate.
Calculate the incl of each product.
Then print thier values.
incl = excl + vat
vat = excl * tax
e.g
product = [
{
"prodname" : "Milk",
"excl"... | true |
1dc2d86b1240db1f91628d8d3acbe7a00c195a70 | MattSokol79/Python_Modules | /exception_handling.py | 843 | 4.4375 | 4 | # We will have a look at the practical use cases and implementation of try, except
# raise and finally
# we will create a variable to store file data using open()
# 1st Iteration
# try: # Use try block for a line of code where we know this will throw an error
# file = open("orders.text")
# except:
# print("Pa... | true |
27fbb699b4d656f29113dbfa803aa1e7a8121b7c | manojnookala/20A95A0503_IICSE-A-python-lab-experiments | /Exp6.3.py | 785 | 4.125 | 4 | Sort the two lists
L1=[45,63,23,12,78]
L2=[12,90,72,-1]
Combine L1&L2 as single list and display the elements in the sorted order
#Dislay
L3=[-1,12,12,23,45,63,72,78,90]
Perform sorting on the list.....
Program
l1=[]
l2=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
b=int(input("Enter elemen... | true |
6d88f10a97c6d25538438847a99efae1d0cb9380 | manojnookala/20A95A0503_IICSE-A-python-lab-experiments | /DictCreationSimple.py | 1,007 | 4.125 | 4 | #Dictionary to store branchcode->name
dict_ds={05:"CSE",12:"IT",03:"ECE",04:"MECH"}
print dict_ds
#type of data structure
print type(dict_ds)
#accessing elements from the dictionary
res=dict_ds[12] #dictionary_name[key]
print "At key 12 the value is {}" .format(res)
#New dictionary
#Key-Unique,value:Repeated
dict_ds1={... | false |
ea73d93111c62459ded64da672161f5252351988 | AdityaDale/Word-Phrase-Alignment | /parser-modification/list-processing1.py | 364 | 4.25 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
my_list = [[[["This"],["desire"]],[["dates"],[["back"]],[["to"],[[[[["at"],["least"]]],["the"],["time"]],[["of"],[["ancient"],["Greece"]]]]]],["."]]]
def print_list(l):
for i in l:
if type(i) is list:
if(len(i) > 1):
print(i)
... | false |
6853a6e911ee6500595b74d9fe859527437c5687 | samuelkb/PythonPath | /range_enumerate.py | 1,551 | 4.28125 | 4 | # Coding question fizz_buzz
def fizz_buzz(numbers):
'''
:param numbers: The list of numbers
:type numbers: list
Given a list of integers:
1. Replace all integers that are evenly divisible by 3 with "fizz"
2. Replace all integers divisible by 5 with "buzz"
3. Replace all integers divisible by... | true |
522dad05bfae5a45a23b0d720c99dc9bafda1d95 | cburleso/Cybersecurity_Login_System | /database_demo.py | 2,446 | 4.71875 | 5 | """
Example SQLite Python Database
==============================
Experiment with the functions below to understand how the
database is created, data is inserted, and data is retrieved
"""
import sqlite3
from datetime import datetime
def create_db():
""" Create table 'plants' in 'plant' database """
try:
... | true |
277c015c89a057a15b2b328394b7c112fbc04da8 | ameliawilson/March-Madness | /first_connection.py | 1,245 | 4.25 | 4 | ################################################
# March Madness
# Day 1 - Making a Connection
#
# Create a connection to a webpage
# Print out what the servers says back to you
################################################
import requests
import sys
def MakeConnection(URL):
'''URL: string that is a website... | true |
d24e017ce0c4dc509e0d04abef2da1fc6495b9a5 | hima-cmd/hello | /src/Chap4/pizzas.py | 403 | 4.1875 | 4 | #using for loop
pizzas_names = ['veggie','chicken','spicy veggie']
for pizzas in pizzas_names:
print("I like "+pizzas+" pizza.")
#message = f"I like {pizzas}"
#print(message)
print("I really like pizzas.")
animal_names = ['dog','cat','fish','hamster']
for pets in animal_names:
print("A "+pets+" wo... | true |
eaf1b3d1f50cbaa6f0f03452054c3046b456484b | hima-cmd/hello | /src/Chap6/looping.py | 303 | 4.34375 | 4 | #looping through dictionaries
rivers = {
'egypt' : 'nile',
'india': 'ganga',
'china': 'yantze',
}
for country, river in rivers.items():
print("\nCountry : "+country)
print("River : " +river)
print(" The "+
river + " flows through "+
country)
| false |
18b0fe0064ee558b5d28d3fb640441be010062c2 | hima-cmd/hello | /src/Chap7/modulus.py | 461 | 4.5 | 4 | '''
input() function takes one argument: the prompt, or instructions,
that we want to display to the user so they know what to do.
'''
# modulo operator (%),
# which divides one number by another number and returns the remainder:
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(n... | true |
e39406fb8b066d24e00840b2cc460d8b38fff0d7 | taylerhughes/Euler | /Euler_Problem_1.py | 814 | 4.15625 | 4 | """
Multiples of 3 and 5
Problem 1
https://projecteuler.net/problem=1
Tue Jan 20 20:09:24 2015
If we list all the natural numbers below 10 that are
multiples of 3 or 5, we get 3, 5, 6 and 9. The sum
of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
container = []
highest_value... | true |
655c389034bfecdc84ccd2c5dfab22da4e1f323e | arshia-puri9/assignment-2and-3 | /assignment2/assign2.py | 538 | 4.28125 | 4 | #answer1: To print anything on screen:
print('Let\'s start Python')
#answer2: To Join two strings using +:
a='hello'
b='world'
print(a+b)
# Or you can simply:
print('hello'+'world')
#answer3:
x=input("enter value for x\n")
y=input("enter value for y\n")
z=input("enter value for z\n")
print("Value of x is",x)
print("... | true |
db446e1ca49ac6fbf9158b5c07da6d0b0244c4b7 | Jhouteddy/python_learn | /datatype.py | 447 | 4.21875 | 4 | # 資料: 程式的基本單位
# 數字
3456
3.5
# 字串
"測試中文"
"hello world"
# 布林值
True
False
# 有順序、可動的列表 List
[3, 4, 5]
["hello", "world"]
# 有順序、不可動的列表 Tuple
(3, 4, 5)
("hello", "world")
# 集合 Set
{3, 4, 5}
{"hello", "world"}
# 字典 Dictionary
{"apple": "蘋果", "data": "資料"}
# 變數: 用來儲存資料的自訂名稱
# 變數名稱=資料
x = 3
# print(資料)
print(x)
| false |
7c6458d82de39bc9b029e003efc3d48fc46c8d6c | darkares23/holbertonschool-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 368 | 4.15625 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
if matrix == [[]]:
print()
for row in range(len(matrix)):
for column in range(len(matrix[row])):
if column < len(matrix[row]) - 1:
print("{:d}".format(matrix[row][column]), end=' ')
else:
... | false |
a94b19b61e99f8d64a63d99d51bfaac8f0565b29 | pratik-practice-work/Code_Practice | /Python_Scripting/2.Dictionaries.py | 1,237 | 4.46875 | 4 | ###########################################################################################################################
#
# A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with
# curly brackets, and they have keys anvalues.
# Functions for Dictionary : dic... | true |
ad0248e7c4c153cd1a00e2eaab4cfa092a076898 | CarlosDaniel0/atividades_tds | /Lista1 Fábio/questao32.py | 321 | 4.125 | 4 | #Diferença entre o número e seu inverso
print('')
numero = int(input('Digite um valor de 3 digitos: '))
c = (numero // 100 % 10)
d = (numero // 10 % 10) * 10
u = (numero // 1 % 10) * 100
inverso = u + d + c
soma = numero - inverso
print('')
print('O valor digitado corresponde a diferença com o inverso de:', soma)
| false |
ca68177e1840f0f252d196fe635ee3a71400b807 | ibrahimBeladi/ICS490 | /HW3/count_word.py | 1,091 | 4.15625 | 4 | #************************File #2**************************#
# This file is used to find the number of reviews #
# containing a specific word. It reads the file #
# "all-words.csv" and count the number of one's in #
# The column contains_{word}. #
# ... | true |
72d5958b0b9f4b834d9acf7322c8d2e7aa685056 | NatalieP-J/python | /jplephem/__init__.py | 2,811 | 4.15625 | 4 | """Use a JPL planetary ephemeris to predict planet positions.
This package uses a Jet Propulsion Laboratory ephemeris to predict the
position and velocity of a planet, or the magnitude and rate-of-change
of the Earth's nutation or the Moon's libration. Its only dependency is
``NumPy``. To take the smallest and most ... | true |
00f4a5c42d0a09e196b1be5f11b7dc7be24b7bfb | LourencoNeto/ces22 | /Aula 2/cap8/Exercicio_8_19_10.py | 1,598 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 6 17:52:27 2018
@author: Lourenço Neto
"""
import sys
def reverse(word):
"""Return the string word reversed"""
start = -2 #Since we will pick the last letter separatly, the start of pick the letter in the reverse direction at the penultimate letter
end = -1 ... | true |
1d5138ec6b9f356f024209cb579baef6d81d8caa | billjasi/My_GitHub_Project | /split3.py | 463 | 4.34375 | 4 | #The split() method can be called with no arguments.
#In this case, split() uses spaces as the delimiter.
#Please notice that one or more spaces are treated the same.
#This split form handles sequences of whitespace.
#Program that uses split, no arguments: Python
# Input string.
# ... Irregular number of spaces betw... | true |
1c9d706b91fd4ff9babef66c0ffc7c832d2551a6 | Chrisvimu/CS50AssignmentsAndStudy | /pset6/mario/less/mario.py | 409 | 4.125 | 4 | from cs50 import get_int
# Declaring pyramid height with 0
pyramid = 0
# Loops asking for user input until an int betwen 1 and 8 is provided.
while(pyramid < 1 or pyramid > 8):
pyramid = get_int("Height: ")
# prints # and spaces depending of the height of the pyramid
for row in range(pyramid):
gatos = row +... | true |
f17f8dd9021198fb497b3d1874671440846fc555 | aditya8081/Project-Euler | /problem14.py | 1,134 | 4.25 | 4 | # There are too many iterations to test by brute force
# instead, we will create a set of iterations to hit 1 for every number
# we start like this
cache = {2:1} # because the sequence for 2 will converge after 1 step
def Collatz(number): # this defines the Collatz operation
if number not in cache: # if the numbe... | true |
efc2000a01cfc5a0f95b9d773e36eafad01674f4 | MarcoMen-Temp/CollatzSeq | /Week3 -Exercise.py | 630 | 4.28125 | 4 | #Marco Men's week 3-Collatz Sequence
raw_input = int(input('Enter a number, please:'))
number = raw_input
steps = 0 #<--- Loop begins here
while number > 1:
if number % 2 == 0:
number = number / 2
print(number) #<--- For even numbers,print
else: #<---Non-even=Odd
number = ... | true |
c6c425df00f1f72e89c6078f4206523f58565543 | AlfredoGuadalupe/Lab-EDA-1-Practica-9 | /Funciones2.py | 352 | 4.15625 | 4 | #Definiendo una función que regresa el cuadrado de un número
def cuadrado(x):
return x**2
x = 5
#La función format() sirve para convertir los parámetros que recibe,
#en cadenas; éstos valores son reemplazadas por las llaves de la cadena.
print("El cuadrado de {} es {}".format(x, cuadrado(x)))
#La función cua... | false |
8c25b4d2b65840e8411a61dac6a76a19bafe194d | MisterDecember/adder | /Adder/Arithmetic.py | 660 | 4.15625 | 4 | #!/usr/bin/env python3
x = 5
y = 3
print("Now let's get mathematical!")
print()
print('Here is your the x ({}) / y ({}) looks like since Python 3'.format(x, y))
z = x / y
print(f'result is {z}')
print('______________________________________')
print()
# *********************************
print('to get no remainder use... | true |
2758e4466cd4be6f78f98b9132f2ba0e9bddd4d5 | Bjcurty/PycharmProjects | /Python-Refresher/12_list_comprehension/code.py | 572 | 4.1875 | 4 | # List comprehension allows us to create new lists from old lists
# Pretty cool stuff
# numbers = [1, 3, 5]
# doubled = [x * 2 for x in numbers]
#
# # antiquated
# # for num in numbers:
# # doubled.append(num * 2)
#
# print(doubled)
friends = ["Rolf", "Sam", "Samantha", "Saurabh", "Jen"]
starts_s = [friend for fri... | true |
e200f41e2929c1689160c41c54241a319c153117 | Bjcurty/PycharmProjects | /Python-Refresher/27_class_composition/code.py | 921 | 4.625 | 5 | # Composition is a counterpart to inheritance that is used to build out classes that use others
# More used than inheritance
class BookShelf:
def __init__(self, *books):
# def __init__(self, quantity):
self.books = books
def __str__(self):
return f"BookShelf with {len(self.books)} books."
... | true |
472f8f6dbba0f89c602fd1e11885c41db8a5fe54 | glaswasser/30DaysOfCode_Python | /Day_9_Recursion_3 | 1,346 | 4.125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the factorial function below.
def factorial(n):
if n == 1:
return(1)
else:
# create a list for the numbers to multiply
number = []
for i in reversed(range(1, n+1)):
number.append(i)
... | true |
50b0974a7c8c0c97c2825390afd0eee024704c46 | nasumilu-owner/cop2002 | /Project 3/ml_homes.py | 1,736 | 4.3125 | 4 | #!/usr/bin/env python3
# Michael Lucas
# COP2002.054
# 2020-1-12
# Project 3 - Real Estate Values
def main():
print('\tReal Estate Values')
print('*' * 35)
home_values = get_values()
if len(home_values) != 0 :
print('*' * 35)
print('Prices of homes in your area:')
print(home... | true |
4de875ac13c9eca13003061e104819cb0d27b1d0 | mikegoescoding/CodeWars-Kata | /python/8-kyu/returnNegative-8kyu.py | 1,009 | 4.59375 | 5 | # Return Negative
# 8kyu
'''
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
Example:
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
Notes:
The number can be negative already, in which case no chang... | true |
b4f70f022dcbecbd07394cad78a1015ea1921be5 | mikegoescoding/CodeWars-Kata | /python/7-kyu/shortestWord-7kyu.py | 804 | 4.3125 | 4 | # SHORTEST WORD
# 7KYU
"""
x Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
"""
# # 1
# def find_short(s):
# words = s.split(' ')
# words.sort(key=len)
# return len(words[0])
# # 2
# def find... | true |
1dc19c1b2dd1f970caf9f6a47fe20b7e7febcd8e | salam1416/100DaysOfCode | /day64.py | 369 | 4.3125 | 4 | # Python Try-Except
try:
print('a')
except NameError: # if this specific exception occured
print('a name-error exception occured')
except: # another exception occured
print('another exception occured')
else: # will print when no error is catched
print('no exceptions! ')
finally: #will happend regardless... | true |
3df1082b6f8774ad647076daf854b8866ca41813 | salam1416/100DaysOfCode | /day15.py | 422 | 4.25 | 4 | # Python Lists 3
# list methods
a = [1,2,3,4,5,6]
print(len(a)) # length of list
a.append(7) # adding an item
print(a)
a.insert(2, 'the new item')
print(a)
a.remove(1) # removing an item
print(a)
a.pop() # remove the last item
print(a)
a.clear() # clear the whole list
print(a)
a = [1,2,4,5,6,7]
b = a.copy() # copying a... | true |
f9cfc9f446a322b794823cac7423e6ae5da2bb0d | salam1416/100DaysOfCode | /day66.py | 367 | 4.25 | 4 | # Python string formatting 2
price = 49
itemno = 567
quanitity = 3
myorder = 'I want {0} pieces of item number {1} for {2:.2f} dollars'
print(myorder.format(quanitity, itemno, price))
# another example
age = 36
name = 'John'
txt = 'His name is {1}. {1} is {0} years old'
print(txt.format(age, name)) # interesting
pri... | true |
34f887ad79ec5cc6ade82b36d674ccdb02ff2caa | salam1416/100DaysOfCode | /day34.py | 693 | 4.125 | 4 | # Python Function 2
def aFun(nums):
for i in nums:
print(i)
N = [3,5,2,5,29,21]
aFun(N)
# you could specify the input of a function
def aFun2(num1, num2, num3):
return num1+num2*num3
print(aFun2(num2 = 5, num3 = 9, num1 = 43))
# unlimited input
def aFun3(*kids):
print('The youngest child is '+... | true |
721e042907e6bc18b39d1078e2d88d0c34f7f38c | halimahbukirwa/Python-Statements-Test | /number_six.py | 241 | 4.25 | 4 | # Use List Comprehension to create a list of the first letters of every word in the string below:
st = 'Create a list of the first letters of every word in this string'
lst = [word[0] for word in st.split() if len(word)%2 == 0]
print(lst) | true |
4b169422db4655c3cfa2bfddbccb0f088d51ba11 | frey-norden/p3-spec | /punc_strip.py | 922 | 4.1875 | 4 |
def punctuation_stripper(s):
''' takes a string s and strips the puncs
returns a new string of only letters '''
punctuation = '''!()-[]{};:'"\, <>./?@#$%^&*_~'''
# punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
# alternative is list above: punctuation_chars --> both work b... | false |
694060764d8fdddb2dbe5531b751c7125586f140 | vanhung1234/vanhung1234.github.io | /page_203_project_03.py | 1,027 | 4.46875 | 4 | """
Author: Mai Văn Hùng
Date: 24/10/2021
Program: Elena complains that the recursive newton function in Project 2 includes an extra
argument for the estimate. The function’s users should not have to provide this
value, which is always the same, when they call this function. Modify the definition of the function s... | true |
cd5b5e78ea29c95d36374f2c5655412aff051d99 | vanhung1234/vanhung1234.github.io | /page_199_exercise_01.py | 340 | 4.375 | 4 | """
Author: Mai Văn Hùng
Date: 24/10/2021
Program: Write the code for a mapping that generates a list of the absolute values of the numbers in a list named numbers.
Solution:
....
"""
number = [1, -2, 3, -4, -5]
print("The original list is : " + str(number))
res = list(map(abs, number))
print("Absolute ... | true |
94a690f032c7e4c4291545f458977e58d008c94e | gridscaleinc/Learning-Python | /domanthan/Less005/Less005.py | 927 | 4.34375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# What we learn here: How to print, for loop controls.
class Magnifier :
def observe(self, obj):
print("----------- Start Observing.......")
print("----------- type:", type(obj))
print("----------- id:", id(obj))
print("-------... | true |
409bd89a1225c1fdcdbd61905fea94eb2397f3cf | slee8835/intro-to-python | /unit.py | 790 | 4.375 | 4 | """
This program contrains two functions: get_input and calc_temp.
These functions are used to take in a temperature input in C
from user, then convert that temperature to Fahrenheit.
"""
def get_input():
"""
this function gets temperature input from users in Celsius.
"""
cel_temp = float(input("Please enter a te... | true |
3761e07acce219aeb14d2f3f84f6b4cb3265b8f2 | riteshmsit/sampleprog | /cspp1-practice/m22/assignment2/clean_input.py | 476 | 4.34375 | 4 | '''
Write a function to clean up a given string by removing the special characters and retain
alphabets in both upper and lower case and numbers.
'''
import re
def clean_string(string):
#function to clean the string of special characters
updated_string = re.sub("[^a-z,^A-Z,0,1,2,3,4,5,6,7,8,9]","",string)
if '^' i... | true |
ebdb0c6a80210e2eecc8ffff1f04488b8c2ef683 | asis-parajuli/Python-Basics | /tuples.py | 922 | 4.5625 | 5 | # tuples are emutable means we can't modify them
point = (1, 2)
# in tuple we can ignore parenthenisis like point = 1 , 2
# if we have only one item in tuple we should use tralying comma like point = 1,
# for defining an empty tuple we should use empty parenthesis like point = ()
# we can concatinate one tuple w... | true |
19ee68fdf253ea8b0d4bedd9141d902c67a44831 | Harry-003/Python_programs | /Q3.py | 210 | 4.25 | 4 | """
WPP to enter value in centimetre and convert it to meter and kilometre.
"""
cm = int(input("Enter value in centimeters : "))
print("Value in meters :",cm/100)
print("Value in kilometeres :",cm/1000) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.