blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
eb36a1165915101c5c3c7fc07f0e8c6339827e29 | Jeevankv/LearnPython | /zComprehension.py | 795 | 4.15625 | 4 |
# Normal method
# ls=[]
# for i in range(100):
# if i%3==0:
# ls.append(i)
# print(ls)
# List Comprehension
ls = [i for i in range(100) if i%3==0 ]
print(ls)
# Dictionary Comprehension
dic = { i:f"item{i}" for i in range(10) if i%2==0 }
print(dic)
# Reversing Key value Pair
... | false |
140948186b164ef8db9149326cff5cd101be0e8c | CoderBleu/study_python | /class/函数属性 property.py | 1,664 | 4.25 | 4 | import random
'''
函数属性:
1、通过property方法直接访问私有属性
- 本来__weight是类私有属性,然后通过property后可以直接访问,但是还是会经过定义的get_weight和set_weight方法
2、通过装饰器修饰[注解]
- @property 装饰器修饰,提供一个get方法
- @age.setter 提供age字段的set方法
- @age注解的字段名和函数名需要匹配
'''
class Person:
# 初始化类的属性,在实例化时被执行,可以理解为构造器
def __init__(self, weight):
... | false |
23c585f29a21fc65ae1fb7076652126aaa16241f | MohammedHijazi/personalwebsite | /exercise3.py | 581 | 4.21875 | 4 |
def creat_dict():
country_capital = {
"Palestine":"Jerusalem",
"Egypt":"Cairo",
"USA":"DC",
"Germany":"Berlin"}
return country_capital
def main ():
dectionary = creat_dict()
country= raw_input ("Enter Your Country or enter to quit :")
while (country != "" ):
if country in dectionary:
out_put(decti... | false |
2ace2896fbc1dd80daca1885a1a91c32a65c50dc | Mat24/stop_game | /jugador.py | 1,011 | 4.1875 | 4 | """
Clase de un jugador
Define el "molde" de un judador, es decir las propiedades que identifican a un jugador.
es decir:
- nombre: cada jugador se identifica por un nombre
- puntos: cada jugador lleva la "contabilizacion" de sus puntos (por defecto son cero)
- respuestas: diccionario que contie... | false |
2e2192d69a9f9c1fc0c50d750dbe39b389b3d9b0 | ilyaSerebrennikov/ilyaSerebrennikov | /Module_7_ Algo 7_2.py | 1,286 | 4.125 | 4 | '''
2.Отсортируйте по возрастанию методом слияния одномерный вещественный массив,
заданный случайными числами на промежутке [0; 50).
Выведите на экран исходный и отсортированный массивы.
'''
import random
def merge_sort(arr):
def merge(frst, snd):
res = []
x, z = 0, 0
while x <... | false |
0b1460d5dab91ae25b1ea9ff6e2ab587bee6f259 | giraffesyo/School-Assignments | /Intoduction to Computer Programming - CSYS 1203/Assignment 3/average.py | 359 | 4.21875 | 4 | # This simple program will average the numbers entered by a user.
# By Michael McQuade CSYS1203
def main():
print("This program will average comma separated numbers you enter.")
n = eval(input("How many numbers are to be averaged? "))
avg = eval(input("Please enter the numbers you would like averaged: "))
... | true |
ff7db4aee1d82ca246adcc2cf2e065e08adef553 | Harsh5751/Python-Challenges-with-CodeWars | /Binary Addition.py | 533 | 4.34375 | 4 | '''
Binary Addition
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.
The binary number returned should be a string.
'''
def add_binary(a,b):
binary = str(bin(a + b))
return binary[2: ]
#Sample Tests
Te... | true |
06681e8dbe843cdcdab6b5bbccef4c17042f9a5c | Harsh5751/Python-Challenges-with-CodeWars | /sum of odd numbers.py | 510 | 4.125 | 4 | '''
Sum of odd numbers
Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:
rowSumOddNumbers(1); // 1
rowSumOddNu... | true |
f8f70eaf3830c19b5d91ba2b25e34e667e2c337e | Greycampus/python | /datatypes/array.py | 546 | 4.46875 | 4 | '''
Python program to take input a sequence of numbers from user and store it in a list or array
Input
3
11
12
13
Output
[11, 12, 13]
'''
msg = 'enter the number of elements:'
#printing message for user input
print(msg)
# taking length of list to be inputted
a = raw_input()
#stripping extra spaces in input
a = int(a.... | true |
c1c87e66aa1e0677343f57612e69493660e18f23 | Greycampus/python | /variables/local.py | 915 | 4.15625 | 4 | '''
python program to use local variable by taking user input and print nearest power of 3
Input
4
Output
3
'''
#import math library for log functions
from math import log,floor,ceil
msg = 'enter the number:'
#printing message for user input
print(msg)
#taking input and casting it into integer
n = raw_input()
#stripp... | true |
c735202659fff96ffa73d2b0a1379343d90618b0 | Greycampus/python | /regex/repla.py | 478 | 4.5 | 4 | '''
Python program to replace all the patterns like '[!*]' using loops
Input
enter the string:
[![![!*][!*]*]*]abc
Output
string before modification:[![![!*][!*]*]*]abc
abc
'''
import re
msg = 'enter the string:'
print(msg)
k = str(raw_input())
print('string before modification:'+k)
#replacing the pattern in string
... | true |
b40c1ecde281f3021e79e19a2b5fa25dcfb239fc | Greycampus/python | /regex/occur.py | 728 | 4.21875 | 4 | '''
python program to find the total occurences of a symbol in string using reqular expressions
Input
enter the main string:
1qaz!@#$!@#$zxswedc@#$%
enter the symbol you wish find occurences:
@
Output
@ occured 3 times in 1qaz!@#$!@#$zxswedc@#$%
'''
import re
msg= 'enter the main string:'
print(msg)
#getting main st... | true |
367e24a60d82ca14411c927ba4a66a402eb90eeb | Greycampus/python | /oops/over.py | 514 | 4.5 | 4 | '''
Python program to Use Function Overridingin a class.
Output
B's hello
A's GoodBye
'''
class A():
#constructor of A
def __init__(self):
self.__x = 1
#m1 function of parent
def m1(self,Ab):
print('A\'s '+str(Ab))
class B(A):
#constructor of B
def __init__(self):
s... | false |
ba2082fbbcf8ddf40333a4c3e6930584416991d0 | Greycampus/python | /file_handling/filenopen.py | 583 | 4.125 | 4 | '''
Python program to open a text file and print the nth line in text file if nth line does not exist print 'no data'
Input
enter the line number:
4
Ouput
4th line:hello python programmer
'''
#opeing the text file
f = open('text1.txt','r')
#getting nth line number from user
msg = 'enter the line number:'
print msg
n... | true |
669c1c377f6336ac8bde5baa2a43cfb28f4fdfcf | haddow64/CodeEval | /Easy/01 - Fizz Buzz.py | 2,470 | 4.25 | 4 | #Players generally sit in a circle. The player designated to go first says the number "1",
#and each player thenceforth counts one number in turn. However, any number divisible by 'A' e.g.
#three is replaced by the word fizz and any divisible by 'B' e.g. five by the word buzz. Numbers
#divisible by both become fizz buz... | true |
e3b7a1ddd339af3646ba2b60d0da043bd1fe8d05 | Piwero/bootcamp_projects | /find_py.py | 333 | 4.21875 | 4 | '''
Find PI to the Nth Digit -
Enter a number and have the program generate PI up to that many decimal places.
Keep a limit to how far the program will go.
'''
#import the math
import math
def find_pi(n):
print(format(math.pi,'.{}f'.format(n)))
#---------------------TEST-------------------
find_pi(6)
find_pi(4... | true |
4b506d5b5e52cd352177df56e39a5cb77009e4de | kamilloads/prog1ads | /lista3-9.py | 1,132 | 4.1875 | 4 | #9 - Faça um Programa que leia três números e mostre-os em ordem decrescente.
print("9 - Faça um Programa que leia três números e mostre-os em ordem decrescente.")
num1 = int (input("Digite o primeiro numero: "))
num2 = int (input("Digite o segundo numero: "))
num3 = int (input("Digite o terceiro numero: "))
if num1 > ... | false |
bd29c7dc82dcbedb74384ad3a10f9e84ec7290bb | kamilloads/prog1ads | /lista3-2.py | 283 | 4.21875 | 4 | #2 - Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.
num = float (input("digite um numero: "))
if num > 0:
print(f"{num} é um numero positivo.")
elif num < 0:
print(f"{num} é um numero negativo.")
else:
print(f"{num} é nulo")
| false |
e1044cb36bdfb2180af54f435d5cb202f5213501 | Anna1027/CaesarCipherEncryption | /caesarCipher.py | 485 | 4.125 | 4 | #c = (x - n)%26
def encrypted(string, shift):
cipher= ' '
for char in string:
if char==' ':
cipher = cipher+char
elif char.isupper():
cipher= cipher+chr((ord(char)+shift-65)%26+65)
else:
cipher=cipher+chr((ord(char)+shift-97)%26+97)
return cipher
... | true |
be76d86c066d19f1eb3c787f3cf54c26292b71de | mtthwgrvn/Python-Resources | /operators.py | 2,052 | 4.6875 | 5 | #Python Operators
#Operators are used to perform operations on variables and values.
#Python divides the operators in the following groups:
#Arithmetic operators
#Assignment operators
#Comparison operators
#Logical operators
#Identity operators
#Membership operators
#Bitwise operators
#Python Arithmetic Operators
#... | true |
a32f351dcbec0cb4051e4afaf172d7742ba36836 | GiftofHermes/Practice | /Odd or Even.py | 996 | 4.21875 | 4 | #Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user.
#Hint: how does an even / odd number react differently when divided by 2?
#If the number is a multiple of 4, print out a different message.
#Ask the user for two numbers: one number to check (call... | true |
afb9a0cdb6ab48ef53d67deeeab070acdca2548b | GiftofHermes/Practice | /Birthday JSON.py | 940 | 4.5 | 4 | #load the birthday dictionary from a JSON file on disk,
# rather than having the dictionary defined in the program.
#Ask the user for another scientist’s name and birthday
# to add to the dictionary, and update the JSON file
# you have on disk with the scientist’s name.
import json
with open('Writings/info.json', '... | true |
02e70f100addb87527434118fb24357083b08b8f | bryanalves/euler-py | /src/001.py | 351 | 4.21875 | 4 | #!/usr/bin/env python
"""
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.
"""
def euler_1(n):
return sum(a for a in range(n) if a % 3 == 0 or a % 5 ==0)
if __name__ == "__mai... | true |
112d62993b58f994ff2c9bf977c357b903990a49 | AslanDevbrat/Programs-vs-Algorithms | /Problem 1 Square Root of an Integer/Problem 1 Square Root of an Integer.py | 1,260 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
def find_floor_sqrt(number,start,stop):
#print(start,stop)... | true |
30403759ba6885955b176dba5d27d19c1b2b8e93 | MaoningGuan/Python-100-Days | /Day01-15/07_exercise_7.py | 647 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
列表的相关函数操作
"""
list1 = [1, 3, 5, 7, 100]
# 添加元素
list1.append(200)
print(list1)
list1.insert(1, 400)
print(list1)
# 合并两个列表
# list1.extend([1000, 2000])
list1 += [1000, 2000]
print(list1)
print(len(list1)) # 获取列表长度
print(list1)
# 先通过成员运算判断元素是否在列表中,如果存在就删除该元素
if 3 in list1... | false |
f0b07aea5b1d1ab99a53c6024858e4fc6a53f89b | jdevadkar/Python | /Basic Python/calculator.py | 1,078 | 4.21875 | 4 | # this method implement addintion of two number
def add(x,y):
return x + y
# this method implement subtraction of two number
def subtract(x,y):
return x -y
# this method implement multiplication of two number
def multiply(x,y):
return x * y
# this method implement Division of two number
def divide(x, y):
... | true |
a4a23f40a60dbdb11f967fa7e636997ec005bb48 | 99YuraniPalacios/Trigometria | /trigonometry.py | 1,208 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 13:07:28 2019
@author: jzuluaga
"""
from enum import Enum
import numpy as np
PI=3.14159265359
class Unit(Enum):
DEG=1
RAD=2
class Angle(object):
#Atributos: value, unit
#Métodos
def __init__(self,value,unit):
s... | true |
7617a7d2233c7dcaa3e2db5a3b4a20c2703003b8 | atkell/learn-python | /exercises/ex31.py | 1,873 | 4.40625 | 4 | # making decisions: now that we have if, else and elif we may start to create scrpipts that decide things!
# in this exercise, we'll explore asking a user questions nd then make decisions based on the answer(s) provided
print("""You enter a dark room with two doors.
Do you go through the door #1 or door #2?""")
door ... | true |
9a5f9d8b5920456ffe5e9a3e1d5c07a5d9262536 | atkell/learn-python | /exercises/ex24.py | 1,790 | 4.3125 | 4 | # this exercise is intentionally long and all about building up stamina
# the next exericse will be the same. do them both, get them exactly right and do your checks
print("Let's practice everything we know thus far...")
print('You\'d need to know \'bout escapes with \\ that do:')
print('\n newlines and \t tabs')
poe... | true |
3b0e57fb2b13652513fb9d080fb24eaab5a09ad5 | atkell/learn-python | /exercises/ex19.py | 1,811 | 4.21875 | 4 | # functions and variables
# the takeaway here is scope, mostly that the variable we use in our functions are not connected to variables in our script
def cheese_and_crackers(cheese_count, boxes_of_crackers): # here we define our function for ex19 called cheese_and_crackers. it takes 2 arguments, cheese_count and boxe... | true |
a9f51c70c1a4979e1fa49a7030c3aeeab59d4b00 | atkell/learn-python | /exercises/ex8.py | 702 | 4.3125 | 4 | formatter = "{} {} {} {}"
# huzzah! we are introducing the concept of a function
# we're just working with integers here
print(formatter.format(1, 2, 3, 4))
# now we're working with strings
print(formatter.format("one","two","three","four"))
# now we're workign with booleans
print(formatter.format(True, False, False, T... | true |
4a809d9f88da2db4541509cb254d492d407ac6f1 | atkell/learn-python | /exercises/ex3.py | 968 | 4.53125 | 5 | # numbers and math, joy!
# + is addition (plus)
# - is subtraction (minus)
# / is division (slash)
# * is multiplication (asterisk)
# & is remainder after division (modulous)
# < is less than and > is greatter than
# <= is less than or equal to and >= is greater than or equal to
# remember the order of operations "PEM... | true |
f9f4914364541aafeb58b593b7117926b73e24d8 | xuwei0455/design_patterns | /FactoryMethod.py | 2,357 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Factory Method pattern
The distinction of Simple Factory and Factory Method is,
Simple Factory pattern only offer one factory to produce,
otherwise, Factory Method can horizontal scaling by add
new Factory.
And, when there just one factory, pattern fall back to
Simple Factory.
When just ... | true |
24c755ce860af891b453f245740705eb406206e5 | gunveen-bindra/OOP | /single_inheritance.py | 684 | 4.21875 | 4 | # Defining base class "Shape".
class Shape:
# Function to initialize data members.
def _getdata(self, length, breadth):
self._length = int(input("Enter the Length: "))
self._breadth = int(input("Enter the Breadth: "))
# Defining derived class "Rectangle".
class Rectangle(Shape):
... | true |
e25de8b07e2449f5be7cc2df8284cf8815bbd99a | TheFutureJholler/TheFutureJholler.github.io | /module 6-Tuples/tuple_delete.py | 321 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 31 20:38:37 2017
@author: zeba
"""
tup = ('physics', 'chemistry', 1997, 2000);
print(tup)
del tup
print ("After deleting tup : ")
print(tup)
'''This produces the following result. Note an exception raised,
this is because after del tup tuple does not exist any more '''... | true |
7e282a9e3b589c4e641054900b47a060146e07e4 | dhanrajsr/hackerrank-practice-exercise | /if_else_ex.py | 583 | 4.5 | 4 | #https://www.hackerrank.com/challenges/py-if-else/problem
def find_odd_even(input_number):
""" If a number divided by 2 leaves a remainder 1, then the number is odd,
if a number divided by 2 leaves a remainder 0, then the number is even.
The % helps to calculate the remainder.
eg: number % ... | true |
e9895212e0dbc87a4adc3b412c8635b22877c7b7 | lyqtiffany/learngit | /pythonChapter/03_ifElse.py | 2,194 | 4.125 | 4 | #分支语句
#input读取用户的输入,返回字符串类型
# score = int(input('please input score, then press Enter'))
#
# #分支语句在任何情况下,只会执行其中一个分支
# if score >= 90:
# print('优秀')
# elif score >= 80:
# print('良好')
# elif score >= 60:
# print('及格')
# else:
# print('不及格')
# if-if-if 与if-elif-elif的区别,多个if之间没有互斥性,所以使用分支语句时,要用if-elif
#... | false |
8d9b15cf0add58beed7dca83ebbd5f84a0f248b8 | joedeller/pymine | /mandel.py | 2,074 | 4.21875 | 4 | #!/usr/bin/python
# Joe Deller 2014
# A very simplified version of the Mandelbrot set
# Level : Intermediate
# Uses : Libraries, variables, lists
# I have taken some example code for how to draw the Mandelbrot set from Wikipedia
# and made it compatible with the Pi.
# This isn't a true fractal program as we can't zo... | true |
68677dfb9e403db0d499fbea60a29fb69e3a7bb2 | zchq88/mylearning | /设计模式/创建类模式/建造者模式.py | 2,715 | 4.125 | 4 | # 将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。(注重构建过程的解耦分离)
# 抽象产品
class Car:
# 顺序队列
sequence = []
def run(self):
for todo in self.sequence:
if hasattr(self, todo):
_attr = getattr(self, todo)
_attr()
print("------------------")
# 产品1
class BMW(Car):
... | false |
36761b573cf0907ef8fff401966de660a6671975 | zhchwolf/pylearn | /python_code/frist.py | 401 | 4.59375 | 5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# calculate the area and circumference of a circle from its radius
# Step 1: prompt for a radius
# Step 2: apply the area formula
# Step 3: print out the results
import math
radiusString = input('Enter radius of circle:')
radiusInt = int(radiusString)
circumference = 2*ma... | true |
2c98e141be2c7fbebaf03d61928af8ce8c7a659e | zhchwolf/pylearn | /python_code/solution01.py | 1,020 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding:UTF-8 -*-
# python 入门经典以解决计算问题为导向的python编程实践
# a1 = input('input a number:')
a1 = 88
a2 = (( int(a1) + 2 )*3 -6 )/3
print ("((number+2)*3 -6)/3 The result is ",a2)
'''
我要去圣艾夫斯,我碰到一个男人,他有7个妻子,
每个妻子有7个麻袋,每个麻袋有7只猫,每只猫有7只小猫,
一共有多少人和物要去圣艾夫斯。
'''
all_object = 1 + 7 + 7*7 +7*7*7 + 7*7*7*7
prin... | false |
2b14e9c509c5d2e3f6cae1dd81eac27d8313d61c | GriffGeorgiadis/python_files | /decode.py | 2,128 | 4.21875 | 4 | #Griffin Georgiadis
#Write a program that uses a dictionary to assign “codes” to each letter of the alphabet
#set global variables
ENCRYPT = 1
DECRYPT = 2
#start main function
def main():
try:
#print menu
print('Welcome to my encryption program, You can choose to encrypt a file or decrypt an encryp... | true |
2f3e73af97ec226ddb0da068830b2de7b072facb | dandenseven/week1 | /day2/Day2_exercises/exercises/1-core-functions/define_functions.py | 433 | 4.34375 | 4 | #print allows you to output to your console what you want to print.
print("this is my string")
print(" 2 + 2 equals 4 this is the answer.")
a = 9 * 9
relax = ("meditating is good for your mind")
print( a )
print("meditating", a, "times is good for your mind")
#input lets you ask a use for some text to input, it tells ... | true |
6e2a7e74c4ef4859eb18fd571044e12bde07a115 | jesse-bro/Data_Structure_Problems | /Compress_String.py | 715 | 4.25 | 4 | ### Method to perform basic string compression using the
### counts of repeated characters. String only contains
### uppercase and lowercase letters (a-z).
def stringCompress(string):
compressed = ""
count = 0
for i, ch in enumerate(string[:-1]):
if ch != string[i+1] or i+1 >= len(strin... | true |
f792c60fca40895c5b85f7b35db15d79e2a5ae8a | PacktPublishing/Python-3-Project-based-Python-Algorithms-Data-Structures | /Section 03/4_strings_2_notes.py | 1,446 | 4.6875 | 5 | # We can use string concatenation and add strings
# together
message = "Welcome to the course"
name = "Mashrur"
print(message + name)
# We can add an empty space in there too
print(message + " " + name)
# Strings are sequences of characters which are indexed
# We can index into a string by using square bracket notati... | true |
2670d9d8d6c53b26330b4983790bef744c24e8c9 | PacktPublishing/Python-3-Project-based-Python-Algorithms-Data-Structures | /Section 04/12_merge_sort_demo_starter.py | 454 | 4.125 | 4 | def merge_sorted(arr1,arr2):
print("Merge function called with lists below:")
print(f"left: {arr1} and right: {arr2}")
sorted_arr = []
i, j = 0, 0
print(f"Left list index i is {i} and has value: {arr1[i]}")
print(f"Right list index j is {j} and has value: {arr2[j]}")
return sorted_arr
# xxx... | true |
578df8e4753a6be6252f68cead393522cd4d1559 | ramonsolis159/csc1010 | /csc1010_Pycharm_Projects_Python/hmwk_4.py | 849 | 4.34375 | 4 | # Ramon Montoya
# 10/08/2018
# This program is for an assignment.
movie = "I am currently watching a movie!"
print(movie)
type = "It is a action and scifi movie."
print(type)
type = "It is pretty good!"
print(type)
name = "eric"
message = "Hello " + name.title() + ", would you like to learn Python today?"
print(m... | true |
ec895f5c728871d691c3816cb53cc16f633818d3 | priyankapiya23/BasicPython | /String/reverse_string.py | 788 | 4.1875 | 4 | #reverse string
string=input("enter any string")
print('reverse of string is using methhod')
print(string[::-1]) # extended slice syntax
'''Explanation : Extended slice offers to put a “step” field as [start,stop,step], and giving no field as start and stop indicates default to 0 and string length respectively and “-1”... | true |
24601bddd6d86b6233380e3b65011276164373ac | ahmadabdullah407/python-basics | /stringlisttupleindexcountconcatinaterepeat.py | 1,460 | 4.1875 | 4 | # # Concatination(Addition of lists)(+):
# fruit = ["apple","orange","banana","cherry"]
# print([1,2] + [3,4]) #Concatination
# print(fruit+[6,7,8,9]) #Concatination
# # Repitition(Multiplication of lists)(*):
# print((fruit + [0,1])*4) #Repitition (Use parenthisis)
# # a = ['first'] + ("second","green") # Error List ... | true |
d929cfc88e59978e8add9795e5513ce6c73e11c6 | danielnwankwo/control_flow | /control_flow.py | 1,149 | 4.34375 | 4 | # control flow
# if statements
# syntax: if then conditions
age = 15
# will run because conditions have been met. without the = then it will not run as 15 does not satisfy either statement
# by itself
if age > 15:
print("Thank You. You may watch this movie ")
elif age <= 15:
print("sorry you are not the requi... | true |
ae06fa14c956784541cffec401aa4d56817782e3 | jimjshields/interview_prep | /interview_cake/19.py | 601 | 4.15625 | 4 | class StackQueue(object):
"""A queue implemented with two stacks."""
def __init__(self):
self.enqueue_stack = []
self.dequeue_stack = []
def enqueue(self, item):
self.enqueue_stack.append(item)
def dequeue(self):
if self.dequeue_stack == []:
while len(self.enqueue_stack) > 0:
self.dequeue_stack.ap... | false |
7494a5d939e68da759c450b3eeda9c80db3382d3 | jimjshields/interview_prep | /hashing/map_class.py | 2,508 | 4.1875 | 4 | class Map(object):
"""Represents a map/assoc. array/dictionary ADT."""
def __init__(self):
"""Initializes w/ an empty list of keys and empty list of values."""
self.dict = {}
def add_key_val_pair(self, key, val):
"""Adds a key/value pair to the map. Replaces value if key already present."""
self.dict[key... | true |
1b5a0da81fab26681c9cab11fa45d5586d06cee2 | jimjshields/interview_prep | /practice/19_shell_sort.py | 959 | 4.125 | 4 | # Shell sort - aka diminishing increment sort
# Improves on insertion sort - breaks original list into smaller sublists
# Each of which is sorted using insertion sort
# Big O:
# Worst case: O(n^2)
# Avg. case: Depends on gap selection
# Best case: O(nlog(n))
# Aux. space: O(1)
def shell_sort(a_list):
sub_list_count ... | true |
a629d6a370a39826e03748b571c263ff43c12d84 | code-in-public/leetcode | /best-time-to-buy-and-sell-stock/test.py | 812 | 4.28125 | 4 | #!/usr/bin/env python3
import unittest
import solution
"""
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: ... | true |
92f058ec4f9d59f583e42839a757d604ba961bb7 | Techwrekfix/Starting-out-with-python | /chapter-3/4. Roman_numerals.py | 773 | 4.21875 | 4 | #This program displays the roman numeral version
#of a number entered by a user
#Assigning the numeric numbers to a variable
one = 1
two = 2
three = 3
four = 4
five = 5
six = 6
seven = 7
eight = 8
nine = 9
ten = 10
#Prompting the user to enter a numeric number
number = int(input("Enter a numeric number: "))
#Display... | true |
9d76d0b71433637d8e740f45faa894bc5c96c32c | Techwrekfix/Starting-out-with-python | /chapter-8/Sum_of_digits_in_a_string.py | 560 | 4.34375 | 4 | #This program displays the sum of digits in a string
#ALGORITHM in pseudocode
#1. get a series of single-digit number from the user
# set total accumulator to zero
#2. for every digit in user input:
# convert digit to integer
# add the digit to the accumulator
#3. Display total
#CODE
def main():
u... | true |
1f55026aa62f17b9449bfa7315dba35209d5a220 | Techwrekfix/Starting-out-with-python | /chapter-2/3. land_calculation.py | 385 | 4.125 | 4 | #This program calculates the number of acres in a tract
total_square_feet = float(input('Please enter the total ' \
'square feet of the tract' \
'of land: '))
number_of_acres = total_square_feet / 43560
#Displaying results
print('The number of acres in... | true |
f3d2f5fc63aa813d13150d89f80d71947b478863 | Techwrekfix/Starting-out-with-python | /chapter-2/8. tip_tax_total.py | 541 | 4.15625 | 4 | #This program displays the total
#cost of a meal purchased at a restaurant
meal_charge = float(input('Enter the cost of the meal: '))
tip = 0.18 * meal_charge #calculating 18% tip of the meal
sales_tax = 0.07 * meal_charge #calculating 7% sales tax of the meal
total = meal_charge + tip+sales_tax #calculating total... | true |
147900a7dba4bcf3dcf61da7595d1b8dee7a7612 | Techwrekfix/Starting-out-with-python | /chapter-6/2. File_head_display.py | 618 | 4.28125 | 4 | #File head display program
def main():
#creating variables for max lines and number of line in the file
max_line = 5
count_lines = 0
#ask user for file name
file_name = input('Enter the name of your file: ')
#open the file
user_file = open(file_name,'r')
#read the first line in the fi... | true |
c70c9318953230c1f0816dff97a67a720fa960a4 | Techwrekfix/Starting-out-with-python | /chapter-5/6. Calories_from_fat_and_carbohydrates.py | 724 | 4.28125 | 4 | #This program calculates calories from a fat
def main():
fat_grams = float(input('Enter the number of fat grams: '))
carb_grams = float(input('Etner the number of carb_grams: '))
fat_calories = calculate_fat_calories(fat_grams)
carb_calories = calculate_carb_calories(carb_grams)
#Displaying fats c... | true |
f84509cdcded11e6a1b53af3bbf930437dd0f3e3 | Techwrekfix/Starting-out-with-python | /chapter-9/1. course_Information.py | 1,419 | 4.40625 | 4 | #This proram is about course information
#Algorithm in pseudocode
#1.The create_dictionary function creates three different
# dictionaries(Room_number,Instructor and Meeting_time) and
# returns a refrence to the dictionaries
#
#2. Inside the main fucntion:
# 1.ask user enter a course number
# 2.if user i... | true |
57f08ee56cff62dd8570f2460253461bc550d4ae | Techwrekfix/Starting-out-with-python | /chapter-4/4. Distance_traveled.py | 396 | 4.53125 | 5 | #This program displays distance travelled in miles
speed = int(input('Enter the speed of the vehicle in mph: '))
time = int(input('Enter the hours traveled by the vehicle: '))
#Creating a table
print('Hour \t Distance Traveled')
print('--------------------------')
#Using a loop to display the table
for hours in range... | true |
661837cd7886c47de2847f854b1a86cd6ab8dadb | Techwrekfix/Starting-out-with-python | /chapter-3/5. Mass_and_weight.py | 447 | 4.4375 | 4 | #This program measure the weight of objects
#Getting the mass of an object from user
mass_of_object = float(input("Enter the mass of the" \
" mass of the object: "))
#Calculating the weight:
weight = mass_of_object * 9.8
print("\nThe weight of the object is N", format(weight,'.2f'),sep='')... | true |
9452fa853c8b47b7493a9c76c1aa5c851b0b7d06 | Latinaheadshot/DevF | /semana1-3/semana2/lesson1/sets.py | 1,858 | 4.65625 | 5 | # set de enteros
set_enteros = {1, 2, 3}
# print(set_enteros)
# set de diferentes tipos de datos
set_diferentes_tipos = {1.0, "Hello", (1, 2, 3)}
# print(set_diferentes_tipos)
# set no pueden tener elementos repetidos
set_numeros_repetidos = {1, 2, 3, 4, 3, 2}
# print(set_numeros_repetidos)
# set no pueden tener num... | false |
6c11ae57279bbbaa47daa26e5e56ea85830c3aea | Rohit-iitr/pythonBasics | /PythonProblems/G4G/RotateString.py | 1,078 | 4.125 | 4 | #User function Template for python3
#Function to check if a string can be obtained by rotating
#another string by exactly 2 places.
def isRotated(str1,str2):
flagAntiCloclwise = False
flagCloclwise = False
if (len(str1)>1 and len(str2)>1):
count =0
index =2
y=''
... | true |
46bae5b3aa0c1bb55b3cbaf6c9685a61c1b8d4a2 | AustinPenner/ProjectEuler | /Problems 26-50/euler046.py | 1,065 | 4.1875 | 4 | def is_prime(n):
if n < 2:
return False
# if integer is 2 or 3, then True
elif n == 2:
return True
elif n == 3:
return True
# if integer is even, then False
elif n % 2 == 0:
return False
# only check integers 3 through sqrt(n) + 1, skipping even numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x ==... | true |
8a33ecebf55c86cc08bcfbf5e080c6f8fdf1952a | matheuss3/rpg | /src/phases/aventura.py | 2,132 | 4.1875 | 4 | def aventura():
acao = ''
grito = ''
nome = ''
print('Você esta de olhos fechados. Não sente sua cama, todas as sensações que seu corpo lhe devolve é a sensação de estar deitado na areia molhada.')
print('Não esta no conforto da sua cama. Não sente seu travesseiro.')
print('"Aonde estou?" -... | false |
ad7efabdd3d075a7c1f7c50d7dab560792dc02be | johnmaster/Leetcode | /206.翻转链表/reverseList.py | 780 | 4.125 | 4 | """
执行用时 :28 ms, 在所有 python3 提交中击败了99.85%的用户
内存消耗 :13.8 MB, 在所有 python3 提交中击败了99.62%的用户
双指针迭代
申请两个指针,第一个指针叫pre,最初指向None。
第二个指针叫cur,最初指向head,然后不断遍历cur。
每次迭代到cur,都将cur的next指向pre,然后pre和cur前进一位
都迭代完了(cur变成None),pre就是最后一个节点。
"""
class ListNode:
def __init__(self, x):
self.val = x
self.n... | false |
20293522be0563364f8568d5dc9973f8a0a7afec | ljdutton2/karma_coin | /fanquiz.py | 2,716 | 4.3125 | 4 |
score = 0
def multiple_choice():
global score
answer=input("1. THIS country was formerly known as Yugoslavia: a) Romania b) Russia c) The Netherlands d) Montenegro ")
if answer == ("d"):
score += 1
print(" :) ")
print(f"Current Score: {score}")
else:
print(" :( the c... | false |
93d61b297e961a37a9b97043825b0219e9516f40 | HeapOfPackrats/AoC2017 | /day3.py | 2,556 | 4.34375 | 4 | #http://adventofcode.com/2017/day/3
import sys
def main(argv):
#get input, otherwise prompt for input
if (len(argv) == 2):
inputSquare = int(argv[1])
else:
print("Please specify an input argument (day3.py [input])")
return
#find Manhattan Distance from square # specified by in... | true |
0d82e7f58d632c077b461b22b5bfddaa0aa5e592 | Gamesu/MisionTIC_Python | /Scripts Sin Terminar/ventas.py | 1,707 | 4.125 | 4 | """ Modulo Module ventas
Funciones para el manejo de ventas mensuales
con matrices
Oscar Estrada Suazo
Junio 10-2021 """
# Definición de Funciones
#======================================================================
# E S P A C I O D E T R A B A J O A L U M N O
# ==================... | false |
b293cad2d6dc421ac1abfb1fff941c540bda314e | Bashorun97/python-trainings | /sorting in tuples.py | 506 | 4.375 | 4 | text = 'the university of lagos is loacated in Akoka lagos-mainland lga'
words = text.split() #split text into words
t = list() # create empty list
for word in words:
t.append((len(word), word))#append length of the word and the word to the list
t.sort(reverse = True) #reverse the list from biggest to smallest
#c... | true |
4925a9d09381548678a15f1bd56e22dba28c578b | apnwong/driving | /driving.py | 417 | 4.125 | 4 | country = input('Your country: ')
age = input('How old are you? ')
age = int(age)
if country == 'Taiwan':
if age >= 18:
print('You can drive')
else:
print('You cannot drive')
elif country == 'Japan':
if age >= 20:
print('You can drive')
else:
print('You cannot drive')
elif country == 'Ameria':
if age >= 16... | false |
fd609104207f10e1a9bf4e326af8169fae25b90b | xbh/Home-Work-of-MLES | /exercise/U2_Conditionals/test_paper.py | 875 | 4.125 | 4 | num_people = int(input("How many people to get takeout?"))
price_total = float(input("How much in total?"))
price_people = price_total / num_people
print("Each people needs to pay", price_people, "yuan.")
# --------------------------
num_students = int(input("How many students?"))
num_perGroup = int(input("... | false |
5ea4a953459510df36805ba84636f8426246f344 | himanshishrish/python_practice | /convertor.py | 405 | 4.4375 | 4 | '''to convert temperatures to and from celsius, fahrenheit. Go to the editor
[ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in fahrenheit ]
Expected Output :
60°C is 140 in Fahrenheit
45°F is 7 in Celsius'''
def convertor(c,f):
if f==0:
f=((9*c)/5)+32
else:
c=((f... | true |
b785fdb11138333a4273e0c09ca81e98091397fa | SpencerMcFadden/Learn-Python-the-Hard-Way-Files | /ex33.py | 1,391 | 4.3125 | 4 | i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
# recreating the while loop in a function
print "\nCoverting ... | true |
d398fade4929ed636bb4a78c7515eb376147e0ab | ferreret/python-bootcamp-udemy | /36-challenges/ex130.py | 636 | 4.375 | 4 | '''
three_odd_numbers([1,2,3,4,5]) # True
three_odd_numbers([0,-2,4,1,9,12,4,1,0]) # True
three_odd_numbers([5,2,1]) # False
three_odd_numbers([1,2,3,3,2]) # False
'''
def three_odd_numbers(numbers):
len_numbers = len(numbers)
for cursor in range(2, len_numbers):
sum_test = numbers[cursor - 2] + numbe... | false |
be641cd670af0e38686c2af44fcf34faee8eb5b7 | shukhrat121995/coding-interview-preparation | /hashmap/redistribute_characters_to_make_all_strings_equal.py | 1,083 | 4.125 | 4 | """
You are given an array of strings words (0-indexed).
In one operation, pick two distinct indices i and j, where words[i] is a non-empty string,
and move any character from words[i] to any position in words[j].
Return true if you can make every string in words equal using any number of operations, and false otherw... | true |
c03d348ecf3284995b5bb35b5820c75224915a48 | shukhrat121995/coding-interview-preparation | /dynamic_programming/frog_jump.py | 1,588 | 4.25 | 4 | """
A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or
may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross
the river by l... | true |
7c030872f5e26eb2051c1a8f99e8f946ab2b64d0 | Shuhuipapa/Codeacademy_projects | /AreaCalculator.py | 1,548 | 4.4375 | 4 | '''
Area calcaulator which computes the area of a given shape as selected
by user. the calculator will be able to determine the area of Circle and Triangle
'''
# Creator: Shuhui Ding 9/21/2017
# Codeacademy project
import time
from math import pi # import pi value
from time import sleep
from datetime import datetime
... | true |
4aec1214db3c07ffb5fae0eac3daa1161f045051 | cristianomeul/randomnumbergenerator | /main.py | 597 | 4.21875 | 4 | import random
def randomnumber(): #Making function
print('Give me 2 numbers, a minimum and a max to generate a random number') #Intro message
x = int(input("Enter a minimum: ")) #User inputs a minimum
y = int(input("Enter a maximum: ")) #User inputs a maximum
z = int(input("How many numbers do you want ... | true |
6be9cfab8d0dc0cc0f111a56ad63c1d0c891dddc | snickersbarr/python | /python_2.7/LPTHW/exercise12.py | 372 | 4.1875 | 4 | #!/usr/bin/python
### Exercise 12 ###
### Prompting People ###
y = raw_input("Name? ")
print "Your name is", y
# Rewriting previous exercise with asking within the prompt
age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")
print "So, you're %r... | true |
167336accab3743d41b53598032b9c160026b334 | snickersbarr/python | /python_2.7/other/classes_and_self.py | 515 | 4.21875 | 4 | #!/usr/bin/python
class className:
def createName(self,name):
self.name=name
def displayName(self):
return self.name
def saying(self):
print "hello %s" % self.name
# Create objects to refer to class
first = className()
second = className()
# Use methods within objects to assign values
first.createName('Kuna... | true |
7f7a774088406019df2eb28bf438b4c110468f00 | snickersbarr/python | /python_2.7/udemy/dictionaries.py | 1,934 | 4.59375 | 5 | #!/usr/bin/python
# creates a key with associated values
# associates keys with values separated with colons
# each set is separated with commas
my_dict = {'key1':'value','key2':'value2'}
print my_dict
# just like lists can have different data types (numbers and strings)
print my_dict['key1']
my_dict2 = {'k1':123,... | true |
8616b4e9e22a6849e1f1e5e3c01535a5d8ecb2bb | snickersbarr/python | /python_2.7/udemy/errors_and_exceptions.py | 2,786 | 4.3125 | 4 | #!/usr/bin/python
# This module is about error handling. Specifically with try, except, finally blocks and try, except, else blocks as well as all four concepts put to gether
'''
Example:
try:
2 + 's'
except typeError:
print "There was a type error!"
'''
'''
output:
Traceback (most recent call last):
File "er... | true |
cb30dc5a7322d90a929a7b712a2bd86416558412 | Vishal1003/python-five_Domain | /1_python/operator_overloading.py | 1,153 | 4.40625 | 4 | # python operators work for the built in classes. But the same operator behaves diffrently with different data types.
# + operator is used for arithmatic addition of two num, merge two lists, concatinate two strings
# This feature in python, that allows same operator to have different meaning according to the context ... | true |
46c7c7117d1e9f673484fbe2cad1b077f84a14e4 | squashgray/Hash-Tables | /hashtable/hashtable.py | 2,193 | 4.1875 | 4 | class HashTableEntry:
"""
Hash Table entry, as a linked list node.
"""
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class HashTable:
"""
A hash table that with `capacity` buckets
that accepts string keys
Implement this.
... | true |
6b9d5838c2d1c0b526a177fd229645f9f5de55f3 | Data-Semi/DataStructure-Project3-ProblemsVSAlgorithms | /python_files_from_notes/4.py | 2,773 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# Dutch National Flag Problem
# Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. You're not allowed to use any sorting function that Python provides.
#
# Note: O(n) does not necessarily mean single-traversal. For e.g. if you traverse the ... | true |
e4665cd88eba6423cdc5bad73ab4d0d566e3bf2e | Data-Semi/DataStructure-Project3-ProblemsVSAlgorithms | /problem_4.py | 1,530 | 4.15625 | 4 | def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
pos = 0 #index of current judgement position
next_0 = 0 # index of next possible insert position of 0
next_2 =... | true |
decb476d94340f5c504502c7f7871745e608a34d | PierreBeaujuge/holbertonschool-higher_level_programming | /0x06-python-classes/4-square.py | 737 | 4.3125 | 4 | #!/usr/bin/python3
"""
Access and update private attribute
"""
class Square:
"""define variables and methods"""
def __init__(self, size=0):
"""initialize attributes"""
self.size = size
@property
def size(self):
"""getter for size"""
return self.__size
@size.setter... | true |
3d0ea61d723388381aa90ccb1ad092fb074c6a42 | iuliar/TrainingPython | /suma_int_4_2.py | 585 | 4.34375 | 4 | """
Create a program that computes the sum of all float and integer numbers from a list.
The given list contains other data types as well: strings, tuples, list of lists, etc.
(e.g: at least one list element from each data type +
"""
initial_list = [1, 2, "unu", (3,4,5), "word", ['a', 'b', 'c'], 3, 6, 7.8, 9.2 ]
len... | true |
1d65afac7624a2a620aab7be858b9993de958e3a | maxthemagician/BioInformatics3 | /Assignment1/Assign1_suppl/AbstractNetwork.py | 1,703 | 4.125 | 4 | class AbstractNetwork:
"""Abstract network definition, can not be instantiated"""
def __init__(self, amount_nodes, amount_links):
"""
Creates empty nodelist and call createNetwork of the extending class
"""
self.nodes = {}
self.mdegree = 0
self.__createNetwor... | true |
10b7d7f0025a34e24826b8b83147f56a4824e4b7 | wzqnls/AlgorithmsByPython | /BubbleSort/BubbleSort.py | 347 | 4.1875 | 4 |
def bubble_sort(lists):
length = len(lists)
for i in range(0, length):
for j in range(0, length - 1 - i):
if lists[j] > lists[j + 1]:
lists[j + 1], lists[j] = lists[j], lists[j + 1]
return lists
if __name__ == '__main__':
lists = [1, 2, 3, 6, 8, 22, 11, 77, 66]
... | false |
2e7269ad5cce7b27db13bbfc7ff9a328a7e8b7e7 | vinceajcs/all-things-python | /algorithms/graph/dfs/connected_components.py | 1,196 | 4.125 | 4 | """Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), find the number of connected components in an undirected graph.
Example 1:
Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]]
0 3
| |
1 --- 2 4
Output: 2
Example 2:
Input: n = 5... | true |
0aee5478cf875541f6398a73c281b9deb116c939 | vinceajcs/all-things-python | /algorithms/tree/binary_tree/diameter_of_binary_tree.py | 843 | 4.4375 | 4 | """Given a binary tree, you need to compute the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
This path may or may not pass through the root.
Example:
Given a binary tree:
1
/ \
2 3
/ \
4 ... | true |
ea577a1ae1fa7a6e07a6c61d5fe75a302575957f | vinceajcs/all-things-python | /algorithms/graph/dfs/course_schedule.py | 1,746 | 4.375 | 4 | """There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all cours... | true |
43dd06e1c5b0a2296bcb301a49af8ebb7eb9f0f4 | vinceajcs/all-things-python | /algorithms/math/power.py | 865 | 4.40625 | 4 | """Implement power(x, n), which calculates x raised to the power n (x**n)."""
def power(x, n):
if n == 0:
return 1
if n < 0:
n = -n
x = 1 / x
return power(x * x, n // 2) if (n % 2 == 0) else x * power(x * x, n // 2)
"""Using repeated squaring (both time and space complexity: O(... | true |
42765374350606400390baea2f04538b56675fd6 | vinceajcs/all-things-python | /algorithms/tree/binary_tree/bst/second_largest_element.py | 894 | 4.125 | 4 | """Given a BST, find the second largest element.
Time: O(h)
Space: O(1)
"""
def find_largest(root):
current = root
while current:
if not current.right:
return current.value
current = current.right
def find_second_largest(root):
if not root or not root.left or root.right:
... | true |
6b996f29b51841109ee1d053d899869c1a6528b3 | vinceajcs/all-things-python | /algorithms/tree/binary_tree/populating_next_right_pointers.py | 1,364 | 4.125 | 4 | """Given a perfect binary tree, populate each next pointer to point to its next right node.
If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
We can traverse the binary tree level by level.
Time: O(n)
Space: O(n)
"""
def connect(root):
if not r... | true |
14bc4ded2259854c71e19103c9589e358d941867 | vinceajcs/all-things-python | /algorithms/tree/binary_tree/flatten_binary_tree_to_linked_list.py | 837 | 4.28125 | 4 | """Given a binary tree, flatten it to a linked list in-place.
Idea:
1. Flatten left subtree
2. Find left subtree's tail (end)
3. Set root's left to None, root's right to root's left subtree, and tail's right to root's right subtree
4. Flatten original right subtree
Time: O(n)
Space: O(n)
"""
def flatten(root):
... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.