blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b8f6125de3b647d2b8c3c6a8fee82d258c6b8731 | minaeid90/pycourse | /advanced/example0.py | 2,923 | 4.53125 | 5 | #-*- coding: utf-8 -*-
u'''
DESCRIPTORS EXAMPLE 0: How attributes look up works
'''
# Let's define a class with 'class' and 'instance' attributes
class MyClass(object):
class_attr = "Value of class attrib"
def __init__(self):
self.instance_attr = "Value of instance of {0} attrib".format(self.__class__.... | true |
6692a0b469278f6c6d13eabadab36a6e426b2936 | hydrophyl/Python-1.0 | /TricksnTips/loop2.py | 333 | 4.21875 | 4 | names = ['Cory','Chris', 'Dave', 'Trad']
heroes = ['Peru','Christie', 'David', 'Tradition']
""" for index, name in enumerate(names):
hero = heroes[index]
print(f"{name} is actually {hero}") """
for name, hero in zip(names,heroes):
print(f'{name} is actually {hero}')
for value in zip(names, heroes):
... | false |
e4598a7212964d5dc6440bb57d16342e46b1fd95 | usfrank02/pythonProjects | /project3.py | 288 | 4.34375 | 4 | #! python
import sys
name = input("Enter your name:")
print (name)
#Request user to input the year he was born
year_of_born = int(input("What's the year you were born?"))
#Calculate the age of the user
age = 2020 - year_of_born
print("You will be {} years old this year!".format(age))
| true |
2e046c0d4fc1e243a8ae9e85b56d10f9195e473b | Regato/exersise12 | /Romanov_Yehor_Exercise14.py | 582 | 4.15625 | 4 | # Entering input and making from string all UPPER case:
input_string = input('[!] INPUT: Please enter your value (only string type): ')
upper_string = input_string.upper()
# Function that count letters in string:
def letter_counter(x):
return upper_string.count(x)
# For cycle that check every letter for duplica... | true |
38582bca142960e852de0445e04d76afb018a1fb | Jattwood90/DataStructures-Algorithms | /1. Arrays/4.continuous_sum.py | 435 | 4.25 | 4 | # find the largest continuous sum in an array. If all numbers are positive, then simply return the sum.
def largest_sum(arr):
if len(arr) == 0:
return 0
max_sum = current = arr[0] # sets two variables as the first element of the list
for num in arr[1:]:
current = max(current+num, n... | true |
9b9b07556cc95ec055af0e3ae93af5d7ace7a120 | jvillamarino/python | /Platforms_courses/Platzi/factorial.py | 339 | 4.3125 | 4 |
def calculate_factorial(number):
if number == 1:
return 1;
return number * calculate_factorial(number-1)
if __name__ == '__main__':
number = int(input("Escribe un número a multiplicar: "))
result = calculate_factorial(number)
print(f'El resultado del factorial para el número {numbe... | false |
088a600b0d851da9345a6ef2e336bdf32c9dddb8 | rhaydengh/IS211_Assignment1 | /assignment1_part2.py | 614 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Assignment 1, Part 2"""
class Book:
"""Class for books"""
def __init__(self, author, title):
"""this function returns a book by author and title based on variables"""
self.author = author
self.title = title
def display... | true |
0197bce6a32e97761dce10deb57290cb666b78a7 | y1212/myslite | /tuple.py | 979 | 4.28125 | 4 | # tuple1=(1,2,3,"hello tom",False)
# print(tuple1,type(tuple1))
# list1=[1,2,3,4]
# print(list1,type(list1))
# #列表转换
# tuple2=tuple(list1)
# print(tuple2,type(tuple2))
# #对元组的遍历索引号
# for i in range(len(tuple1)):
# print(tuple1[i])
# #元组遍历
# for element in tuple1:
# print(element)
# print(len(tuple1))
# print(tu... | false |
6e29c29f32d27aa1e76cc0a3ead78b2b3cca6515 | sachlinux/python | /exercise/strings/s3.py | 369 | 4.15625 | 4 | #embedding value in string
value = "500"
message = "i hav %s rupees"
print(message % value)
#we can do without variable also
print(message % 1000)
#more example
var1 = "sachin"
var2 = "dentist"
message1 = "%s: is in love with %s"
message2 = "%s is so %s"
print(message1 % (var1,var2))
print(message2 % ('she',... | true |
658ec398f352a09390fd9534cb448e2a91bffc9c | debakshmi-hub/Hacktoberfest2021-2 | /checkPrime.py | 756 | 4.21875 | 4 | # //your code here
# Program to check if a number is prime or not
num = int(input("Enter a Number "))
flag = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime num... | true |
fb54c0d63382752c3c9a3feb327321a2c77492cc | gautamk/ProjectEuler | /problem1.py | 528 | 4.25 | 4 | # 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.
MAX = 1000
def mul_of(multiple_of, max=MAX):
multiplier = 1
multiple = multiple_of * multiplier
while multiple < M... | true |
250aaa13de0944d78fc6f7a6083c5413ea1961e5 | KhallilB/Tweet-Generator | /Code/practice_code/sampling.py | 1,731 | 4.125 | 4 | import random
import sys
import histograms
def random_word(histogram):
'''Generates a random word without using weights'''
random_word = ''
random_index = random.randrange(len(histogram))
random_word += histogram[random_index][0]
return random_word
def weighted_random_word(histogram):
'''Gen... | true |
79ec249c78604d85bf5612da0d597d41c39214e3 | qcl643062/leetcode | /110-Balanced-Binary-Tree.py | 1,730 | 4.15625 | 4 | #coding=utf-8
"""
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in
which the depth of the two subtrees of every node never differ by more than 1.
"""
class TreeNode(object):
def __init__(self, x, left = None, right = None):
... | true |
1f1529473302b02d543365662b5ea486c153d200 | EngrDevDom/Everyday-Coding-in-Python | /ToLeftandRight.py | 422 | 4.125 | 4 | # ToLeftandRight.py
nums = []
num_of_space = 0
current_num = int(input("Enter a number: "))
nums.append(current_num)
while True:
num = int(input("Enter a number: "))
if num > current_num: num_of_space += 1
elif num == current_num: continue
else: num_of_space -= 1
current_num = num
nums.a... | false |
a2f10d28828b2fe43054860554e2915bbe1a3e13 | EngrDevDom/Everyday-Coding-in-Python | /Distance.py | 379 | 4.25 | 4 | # File : Distance.py
# Desc : This program accepts two points and determines the distance between them.
import math
def main():
x1, y1 = eval(input("Enter first coordinate.(x1, y1): "))
x2, y2 = eval(input("Enter second coordinate.(x2, y2): "))
distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)
pri... | true |
38af1cc91d8307cf8d0adfb77e19b558ad5b6bb5 | EngrDevDom/Everyday-Coding-in-Python | /SciPy/polynomials.py | 830 | 4.25 | 4 | from numpy import poly1d
# We'll use some functions from numpy remember!!
# Creating a simple polynomial object using coefficients
somePolynomial = poly1d([1,2,3])
# Printing the result
# Notice how easy it is to read the polynomial this way
print(somePolynomial)
# Let's perform some manipulations
print("\nSquaring ... | true |
d43dcc1e99425696cdaeff16dc969344a3205a95 | EngrDevDom/Everyday-Coding-in-Python | /Identify_triangle.py | 496 | 4.4375 | 4 | # This program identifies what type of triangle it is
# based on the measure of it's angle
angle = int(input("Give an angle in degrees: "))
type = ""
if angle > 0 and angle < 90:
type = "ACUTE"
elif angle == 90:
type = "RIGHT"
elif angle > 90 and angle < 180:
type = "OBTUSE"
elif angle == 180:
type = ... | true |
96ff1baf71e2a5f8e24a0985a95a4cf52e2d14b4 | EngrDevDom/Everyday-Coding-in-Python | /Ladder.py | 447 | 4.46875 | 4 | # File : Ladder.py
# Desc : This program determine the length of the ladder required to
# reach a given height leaned.
import math
def main():
angle = float(input("Enter the value of angle in degrees: "))
radians = math.radians(angle) # Convert degrees to radians
height = float(input(... | true |
0cea260a3dcf1852cbd66920e3aa23e94e7d26b7 | EngrDevDom/Everyday-Coding-in-Python | /quadratic_5.py | 702 | 4.1875 | 4 | # File : quadratic_5.py
# Desc : A program that computes the real roots of a quadratic equation. Version 5.0
# Note: This program catches the exception if the equation has no real roots.
import math
def main():
print("This program finds the real solutions to a quadratic\n")
try:
a = ... | true |
de25351bfb982437ac08ebd4d1c7ba94ffd86490 | EngrDevDom/Everyday-Coding-in-Python | /quizzes_2.py | 549 | 4.1875 | 4 | # File : quizzes_2.py
# Desc : A program that accepts a quiz score as an input and uses a decision
# structure to calculate the corresponding grade.
def main():
grade = int(input("Enter your grade: "))
scale = ''
if grade <= 100 or grade >= 90: scale = 'A'
elif grade <= 89 or grade... | true |
f05e35fdc63cfcb45bb19620d0478dfc7b91ab8c | EngrDevDom/Everyday-Coding-in-Python | /Eq_of_Motion.py | 261 | 4.28125 | 4 | # Program for computing the height of a ball in vertical motion
v0 = 5 # Initial velocity (m/s)
g = 9.81 # Acceleration of gravity (m/s^2)
t = 0.6 # Time (s)
y = v0*t - 0.5*g*t**2 # Vertical position
print("Height of the ball: ", y, " m")
| true |
0db588fb91a034b200427bc709206e201947fc9f | EngrDevDom/Everyday-Coding-in-Python | /Algorithms/Sorting Algorithms/Tim_sort.py | 2,652 | 4.28125 | 4 | # Tim_sort Algorithm
from random import randint
from timeit import repeat
def timsort(array):
min_run = 32
n = len(array)
# Start by slicing and sorting small portions of the
# input array. The size of these slices is defined by
# your `min_run` size.
for i in range(0, n, min_run):
in... | true |
4fc7f95567c554cd669dc0ef802228a9ed290040 | EngrDevDom/Everyday-Coding-in-Python | /Algorithms/Sorting_from_StackAbuse/Python_sort.py | 584 | 4.28125 | 4 | # Python Built-in Sort Functions
# Sort
apples_eaten_a_day = [2, 1, 1, 3, 1, 2, 2]
apples_eaten_a_day.sort()
print(apples_eaten_a_day) # [1, 1, 1, 2, 2, 2, 3]
# Sorted
apples_eaten_a_day_2 = [2, 1, 1, 3, 1, 2, 2]
sorted_apples = sorted(apples_eaten_a_day_2)
print(sorted_apples) # [1, 1, 1, 2, 2, 2, 3]
# Reverse
# Re... | false |
88f6afcf9589102e21cd694e2ce4f9104d61b08e | EngrDevDom/Everyday-Coding-in-Python | /Resistor_Color_Coding.py | 508 | 4.21875 | 4 | '''
Resistor Color Coding
- This program calculates the value of a resistor based on the colors
entered by the user.
'''
# Initialize the values
black = 0
brown = 1
red = 2
orange = 3
yellow = 4
green = 5
blue = 6
violet = 7
grey = 8
white = 9
gold = 0
silver = 0
bands = input('Enter the color bands: ')
c... | true |
7d5ad562c1fd4fd490af54eeca2429e41b04e95c | sreedhr92/Computer-Science-Laboratory | /Design And Analysis of Algorithms/power_iterative.py | 251 | 4.28125 | 4 | def power_iterative(x,n):
result =1
for i in range(0,n):
result = x*result
return result
x = int(input("Enter the base:"))
y = int(input("Enter the exponent:"))
print("The value of",x,"to the power of",y,"=",power_iterative(x,y)) | true |
910d9d682ef9a8c258b3395b0226a5a4c2039b43 | UzairIshfaq1234/python_programming_PF_OOP_GUI | /list using if statment.py | 551 | 4.15625 | 4 |
print("________________________________________")
list1=[input("enter name 1: "),int(input("Enter any number: ")),input("enter name 2: "),int(input("Enter any number: "))]
print("________________________________________")
for item in list1:
if str(item).isalpha():
print(item)
print("___________________... | false |
15544b46b10a29d6f235de86dbf6a1af00bae4bd | UzairIshfaq1234/python_programming_PF_OOP_GUI | /07_color_mixer.py | 891 | 4.46875 | 4 | colour1 = input("Enter the first primary colour: ")
colour2 = input("Enter the second primary colour: ")
mixed_colour = ""
if (colour1 == "red" or colour1 == "blue" or colour1 == "yellow") and (colour2 == "red" or colour2 == "blue" or colour2 == "yellow"):
if (colour1 == "red" and colour2 == "blue") or (colour2 ... | true |
f8d641ea4352a27b00c1d30c84545fd5e5c7744c | nirakarmohanty/Python | /controlflow/IfExample.py | 248 | 4.375 | 4 | print('If Example , We will do multiple if else condition')
value =int(input('Enter one integer value: '))
print('You entered the value as : ',value)
if value>0:
print('value is an integer')
else:
print('Please enter one integer number')
| true |
9a107acee38a1fc5a4632d6ed1c20b5b81408161 | nirakarmohanty/Python | /datatype/ListExample.py | 513 | 4.46875 | 4 | #Define simple List and print them
nameList=['Stela','Dia','Kiara','Anna']
print(nameList)
#List indexing
print(nameList[1],nameList[2],nameList[3])
print(nameList[-1],nameList[-2])
#length of List
print(len(nameList))
#Add a new list to the original list
nameList= nameList + ['Budapest','Croatia','Prague']
print(n... | true |
b9ec0f8c814393ce080abe964c5c59f417dfc897 | dspwithaheart/blinkDetector | /modules/read_csv.py | 2,833 | 4.1875 | 4 | '''
csv module for reading csv file to the 2D list
Default mode is 'rb'
Default delimiter is ',' and the quotechar '|'
# # #
arguments:
csv_file - read csv file name
coma - if True replaces all the comas with dots (in all cells)
header - specify how many lines (from the beg... | true |
8ad9166fa06a4959d3f4ed1001eebb28ca0a59a8 | fullVinsent/lab_Pyton_1 | /1_level.py | 447 | 4.125 | 4 | import math
frustrumHeight = float(input("Input H:"))
smallRadius =float(input("Input r:"))
bigRadius = float(input("Input R:"))
frustrumLenght = math.sqrt(math.pow(frustrumHeight,2) + (math.pow(bigRadius - smallRadius,2)))
frustrumSideArea = math.pi * frustrumLenght * (bigRadius + smallRadius)
frustrumAllAreaSum =... | false |
1c43a8a8cccb45600465dc2389894102763ad40b | a-bl/counting | /task_1.py | 243 | 4.15625 | 4 | # What is FOR loop?
sum = 0
while True:
n = int(input('Enter N:'))
if n > 0:
for num in range(1, n + 1):
sum += num
print(sum)
break
else:
print('Enter positive integer!')
| true |
53490c2c6e9feba29d73cb1024895eda79298a2e | rollbackzero/projects | /ex30.py | 458 | 4.1875 | 4 | people = 40
cars = 30
trucks = 45
if cars > people:
print("We should take cars")
elif cars < people:
print("We should not take cars")
else:
print("We can't decide")
if trucks > cars:
print("Thats too many trucks")
elif trucks < cars:
print("Maybe we could take the trucks")
else:
print("We sti... | true |
009d63fffab9020cf7c8ebc4b9deec98b0f656a9 | UVvirus/frequency-analysis | /frequency analysis.py | 1,099 | 4.4375 | 4 | from collections import Counter
non_letters=["1","2","3","4","5","6","7","8","9","0",":",";"," ","/n",".",","]
key_phrase_1=input("Enter the phrase:").lower()
#Removing non letters from phrase
for non_letters in non_letters:
key_phrase_1=key_phrase_1.replace(non_letters,'')
total_occurences=len(key_phrase_1)
#Co... | true |
5845f21ac973ca16b7109f843771c0490633c8fc | guilhermemaas/guanabara-pythonworlds | /exercicios/ex022.py | 1,124 | 4.34375 | 4 | """
Crie um programa que leia o nome completo de uma pessoa e mostre:
O nome com todas as letras maiusculas
O nome com todas as letras minusculas
Quantas letras ao todo sem considerar espacos
Quantas letras tem o primeiro nome
"""
nome_completo = input('Digite seu nome completo: ').strip() #Pra pegar ja sem espacos no... | false |
ffff8f3b99def5e98b3bf54fb24a5e1b63a08b03 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex018.py | 1,075 | 4.125 | 4 | """
Faca um programa que leia um angulo qualquer e mostre na tela o valor de seno, cosseno, e tangente desse angulo.
"""
import math
cateto_oposto = float(input('Informe o comprimento do cateto oposto: '))
cateto_adjacente = float(input('Informe o comprimento do cateto adjacente: '))
hipotenusa = math.hypot(cateto_op... | false |
c44172d241d35968253acb2fbe2fef16bc779331 | guilhermemaas/guanabara-pythonworlds | /exercicios/ex063.py | 603 | 4.3125 | 4 | """
Escreva um programa que leia um numero n inteiro qualquer e mostre na tela
os n primeiros elementos de uma sequencia de Fibonacci.
Ex.: 0 -> 1 -> 1 -> 2 -> 3 -> 5 -> 8
"""
print('-'*30)
print('Sequencia de Fibonacci')
print('-'*30)
"""
n = int(input('Informe um numero inteiro inicial: '))
"""
qt = int(input('Infor... | false |
5445d08db0f152cba9a08f2f6d176a071d61c080 | habbyt/python_collections | /challenge_1.py | 292 | 4.15625 | 4 | #Challenge #1
#function takes a single string parameter and
#return a list of all the indexes in the string that have capital letters.
def capital_indexes(word):
word="HeLlO"
x=[]
for i in range(len(word)):
if word[i].isupper()==True:
x.append(i)
return x
| true |
cd2ae708b13c6359cbbcefa0b957fa58d304f722 | okazkayasi/03_CodeWars | /14_write_in_expanded_form.py | 682 | 4.375 | 4 | # Write Number in Expanded Form
#
# You will be given a number and you will need to return it as a string in Expanded Form. For example:
#
# expanded_form(12) # Should return '10 + 2'
# expanded_form(42) # Should return '40 + 2'
# expanded_form(70304) # Should return '70000 + 300 + 4'
#
# NOTE: All numbers will be whol... | true |
4f7cbb96396df971f262b7faecee06a8be3a23a9 | okazkayasi/03_CodeWars | /24_car_park_escape_5kyu.py | 2,297 | 4.15625 | 4 | # Your task is to escape from the carpark using only the staircases provided to reach the exit. You may not jump over the edge of the levels (youre not Superman) and the exit is always on the far right of the ground floor.
# 1. You are passed the carpark data as an argument into the function.
# 2. Free carparking... | true |
8b79cb22ebf59ff6dd2b8f1efbe840c8d519beb3 | okazkayasi/03_CodeWars | /06_title_case.py | 1,651 | 4.375 | 4 | # A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised.
#
# Write a function that will c... | true |
1df122ea8c6cbe2473ffa0be8626f86c38d65760 | abby2407/Data_Structures-and-Algorithms | /PYTHON/Graph/Graph_Finding_Mother_Vertex.py | 1,339 | 4.15625 | 4 |
''' A mother vertex in a graph G = (V,E) is a vertex v such that all
other vertices in G can be reached by a path from v.'''
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = defaultdict(list)
def addEdge(... | true |
04245a627a81d206fd76d72a9808524609498db9 | S-Tim/Codewars | /python/sudoku_solver.py | 1,926 | 4.1875 | 4 | """
Write a function that will solve a 9x9 Sudoku puzzle. The function will take one argument
consisting of the 2D puzzle array, with the value 0 representing an unknown square.
The Sudokus tested against your function will be "easy" (i.e. determinable; there will be
no need to assume and test possibilities on unknowns... | true |
4e2f0756383f20a076086fb655e6ed4b9c76f7ab | xeohyeonx/python-practice | /format and etc.py | 2,656 | 4.1875 | 4 | year = 2019
month = 10
day = 29
print("오늘은 " + str(year) + "년 " + str(month) + "월 " + str(day) + "일입니다.")
# 이렇게 하면 너무 번거로우니까 문자열 포맷팅을 통해서 하면 더 편함
print("오늘은 {}년 {}월 {}일입니다.".format(year, month, day)) # 이렇게 해주면 중괄호 안에 format 뒤의 파라미터들이 순서대로 들어감.
# 이렇게도 가능.
date_string = "오늘은 {}년 {}월 {}일입니다."
print(date_str... | false |
58ddbfe8f4eca1b019b54c2dcac4c73c94f145e9 | clarkmp/CSCI215_Assignment_1 | /portfolio/csci220/Assignment03/assignment03.py | 2,218 | 4.15625 | 4 | from math import *
def checkIfPrime():
userNumber = eval(input("Give me a number: "))
if userNumber > 1: #this makes sure the number is greater than 1 which is not a prime number
while userNumber > 1: #this only loops if the number is greater than 1
if userNumber % 2 == 0: #this will determ... | true |
0678f44e86e93fdef14ff4f35e8b6e5b7fe3ad31 | gkc23456/BIS-397-497-CHANDRATILLEKEGANA | /Assignment 2/Assignment 2 - Excercise 3.16.py | 477 | 4.15625 | 4 | # Exercise 3.16
largest = int(input('Enter number: '))
number = int(input('Enter number: '))
if number > largest:
next_largest = largest
largest = number
else:
next_largest = number
for counter in range(2, 10):
number = int(input('Enter number: '))
if number > largest:
next_largest = lar... | true |
d368e0f0e8acbbf8dbecb6a5e6a9a64f8f3efdd7 | fmojica30/learning_python | /Palindrome.py | 2,851 | 4.21875 | 4 | # File: Palindrome.py
# Description:
# Student Name: Fernando Martinez Mojica
# Student UT EID: fmm566
# Course Name: CS 313E
# Unique Number: 50725
# Date Created: 2/20/19
# Date Last Modified: 2/20/19
def is_palindrome(s): #define if a string is a palindrome
for i in range(len(s)//2):
if... | true |
086131ab344102d2b8f8591b21314f68ab7eef72 | manjusha18119/manju18119python | /function/d5.py | 437 | 4.5 | 4 | # Python's program to iterating over dictionaries using 'for' loops
x = {'z': 10, 'l': 50, 'c': 74, 'm': 12, 'f': 44, 'g': 19}
for key, val in x.items():
print(key, "=>", val)
print("\n------------------------\n")
for key in x:
print(key, "=>", x[key])
print("\n------------------------\n")
for key in ... | false |
1807e2597e8d8c7ac920d57a3dd53ed7d5e14033 | manjusha18119/manju18119python | /python/swap.py | 207 | 4.3125 | 4 | #2.Write a program to swap two variables.
a=input("Enter the value of a :")
#a=int(a)
b=input("Enter the value of b :")
#b=int(b)
temp=a
a=b
b=temp
print("swap value of a=",a)
print("swap value of b=",b)
| true |
3e0c9760a73a7629837f54f67d86ac97157cfa32 | PriceLab/STP | /chapter4/aishah/challenges.py | 575 | 4.25 | 4 | #1 ------write function that takes number as input and returns it squared
def func1(x):
return x ** 2
print(func1(2))
#2---- write a program with 2 functions-- first one takes an int
#and returns the int by 2. second one returns an integer * 4.
#call the first function, save the number, then pass to the second on... | true |
6f2f3648576cdf8da47ca0dc88ee1a8d9ea4d80d | Kotuzo/Python_crash_course | /Follow_Up/OOP.py | 1,284 | 4.34375 | 4 | import math
# This is examplary class
class Point:
# This is constructor
# Every method from class, needs to have self, as a first argument
# (it tells Python that this method belongs to the class)
def __init__(self, x, y):
self.x = x # attributes
self.y = y
# typical method
... | true |
713459f79b180b49c44dec9a671f1a08558f58ce | tonytamsf/hacker-rank | /algo/reverse.py | 297 | 4.25 | 4 | #!/usr/bin/env python3
print('''This will take an array and reverse it by
swaping items in place.
''');
def reverse(s):
for i in range (0, int(len(s) / 2)):
tmp = s[i]
s[i] = s[len(s) - 1 - i]
s[len(s) - 1 - i] = tmp
return s
print (reverse ([400,300,200,100]))
| false |
3c9d22585fbe44b08c62171c6147fbaf899cd832 | neethupauly/Luminarmaybatch | /python collections/List/lists.py | 1,191 | 4.1875 | 4 | # supports duplicates elements
# order keeps
# supports hetrogenous data
# nesting is possible
# mutable - can be updated
# lst=[1,2,3,1,2,3,"hello",True]
# print(lst)
# print(type(lst))
# lst1=[] #empty list creation
# print(lst1)
# print(type(lst1))
# lst1.append("hello")
# lst1.append(8)
# print(lst1)
# iterating... | false |
66ec4ee68f6db85940fd3bd9e22f91179507e5c2 | sushidools/PythonCrashCourse | /PythonCrashCourse/Ch.4/try it yourself ch4.py | 1,434 | 4.28125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 5 15:55:17 2018
@author: aleksandradooley
"""
spc = "\n"
pizzas = ['Hawaiin', 'BBQ chickcen', 'pepperoni']
friend_pizzas = pizzas[:]
for pizza in pizzas:
print "I like " + pizza + " pizza."
print "I really love pizza!"
pizzas.append('cheese')
... | true |
dea18ed1dcc6504cf5d31352a5f76485418e18d6 | catalanjrj/Learning-Python | /exercises/ex19.py | 1,560 | 4.21875 | 4 | # create a function named chees_and_crackers with two arguments.
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# print the amount of cheeses.
print(f"You have {cheese_count} cheeses!")
# print the number of boxes of crackers.
print(f"You have {boxes_of_crackers} boxes of crackers!")
# print "Man t... | true |
5bbf167d0de558186b79ad5aade880d6119973fb | catalanjrj/Learning-Python | /exercises/ex4.py | 1,232 | 4.15625 | 4 | # Assign a value of 100 to cars
cars = 100
# Assign a value of 4 to space_in_a_car
space_in_a_car = 4
# Assign a value of 30 to drivers
drivers = 30
# Assign a value of 90 to passengers
passengers = 90
# Assign the result of cars minus drivers to cars_not_driven
cars_not_driven = cars - drivers
# Assign the value... | true |
322bdb0b3381a696bc3b088f015f2e3c1b5e2665 | himeshnag/Ds-Algo-Hacktoberfest | /Python/ArrayRotation.py | 569 | 4.28125 | 4 |
from Arrays import Array
def rotation(rotateBy, myArray):
for i in range(0, rotateBy):
rotateOne(myArray)
return myArray
def rotateOne(myArray):
for i in range(len(myArray) - 1):
myArray[i], myArray[i + 1] = myArray[i + 1], myArray[i]
if __name__ == '__main__':
myArray = Array(10)
... | false |
3d33eb6cadd1028c81b2190b91fb3cdde5763a7c | sewald00/Pick-Three-Generator | /pick_three.py | 951 | 4.28125 | 4 | """Random pick three number generator
Seth Ewald
Feb. 16 2018"""
import tkinter as tk
from tkinter import ttk
from random import randint
#Define the main program function to run
def main():
#Define function to change label text on button click
def onClick():
a = randint(0, 9)
... | true |
7d3279e79e140c6feffd735171703b00a5310377 | katcosgrove/data-structures-and-algorithms | /challenges/binary-search/binary_search.py | 321 | 4.21875 | 4 |
def BinarySearch(arr, val):
"""
Arguments: A list and value to search for
Output: The index of the matched value, or -1 if no match
"""
if len(arr) == 0:
return -1
counter = 0
for item in arr:
counter += 1
if item == val:
return counter - 1
return -1... | true |
3cbb921b6d67b3811de9e9e117d3013dd03bb5bc | renefueger/cryptex | /path_util.py | 980 | 4.4375 | 4 | def simplify_path(path: str, from_separator='/', to_separator='/') -> str:
"""Returns the result of removing leading/trailing whitespace and
consecutive separators from each segment of the given path."""
path_parts = path.split(from_separator)
stripped_parts = map(lambda x: x.strip(), path_parts)
va... | true |
da73cd924c0b1e5b33b8a47a882815fb8c232b3a | nramiscal/spiral | /spiral.py | 1,598 | 4.25 | 4 | '''
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5], <-- matrix[0]
[6, 7, 8, 9, 10], <-- matrix[1]
[11, 12, 13, 14, 15], <-- matrix[2]
[16, 17, 18, 19, 20]] <-- matrix[3]
You should print out the f... | true |
2047056b45017b5284555de99a086a164252e82c | Mattdinio/Code-at-GU-2019 | /Assignment 1.py | 1,303 | 4.1875 | 4 | # Question 1
def divisibleByThree ():
for i in range(1,101):
if i % 3 == 0:
print (i)
# Question 2
def shakespeare ():
quote = ""
# Question 3
def numberThing():
for i in range (1,11):
if i % 3 == 0:
print (i**3)
elif i % 2 == 0:
print (i**2)
... | false |
04e6251f38a87afe8d52bcc270898de75aa45b44 | Lyondealpha-hub/Python-Programs | /FizzBuzz.py | 325 | 4.15625 | 4 | #A program that changes multiple of 3 to fizz, multiple of 5 to buzz and multiple of
#both 3 and 5 to fizzbuzz
print("A program for a FIZZBUZZ ")
for i in range(1,101):
if i%3==0:
print( i, "\t","Fizz")
if i%5 == 0:
print(i, "\t","Buzz")
if i%3==0 and i%5==0:
print(i, "\t","FizzBu... | false |
adf804c78c165f98bff660077784aeca3bbc1932 | BryantCR/FunctionsBasicII | /index.py | 2,717 | 4.3125 | 4 | #1 Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countDown(num):
result = []
for i in range(num, -1, -1):
result.... | true |
1ef6cc0dd575247f5b227eca08802a0f623744f1 | dhilankp/GameDesign2021 | /Python2021/VarAndStrings.py | 902 | 4.15625 | 4 | #Dhilan Patel
# We are learning how to work with Srtings
# While loop
# Different type of var
num1=19
num2=3.5
num3=0x2342FABADCDACFACEEDFA
#How to know what type of data is a variable
print(type(num1))
print(type(num2))
print(type(num3))
phrase='Hello there!'
print(type(phrase))
#String functions
num=len(phrase)
p... | true |
c866c92036fbd6d45abb7efc3beca71b065abda9 | DNA-16/LetsUpgrade-Python | /Day3Assign.py | 679 | 4.21875 | 4 | #Assignment1:Sum of N numbers using while
sum=0
N=eval(input("Enter the number "))
flag=0
n=0
while n!=N+1:
if(type(N)==float):
flag=1
break
sum=sum+n
n+=1
if(flag==1):
print(N,"is not a natural number")
else:
print("Sum of first",N,"natural number is ",sum)
... | true |
594cd76e835384d665f0a8390f82265616e34359 | stackpearson/cs-project-time-and-space-complexity | /csSortedTwosum.py | 667 | 4.1875 | 4 | # Given a sorted array (in ascending order) of integers and a target, write a function that finds the two integers that add up to the target.
# Examples:
# csSortedTwoSum([3,8,12,16], 11) -> [0,1]
# csSortedTwoSum([3,4,5], 8) -> [0,2]
# csSortedTwoSum([0,1], 1) -> [0,1]
# Notes:
# Each input will have exactly one so... | true |
263e35c47464a3fee4967b212ac0b7ba6a2c286e | maheshbabuvanamala/Python | /LinkedList.py | 839 | 4.15625 | 4 | class Node:
""" Node in Linked List """
def __init__(self,value):
self.data=value
self.next=None
def set_data(self,data):
self.data=data
def get_data(self):
return self.data
def set_next(self,next):
self.next=next
def get_next(self):
return self.ne... | true |
4952a6ac5f3d8f91bd165603355c75eb68450fcf | muthoni12/ppython_listsandforloops | /dictionary.py | 614 | 4.125 | 4 | #student = {
# "name" : "pal",
# "age" : 19,
# "gender" : "F"
#}
#
#student["name"] = "val"
#print(student["name"])
'''
combined list with dictionary to have all that same data but for more than one item.
'''
users = [
{
"name" : "hal",
"age" : 19,
"gender" : "F"
},
{
"name" : "ma... | false |
12f482950563599c33857c3264b4ce5c56e6a64d | xwinxu/foobar | /p1/cake.py | 2,679 | 4.1875 | 4 | """
The cake is not a lie!
======================
Commander Lambda has had an incredibly successful week: she completed the first test run of her LAMBCHOP doomsday device, she captured six key members of the Bunny Rebellion, and she beat her personal high score in Tetris. To celebrate, she's ordered cake for everyone -... | true |
f30a9c52b7223972fcacf450c8815820989f22a7 | AdamJDuggan/starter-files | /frontEndandPython/lists.py | 847 | 4.59375 | 5 | the_count = [1, 2, 3, 4, 5]
fruits = ["apples", "oranges", "pears", "apricots"]
change = [1, "pennies", 2, "dimes", 3, "quarters"]
#this kind of for loop goes through a list
for number in the_count:
print("This is count {}".format(number))
#same as above
for adam in fruits:
print("A fruit of type {}... | true |
a8e5e788a73225147820189ea73a638e1547345e | sherrymou/CS110_Python | /Mou_Keni_A52_Assignment4/1. gradeChecker.py | 1,188 | 4.125 | 4 | '''
Keni Mou
Kmou1@binghamton.edu
Assignment 4, Exercise 1
Lab Section 52
CA Kyle Mille
'''
'''
Analysis
Get grade from mark
Output to monitor:
grade(str)
Input from keyboard:
mark(float)
Tasks allocated to Functions:
gradeChecker
Check the mark, determine the mark belongs to which grade
'''... | true |
c438c3f44c1a2e9b7e12d3a8289e058361f99228 | sherrymou/CS110_Python | /Mou_Keni_A52_Lab9/#1-2.py | 1,729 | 4.21875 | 4 | '''
Keni Mou
Kmou1@binghamton.edu
Lab9, Excerise 1-2
Lab Section 52
CA Kyle Mille
'''
'''
Analyze
To compute the max rain fall, min rain fall, and average rain fall
use the readline() method
Output to the monitor:
maxrain(float)
minrain(float)
average(float)
Input from keyboard:
filename(str)
Tasks:
g... | true |
cc2d9b75be11f392906fab1f1e840f0865773c87 | vicasindia/programming | /Python/even_odd.py | 376 | 4.5 | 4 | # Program to check whether the given number is Even or Odd.
# Any integer number that can be exactly divided by 2 is called as an even number.
# Using bit-manipulation (if a number is odd than it's bitwise AND(&) with 1 is equal to 1)
def even_or_odd(n):
if n & 1:
print(n, "is Odd number")
else:
print(n, "is Ev... | true |
419411b48b60121fec7809cb902b8f5ad027a6d2 | PDXDevCampJuly/john_broxton | /python/maths/find_prime.py | 813 | 4.1875 | 4 | #
# This program inputs a number prints out the primes of that number in a text file
#
###################################################################################
import math
maximum = eval(input("Please enter a number. >>> "))
primes = []
if maximum > 1:
for candidate in range(2, maximum + 1):
is_prime... | true |
e80520fea7160878811113027d0483d028041d82 | PDXDevCampJuly/john_broxton | /python/sorting/insertion_sort.py | 1,441 | 4.25 | 4 | def list_swap(our_list, low, high):
insIst[low], insIst[high] = insIst[high], insIst[low]
return insIst
pass
def insertion_sort(insIst):
numbers = len(insIst)
for each in range(numbers - 1):
start = each
minimum = insIst[each]
for index in range(1, len(insIst)):
... | true |
31ea7b76addea2e6c4f11acd957550a69c864ef1 | DKNY1201/cracking-the-coding-interview | /LinkedList/2_3_DeleteMiddleNode.py | 1,263 | 4.125 | 4 | """
Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but
the first and last node, not necessarily the exact middle) of a singly linked list, given only access to
that node.
EXAMPLE
Input: the node c from the linked list a -> b -> c -> d -> e -> f
Result: nothing is returned, but... | true |
bb3f4cde389b50ffa4157e4310c764f66d7f9cb0 | KUSH2107/FIrst_day_task | /17.py | 237 | 4.125 | 4 | # Please write a program to shuffle and print the list [3,6,7,8]
import random
a1_list = [1, 4, 5, 6, 3]
print ("The original list is : " + str(a1_list))
random.shuffle(a1_list)
print ("The shuffled list is : " + str(a1_list))
| true |
bd4fb7517823537a46ff3d5b28ff2f5fe36efc32 | ethanschafer/ethanschafer.github.io | /Python/PythonBasicsPart1/labs/mathRunner.py | 957 | 4.125 | 4 | from mathTricks import *
inst1 = "Math Trick 1\n\
1. Pick a number less than 10\n\
2. Double the number\n\
3. Add 6 to the answer\n\
4. Divide the answer by 2\n\
5. Subtract your original number from the answer\n"
print (inst1)
# Get input for the first math trick
num = inpu... | true |
8e80b1006bc765ff53493073f34731554ff52c27 | yuliaua1/algorithms | /RandomList_01.py | 382 | 4.3125 | 4 | # This is a simple program to generate a random list of integers as stated below
import random
def genList(s):
randomList = []
for i in range(s):
randomList.append(random.randint(1, 50))
return randomList
print(genList(30))
#This is creating the list using list comprehensions
#randomList = [ ra... | true |
37aaf1fd82c0ded9d0578e8a971eb146463ba95f | testlikeachamp/codecademy | /codecademy/day_at_the_supermarket.py | 1,874 | 4.125 | 4 | # from collections import Counter
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
assert isinstance(food, (list, tuple, set)), "{... | true |
20849ee4f75e876464e380437d45a5b0f8835f4d | shedaniel/python_3 | /Lesson4.2.py | 235 | 4.5 | 4 | #Range
#It is used for loops
#it will run the loop form %start% to %stop% which each time added it by %plus%
#range(start, stop)
for x in range(1 , 6):
print(x)
#range(start, stop, plus)
for x in range(100, 107, 3):
print(x)
| true |
18c656d4e69e8c6ee881c0c9a4bd9af8908196c9 | GlenboLake/DailyProgrammer | /C204E_remembering_your_lines.py | 2,868 | 4.21875 | 4 | '''
I didn't always want to be a computer programmer, you know. I used to have
dreams, dreams of standing on the world stage, being one of the great actors
of my generation! Alas, my acting career was brief, lasting exactly as long as
one high-school production of Macbeth. I played old King Duncan, who gets
brutally mu... | true |
26d5df3fd92ed228fb3b46e32b1372a0eb5e9664 | UIHackyHour/AutomateTheBoringSweigart | /07-pattern-matching-with-regular-expressions/dateDetection.py | 2,902 | 4.46875 | 4 | #! python3
# Write a regular expression that can detect dates in the DD/MM/YYYY format.
## Assume that the days range from 01 to 31, the months range from 01 to 12, and the years range
## from 1000 to 2999. Note that if the day or month is a single digit, it’ll have a leading zero.
# The regular expression doesn’t ... | true |
24e238601bfe282712b8fbea574a98114ecf9b99 | omarBnZaky/python-data-structures | /check_palanced_parenthece.py | 1,231 | 4.3125 | 4 | """
Use a stack to check whether or not a string
has balanced usage of parnthesis.
"""
from stack import Stack
def is_match(p1,p2):
print("math func:" + str((p1,p2)))
if p1 == '(' and p2 == ')':
print("match")
return True
elif p1 == '{' and p2 == '}':
print("match")
return... | true |
dacd4f6e242c40d72e9f5a664828d26c576d457d | Katt44/dragon_realm_game | /dragon_realm_game.py | 1,195 | 4.1875 | 4 | import random
import time
# having the user pick between to caves, that randomly are friendly or dangerous
# printing text out slowly for suspense in checking the cave
# asking user if they want to play again
def display_intro():
print ('''Standing at the mouth of a cave you take one long inhale
and you exhale as... | true |
9cea2b8c8abb1262791201e1d03b12e2684673ea | gsandoval49/stp | /ch5_lists_append_index_popmethod.py | 712 | 4.25 | 4 | fruit = ["Apple", "Pear", "Orange"]
fruit.append("Banana")
fruit.append("Tangerine")
#the append will always store the new at the end of the list
print(fruit)
#lists are not limited to storing strings
# they can store any data type
random = []
random.append(True)
random.append(100)
random.append(1.0)
random.appe... | true |
cf8f18ec1b0e9ae0ee1bfce22be037b352681437 | afialydia/Intro-Python-I | /src/13_file_io.py | 982 | 4.1875 | 4 | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
# Note: pay close... | true |
d15f9b28307a2180cd2a1e7d6a6c7cf9deb6d85c | zuwannn/Python | /Tree based DSA/PerfectBinaryTree.py | 1,382 | 4.28125 | 4 | # perfect binary tree
'''
A perfect binary tree เป็น binary tree ชนิดหนึ่ง
โดยที่ทุกโหนดภายใน (internal node) ต้องมีโหนดย่อยสองโหนด
และ(leaf nodes) ทั้งหมดอยู่ในระดับเดียวกัน
'''
class Node:
def __init__(self, k):
self.k = k
self.right = self.left = None
# Calculate the depth
def calculateTheDepth(... | false |
c48dcb189abf82abb6bee0cac9b92777b6ab1380 | zuwannn/Python | /Tree based DSA/TreeTraversal.py | 1,029 | 4.21875 | 4 | # tree traversal - in-order, pre-order and post-order
class Node:
def __init__(self, item):
self.left = None
self.right = None
self.value = item
# left -> root -> right
def inorder(root):
if root:
# traverse left
inorder(root.left)
# traverse root
print(... | true |
e367ed81791d2dfc42e60202b1c12e8d75d47de8 | zuwannn/Python | /Tree based DSA/binary_tree.py | 1,362 | 4.21875 | 4 | #Binary Tree
"""
Tree represents the nodes connected by edges(Left Node & Right Node). It is a non-linear data structure.
-One node is marked as Root node.
-Every node other than the root is associated with one parent node.
-Each node can have an arbiatry number of chid node.
We designate one node as root node and then... | true |
eac9eea7860abcb3474cfa2c4599b31c3e2a0af1 | ayushiagarwal99/leetcode-lintcode | /leetcode/breadth_first_search/199.binary_tree_right_side_view/199.BinaryTreeRightSideView_yhwhu.py | 1,597 | 4.125 | 4 | # Source : https://leetcode.com/problems/binary-tree-right-side-view/
# Author : yhwhu
# Date : 2020-07-30
#####################################################################################################
#
# Given a binary tree, imagine yourself standing on the right side of it, return the values of the
# nod... | true |
ebe8b1f54b32754316095c4e8f979c19f2b01e3e | rodrilinux/Python | /Python/_3.1-chamadaDeFuncao.py | 929 | 4.40625 | 4 | # coding: iso-8859-1_*_
# Voc j viu um exemplo de uma chamada de funo:
# >>> type(32)
# <class str>
# O nome da funo type e ela exibe o tipo de um valor ou varivel. O valor ou varivel, que chamado de
# argumento da funo, tem que vir entre parnteses. comum se dizer que uma funo recebe um valor ou mais
# valores e ... | false |
d0a5e8fdbdaec96173164faf66143bfac359b689 | MarcoHuXHu/learningpython | /Algorithm/Heap.py | 1,541 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 如果一颗完全二叉树中, 每个父节点的值都大于等于(或者都小于等于)其左右子节点的值, 这样的完全二叉树称为堆.
# 此处以一个小根堆为例(即父节点的值小于等于左右子节点的值)
# 堆的插入, 弹出(删除根节点), 以及利用堆进行排序
class Heap(object):
def __init__(self):
self.data = []
def swap(self, indexA, indexB):
y = self.data[indexA]
self.da... | false |
331ba25d4f34c30d1ac418c0d05a0b9b1cce35bb | MarcoHuXHu/learningpython | /Function/filter.py | 1,520 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# filter传入一个返回True或False的函数,与一个Iterable对象,返回经过函数筛选为True的元素
# filter返回为iterator
def is_odd(n):
return n % 2 == 1
print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))
# 结果: [1, 5, 9, 15]
# 例1:筛选回文数
def is_palindrome(n):#0123456
digits = str(n)
length = le... | false |
3e75a6666d33bc5965ff3df6d54f7eef487a9900 | sammienjihia/dataStractures | /Trees/inOrderTraversal.py | 2,293 | 4.15625 | 4 | class Node:
def __init__(self, val):
self.val = val
self.rightchild = None
self.leftchild = None
def insert(self, node):
# compare the data val of the nodes
if self.val == node.val:
return False
if self.val > node.val: # make the new node the left chi... | true |
6cc412ee2ed4e71fd9aff6409db2434a64735ec2 | Chuxiaxia/python | /hm_10_列表基本使用.py | 955 | 4.21875 | 4 | name_list = ["xey", "ajl", "xx"]
# 1. 取值和取索引
print (name_list[2])
# 知道数据的内容,想确定数据在列表的位置
# 使用index方法需要注意,如果传递的数据不在列表中,程序会报错。
print(name_list.index("xey"))
# 2. 修改
# 注意: 列表指定的索引超出范围,程序会报错
name_list[1] = "安家樑"
# 3. 增加
# append方法可以向列表末尾增加数据
name_list.append("夏夏")
# insert方法可以在列表的指定索引位置插入数据
name_list.insert(1, "an")
# ex... | false |
20ce3fc899aa6766a27dfe73c6dd0c14aa3d4099 | Julien-Verdun/Project-Euler | /problems/problem9.py | 711 | 4.3125 | 4 | # Problem 9 : Special Pythagorean triplet
def is_pythagorean_triplet(a,b,c):
"""
This function takes 3 integers a, b and c and returns whether or not
those three numbers are a pythagorean triplet (i-e sum of square of a and b equel square of c).
"""
return a**2 + b**2 == c**2
def product_pythagorean_triplet(N):
... | true |
ccee97b325a717c7031159ee1c4a7569ff0675d6 | digant0705/Algorithm | /LeetCode/Python/274 H-Index.py | 1,647 | 4.125 | 4 | # -*- coding: utf-8 -*-
'''
H-Index
=======
Given an array of citations (each citation is a non-negative integer) of a
researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h
if h of his/her N papers have at least h citations eac... | true |
e8163d4faddd7f6abeacdea9c6ebbb86a57dd195 | digant0705/Algorithm | /LeetCode/Python/328 Odd Even Linked List.py | 1,532 | 4.28125 | 4 | # -*- coding: utf-8 -*-
'''
Odd Even Linked List
====================
Given a singly linked list, group all odd nodes together followed by the even
nodes. Please note here we are talking about the node number and not the value
in the nodes.
You should try to do it in place. The program should run in O(1) space
compl... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.