blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
796531ea77eaec4ece9afdfdcde2ab94bdac913c | domingomartinezstem/QC | /SymmetricKeyEncryption.py | 720 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 21:41:05 2018
@author: domin
"""
#this works!
def encrypt(sentence):
result = []
for letter in sentence:
l= ord(letter)
result.append(l)
print("encrypted message")
for numbers in result:
print(numbers, end='')
... | true |
e104f9ebfb10a9d46c3d633b354732e2bb6cec47 | amobiless/Assessment | /04_number_checker_v2.py | 731 | 4.1875 | 4 | # Integer checker - more advanced
def calculate():
valid = False
while not valid:
try:
num = float(input("Enter participant's time: "))
if isinstance(num, float):
valid = True
return num
except ValueError:
print("That is not a n... | true |
f7d88e43d87cac893ff58334f062d48875dc4599 | OlyaBakay/UCU-blockchain-lesson1 | /point_prime.py | 1,781 | 4.25 | 4 | class Point:
"""
Class Point represents a point on crypto curve y^2 = x^3 + ax + b
"""
def __init__(self, x, y, a, b, mod):
if (y ** 2 - x ** 3 - a * x - b) % mod != 0:
raise ValueError('Incorrect values')
self.x = x
self.y = y
self.a = a
self.b = b
... | false |
c234b405bf139ce2fdc17c10911b2b94c42d8787 | calel95/testes | /class_exemplo.py | 1,933 | 4.125 | 4 | # EXEMPLO 1
class calculadora:
def __init__(self,n1 , n2): #define os parametros, por padrao o self tem que ter, o init que inicia a class
self.a = n1
self.b = n2
def soma(self):
return self.a + self.b
def sub(self):
return self.a - self.b
def div(self):
re... | false |
2603bdce02bdd5e69c983226dedb98ea04b17f00 | hqs2212586/startMyPython3.0 | /第三章-文件操作和函数/函数/高阶函数.py | 803 | 4.25 | 4 | '''
高阶函数:一个函数就可以接收另一个函数作为参数(变量可以指向函数,函数的参数能接收变量)
满足以下任意条件可以判断是高阶函数:
1、接受一个或多个函数作为输入
2、return返回另外一个函数
'''
# 下述例子说明变量可以指向函数
'''
def calc(x):
return x*x
f = calc
print(f(2))
'''
# 下述例子说明函数的参数能接收变量
def func(x,y):
return x+y
def calc(x):
return x
n = func
print(calc(n))
# 输出:<function f... | false |
d5f30ca89e69fb7b4afb8d4e3688d89aeaff1354 | hqs2212586/startMyPython3.0 | /第五章-面向对象/8 练习.py | 1,027 | 4.3125 | 4 | """
练习1:编写一个学生类,产生一堆学生对象
要求:
有一个计算器(属性),统计总共实力了多少个对象
"""
class Student: # 类名头字母大写
school = 'whu'
count = 0
def __init__(self, name, age, sex): # 为对象定制对象自己独有的特征
self.name = name
self.age = age
self.sex = sex
# self.count += 1 # 每个对象都是1,无法实现累加,student类的count一直都是0
... | false |
195b0a84417fe61bae217a07c9c9167b8a2f5273 | hqs2212586/startMyPython3.0 | /第五章-面向对象/6 补充说明.py | 815 | 4.5 | 4 | """
补充说明:
1、站的角度不同,定义出的类截然不同
2、现实中的类并不完全等于程序中的类,比如现实中的公司类,往往会在程序中拆分为部门类,业务类等;
3、有时为了编程的需求,程序中也可能会定义现实中不存在的类,比如策略类(现实中不存在,但在程序中却非常常见的类)
"""
class student:
school = 'whu'
# python当中一切皆对象,在python3中统一了类和类型的概念
print(list)
print(dict)
print(student)
"""
<class 'list'>
<class 'dict'>
<class '__main__.stud... | false |
0c1c743294fcbc3af4bfc97eb8ccda73c7f33f2f | hqs2212586/startMyPython3.0 | /第五章-面向对象/19 封装的意义.py | 1,672 | 4.25 | 4 | # 一、封装数据属性:明确地区分内外,控制外部对隐藏属性的操作行为
# class People:
# def __init__(self, name, age):
# self.__name = name
# self.__age = age
#
# def tell_info(self):
# print('Name:<%s> Age:<%s>' % (self.__name, self.__age))
#
# def set_info(self, name, age):
# if not isinstance(name, str):
# ... | false |
96445bb7a92516766a7c289064aa613eb6557d2f | hqs2212586/startMyPython3.0 | /第五章-面向对象/24 反射.py | 982 | 4.28125 | 4 | # 反射:通过字符串映射到对象的属性
class People:
def __init__(self, name, age):
self.name = name
self.age = age
def talk(self):
print('%s is talking' %self.name)
obj=People('egon', 18)
print(obj.name) # obj.__dict__('name')
obj.talk()
hasattr(obj, 'name') # 判断obj内有没有name属性,obj.name # obj.__dict... | false |
e817977014fc2fec163f0df739ba34ccf728c24b | trohit920/leetcode_solution | /python/521. Longest Uncommon Subsequence I.py | 1,662 | 4.21875 | 4 | # Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
#
# A subsequence is a sequence that can... | true |
e8a0f8465b56dd066ed0dbb4258653ce948e9d4d | trohit920/leetcode_solution | /python/TopInterviewQuestionEasy/others_easy/Hamming Distance.py | 1,525 | 4.21875 | 4 | '''
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows p... | true |
0d082ed58b1c6623993a08ad21fec121e813c406 | YongHoonJJo/Python | /Lang_J2P/Tuple.py | 498 | 4.21875 | 4 | ### How to make Tuple ###
t1 = ()
t2 = (1, ) # only one element
t3 = (1, 2, 3)
t4 = 1, 2, 3
t5 = ('a', 'b', ('ab', 'cd'))
# It is impossible to delete or to replace elements.
t = (1, 2, 'a', 'b')
# del t[0] (error)
# t[0] = 'c' (error)
### Indexing, Slicing, Operator ###
t = (1, 2, 'a', 'b')
# t[0] : 1
# t[3] : '... | false |
dc3a60a000dae627cab5834261378e83d263b258 | Horatio123/PythonProgram | /firstTest/hello.py | 1,113 | 4.28125 | 4 | print ("hello python world")
class Student:
pass
student1 = Student()
print (student1)
student1.name = "horatio"
print (student1.name)
class Employee:
def __init__(self, first='Tom', last='Gates', pay=1000):
self.first = first
self.last = last
self.pay = pay
self.email = ... | false |
bce300aea98561a98bb61d797445903c8c1d0bca | Schachte/Learn_Python_The_Hard_Way | /Excercise_33/Excercise_33.py | 621 | 4.40625 | 4 | ################################
######### Excercise 33##########
# Learning Python The Hard Way#
####### Ryan Schachte ##########
################################
#Gain exit conditional input from the user
print 'Loop Count?' #Count number of times user would like to loop through string format
exit_conditional = raw... | true |
163bc5411b58de28c9fb80339d01f5b23629c056 | Schachte/Learn_Python_The_Hard_Way | /Excercise_29/Excercise_29.py | 735 | 4.71875 | 5 | ################################
######### Excercise 29##########
# Learning Python The Hard Way#
####### Ryan Schachte ##########
################################
#Implement a what if statement for python to execute certain code under certain condition
'''
Initial Assignments to children and adults
'''
adults = 30
c... | true |
d2a7dc9657d3c03124364566d5357cfb366e9728 | Schachte/Learn_Python_The_Hard_Way | /Excercise_39/Excercise_39.py | 1,285 | 4.46875 | 4 | ################################
######### Excercise 39##########
# Learning Python The Hard Way#
####### Ryan Schachte ##########
################################
#Description:
#Working with dictionaries in Python
#Mapping multiple items to elements in a list. Each element is a key.
#Example
dict_info = {
'Sta... | true |
570c634276f332186e724395acf46982be490a0f | Schachte/Learn_Python_The_Hard_Way | /Excercise_32/Excercise_32.py | 2,218 | 4.4375 | 4 | ################################
######### Excercise 32##########
# Learning Python The Hard Way#
####### Ryan Schachte ##########
################################
#Objective:
#Build a loop that adds data into a list and then have python print the data using string formatter
'''
loop_data = [] #Instantiate an empty li... | true |
4af768058ec3159db5565e0bcfd1f6bdd2d6a86a | DavinderSohal/Python | /Activities/Activity_9/Exercise2.py | 679 | 4.59375 | 5 | # Create a dictionary with keys ‘firstname’, ‘lastname’ and ‘age’, with some values assigned to each
# Add an additional key ‘address’ to the dictionary
# Print out the list of keys of your dictionary
# Create a ‘name’ key with the value as a string containing both first and last name keys. Is it possible to do this
# ... | true |
8adf5bc896807610f51ac9496e2ed64fdf8c2235 | DavinderSohal/Python | /Activities/Activity_6/Exercise2.py | 1,068 | 4.34375 | 4 | # Create the following python program:
# This program will display a mark table to the user, depending on its input.
# The columns represents the subjects.
# The rows represents the students.
# Algorithm to input data from the user:
# o Ask the user how many subjects (columns) is necessary.
# o Ask the user... | true |
773b2d7e700e82c2205b4f0a41b1c813b510452d | DavinderSohal/Python | /Activities/Activity_2/split.py | 752 | 4.40625 | 4 | # Exercise: Using the following sentence:
# “The quick brown fox jumps over the lazy dog”,
# convert this string into a list and then find the index of the word dog and sort the list of terms/words in
# ascending order. Print out the first two elements of this sorted list. Additionally, as a bonus, try to reverse
... | true |
efa9da8b6523c80bca5f9dfc9c34af4157a57cce | DavinderSohal/Python | /Activities/Activity_11/Exercise1.py | 414 | 4.3125 | 4 | # Create an empty class called Car.
#
# Create a method called initialize in the class, which takes a name as input and saves it as a data attribute.
#
# Create an instance of the class, and save it in a variable called car.
#
# Call the initialize method with the string “Ford".
class Car:
def initialize(self, nam... | true |
4e8fe4ef896f9bd4a7546a1cfa61ff11e0a2143a | DavinderSohal/Python | /Activities/even/even.py | 229 | 4.1875 | 4 | def even_number(number):
try:
if number % 2 == 0:
print("This entered number is even")
except:
print("The number entered by you is not even")
num = input("Enter the number")
even_number(num)
| true |
54adb4c74bdfcd80e96fdef01e7ac94c3f38602e | DavinderSohal/Python | /Activities/Activity_4/Exercise1.py | 409 | 4.28125 | 4 | # Create a string with your firstname, lastname and age, just like in the first week of the class, but this time using
# the string formatting discussed on the previous slides – and refer to the values by name, the output should be
# similar to the following:
# Name:
# Age:
print("Name: {first_name} {last_name} \nAg... | true |
6584a6355434917aca87047cd83addc6e3c5d997 | DavinderSohal/Python | /Explanations/10-Regex/nonGreedy.py | 305 | 4.28125 | 4 | # Example of greedy regex
import re
txt = 'Hello World'
pattern1 = re.compile("([A-Za-z]+).*([A-Za-z]+)") # greedy
pattern2 = re.compile("([A-Za-z]+).*?([A-Za-z]+)") # not greedy
print(pattern1.match(txt).groups()) # ==> ('Hello', 'd')
print(pattern2.match(txt).groups()) # ==> ('Hello', 'World')
| false |
6a3522904f129a5980912a88d1793ac71b38045c | Chetana-Nikam/python | /Python Udemy Course/WhileLoop.py | 301 | 4.28125 | 4 | #While Loop
#i=0
#while i<5:
# print(i) # infinite times loop will exist because i=0 always less than 5
i=0
while i<5:
print(i)
i += 1
i=0
while i<=10:
i += 1
if i==6:
break
print(i)
i=0
while i<=10:
i += 1
if i==6:
continue
print(i)
| false |
aeda5f94162716a34fb7808246727645197b8a5c | Chetana-Nikam/python | /Python Udemy Course/Function.py | 876 | 4.25 | 4 | # function - It is block of code and it will work only when we call it
def myfun():
print("I am Function")
myfun() # Function call
def myfun(name, age):
print(f"My name is {name} and my age is {age}")
myfun('Chetana', 21)
myfun('Google', 20)
def myfun(*name): # * indicats ... | true |
60ebc2b61f6e2d949fdb22b41ca77d7e5de3bb99 | cs-fullstack-2019-fall/python-arraycollections-b-cw-marcus110379 | /cw.py | 2,002 | 4.1875 | 4 | # Create a function with the variable below. After you create the variable do the instructions below that.
# # ```
# # arrayForProblem2 = ["Kenn", "Kevin", "Erin", "Meka"]
# a) Print the 3rd element of the numberList.
# b) Print the size of the array
# c) Delete the second element.
# d) Print the 3rd element.
def probl... | true |
6557645116815000d065cf2aca60415229417617 | rkang246/data-regression | /Plot Data/plot_data.py~ | 1,915 | 4.125 | 4 | #!/usr/bin/env python2
#
# ======================================================
# Program: plot_data.py
# Author: Robert Kang
# (rkang246@gmail.com)
# Created: 2018-08-01
# Modified 2018-08-01
# ------------------------------------------------------
# Use: To plot a set of data and connect each data point
# w... | true |
9d54db62c0dbed116593bbba257b400bef643cf3 | vinodyadav7490/PythonPractice | /palindrome.py | 724 | 4.21875 | 4 | '''
what is palindrome
if string and its reverse is same then we call the string as palindrome
'''
def palindromeUsingList(s):
ps = s[::-1]
if ps == s:
return True
else:
return False
def palindromeUsingBuiltInFn(s):
ps = ''.join(reversed(s))
if ps == s:
return True
else:
ret... | false |
b70c21ffd48778f8b30c0673d7bb474c7023d77d | Golgothus/Python | /Ch2/yourName.py | 565 | 4.25 | 4 | # Beginning of the end.
# I'm embarking on my journey to learn Python
# These comments will always be in the beginning of my programs
# Enjoy, Golgothus
# Ch. 2 While Statements
name = ''
while name.lower() != 'your name':
# Above statment makes the users input and forces it to all lower case
print('Please type \'... | true |
5534c84906fc2bb54970d85a825749ec942088f1 | Golgothus/Python | /Ch4/tupleListExamples.py | 658 | 4.21875 | 4 | #! /usr/bin/python3
# tuples are made using () not []
print('an example of a tuple is as follows:')
print('(\'banana\',\'eggs\',\'potato\').')
print('an example of a list is as follows:')
print('[\'banana\',\'eggs\',\'potato\'].')
exampleTuple = ('eggs','potato')
exampleList = ['eggs','potato']
type(exampleTuple)
t... | true |
99d4bc94b4876f5e8579cecde7a4dd475ffa93b8 | Golgothus/Python | /Ch5/validate_chess_board.py | 2,503 | 4.71875 | 5 | #! /usr/bin/python
'''
In this chapter, we used the dictionary value {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'} to represent a chess board. Write a function named isValidChessBoard() that takes a dictionary argument and returns True or False depending on if the board is valid.
A v... | true |
e8deec66e76c130a49e88029d373b61ef49f24c2 | rahulrpatil/coding-interview-bootcamp | /python/fizzbuzz/index.py | 564 | 4.40625 | 4 | # Write a program that console logs the numbers
# from 1 to n. But for multiples of three print
# 'fizz' instead of the number and for the multiples
# of five print 'buzz'. For numbers which are multiples
# of both three and five print 'fizzbuzz'.
# Example
# fizzBuzz(5);
# 1
# 2
# fizz
# 4
# buzz
def fiz... | false |
4e14b565661cad000f21cb9cfadd6b2d09771ad3 | JN1995/Programming-Languages | /python for Beginner/Most_used_Built_in_Functions_and_List_Comprehension.py | 1,663 | 4.5 | 4 | ## Commonly used Built-in functions in Python
# 1) Range function
# 2) Enumerate
# 3) zip
# 4) in
# 1) Range function
for num in range(10):
print(num)
for num in range(3,10):
print(num)
for num in range(0,11,2):
print(num)
my_list = [1,2,3,4,5,6,7,8,9,10]
range(10)
list(r... | true |
ad79810cbd5671b8ad6307d8d1b2dd0adfed9567 | JN1995/Programming-Languages | /python for Beginner/function/Lambda Expression.py | 1,294 | 4.28125 | 4 | ## Map, Filter and Lambda Expressions
# 1) map function
# 2) filter function
# 3) lambda expression
# 4) lambda expression with map and filter function
# Map function
def cal_square(n):
return n*n
cal_square(4)
my_num = [1,2,3,4,5]
map(cal_square, my_num)
list(map(cal_square, my_num))
f... | false |
ec8560d4b6c63653d71fbfe6fe094e4cb1aaf198 | JN1995/Programming-Languages | /python for Beginner/datatype/List's.py | 1,224 | 4.375 | 4 | ## List's ##
# 1) concatenation
# 2) Define empty list
# 3) Indexing in list
# 4) Editing the list's
# 5) Add list into list
# 6) Python in-build functions with the list's
my_list = ["Hello", 100, 23.47]
print(my_list)
second_list = ["one", "two", "three"]
print(second_list)
print(my_list, second_lis... | true |
5ded636ffafb656e05509d03e6d272fc3323e43f | phaustin/eoas_nbgrader | /Notebooks/python/NotebookStudent4.py | 934 | 4.40625 | 4 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.2'
# jupytext_version: 1.2.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# Que... | true |
662701aaf99b8b5fed985c3ebcf20018f373c82d | alenavee/cs102 | /homework01/caesar.py | 1,322 | 4.5 | 4 | def encrypt_caesar(plaintext) -> str:
"""
Encrypts plaintext using a Caesar cipher.
>>> encrypt_caesar("PYTHON")
'SBWKRQ'
>>> encrypt_caesar("python")
'sbwkrq'
>>> encrypt_caesar("Python3.6")
'Sbwkrq3.6'
>>> encrypt_caesar("")
''
"""
ciphertext = ''
shift = 3
for ... | false |
b5e14aa7c7d4fe50bb56b8b83de4e00afa91d8e3 | Alex-HK-Code/Mini-Database-Exercise | /main.py | 503 | 4.15625 | 4 | books = [] #this is used to store new inputs
while(True):
user_selection = input("Enter '1' to add a new book | Enter '2' to view all books | Enter '3' to quit the program\n")
if(user_selection == str(0)): #str(0) == '0'
break
if(user_selection == str(1)): #str(1) == '1'
book_name = input("Enter Book N... | true |
a71d6595e324adbed8851eea163ad68550a11c1f | Varun901/Small-Projects | /McMaster GPA Calculator.py | 961 | 4.3125 | 4 | from operator import mul
def sum_func(units, grades):
""" For product below you can also use the following commands:
1. [a*b for a,b in zip(a,b)]
2. import numpy as np
product = np.multiply(units,grades)
"""
product = map(mul,units,grades)
sum_product = sum(product)
return sum_product
def num_fun... | true |
06c6af3f560ea8d3f428aa85bdfa8d188c6a9124 | yzziqiu/python-class | /labs/lab2-payment-modi.py | 1,374 | 4.15625 | 4 | # lab2
# algebraic equation
# payment = (((1+rate)^years)*principal*rate/(1+rate)^years-1)
# use variables and two decimal places
# find out annual and monthly payment
principal_in = ((raw_input('Please enter the amount you borrowed:')))
# enter with dollar sign
principal = float(principal_in.replace('$',''))
... | true |
e8a7e98aa75a0e8e2ce1cabda5fb98732803e990 | yzziqiu/python-class | /notes/week2-notes.py | 1,644 | 4.21875 | 4 | # week2-notes
# python week2-notes.py
# array index print
test_string = "hello world"
print(test_string)
# hell
print('"{0}"'.format(test_string[0:4]))
#hell
print('"{0}"'.format(test_string[:4]))
#hello world
print('"{0}"'.format(test_string[0:]))
#hello world
print('"{0}"'.format(test_string[:]))
#ello worl
print('... | false |
4c10480ed9277a02275d13d06a07902de5e15d6e | theskinnycoder/python-lab | /week8/b.py | 662 | 4.1875 | 4 | '''
8b. Write a program to convert the passed in positive integer number into its prime factorization form
'''
from math import sqrt
def get_prime_factorization_form(num):
ans_list = []
for factor in range(2, int(sqrt(num)) + 1):
count = 0
while num % factor == 0:
count += 1
... | true |
48514e765b3a19947c7056197e9bac63626c6a62 | theskinnycoder/python-lab | /week2/a.py | 418 | 4.1875 | 4 | '''
2a. Write a program to get the number of vowels in the input string (No control flow allowed)
'''
def get_number_of_vowels(string):
vowel_counts = {}
for vowel in "aeiou":
vowel_counts[vowel] = string.count(vowel)
return sum(vowel_counts.values())
input_string = input('Enter any string : ')
p... | true |
1ec4ab7cc18b0a158484a300fb3a6011d3ac6ff0 | brunozupp/TreinamentoPython | /aula7/teste3.py | 458 | 4.15625 | 4 | if __name__ == '__main__':
n1 = int(input('Número 1: '))
n2 = int(input('Número 2: '))
s = n1 + n2;
m = n1 * n2;
d = n1 / n2;
di = n1 // n2;
e = n1 ** n2
#print('A soma é {}, o produto é {}, e a divisão é {:.3f}'.format(s,m,d))
print('A soma é {}, \no produto é {}, e a divisão é {:... | false |
6615d75240973f3f1596e8ebea0a58763ab31663 | brunozupp/TreinamentoPython | /exercicios/exercicio033.py | 532 | 4.1875 | 4 | if __name__ == '__main__':
num1 = int(input("Digite o número 1 = "))
num2 = int(input("Digite o número 2 = "))
num3 = int(input("Digite o número 3 = "))
if num1 >= num2 and num1 >= num3:
print(f"{num1} maior")
elif num2 >= num1 and num2 >= num3:
print(f"{num2} maior")
else:
... | false |
c44c80c53f14499d0c65e63f469230a4996baa2e | brunozupp/TreinamentoPython | /aula17/teste1.py | 1,789 | 4.28125 | 4 | if __name__ == '__main__':
# LISTA SÃO MUTÁVEIS
num = [3, 2, 1, 4, 5]
print(num)
print("-" * 30)
num[2] = 6
print(num)
print("-" * 30)
num.append(7)
print(num)
print("-" * 30)
num.sort()
print(num)
print("-" * 30)
num.sort(reverse=True)
print(num)
... | false |
0c5e6f7b4958e48e90ffa1d5ea40c5a65c2fe990 | sarbajitmohanty/OOPS-Python | /Polymorphism.py | 688 | 4.15625 | 4 | class Students:
def __init__(self, fname, lname, email):
self.fname = fname
self.lname = lname
self.email = email
def fullName(self):
print(self.fname.capitalize() + " " + self.lname.capitalize())
class Teachers:
def __init__(self, fname, lname, email):
self.fname =... | false |
b77879c0e990b72f693b7a7e61ef41a4d97ce239 | AmilaSamith/snippets | /Python-data-science/lambda_functions.py | 848 | 4.15625 | 4 | # Lambda fuctions
"""
lambda syntax
----------------------------------------------------------------
lambda (inputs) : (output_expression)
"""
# Example 01
add = lambda x,y: x + y
print(add(4,6))
print((lambda x,y: x + y)(4,10))
# Example 02
ages = {"michel":50,"martha":45,"vince":18,"Hilton":23}
def ge... | false |
84f8f5df072c9e6bc9d026daada6f3ddf90eea47 | AmilaSamith/snippets | /Python-data-science/if_statement.py | 885 | 4.375 | 4 | # if statement
"""
Single if statement
----------------------------------------------------------------
if(condition):
(code to be executed if condition is True)
if-else statement
----------------------------------------------------------------
if(condition):
(code to be execute... | true |
1d273a7086c4554096a9724085d304a21cfcaa53 | dim4o/python-samples | /dynamic-programming/max_sum_subsequence_non_adjacent.py | 1,004 | 4.28125 | 4 | def find_max_non_adjacent_subsequence_sum(sequence):
"""
Given an array of positive number, find maximum sum subsequence such that elements
in this subsequence are not adjacent to each other.
For better context see: https://youtu.be/UtGtF6nc35g
Example: [4, 1, 1, 4, 2, 1], max_sum = 4 + 4 + 1 = 9
... | true |
fc264f6a5a5b7142c7ce9bc619af9e046d578777 | dim4o/python-samples | /dynamic-programming/total_ways_in_matrix.py | 838 | 4.125 | 4 | def calc_total_ways(rows, cols):
"""
Given a 2 dimensional matrix, how many ways you can reach bottom right
from top left provided you can only move down and right.
For better context see: https://youtu.be/GO5QHC_BmvM
Example with 4x4 matrix:
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20 ->... | true |
0a8110b50e90fa492f518f18de598d79143a0d29 | dim4o/python-samples | /dynamic-programming/weighted_job_scheduling.py | 1,736 | 4.25 | 4 | def find_best_schedule(jobs):
"""
Given certain jobs with start and end time and amount you make on finishing the job,
find the maximum value you can make by scheduling jobs in non-overlapping way.
For better context see: https://youtu.be/cr6Ip0J9izc
Example:
(start_time, end_time, value)
(... | true |
de7cd735d609c6090ad37cc010ca0ee27992ab78 | dim4o/python-samples | /dynamic-programming/box_stacking.py | 2,675 | 4.34375 | 4 | def find_max_height(boxes):
"""
Given boxes of different dimensions, stack them on top of each other to get maximum height
such that box on top has strictly less length and width than box under it.
For better context see: https://youtu.be/9mod_xRB-O0
This algorithm is actually like "longest increas... | true |
5ff36bc06f94a32dab69de7398a305f891db2669 | greseam/module5_python_practice_SMG | /Module 5/mod5_hw1_task1_SMG.py | 647 | 4.28125 | 4 | ######
# String counter
#
# Sean Gregor
#
#desc: count the number of occurances in a string of characters for a specific character
######
def stringCounter():
userString = input("Please enter a string: ")
searchChar = input('Enter a charater of this string to know its position: ')
charCount = us... | true |
7003780f6609399c2a290dcbba2f9a82be060a01 | MuhammadYossry/MIT-OCW-6-00sc | /ps1/ps1a.py | 1,132 | 4.53125 | 5 | # A program to calculate and print the credit card balance after one year if a person only pays the
# minimum monthly payment required by the credit card company each month.
balance = float(raw_input('Enter the outstanding balance on your credit card:'))
annual_interest_rate = float(raw_input('Enter the annual credit ... | true |
afd25e49906b4dcf0f76a84f2ca098fa6a927693 | venilavino/mycode | /palindrome_number.py | 235 | 4.3125 | 4 | num = raw_input("Enter any number: ")
rev_num = reversed(num)
# check if the string is equal to its reverse
if list(num) == list(rev_num):
print("Palindrome number")
else:
print("Not Palindrome number")
| true |
5bf7078e98af056f45d0601c42d643328fd930ce | Fargolee/practice | /3-列表简介/3.2.1-修改列表元素.py | 1,446 | 4.15625 | 4 | motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
# 1、修改:利用索引赋值
# motorcycles[0] = 'ducati'
# print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
# ['ducati', 'yamaha', 'suzuki']
# 2、list.append(a) 添加
# motorcycles.append('ducai')
# print(motorcycles)
# ['honda', 'yamaha', 'suzuki']
# ['honda', 'yamaha',... | false |
4a2ff55c0dbfb64e9500f13c939031c6241504f7 | pmazgaj/tuition_advanced | /biblioteki/Pozostałe/[1] Dekoratory/zadania/[DEKORATORY] [3] przypadki_użycia.py | 1,070 | 4.25 | 4 | def argument_test_natural_number(f):
""" Check, if given number is an integer, and then decorate with it, for factorial operation """
def helper(x):
if isinstance(x, int) and x > 0:
return f(x)
else:
raise Exception("Argument is not an integer")
return helper
@arg... | true |
e92fed1a1019b98e68ebcf5c5e4a5a3b3fd529a6 | Unkerpaulie/tyrone | /hangman/hangman.py | 1,602 | 4.1875 | 4 | import random
import time
# create list of words
words = ["ADVICE", "BREATHE", "COMPLAIN", "DELIVER", "EXAMPLE", "FORGETFUL", "GRADUATE", "HIBERNATE", "INFERIOR", "JUSTIFY"]
# choose a random word from the list
word = random.choice(words)
chances = 5
letters_guessed = []
letter = ""
def clear():
... | true |
f27c46082da7df69872d5d588973a913192d8fd4 | haoknowah/OldPythonAssignments | /Gaston_Noah_NKN328_Hwk19/fraction.py | 2,117 | 4.1875 | 4 | class Fraction:
def __init__(self, numerator=1, denominator=1, decimal=0.5, numerator2=0, denominator2=0):
self.numerator=numerator
self.denominator=denominator
self.decimal=decimal
self.numerator2=numerator2
self.denominator2=denominator2
def simplify(self):
... | true |
eea921d913b7fe42cb4cc2c77f3cb3f126a783df | haoknowah/OldPythonAssignments | /Gaston_Noah_NKN328_Hwk18/007_alphabeticalOrder.py | 786 | 4.21875 | 4 | def alphabeticalOrder(L):
'''
alphabeticalOrder()=checks to see if input list of letters has letters
in abc order
@param L=input list
'''
try:
abc=False
if len(L)==1:
abc=True
elif L[0]<=L[1]:
abc=alphabeticalOrder(L[1:])
return abc
except:
... | true |
842c85348f7e451517ef5b13913fae33edbbb66c | haoknowah/OldPythonAssignments | /Gaston_Noah_nkn328_Hwk04/chapRev#6_lengthConversion.py | 1,248 | 4.46875 | 4 | def lengthConvertion():
'''
converts the units of miles, yards, feet, and inches to kilometers, meters, and
centimeters
@param m=miles
@param y=yards
@param f=feet
@param i=inches
@param ti=total inches
@param tmeters=total meters
@param km=kilometers
@param meters=meters
@param cm=centimeters
Note the commentary, ... | true |
151287d178e0acd653ceb0bcfc9ded9508d04790 | singhwarrior/python | /python_samples/python-advance/01_oop/03_polymorphism/02_operator_overloading.py | 1,230 | 4.625 | 5 | # Operator Overloading
# There are multiple kinds of operators in Python
# For example : +, -, /, * etc. But what happens
# behind the scene is there is function called for
# every such operator. Like __add__, __sub__, __div__
# __mul__ etc. These are called "Magic Functions".
# We can also apply such kinds of oper... | true |
78a18efdd547fc5836c16269fd94e612c41337d4 | dustinrubin/FiLLIP | /alternatingCharacters/alternatingCharactersDustin.py | 417 | 4.15625 | 4 | #!/bin/python3
# Complete the alternatingCharacters function below.
def alternatingCharacters(string):
lastCharater = ''
deletedCharacters = 0
for charater in string:
if not lastCharater:
lastCharater = charater
continue
if lastCharater == charater:
delet... | true |
4397a6dbfd69f8db91620efcdefb408d4218791a | 90sidort/exercises_Python | /domain_Name.py | 709 | 4.25 | 4 | # Description: https://www.codewars.com/kata/514a024011ea4fb54200004b/python
# Short task summary:
# Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example:
# domain_name("http://github.com/carbonfive/raygun") == "github"
# domain_name("http://... | true |
15cd9bee66293582f4ef789cd30527269b7d4a29 | 90sidort/exercises_Python | /the_Vowel_Code.py | 988 | 4.1875 | 4 | # Description: https://www.codewars.com/kata/53697be005f803751e0015aa
# Short task summary:
##Step 1: Create a function called encode() to replace all the lowercase vowels in a given string with numbers according to the following pattern:
##
##a -> 1
##
##e -> 2
##
##i -> 3
##
##o -> 4
##
##u -> 5
##
##For example, en... | true |
69d051a8ac8a5e58e710f1ce69b527537403abc6 | 90sidort/exercises_Python | /hydrate.py | 952 | 4.125 | 4 | # Description: https://www.codewars.com/kata/5aee86c5783bb432cd000018/python
# Short task summary:
##Welcome to the Codewars Bar!
##
##Codewars Bar recommends you drink 1 glass of water per standard drink so you're not hungover tomorrow morning.
##
##Your fellow coders have bought you several drinks tonight in th... | true |
73a57d6fa0dd8ca1ef3e795b4bd95cf07f942355 | rodcoelho/python-practice | /archived_problems/amazon_majority_element.py | 968 | 4.1875 | 4 | #!/usr/bin/env python3
# Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.
# Output: For each test case the output will be the majority element of the array. Output "-1" if no majority element... | true |
3bc230e6df8bf0e597c4958bf9104cb9bc330a50 | rodcoelho/python-practice | /archived_problems/amazon_pythagorean_triplet.py | 940 | 4.125 | 4 | #!/usr/bin/env python3
import itertools
# Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2.
# Output: For each testcase, print True or False
def bool_py_triplet(s):
arr = s.split(" ")
arr = [int(x) for x in arr]
c2 = {}
for i... | true |
7ec80a2f8c691162457acc19d2ac9c0c170a859b | rodcoelho/python-practice | /archived_problems/amazon_how_many_x.py | 1,396 | 4.28125 | 4 | #!/usr/bin/env python3
# Given an integer X within the range of 0 to 9, and given two positive integers as upper and lower bounds respectively, find the number of times X occurs as a digit in an integer within the range, excluding the bounds. Print the frequency of occurrence as output.
# Input:
# The first line of i... | true |
2a8cfb68d48ce33c6b19f724ede5390a4d49f08d | rodcoelho/python-practice | /cracking_coding_interview/ch_2/prob_5.py | 1,016 | 4.15625 | 4 | #!/usr/bin/env python3
import unittest
from linkedlist import CustomLL
"""Given a circular linked list, implement an algorithm which returns node at the beginning of the loop."""
class LLLoopDetector:
def __init__(self):
pass
def detect(self, ll):
one_step, two_step = ll.head, ll.head
while two_step and ... | true |
82649227d51d64e935b51ad69a50226991271fc8 | rodcoelho/python-practice | /archived_problems/keypad_typing.py | 943 | 4.5 | 4 | #!/usr/bin/env python3
# You are given a string S of alphabet characters and the task is to find its
# matching decimal representation as on the shown keypad.
# Output the decimal representation corresponding to the string. For ex: if
# you are given “amazon” then its corresponding decimal
# representation will be... | true |
5433490f8d54b2ad207913346ec0d932cd01f14c | rodcoelho/python-practice | /archived_problems/majority_element.py | 540 | 4.21875 | 4 | #!/usr/bin/env python3
# Given an array A of N elements. Find the majority element in the array.
# A majority element in an array A of size N is an element that appears
# more than N/2 times in the array.
def get_majority(nums):
for num in nums:
if nums.count(num) > len(nums)/2:
return num
... | true |
c8ebdb3d30eb502efd1fcd80b02fbaead158b245 | Janith123gihan/Python-Files | /function_demo_10.py | 511 | 4.25 | 4 | #recursion
#Recursive function
#a function call itself directly or indirectly
#A function A calls A or (A calls B and B calls A)
def _factorial(n) :
if n==0 or n==1 :
return 1
return n * _factorial(n-1)
def factorial_it(n) :
f = 1
for i in range(1, n+1) :
f *= 1
#end ... | false |
fbab0d8a7401c74c927a633cffaf3ed7a7ff9f51 | varun531994/Python_bootcamp | /prime.py | 202 | 4.375 | 4 | #Prime numbers:
x = int(input("Enter the number:"))
if x % 2 == 0 or x % 3 == 0 or x % 5 == 0 or x % 7 == 0:
print('Its not a Prime number!!')
else:
print(f'{x} is a prime number!')
| true |
74015d2bf08164f68a797dbde1cc600e92a04845 | varun531994/Python_bootcamp | /count_prime.py | 570 | 4.3125 | 4 | #Write a function to print out the number of prime numbers that exist upto and including the given number:
#0 and 1 are not considered prime
def count_primes2(num):
primes = [2]
x = 3
if num < 2:
return 0
while x <= num:
for y in primes:
if x%y == 0:
... | true |
6257bb325f69bf1a4c9299f3d7ea114599eb6f66 | Rptiril/pythonCPA- | /chapter-8-pracrtice-set_functions/pr1_greatestOf3.py | 296 | 4.3125 | 4 | # Write a program using the function to find the greatest of three numbers.
def greatest(n1,n2,n3):
if n1>=n2 and n1>=n3:
return n1
elif n2>=n1 and n2>=n3:
return n2
else:
return n3
print(greatest(3,5,12))
print(greatest(3,55,12))
print(greatest(23,5,12))
| true |
e84977e22dd05a1ec59ee27b0389e9bf86394ec1 | Rptiril/pythonCPA- | /chapter-7-practise_set-loops/pr_Q5_sumofNaturals.py | 207 | 4.21875 | 4 | # Write a program to find the sum of first n natural numbers using a while loop
sum = 0
i = 0
last = int(input("Enter the number till sum is wanted : "))
while(i <= last):
sum+=i
i+=1
print(sum) | true |
7b49d6ec8940e105410b31178fac3d06ad027544 | Rptiril/pythonCPA- | /chapter-6-practice-set_if_logical/pr_4_len.py | 253 | 4.28125 | 4 | # Write a program to find whether a given username contains less than 10 characters or not.
username = input("Enter your username : ")
if len(username) < 10:
print("username contains less than 10 characters.")
else:
print("username accepted.") | true |
287d026500c2fe0ef3f9e675d0aa309cd028fe88 | lcsllima/Data-Structure | /tuplas.py | 254 | 4.125 | 4 | """
(a, b, c) = (1, 2, 3)
print(c) # 3
print(b) # 2
"""
frutas = dict()
frutas['Laranjas'] = 4
frutas['Banana'] = 6
for (k, v) in frutas.items():
print(k, v)
tups = frutas.items()
print(tups) # Nos da uma tupla
print (('d', 'c') > ('b', 'c'))
| false |
30a1094ba833c3b5bf675709ec9a783b0cd1d627 | siddhanthramani/Data-Structures-and-Algorithms | /Using Python/Reading_lines_in_a_file/reading_single_lines.py | 1,760 | 4.4375 | 4 | import turtle
def main():
# creates a turtle graphic window to draw in
t = turtle.Turtle()
# the screen is used at the end of the program
screen = t.getscreen()
filename = input('Enter name of file to be opened : ')
file = open(filename, 'r')
for line in file:
# print(line) # ... | true |
257b0735d0cbc8b15b87002abb0b56dc1dff37db | ManarJN/Automate-the-Boring-Stuff | /ch13_working_with_pdf_and_word/13.1_combine_pdfs.py | 831 | 4.125 | 4 | #! /usr/bin/env python3
# Automate the Boring Stuff
# Chapter 13 - Working with PDF and Word
# Combine PDFs - Combines all the PDFs in the current working directory
# into a single PDF.
import os
import PyPDF2
# gets all the PDF filenames
pdfFiles = []
for filename in os.listdir('.'):
if filename.... | true |
809ab5a8fcad2a8d35e8fa6d171adb125f2459c1 | ManarJN/Automate-the-Boring-Stuff | /ch7_pattern_matching_with_regex/7.2_strong_password_detection.py | 1,297 | 4.65625 | 5 | #! /usr/bin/env python3
# Automate the Boring Stuff
# Chapter 7- Pattern Matching with Regex
# Strong Password Detection - Ensures a password is strong.
import re
# creates password regex
pwLowCase = re.compile(r'[a-z]') # checks for a lowercase letter
pwUpCase = re.compile(r'[A-Z]') # checks for an uppercase let... | true |
1226e7ac786317695fcaa47a97c0b124308b04f4 | harrifeng/leet-in-python | /065_valid_number.py | 1,543 | 4.21875 | 4 | """
Validate if a given string is numeric.
Some examples:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
Note: It is intended for the problem statement to be ambiguous. You should
gather all requirements up front before implementing one.
"""
import unittest
class MyTest(unittest.TestCase):
... | true |
9c6bf0b39e3227009d5046396f9367cb5f9e9ec7 | olaniyanjoshua/Joshua2 | /area_of_a_cylinder_by_Olaniyan_Joshua[1].py | 275 | 4.28125 | 4 | """
This program calculates the area of a cylinder
r is the radius of the cylinder
h is the height of the cylinder
"""
r=float(input("Enter the value of r:"))
h=float(input("Enter the value of h:"))
π=22/7
area=2*π*(r**2)+2*π*r*h
print("The area of the cylinder is",area)
| true |
8aafcbb854fdb84e59890dc14fd9cba79ece4448 | MarvinSilcGit/Alg | /Python/2018-2019/Exercício 7.1.py | 919 | 4.21875 | 4 | p = input("Digite um texto: ")
a = input("Digite outro texto: ")
if p.isalpha() == True and a.isalpha() == True:
if len(p) > len(a):
d = p.find(a, 0)
if d >= 0:
print("a posição encontrada foi a partir da %d° posição" % d)
else:
print("A string... | false |
e2a4f07d0dc2fed12cca426bd5a875edfce1fe15 | laboyd001/python-crash-course-ch4 | /my_pizza_your_pizza.py | 387 | 4.4375 | 4 | #add a new pizza to the list, add a different pizz to friends list, prove you have two lists
pizzas = ['cheese', 'peperoni', 'supreme']
friends_pizzas = pizzas[:]
pizzas.append('mushroom')
friends_pizzas.append('bbq')
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza)
print("\nMy friends fa... | true |
02248233ec1aca43707b0710106f9e3b544b7f81 | YGragon/PythonSelfStudy | /test_case/case79.py | 627 | 4.3125 | 4 | # 题目:字符串排序。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# if __name__ == '__main__':
# str1 = input('input string:\n')
# str2 = input('input string:\n')
# str3 = input('input string:\n')
# print(str1,str2,str3)
# if str1 > str2 :
# str1,str2 = str2,str1
# if str1 > str3 :
# ... | false |
06cb80c8a2f44a1cb955fa474fc74857f43f5012 | erjohnyelton/Tkinter-Tutorial | /entry1.py | 315 | 4.125 | 4 | from tkinter import *
root = Tk()
e = Entry(root, width=50, bd=5)
e.pack()
e.insert(0, "Enter your name")
def myClick():
myLabel = Label(root, text="Hello " + e.get())
myLabel.pack()
myButton = Button(root, text = 'Click here', padx = 50, pady = 50, bd=5,command=myClick)
myButton.pack()
root.mainloop()
| true |
99b9dc56857d1cec6515dcb1c881219efa28224a | Nicomunster/INF200-2019-Exercises | /src/nicolai_munsterhjelm_ex/ex04/walker.py | 1,124 | 4.1875 | 4 | # -*- coding: utf-8 -*-
__author__ = 'Nicolai Munsterhjelm'
__email__ = 'nicolai.munsterhjelm@nmbu.no'
import random
class Walker:
def __init__(self, x0, h):
self.position = x0
self.home = h
self.steps = 0
def move(self):
self.position += random.choice((-1, 1))
self.... | true |
e7da60ad81ee7b373bbad1cadc7e3e20a111639f | spareribs/data-analysis | /Book_one/chapter2/demo/code/2-1 numpy_test.py | 664 | 4.125 | 4 | # -*- coding: utf-8 -*-
import numpy as np # 一般以np作为numpy的别名
a = np.array([2, 0, 1, 5]) # 创建数组
print(a, type(a)) # 输出数组[2 0 1 5] <class 'numpy.ndarray'>
print(a[:3], type(a[:3])) # 引用前三个数组(切片)[2 0 1] <class 'numpy.ndarray'>
print(a.min(), type(a.min())) # 输出a的最小元素0 <class 'numpy.int32'>
a.sort()
print(a, type(a))... | false |
24b4d7e444a55c375cefb55bda23401642f442ab | Zuimengxixia/Web_Selenium | /python学习/Chapter_4_list/4-3练习.py | 1,119 | 4.1875 | 4 | #数到20,使用一个for循环打印数字(包含20)
sums = range(1,21)
for suma in sums:
print(suma)
'''
#创建一个列表,其中包含数字1~1000000,用for打印出来
for sumaa in range(1,1000001):
print(sumaa)
'''
#创建一个列表1~1000000,使用min()和max()函数,在用sum()函数统计和
squares = []
for value in range(1,1000000):
square = value**1
squares.append(square)
print(min(sq... | false |
11213be3a997c4ac49923eb3ebd1f0c559339a82 | eunnovax/python_algorithms | /binary_tree/linked_list_from_tree.py | 1,710 | 4.15625 | 4 | class BTNode():
def __init__(self, data=0, left = None, right=None):
self.left = left
self.right = right
self.data = data
class BinaryTree(): # fills nodes left-to-right using queue
def __init__(self, data=0):
self.root = BTNode(data)
def insert(self, data):
if ... | true |
f29e4742150e064dd40f431cbf96e5f1cb2712dc | Gabrielly1234/Python_WebI | / exercícios senquenciais/questao9.py | 225 | 4.125 | 4 | #Faça um Programa que peça a temperatura em graus Fahrenheit,
# transforme e mostre a temperatura em graus Celsius.
print("temperatura em Fahrenheit:")
temp=int(input())
c1= temp-32
c2= (c1*5)/9
print(c2," graus Celsius") | false |
8a1c26bd443a0ead4124c78a11469a130d996d33 | Gabrielly1234/Python_WebI | /estruturaDecisão/questao2.py | 257 | 4.125 | 4 | #Faça um Programa que peça um valor e mostre na tela se o valor é positivo ou negativo.
print("digite um número:")
num= int(input())
if (num>0):
print(num, "é positivo")
if (num<0):
print(num, "é negativo")
if (num==0):
print("neutro")
| false |
eddfb81c30b6cb9e808f60112cfc8ead1d3e86ad | lenablechmann/CS50xPsets | /pset6/readability.py | 836 | 4.21875 | 4 | # Computes the approximate grade level needed to comprehend some text.
from cs50 import get_string
import re
# Prompts user for text input.
text = get_string("Enter your text: ")
# Counting letters and words.
# Found here https://stackoverflow.com/questions/24878174/how-to-count-digits-letters-spaces-for-a-string-in... | true |
186f3b8180e6cef24c5e14b53606b265e93af50c | mikeodf/Python_Line_Shape_Color | /ch4_prog_3_repositioned_star_polygon_1.py | 2,207 | 4.28125 | 4 | """ ch4 No.3
Program name: repositioned_star_polygon_1.py
Objective: Draw a series of stars each with their own start position.
Keywords: polygon, anchor point, star
============================================================================79
Comments:Each separate star is drawn relative to a pair variables,
x... | true |
ff27021cd885bd28af1946db9cb3e62932f0fdcc | mikeodf/Python_Line_Shape_Color | /ch6_prog_3_text_width_overflow_1.py | 1,096 | 4.5 | 4 | """ ch6 No.3
Program name: text_width_overflow_1.py
Objective: Draw text onto the canvas at a chosen location.
Keywords: canvas,text
============================================================================79
Comments: The text is written starting at co-ordinate location (x,y) = 200,20.
The "width=200" is t... | true |
64d5c404615ae84d6cf146c91d07e4e65bc16b82 | mikeodf/Python_Line_Shape_Color | /ch1_prog_3_line_styles_1.py | 1,511 | 4.21875 | 4 | """ ch1 No.3
Program name: line_styles_1.py
Objective: Four straight lines, different styles on a canvas.
Keywords: canvas, line, , color, dashed line, default
============================================================================79
Comments: When drawing lines you MUST specify the start and end points.
Dif... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.