blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8dc4ebaf99230ef7580ab39d1860e21dbe745b7b | andrewsanc/pythonOOP | /exerciseCatsEverywhere.py | 691 | 4.34375 | 4 | # Python Jupyter - Exercise: Cats Everywhere
#%%
#Given the below class:
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
# 1 Instantiate the Cat object with 3 cats
#%%
cat1 = Cat('Grumpy Cat', 2)
cat2 = Cat('Keyboard Cat', 1)
cat3 = Cat('Garfield', ... | true |
4b9764b1034df16e9a0fb1315298b8103d92184d | SiTh08/python-basics | /Exercises/Exercise1.py | 1,213 | 4.5625 | 5 | # Define the following variables
# first_name, last_name, age, eye_colour, hair_colour
first_name = 'Francis'
last_name = 'Thevipagan'
age = 25
eye_colour = 'Brown'
hair_colour = 'Black'
# Prompt user for input and Re-assign these
first_name = input('What is your first name?').capitalize().strip()
print(first_name)
l... | true |
278d3be29a6dc8c5af985c0fcdbe24d39a4f84f7 | sharmayuvraj/cracking-the-coding-interview | /linked-lists/loop-detection.py | 704 | 4.125 | 4 | """
Given a circular linked list, implement an algorithm that return the node at the begining of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a
loop in the linked list.
Example:
Input: A -> B -> C -> D -> E -> C [the same C... | true |
d4000957ed00bf01fdda0e8db562c2f2cd0c68f8 | sharmayuvraj/cracking-the-coding-interview | /Recusrion-and-Dynamic-Programming/nth-fibonacci-number.py | 809 | 4.21875 | 4 | """
Compute the nth Fibonacci Number.
"""
# Recusive Approach
# Time Complexity -> O(2^n)
def fib_recursive(n):
if n <= 1:
return n
return fib_recursive(n-1) + fib_recursive(n-2)
# Top Down Approach (or Memoization)
# Time Complexity -> O(n)
# Space Complexity -> O(n)
def fib(n):
memo = [0] *... | false |
afa178c6451ff803e343f8e3a238a69e0cd0369e | congnbui/Group3_Project | /Homeworkss5/Hwss4.study.4.9.8.py | 246 | 4.28125 | 4 | def area_of_circle(r):
"""area of a circle with radius r"""
import math
a = math.pi * (r**2)
return a
##import math
while True:
r = int(input("Enter the radius: "))
print("The area of the circle is: ",area_of_circle(r))
| true |
9bc65899c5ee88b5972df5d1215b4ae85ef57db8 | yogeshdewangan/Python-Excersise | /listPrograms/permutation.py | 1,074 | 4.1875 | 4 |
"""
Write a Python program to generate all permutations of a list in Python
"""
"""
In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence or order,
or if the set is already ordered, rearranging (reordering) its elements, a process called permuting. Thes... | true |
983427e4b9dbfc51060f5bfddba622c4bc9f2d9d | yogeshdewangan/Python-Excersise | /shallow_and_deep_copy/assignment_copy.py | 524 | 4.25 | 4 | import copy
#Copy via assignment
#only reference will be copied to new instance. Any modification in new one will reflect on other one
#Memory location is same for both the instances
print("Assignment copy ----------")
l1 = [1,2,3,4]
print("L1: " + str(l1))
print("Memory Location L1: "+ str(id(l1)) )
l2= l1 ... | true |
0aa67f9ed7ac4bd1640768dee7cb3613beeefcfd | LofiWiz/CS-1400 | /exercise3/exercise3.1.py | 915 | 4.1875 | 4 | # Seth Mitchell (10600367)
# CS 1400
# exercise 3.1
import math
# Translations:
#1
print(float((3+4) * 5))
print()
#2
n = float(input("define the numeric value of n; n = "))
print((n * (n-1)) / 2)
print()
#3
r = float(input("define the value of r (radius); r = "))
print((4 * math.pi * r ** 2))
p... | false |
d583a40e72833a31104cb1724fdcba8edb4b1c41 | jdaeira/Python-Collections | /slices.py | 930 | 4.1875 | 4 | my_string = "Hello there"
new_string = my_string[1:5]
print(new_string)
my_list = list(range(1,6))
print("My list is: {} ".format(my_list))
# This will get the last item of the list
new_list = my_list[2:len(my_list)]
print(new_list)
beginning = my_list[:3]
print(beginning)
end = my_list[0:]
print(end)
all_list = ... | true |
5d3b35a39d67e1158ea9440ba19230274cb6c3d7 | jpmolden/python3-deep-dive-udemy | /section5_FunctionParameters/_66_extended_unpacking.py | 1,801 | 4.34375 | 4 |
print('*** Using python >=3.5 ***')
l = [1, 2, 3, 4, 5, 6]
# Unpacking using slicing, :
a, b = l[0], l[1:]
print('\n**** Using the * Operator ***')
print('\ta, *b = l')
a, *b = l
print("\ta={}\n\tb={}".format(a,b))
print('\tThis works with any iterable including non-sequence types (set, dict)')
c, *d = (1,2,3,4,5... | true |
2e2eacf22e11cb41a803a44c0e76827670338018 | susantamoh84/Python-Learnings | /python-matplotlib.py | 2,073 | 4.25 | 4 | # Print the last item from year and pop
print(year[-1]);print(pop[-1])
# Import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
# Make a line plot: year on the x-axis, pop on the y-axis
plt.plot(year,pop)
# Display the plot with plt.show()
plt.show()
# Change the line plot below to a scatter plot
plt.scatt... | true |
2ef6f5b9fe8c229905b5e63bc49f46de76dcb16b | ashu20031994/HackerRank-Python | /Day-2-Python-DataStructure/4.Find_percentage.py | 1,061 | 4.21875 | 4 | """
The provided code stub will read in a dictionary containing key/value pairs of name:[marks] for a list of students.
Print the average of the marks array for the student name provided, showing 2 places after the decimal.
Example
The query_name is 'beta'. beta's average score is .
Input Format
The first line ... | true |
9b57bb348adca0ef1d41facb467f6042a908f189 | Ahmad-br-97/DataMining-Exercise-1 | /Exercise_01-04.py | 491 | 4.25 | 4 | text = input("Please enter a comma separated string of words: ")
split_text = text.split(',')
output_set = set()
output_list = []
for word in split_text : output_set.add(word) #Add words to a Set for remove duplicate words
for word in output_set : output_list.append(word) #convert Set To List
output_list... | true |
1ad59660fa739a147a3284fe5cadcd4d9cb4915d | Nutenoghforme/Manatal | /Ex2.py | 720 | 4.15625 | 4 | #Exercise 2: Randomness Test
#In a lottery game, there is a container which contains 50 balls numbered from 1 to 50. The lottery game consists in picking 10 balls out of the container, and ordering them in ascending order. Write a Python function which generates the output of a lottery game (it should return a list). A... | true |
e07cc6e8955978e79e261b05626758ecc334b987 | j-a-c-k-goes/compound_interest | /comp_interest.py | 2,818 | 4.15625 | 4 | '''
most investments use a compound interest formula,
which is more accurate than computing simple interest.
'''
def starting_amount():
starting_amount = float(input('enter investment starting amount: '))
return starting_amount
def investment_time():
investment_time = float(input('enter time to invest (in ye... | false |
b176cf4b2b6e44779848af26ccc65076d172158e | AndresRodriguezToca/PythonMini | /main.py | 1,755 | 4.25 | 4 | # Andres Rodriguez Toca
# COP1047C-2197-15601
# 10/3/2019
#Declare variables
numberOrganisms= 0
dailyPopulation = 0.0
averageIncrease = 0.0
numberDays = 0
counter = 2
#Get the number of organism
print("Starting number of organisms:", end=' ')
numberOrganisms = int(input())
# If necessary loop through the input until... | true |
bf86ec9fc09cb4caa7d9383de96b15e357d7994f | samiulla7/learn_python | /datatypes/dict.py | 1,204 | 4.3125 | 4 | my_dict = {'name':'Jack', 'age': 26}
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
##########################################################################... | true |
1d75087f26ee00058c26ae5795c2f81af239161f | eltondornelas/hackerrank-python | /text_alignment.py | 1,927 | 4.40625 | 4 | """
In Python, a string of text can be aligned left, right and center.
.ljust(width)
This method returns a left aligned string of length width.
>>> width = 20
>>> print 'HackerRank'.ljust(width,'-')
HackerRank----------
.center(width)
This method returns a centered string of length width.
>>> width = 20
>>> print ... | true |
c34a9cea2effc8d23f885d6cb2afc3c5612e819e | Stanbruch/Strong-Password-Checker | /strong_password_check.py | 1,132 | 4.1875 | 4 | import re
#strong password
passStrong = False
def passwordStrength():
#Enter password
passwordText = input('Enter password: ')
#Strength check
charRegex = re.compile(r'(\w{8,})')
lowerRegex = re.compile(r'[a-z]+')
upperRegex = re.compile(r'[A-Z]+')
digitRegex = re.compile(r'[0-9]+')
... | true |
27651140b12fd771972ec657b968e37b68a3d0c4 | skgande/python | /pythoncoding/com/sunil/functions/print_3_times_each_character.py | 832 | 4.34375 | 4 | class Print3TimesEachCharacter:
"""
Given a string, return a string where for every character in the original there are three characters.
paper_doll('Hello') --> 'HHHeeellllllooo’
paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii’
"""
def __init__(self):
return
def pr... | true |
dcb168a423a010ee955af5c89d337ef411b40f4d | Its-me-David/Hangman-2.0 | /hangman/hangman.py | 2,438 | 4.125 | 4 | import output
import time
# Den Spieler einladen zu spielen
print("Willkommen bei Hangman")
name = input("Gib deinen Namen ein: ")
print("Hallo " + name + ", viel Glück!")
time.sleep(1)
print("Lasset das Spiel beginnen!")
time.sleep(2)
class visualisation:
def __init__(self, word):
self.word = word.upper... | false |
7e9be152c65ecbce6d997a7c7bf5c0c7e5bbd69e | alexpereiramaranhao/guppe | /args.py | 594 | 4.28125 | 4 | """
Entendendo o *args
- É um parâmetro, como outro qualquer;
- Pode chamá-lo de qualquer nome, desde que inicie com *
- Por convenção, utiliza-se o *args
- Guarda os valores de entrada em uma tupla
"""
def somar_numeros(*args):
return sum(args)
print(somar_numeros(1, 2))
print(somar_numeros... | false |
ad7d1249367d98b1570775c3adbfabaa1e83c909 | Henrique-Temponi/PythonForFun | /PythonOtavio/PythonBasic/05-operators.py | 781 | 4.34375 | 4 | """
we have a few operators in python:
+, -, *, **, /, //, %, ()
"""
# Both + - are quite simple, the first adds, the second subtracts
print(1 + 1)
print(1 - 1)
# note with +, you add strings together
print("bana" + "na")
# * = multiples
print(2*2)
# NOTE: you can multiply strings, with you copy x number of times a... | true |
93e2f9044e3c5fbd595cc325171be2892791fbc8 | Henrique-Temponi/PythonForFun | /PythonOtavio/PythonBasic/17-split_join_enumerate.py | 1,887 | 4.53125 | 5 | """
Split - this will split a string with the chosen separator, ( default is whitespace )
Join - this will join multiple elements (eg. in a list or a string)
enumerate - this will create a index for a iterable object (eg. list, string, dictionary, etc)
these function covers a lot of grou... | true |
99fef6c9ac257ed5c56df6308f37e9f16d607b3c | KostaPapa/Python_Works | /Practice/a30ClassGeneralForm.py | 2,806 | 4.5 | 4 | class TypeName( object ):
'''This class will contain the general form of a class.'''
def __init__( self, dataMember_1, dataMember_2, dataMember_3 = 3 ): # defaultValue
'''This function will initialize the variables needed to be used during class design. Notice that other variables may be needed
... | true |
b5006fe99312946863316ce419427aad74635803 | KostaPapa/Python_Works | /LAB/REC02/rec02.0 ( Box ).py | 2,468 | 4.375 | 4 | """
User Name: kpapa01
Programmer: Kostaq Papa
Purpose of this program: This program will print a box with a certain width and character.
Constrains: It will compile from left to right. The is an integer number.
"""
def askTheuserToenterCharacter ():
'''This function will ask the user to enter a char... | true |
1701db222173b6b1c61555835dfa4d345b0cf30a | jkrobinson/crash | /Ch04/friend_pizzas.py | 299 | 4.125 | 4 | pizzas = ['meat lovers', 'hawaiian', 'cheesy']
pizzas.append('supreme')
friend_pizzas = pizzas[:]
friend_pizzas.append('bbq chicken')
print("My favourite pizzas are:")
for pizza in pizzas:
print(pizza)
print("\nMy friend's favourite pizzas are:")
for pizza in friend_pizzas:
print(pizza)
| true |
ddc554e34944d80e82ddfc5b3013a989f2026e5b | Surafel-zt/Final-website | /GUI questions.py | 1,761 | 4.21875 | 4 | from tkinter import *
from tkinter import messagebox
root = Tk()
root.title('Assignment 2 GUI')
question_1 = Label(root, text="Who lives in the second corner?", font=('Verdana', 12))
question_1.grid(row=0, column=0)
question_2 = Label(top, text="Who lives in the middle?", font=('Verdana', 12))
question_2.g... | true |
86654923966393893975ca3b0ebcb9ed3720cb09 | inwenis/learn_python | /01_print.py | 1,298 | 4.53125 | 5 | print("Hello there human!")
print("do you know you can put any text into a print()?")
print("like stars *******, numbers: 1,2,42,999")
# exercise 1: Use print() to display "Hello world" in the console
# Do one exercise at a time.
# exercise 2: Use print() to display some asterisks (this is a
# asterisk -> * )
# ex... | true |
b6ec41689760a4e558bd4605a5fcf99ee9139079 | inwenis/learn_python | /08_interactive_shell.py | 2,605 | 4.21875 | 4 | # This file is not about a new part of the python language. It's
# about another way to execute python code.
# Till now we have execute our python scripts by invoking the python
# program from terminal and passing it a script to execute.
# If you use PyCharm and run scripts with "right click" + "Run ...."
# PyCharm in... | true |
68d06770e3db6145a77e8fe1c4fa8515cbbbeb0e | kannan4k/python_regex_implementation | /SubString.py | 2,604 | 4.3125 | 4 | """Implementation of the Python Programming Contest 1"""
from __builtin__ import range
def split_string(text):
""" This function will split the string into list based on the '*' as delimiter
For Ex: input = "Hello*Python"
Output = ['Hello', 'Python']
and Yes it will remove t... | true |
34a1c766420bf8a0ad3b5074fcfd615a0ae22e06 | RichHomieJuan/PythonCourse | /Dictionaries.py | 388 | 4.15625 | 4 | #dictionaries are indexed by keys.
dictionary = {} #not very useful
tel = {"Mary": 4165, "John" : 4512, "Jerry" : 5555 }
print(tel)
tel ["jane"] = 5432 #inserts into the dictionary
print(tel)
print(tel ["Jerry"]) #looks up the specified thing in dictionary
del tel["Jerry"] #deletes said person or value.
print(tel)
... | true |
96644660d0c878ea20b83c708ac773f4e0250a3c | georgetaburca/analog-clock | /analog_clock.py | 1,556 | 4.15625 | 4 | #simple analog clock in Python
import time
import turtle
wn = turtle.Screen()
wn.bgcolor("black")
wn.setup(width=600, height=600)
wn.title("Analog Clock")
wn.tracer(0)
#Create the drawing pen
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.pensize(3)
def draw_clock(h, m, s, pen):
#... | true |
eb0b85afa0d48d3ffd65d74b0448e7aaa2af526e | ssharp96/Comp-Sci-350 | /SSharpArithmeticMean.py | 316 | 4.125 | 4 | # Arithmetic Mean
# author: SSharp
def arithmeticMean(a,b):
'''Computes and returns the arithemtic mean of a and b'''
return ((a+b)/2)
a = float(input("Enter a number: "))
b = float(input("Enter another number: "))
result = arithmeticMean(a,b)
print("The arithmetic mean of",a,"and",b,"is",result)
| true |
fe8de17a88fafa45a31d22fefd6cc4404e2d219a | jeffonmac/Fibonacci-Numbers | /Search_dichotomy.py | 2,149 | 4.3125 | 4 | # Fonction fibonacci Sequence with loop "recursive" :
mem = {}
def fib(number):
# print("fib" + str(number))
if number < 1:
return 0
if number < 3:
return 1
if number not in mem:
mem[number] = fib(number - 1) + fib(number - 2)
return mem[number]
# With loop "for" :
def f... | false |
a4e4d9ba8286920529b347b58aa34d40a065eb77 | MthwBrwn/data_structures_and_algorithms | /data_structures/hash_table/hash_table.py | 2,355 | 4.15625 | 4 | class Hashtable:
"""
"""
def __init__(self):
self.size = 64
self.bucket = [None] * self.size
def __repr__(self):
return f'bucket size : {self.size}'
def __str__(self):
return f'bucket size : {self.size}'
# A hash table should support at least the following methods... | true |
87b2555f4151df0cf97d84d3dddd5639d9eb7433 | OlehPalka/Algo_lab | /insertion_sort.py | 1,068 | 4.21875 | 4 | """
This module contains insertion sort.
"""
def insertion_sort(array):
"""
Insertion sort algorithm.
"""
for index in range(1, len(array)):
currentValue = array[index]
currentPosition = index
while currentPosition > 0 and array[currentPosition - 1] > currentValue... | true |
62d6467157d0a54e20dca9a14ff9d5020c3dbe79 | error-driven-dev/Hangman-game | /hangman.py | 2,544 | 4.125 | 4 | import random
import string
#open text file of words, save as a list and randomly select a word for play
def new_word():
with open("words.txt", "r") as word_obj:
contents = word_obj.read()
words = contents.split()
word = random.choice(words)
return word
def lett... | true |
e38f902083d53e2ecdcec7e42d6b0e1bdeb4b7af | dj5353/Data-Structures-using-python | /CodeChef/matrix 90(anticlockwise).py | 523 | 4.375 | 4 | #for matrix 90 degree anticlockwise rotation
#and transpose the matrix
#reverse matrix all column wise
def matrix_rotate(m):
print("Matrix before rotation")
for i in (m):
print(i)
# Transpose matrix
for row in range(len(m)):
for col in range(row):
m[row][col], m[c... | true |
7f5b4896c3c47f834ff7dbb4aa5b65e2dba2437c | dj5353/Data-Structures-using-python | /CodeChef/Binary-search.py | 738 | 4.15625 | 4 | def binarySearch(a,n,searchValue):
first = 0
last = n-1
while(first<last):
mid = (first + last)//2
if(searchValue<a[mid]):
last = mid-1
elif(searchValue>a[mid]):
first = mid+1
else:
return mid
return -1
n = int(input("Enter ... | true |
258d837ce4d5bfd7c4e4a7cbdc5517aec582d9e1 | abusamrah2005/Saudi-Developer-Organization | /Week4/secondLesson.py | 1,268 | 4.3125 | 4 | # set of names , we have four names.
setOfNames = {'waseem', 'ahmed', 'ali', 'dayili'}
# by using len() function to calculate the number of items seted in the set
print('we have ' + str(len(setOfNames)) +' names are there.')
# there are two function to remove elemen in set 'remove() & discard()'
print('Names: ' + st... | true |
5066c5fccfc4e132798a0d04d59fb1de6e0f68da | AntonioRice/python_practice | /strings.py | 752 | 4.1875 | 4 | num = 3;
print(type(num));
print(5 + 2);
print(5 / 2);
print(5 - 2);
# exponents
print(5 ** 2);
# modulus
print(5 % 2);
print(4 % 2);
# OOP
print(3 * 2 + 4);
print(3 * (2 + 4));
num = 1;
num += 1;
print(num);
# absolute value
print(abs(-3));
# round
print(round(5.8901));
# how many digits id like to round to
print(r... | true |
d3b2a74ce570df798dc7da790b6bdfcdb20448d1 | JiangRIVERS/data_structure | /LinkedBag/linked_structure.py | 743 | 4.375 | 4 | #定义一个单链表节点类
class Node:
"""Represents a singly linked node"""
def __init__(self,data,next=None):
"""Instantiates a Node with a default next of None"""
self.data=data
self.next=next
class TwoWayNode(Node):
"""Represents a doubly linked node"""
def __init__(self,data,previous=Non... | true |
1a51c8997f8090c61af75592596f44571005001f | JiangRIVERS/data_structure | /Calculate_arithmetic_expressions/calculate_function.py | 543 | 4.375 | 4 | """
Filename:calculate_function
Convert string operator to real operator
"""
def calculate_function(string,operand1,operand2):
"""Raises KeyError if the string operator not in string list"""
string_list=['+','-','*','/']
if string not in string_list:
raise KeyError('We can\'t deal with this operator... | true |
00b3c3106f95ccb9059c195315d28812ec71f1f6 | RMolleda/Analytics_course | /delivery/basic_functions.py | 540 | 4.15625 | 4 | def append_item(item, where):
"""
U must set the object u want to append as the value of "object"
and "where" should be the list where u want to append it
"""
where.append(item)
def remove_item_list(item, where):
"""
pop the input from a list
it will loop arround all the list, and if ... | true |
d4c588d0811d01742dcfd25915554ea1fd06fe69 | Anonymous-indigo/PYTHON | /shapes/heptagon.py | 231 | 4.15625 | 4 | #To draw a heptagon, you will need to have seven sides and have a 51.42 degree angle on each side. The lenth of each side will not affect the angle needed.
import turtle
t=turtle
for n in range(7):
t.forward(100)
t.right(51.42) | true |
6abf212d5cbd88ec6c3802cee3a9da7c4b740bcc | RuidongZ/LeetCode | /code/290.py | 1,373 | 4.125 | 4 | # -*- Encoding:UTF-8 -*-
# 290. Word Pattern
# Given a pattern and a string str, find if str follows the same pattern.
#
# Here follow means a full match, such that there is a bijection
# between a letter in pattern and a non-empty word in str.
#
# Examples:
# pattern = "abba", str = "dog cat cat dog" should return t... | true |
e0fa225b4ed69b3234517176b2c8c3a519b93c39 | RuidongZ/LeetCode | /code/451.py | 1,130 | 4.125 | 4 | # -*- Encoding:UTF-8 -*-
# 451. Sort Characters By Frequency
# Given a string, sort it in decreasing order based on the frequency of characters.
# Example 1:
# Input: "tree"
# Output: "eert"
#
# Explanation:
# 'e' appears twice while 'r' and 't' both appear once.
# So 'e' must appear before both 'r' and 't'. Theref... | true |
3651948d047f7ab76cba9e74c98e2b9d53a62504 | RuidongZ/LeetCode | /code/537.py | 1,011 | 4.15625 | 4 | # -*- Encoding:UTF-8 -*-
# 537. Complex Number Multiplication
# Given two strings representing two complex numbers.
# You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
# Example 1:
# Input: "1+1i", "1+1i"
# Output: "0+2i"
# Explanation: (1 + i) * (1 + i) = 1 + i2... | true |
050bb7bbddb8040a778bfae81d54776c95f375c9 | Dillon1john/Python | /finalreview4finishit.py | 203 | 4.1875 | 4 | temp=70
humid=45
if(temp<60) or (temp>90) or (humid>50):
print("Stay inside")
else:
if (humid==100):
print("It is raining outside")
else:
print("Do you want to take a walk?")
| true |
a28854b23700b3af588a06aa525c53ad503a5ad5 | Dillon1john/Python | /classworkstudynov7.py | 575 | 4.125 | 4 | #example of input list
name=[ ]
ssn=[ ]
age= [ ]
while True:
Last_name=input("Enter your last name: ")
if Last_name in name:
print("Your name already in the list")
else:
name.append(Last_name)
print("I just got your registered")
Social= input("Enter your SSN: ")
if So... | true |
450a60088fd4913f56d817ef4681a9550ef12198 | btgong/Cmpe131Homework-Python | /calculator.py | 1,215 | 4.4375 | 4 | def calculator(number1, number2, operator):
'''
Returns the calculation of two decimal numbers with the given operator
Parameters:
number1 (float): A decimal integer
number2 (float): Another decimal integer)
operator (string): Math operation operator
Returns:
Calculation of number1 and number2 with ... | true |
119c4153fe8a13d13ad8f522aa008623362a4218 | skinisbizapps/learning-python | /ch02/loops.py | 906 | 4.15625 | 4 |
def main():
print('welcome to loops')
x = 0
# define a while loop
while x < 5:
print(x)
x = x + 1
# define a for loop
for x in range(5, 10):
print(x)
# use a for loop over a collection
days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
for day in day... | true |
bcd4b4dea007d8621524af3939d45d96c482236d | jonasht/CursoEmVideo-CursoDePython3 | /mundo3-EstruturasCompostas/106-sistemaInterativoDeAjuda.py | 862 | 4.28125 | 4 | # Exercício Python 106:
# Faça um mini-sistema que utilize o Interactive Help do Python.
# O usuário vai digitar o comando e o manual vai aparecer.
# Quando o usuário digitar a palavra 'FIM', o programa se encerrará.
# Importante: use cores.
vermelho = '\033[41m'
verde = '\033[42m'
amarelo = '\033[43m'
azul = '\033... | false |
51e035be77493ab9fcf143b7b6bc192493fb087d | MattRijk/algorithms | /randomization_algorithm.py | 508 | 4.1875 | 4 | """
Randomization Algorithm - Randomizing an array.
For i = 1 To N
' Pick an item for position i.
j = Random number between i and N
' Swap items i and j.
temp = value[i]
value[i] = value[j]
value[j] = temp
Next i
"""
# python
from random import randint
alist = [1,2,3,4,5,6]
resul... | false |
825d001f7eba45a6d8a663321370a608a7a6cbca | egalleye/katas | /two_smallest.py | 659 | 4.1875 | 4 |
def sum_two_smallest_numbers(numbers):
smallest = -1
secondSmallest = -1
for num in numbers:
if ( smallest < 0 ):
smallest = num
else:
if ( num < smallest ):
secondSmallest = smallest
smallest = num
elif ( num < secondSmal... | true |
bc69b59ed4ac02f07ca0b48a4581787feb7e6416 | csouto/samplecode | /CS50x/pset6/caesar.py | 1,067 | 4.15625 | 4 | import sys
import cs50
# Allow two arguments only, program will exit otherwise
if len(sys.argv) != 2:
# change error message
print("Please provide one argument only")
exit(1)
# Use the the second argument as key
k = int(sys.argv[1])
# Print instructions on screen, ask for input and calculate the length o... | true |
04fb3910612a6d0bd6167dcfa7a4e7d22333522d | Wolverinepb007/Python_Assignments | /Python/prime.py | 348 | 4.125 | 4 | num=int(input("Enter a number: "))
i=0
n=2
while(n<num):
if(num%n==0):
i+=1
break
n+=1
if(i==0 and num !=1 and num !=0):
print(num," is a prime number.")
elif(num ==1 or num ==0):
print(num," is neither prime nor a composite number.")
else:
print(num," is not a prime ... | true |
f604a334cda7df8ebcc58e105deeb911dc62a7f8 | PrashantThirumal/Python | /Basics/RandomGenEclipse.py | 371 | 4.125 | 4 | '''
Created on May 30, 2019
@author: Prashant
'''
import random
#Randomly generate numbers 0 to 50
com = random.randint(0,50)
user = 51
while(user != com):
user = int(input("Enter your guess"))
if(user > com):
print("My number is smaller")
elif(com > user):
print("My num... | true |
5158be40ab24bb386d426c859f030ee40ab92176 | happy5205205/PythonProjects | /History/day01/ProcseeControl.py | 1,192 | 4.1875 | 4 | #if的条件可以是数字或字符串或则布尔值True和False(布尔表达式)
#如果是数字,则只要不等于0,就为True
#如果是字符串,则只要不是空串,就为True
#if语句
# var1 = 100 #ture输出
# if var1:
# print("1-Got a ture expression value")
# print(var1)
# var2 = 0 #False不输出
# if var2:
# print("2-Got a ture expression value")
# print(var2)
# print("Good bye")
#if... | false |
98d5f200a0168bb4dda7ff62f14e1e4e73c016c7 | golbeckm/Programming | /Python/the self-taught programmer/Chapter 14 More Object Oriented Programming/chapter_14_challenge_1.py | 369 | 4.15625 | 4 | # Add a square_list class variable to a class called
# Square so that every time you create a new Square
# object, the new object gets added to the list.
class Square():
square_list = []
def __init__(self, s):
self.side = s
self.square_list.append((self.side))
s1 = Square(5)
s2 = Square... | true |
35d1c727021ecfc6c40dac30832cce0df861fb6b | golbeckm/Programming | /Python/the self-taught programmer/Chapter 3 Intro to Programming/chapter_3_challenge_5.py | 323 | 4.25 | 4 | # create a program that takes two varibales,
# divides them, and prints the quotient.
print("Give me two numbers to divide by.")
variable_1 = int(input("Enter the first number: "))
variable_2 = int(input("Enter the second number: "))
print("The quotient of ", variable_1,"/", variable_2, "is", variable_1 // variable_... | true |
1f694b39cee317c3c32ea34a773a98b326d87677 | golbeckm/Programming | /Python/the self-taught programmer/Chapter 3 Intro to Programming/chapter_3_challenge_2.py | 303 | 4.28125 | 4 | # write a program that prints a message if a variable is less than 10,
# and different message if the variable is less than or equal to 10.
variable = int(input("Enter a number: "))
if variable < 10:
print(variable, "is less than 10")
elif variable > 10:
print(variable, "is greater than 10")
| true |
ce4905f64e2981632c19df7e2e5b0c64d0dfabaf | marianpg12/pcep-tests | /block3_flow_control/test2.py | 411 | 4.15625 | 4 | # What is the output of the following code snippet when the :
milk_left = "None"
if milk_left:
print("Groceries trip pending!")
else:
print("Let's enjoy a bowl of cereals")
# Answer: Groceries trip pending!
# Explanation: If the value of a variable is non-zero or non-empty,
# bool(non_empty_variable) will be be T... | true |
cc580e2311da3d5358d3710f044ba6b63df035f6 | marianpg12/pcep-tests | /block4_data_collections/test1.py | 298 | 4.15625 | 4 | # What do you expect when the following code snippet is run:
weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday")
weekdays.append("Friday")
print(weekdays)
# Answer: AttributeError: 'tuple' object has no attribute 'append'
# Explanation: Tuples are immutable and can't be amended once created
| true |
d34a70c3d5ba30d5fe02f360e8946b9a3a1dbdb4 | marianpg12/pcep-tests | /block5_functions/test7.py | 442 | 4.34375 | 4 | # What is the output of the following code
def fun(a = 3, b = 2):
return b ** a
print(fun(2))
# Answer: 4
# Explanation: The function expects two values, but if not provided,
# they can be defaulted to 3 and 2 respectively for a and b.
# Note that he function calculates and returns b to the power of a.
# When yo... | true |
bb45e2ba337d201916858aebe6f6433cce8d14d9 | Pandaradox/LC101-WeeklyAssigns | /python/ch9weekly.py | 1,333 | 4.15625 | 4 |
# ##################################################Chapter 9 Weekly Assignment
# Function to scan a string for 'e' and return a percentage of the string that's 'e'
import string
def analyze_text(text):
es = 0
count = 0
for char in text:
if char in string.ascii_letters:
count += 1
... | true |
13fa5532359fcf0ea526297328cb5cba1e1fe292 | katrina376/or2016 | /hw_3/Fibo.py | 256 | 4.125 | 4 | n = int(input("Please input the term n for the Fibonacci sequence: "))
print "The Fibonacci sequence = "
def fibo(n) :
if (n <= 2) :
return 1
else :
return fibo(n-1) + fibo(n-2)
s = ""
for i in range(1, n+1) :
s += str(fibo(i)) + " "
print s
| false |
2cb987fd5d1852847c30f7cd000ed8a1f61e0a8a | akashbhanu009/Functions | /Lambda_Function.py | 667 | 4.34375 | 4 | '''->Sometimes we can declare a function without any name,such type of nameless functions
are called anonymous functions or lambda functions.
The main purpose of anonymous function is just for instant use(i.e for one time usage)'''
#normally we can use 'def' keyword
def square(a):
print(a*a)
square(10)
#no... | true |
0fe91c1d26853ba69130e2925e6935d5eee882f6 | Adenife/Python_first-days | /Game.py | 1,571 | 4.125 | 4 | import random
my_dict = {
"Base-2 number system" : "binary",
"Number system that uses the characters 0-F" : "hexidecimal",
"7-bit text encoding standard" : "ascii",
"16-bit text encoding standard" : "unicode",
"A number that is bigger than... | true |
051364e41d439c7402c6e2a7e57a5583c2bfad26 | djtongol/python | /OOP/OOP.py | 2,718 | 4.15625 | 4 | #Basic OOP
class Beach:
#location= 'Cape Cod'
def __init__(self, location, water, temperature):
self.location= location #instance variable
self.water= water
self.temperature= temperature
self.heat = 'hot' if temperature >80 else 'cool'
self.parts= ['water'... | true |
6c010e3b0462d6ea40a5966839571ed6ab0a0355 | asmitapoudel/Python_Basics-2 | /qs_7.py | 672 | 4.125 | 4 | """
Create a list of tuples of first name, last name, and age for your
friends and colleagues. If you don't know the age, put in None.
Calculate the average age, skipping over any None values. Print out
each name, followed by old or young if they are above or below the
average age.
"""
lioftuples=[('Shruti','Poudel',2... | true |
66470c73af52ffecfa327eddf1cb32c790854aa6 | mctraore/Data-Structures-and-Algorithms | /Linked Lists/linked_list.py | 1,850 | 4.125 | 4 | class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current... | true |
97bbcb83752b42fdb44fe31872d1e8b2e18edeec | My-Sun-Shine/Python | /Python3/Learn/Learn30.py | 713 | 4.125 | 4 | # 错误处理机制 try...except...else...finally...
# 所有的错误类型都继承BaseException
import logging
try:
print("try...")
r = 10/int("2")
print("result:", r)
except ValueError as e:
print("ValueError", e)
except ZeroDivisionError as e:
print("ZeroDivisionError", e)
else:
print("NO error") # 没有错误时执行
finally:
... | false |
77373257b4daaa97c0703f6f92d9f7744bc5c711 | drakezhu/algorithms | /random_selection/randSelect.py | 1,900 | 4.15625 | 4 | ##########################################################################
#
# Tufts University, Comp 160 randSelect coding assignment
# randSelect.py
# randomized selection
#
# includes functions provided and function students need to implement
#
##########################################################... | true |
0e4b3a8cc3b6cb693b030e663a1f15611669233c | dineshbalachandran/mypython | /src/gaylelaakmann/1_6.py | 592 | 4.21875 | 4 | def compress(txt):
if len(txt) < 3:
return txt
out = []
currchar = txt[0]
count = 0
for char in txt:
if char != currchar:
out.append(currchar)
out.append(str(count))
currchar = char
count = 1
else:
count += 1
... | true |
919e93118fc21b5f45a947257bee54a667752573 | dakshtrehan/Python-practice | /Strings/Alternate_capitalize.py | 297 | 4.1875 | 4 | #Write a program that reads a string and print a string that capitalizes every other letter in the string
#e.g. passion becomes pAsSiOn
x=input("Enter the string: ")
str1= ""
for i in range(0, len(x)):
if i%2==0:
str1+=x[i]
else:
str1+=x[i].upper()
print(str1) | true |
1e438dd75672e236927476f9e7cfc964aba9b7f3 | Minyi-Zhang/intro-to-python | /classwork/week-2/groceries.py | 1,567 | 4.375 | 4 | #!/usr/bin/env python3
# Built-in data type: Sequence Types
# list (mutable)
# groceries = list(
# "apples",
# "oranges",
# )
groceries = [
"apples",
"oranges",
"pears",
"kiwis",
"oranges",
"pears",
"pears",
]
# print(groceries[3:6])
# example: groceries.count(x)
# Return the nu... | true |
5f3c7c4bfd558d02e3788e6e1434325c22568304 | atm1992/nowcoder_offer_in_Python27 | /p7_recursion_and_loop/a1_Fibonacci.py | 1,740 | 4.125 | 4 | # -*- coding:utf-8 -*-
"""
斐波那契数列。
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=39
f(0)=0 f(1)=1
f(2)=1 f(3)=2
f(4)=3 f(5)=5
"""
class Solution:
def Fibonacci_1(self, n):
"""方法一:递归实现。时间复杂度为O(2^n)"""
if n == 0:
return 0
if n == 1:
return 1
return ... | false |
c5b17caf6c10b1879210cc1ecaba2b5c94c9e98a | satrini/python-study | /exercises/exercise-26.py | 286 | 4.15625 | 4 | # Calc leap year
from datetime import date
year = int(input("Choose a year (0 for actual year):"))
if year == 0:
year = date.today().year
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print(f"{year} - Leap year: YES!")
else:
print(f"{year} - Leap year: NO!")
| false |
4d6c34943ae50b8df95ab0371180ea69be434981 | satrini/python-study | /exercises/exercise-37.py | 718 | 4.40625 | 4 | # BMI
weigh = float(input("How much do you weigh? KG"))
height = float(input("How tall are you? (M)"))
# normal, obesity morbid, under normal weight, over weigh
bmi = weigh / (height ** 2)
if bmi < 18.5:
print(f"Your BMI is {bmi}")
print("You are in the {} weight range!")
elif bmi >= 18.5 and bmi < 25:
pr... | false |
298f2bca4de971310d4573716715e0180f12d4b7 | satrini/python-study | /exercises/exercise-55.py | 201 | 4.1875 | 4 | num = int(input("Calculate factorial: !"))
factorial = 1
for i in range(num, 0, -1):
print(f"{i}", end = "")
print(" x " if i > 1 else " = ", end = "")
factorial *= i
print(f"{factorial}")
| false |
9a40697a33b75f341c3c4aeb502f4bb3051618db | RdotSilva/Harvard-CS50 | /PSET6/caesar/caesar.py | 1,022 | 4.125 | 4 | from sys import argv
from cs50 import get_string
def main():
# Check command line arguments to make sure they are valid.
if len(argv) == 2:
k = int(argv[1])
if k > 0:
print(k)
else:
print("NO")
else:
print("Invalid Input")
exit(1)
# Prom... | true |
946c278ccc0a1e0a26c8c87b1b10f3dd201701ec | rohanaurora/daily-coding-challenges | /Problems/target_array.py | 1,098 | 4.34375 | 4 | # Create Target Array in the Given Order
# Given two arrays of integers nums and index. Your task is to create target array under the following rules:
#
# Initially target array is empty.
# From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
# Repeat the previous st... | true |
acbc16d28d1eecdf125d26a44572ee035857fb15 | lungen/Project_Euler | /p30-digit-fifth-powers-0101.py | 1,381 | 4.1875 | 4 | <<<<<<< HEAD
"""
Digit fifth powers
Problem 30
Surprisingly there are only three numbers that can be
written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 is not a sum it is not included.
The sum of these numbers i... | true |
323921991a78e974ed30a01d14b01ec1b2f5ffb0 | lungen/Project_Euler | /_training_/codes/001.001_recursive_memoization_fibonacci.py | 885 | 4.34375 | 4 | """
Published on 31 Aug 2016
Let’s explore recursion by writing a function to generate the terms of the Fibonacci sequence.
We will use a technique called “memoization”
to make the function fast. We’ll first implement our own caching, but then we will use Python’s
builtin memoization tool: the lru_cache
decorator.
To ... | true |
749c0846784ae81b34c06c09115e6102b42d63d1 | mikaelbeat/The_Python_Mega_Course | /The_Python_Mega_Course/Basics/Check_date_type.py | 570 | 4.15625 | 4 |
data1 = 5
data2 = "Text"
data3 = 3
print("\n***** Data is int *****\n")
print(type(data1))
print("\n***** Data is str *****\n")
print(type(data2))
print("\n***** Check data type *****\n")
if isinstance(data3, str):
print("Data is string")
elif isinstance(data3, int):
print("Data is interg... | true |
63b5273dd2d85b4b412522e61266430592ba4b30 | RajeshNutalapati/PyCodes | /OOPs/Inheritence/super() or function overriding/super with single level inheritance_python3.py | 1,115 | 4.25 | 4 | '''
Python | super() function with multilevel inheritance
super() function in Python:
Python super function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions. It returns the proxy object that allows us to refer parent class by 'super'.
T... | true |
48626c838ebc03ddbf36ea98d78c7186359a332e | RajeshNutalapati/PyCodes | /OOPs/Inheritence/super() or function overriding/super with multilevel inheritence_python3.py | 1,727 | 4.40625 | 4 | '''
Python super() function with multilevel inheritance.
As we have studied that the Python super() function allows us to refer the superclass implicitly. But in multi-level inheritances, the question arises that there are so many classes so which class did the super() function will refer?
Well, the super() function h... | true |
a22d680571411459964d7db525fe155ab2fe09b6 | RajeshNutalapati/PyCodes | /DataAlgorithms/LinkedLists/single linked list.py | 701 | 4.25 | 4 | # make node class
#creating singly linked list
class Node:
def __init__(self,data):
self.data = data
self.next = None #initializing next to null
class LinkedList:
def __init__(self):
self.head = None
#This will print the contents of the linked list
#starting from head
def ... | true |
9ea49d349b93a71d8db360525968a065e08d71fc | johanna-w/hello-world | /plane.py | 1,296 | 4.3125 | 4 | """
Programmet skriver, och tar höjd, hastighet och temperatur i m, km/h och Celcius som input från användaren.
Värdena användaren skriver in används för att skapa mått som är konverterade till feet, mph och Farenheit.
"""
höjd = input("Höjd över havet (meter): ") # Användaren matar in höjd
hastighet = input("Hastighe... | false |
534d5357b9157fd8f63b8576226e003b4f132806 | lare-cay/CSCI-12700 | /10-16-19.py | 1,217 | 4.25 | 4 | #Name: Clare Lee
#Email: Clare.Lee94@myhunter.cuny.edu
#Date: October 16, 2019
#This program modifies a map according to given amount of blue crating a new image
import numpy as np
import matplotlib.pyplot as plt
blue = input("How blue is the ocean: ")
file_name = input("What is the output file: ")
#Read ... | true |
151dcc61aadad894cfffbd9f28deb772f130d578 | clush7113/code-change-test | /linearSearch.py | 357 | 4.1875 | 4 | testString = ""
searchChar = ""
newChar= ""
while testString == "" and len(searchChar) != 1 and newChar=="":
testString = input("Please enter some text to search : ")
searchChar = input("Enter a character to search for : ")
newChar = input("What would you like to replace the character with? : ")
print(tes... | true |
6fe4268d4b54cb1f6b0281e078402fb4115d07ad | SurajMondem/PythonProgramming | /Day_4/DucksAndGoats.py | 735 | 4.125 | 4 | # There are some goats and ducks in a farm. There are 60 eyes and 86 foot in total.
# Write a Python program to find number of goats and ducks in the farm
# You can use Cramer’s rule to solve the following 2 × 2 system of linear equation:
# ax + by = e
# cx + dy = f
#
# x = (ed – bf) / (ad – bc).
# y = (af – ec) / (ad... | false |
cddc867538535903d69e4795aaf554bb3260c602 | puntara/Python- | /Module3/m1_m2_concat_dict.py | 445 | 4.4375 | 4 | #1) Write a Python script to concatenate following dictionaries to create a new one.
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
result1={**dic1, **dic2, **dic3}
print(result1)
#2) Write a Python script to generate and print a dictionary that contains a number
# (between 1 and n) in the form (x, x*x).
nu... | true |
465bae6eadd928fbd7fd9cf3c80fc8de3dbbb0b7 | UjjwalSaini07/Tkinter_Course_1 | /Tkinter_13.py | 983 | 4.46875 | 4 | # https://www.codewithharry.com/videos/python-gui-tkinter-hindi-19
# todo : Sliders In Tkinter Using Scale()
from tkinter import *
import tkinter.messagebox as tmsg
root = Tk()
root.geometry("455x233")
root.title("Slider tutorial")
# get(): This method returns the current value of the scale.
# set(value):... | true |
e23c1a608d0172466d94f7619215a3df61b0bd84 | RandyKline/Self_Paced-Online | /students/ian_letourneau/Lesson03/slicing_lab.py | 2,973 | 4.25 | 4 | ## Ian Letourneau
## 4/26/2018
## A script with various sequencing functions
def exchange_first_last(seq):
"""A function to exchange the first and last entries in a sequence"""
middle = list(seq)
middle[0] = seq[-1]
middle[-1] = seq[0]
if type(seq) is str:
return "".join(middle)
elif t... | true |
14537d1a3dfbd4423de9ae80124510d697435069 | leelu62/PythonPractice | /BirthdayDictionary.py | 336 | 4.53125 | 5 | #store family and friend's birthdays in a dictionary
#write a program that looks up the birthday of the person inputted by the user
birthdays_dict = {"Amon":"10/03/2016","Christopher":"12/18/1983","Jenna":"6/2/1985"}
person = input("Whose birthday would you like to look up? ")
print(person + "'s birthday is",birthdays_... | true |
f0a1e316b9c2c0f0d740326ab98c0a6040460f6b | leelu62/PythonPractice | /StringLists.py | 374 | 4.5 | 4 | # ask user to input a word, then tell user whether or not the word is a palindrome
word = input("Please enter a word for palindrome testing: ")
letters_list = []
for letter in word:
letters_list.append(letter)
reverse = letters_list[::-1]
if letters_list == reverse:
print("Your word is a palindrome!")
else:
... | true |
9b64132ab776ebaaee149d27ca892421a5d9c0b7 | Abhinesh77/python_intern | /task4.py | 393 | 4.1875 | 4 | #list
a=[1,2,3,4]
for x in a:
print(x,end="");
print("")
a.append(5);
for x in a:
print(x,end="");
print("")
a.remove(2);
for x in a:
print(x,end="");
print("")
max=max(a);
min=min(a);
print("largest element is",max);
print("smallest element is",min);
#tuple
b=(6,7,8,... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.