blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ee31c03c140160d5ec47e21eccfa56388aa93343 | Nduwal3/Python-Basics-II | /soln10.py | 926 | 4.34375 | 4 | # Write a function that takes camel-cased strings (i.e. ThisIsCamelCased), and converts them to snake case (i.e. this_is_camel_cased).
# Modify the function by adding an argument, separator, so it will also convert to the kebab case (i.e.this-is-camel-case) as well.
def snake_case_to_camel_case(camel_cased_string):
... | true |
2dd2cffad194197ca43e70ed7ea2bd26a802ddf3 | Nduwal3/Python-Basics-II | /soln14.py | 719 | 4.40625 | 4 | # Write a function that reads a CSV file. It should return a list of dictionaries, using the first row as key names, and each subsequent row as values for those keys.
# For the data in the previous example it would
# return: [{'name': 'George', 'address': '4312 Abbey Road', 'age': 22}, {'name': 'John', 'address': '54... | true |
e278cf23b50a47545b4032721cdf8bbe043438c7 | Nduwal3/Python-Basics-II | /soln12.py | 306 | 4.34375 | 4 | # Create a function, is_palindrome, to determine if a supplied word is
# the same if the letters are reversed.
def is_palindrome(input_string):
if( input_string == input_string[::-1]):
return True
else:
return False
print(is_palindrome("honey"))
print(is_palindrome("rotator"))
| true |
9e34b34cff0ce614ca57b94da8f64d4c8f1bf31e | yueyue21/University-of-Alberta | /INTRO TO FNDTNS OF CMPUT 2/lab2/lab2(3).py | 492 | 4.125 | 4 | import random
num=random.randint(1,20)
print(num)
count = 0
while (count<6):
a = int(input('Enter a guess (1-20):'))
if a >20 or a<1:
print ('That number is not between 1 and 20!')
elif a == num:
print('Correct! The number was',num)
break
elif a > num:
print('to... | true |
1b673324f7118fa8cd04c7c9b8f99f7f61c214e7 | liuzhijielzj/Python-100-Days | /Day16-20/notes/d16-20/itertools.py | 212 | 4.1875 | 4 | """
迭代工具 - 排列 / 组合 / 笛卡尔积
"""
import itertools
for permutation in itertools.permutations('ABCD'):
print(permutation)
itertools.combinations('ABCDE', 3)
itertools.product('ABCD', '123') | false |
4223f00115a2bc41b84ccf139ff8cda8e4c2d19c | liuzhijielzj/Python-100-Days | /Day01-15/note/d2/variable.py | 1,604 | 4.28125 | 4 | #变量和类型
#整型, 处理任意大小的整数
print(0b100)
print(0o100)
print(0x100)
#浮点
print(1.2345e2)
#字符串
#原始字符串表示法、字节字符串表示法、Unicode字符串表示法
print('''
this is multi-line string
line 2
''')
#布尔
print(True)
print(False)
#复数
print(3 + 5j)
'''
变量命名:
1. 字母(广义的Unicode字符,不包括特殊字符)
、数字和下划线构成,数字不能开头.
2. 大小写敏感(大写的a和小写的A是两个不同的变量)。
3. 不要跟关键字(有特殊含义的单... | false |
d8365d5b438fd633fadee3c0e2a7b51c4014ca6f | margaridav27/feup-fpro | /Plays/Play02/hypotenuse.py | 230 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 23:30:55 2019
@author: Margarida Viera
"""
import math
def hypotenuse(n):
hypotenuse = math.sqrt(n**2 + n**2)
return round(hypotenuse, 2)
n = float(input())
print(hypotenuse(n)) | false |
b4222698736557531774de0479c227027e99c069 | spiridonovfed/homework-repository | /homework7/hw1.py | 1,841 | 4.3125 | 4 | """
Given a dictionary (tree), that can contains multiple nested structures.
Write a function, that takes element and finds the number of occurrences
of this element in the tree.
Tree can only contains basic structures like:
str, list, tuple, dict, set, int, bool
"""
from typing import Any
# Example tree:
example... | true |
50bc746e10b6ecf40fde69ffb7936620955b6dfb | spiridonovfed/homework-repository | /homework3/task01.py | 1,097 | 4.4375 | 4 | """In previous homework task 4, you wrote a cache function that remembers other function output value.
Modify it to be a parametrized decorator, so that the following code::
@cache(times=3)
def some_function():
pass
Would give out cached value up to `times` number only.
Example::
@cache(times=2)... | true |
9f9af6b0fd90265aab28477a233ec297c3952033 | blackplusy/0330 | /例子-0414-02.字符串操作2.py | 827 | 4.3125 | 4 | #coding=utf-8
#find和index
a='c'
str1='aabbcc'
print(str1.find(a))
a='d'
print(str1.find(a))
a='b'
print(str1.index(a))
a='d'
#print(str1.index(a))
#isalpha()和isdigit()
a='simida'
print(a.isalpha())
a='321simida'
print(a.isalpha())
a='123'
print(a.isdigit())
a='123a'
print(a.isdigit())
#upper()和low... | false |
48827e9313f27e6a34ec3a52251e9be52e7a4902 | alanphantomz/111py | /turtle2/estado_curso.py | 2,081 | 4.125 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/python3
from turtle import Screen, Turtle
def dibuja_pedazo(radio, porcentaje, tortuga, titulo):
# Dibujo de la linea
angulo = 360 * porcentaje / 100
tortuga.left(angulo)
tortuga.forward(radio)
tortuga.backward(radio)
# Escribir el texto
tortuga.penup()
... | false |
fb53aa7185a230fed83e98c64cb4928874059e5f | samirazein20/Week2_Challenge1 | /checkingbirth.py | 439 | 4.46875 | 4 | from datetime import datetime
# Prompting the user to enter their birth year
print('Enter Your Birth Year')
# Capturing the entered year from the keyboard
birthyear = int(input())
# getting the current year as an integer
thisyear = int(datetime.now().year)
# getting the persons age
diffyear = thisyear - birthyear
... | true |
4649d517881faf014a6d3ed6bbeb2afcb1fa2130 | JuBastian/ClassExercises | /exercise n+1.py | 405 | 4.125 | 4 | cost_limit = 5000000.0
duration_limit_in_years = 3.0
print("Please input the cost of the project")
cost = float(input())
print("Please input the duration of the project in years")
duration_in_years = float(input())
if (cost <= cost_limit) and (duration_in_years <= duration_limit_in_years):
print("Start the project"... | true |
9031ec7be69abaffa5fc9c4fb93c48b712b8e085 | ayush-pradhan-bit/object-oriented-programming | /lab 1-4/arrangenumbers_0_4.py | 2,488 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
lab2 - arrangenumbers_0_4.py
Task:
-A random list of 3x3 is provided
-user provides a value to swap
-once the random list is equal to check list user have to input value
-prints "Good work" once match is found
Created on Sat Jan 23 23:15:55 2021
@author: Ayush Pradhan
import random- Genera... | true |
02df24db28632512c6bef0f2013a68ee741649af | dingleton/python_tutorials | /generators1_CS.py | 1,454 | 4.46875 | 4 | # -*- coding: utf-8 -*-
"""
Generators - sample code to test Python Generators
Taken from Corey Schafers You Tube Tutorial on Python Generators
"""
def square_numbers_1(nums):
""" function to accept a list of numbers and
return a list of the square of each number
"""
result = []
for i in nums:
... | true |
153b066ee5a40a1c8548155461352cf843e944ec | Memory-1/PythonTutorials | /1. Data Types/Projects/Project 1 - Tip Calculator.py | 845 | 4.15625 | 4 | """
Tip Calculator
In this project you will make a simple tip calculator. The result should be the bill total + the tip.
It will take two inputs from the user. I use input() which will prompt you to enter something in.
Take those two inputs. Divide the percentage by 100 to get a decimal number and then
This project... | true |
d34f89ff9879cafb023df5d9e5f3924570555ee7 | Memory-1/PythonTutorials | /1. Data Types/Examples/Collections/Dictionaries.py | 1,065 | 4.34375 | 4 | """
Dictionaries are key value pairs. They're great for storing information for a particular thing and being able to quickly
access it without even knowing it's index
Once again, you can store anything for the value in the key-value pair, but the key must be either a string or an int
"""
Dictionary_1 = {} # ... | true |
42fe45920032505b7a2832b0d2f584767f9e6dc8 | 22zagiva/1-1_exercises | /mpg.py | 716 | 4.34375 | 4 | #!/usr/bin/env python3
# display a welcome message
print("The Miles Per Gallon program")
print()
# get input from the user
miles_driven= float(input("Enter miles driven:\t\t"))
gallons_used = float(input("Enter gallons of gas used:\t"))
miles_gallon_cost = float(input("Enter cost per gallon:\t\t"))
# calc... | true |
68fc8bd40c7f35370cb5dbf1e7bf452e226f6a29 | mkramer45/PythonCluster3 | /Ch16_DefaultFunctionParameters.py | 287 | 4.125 | 4 | def optional_parameter(first_parameter = 0): # defining our function ... argument is we are defaulting first_param to 0
print(first_parameter + 8) # here is our function's command, where we are telling to print the first param of the argument + an integer (8)
optional_parameter() | true |
8a70f50cab87b0c271136685d2a1ac76cb336270 | Masoninja/python | /turtle/plot-circle-list-mka.py | 2,552 | 4.25 | 4 | '''
Test this.
https://tritech-testsite.smapply.io/
python-circle-list-assignment.py
Get the code: 10.183.1.26 code python
Plot circle data using python
- Use your data
- Change the background color
- Change the graph line colors
- Change the plot line color
- Change the plot dot color
- Label the graph with text Plot... | true |
07885aced3e5dda43b0afc7989bdabf4e4c95cac | chenwensh/python_excrise | /graphic_test.py | 776 | 4.15625 | 4 | #This program is to test the graphic codes from the book <Python for Kids>.
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
from tkinter import *
import random
def hello():
print("hello there")
def random_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + ran... | true |
031d8fc9ce91cf12de432b2c1a1168e9cd9cb70e | lucasjurado/Alura-IO | /testa_escrita.py | 942 | 4.1875 | 4 | # Sempre que abrimos algum arquivo em modo w, o Python vai truncar o arquivo, isto é, limpará seu conteúdo.
# Para adicionar conteúdo a um arquivo sem apagar o que já está escrito, temos que utilizar o modo a.
# (+) --> mode de atualização do arquivo
arquivo_contatos = open('contatos-lista.csv', encoding='latin_1', mo... | false |
090577072b196397dc6bcf7f44a4bbb7437c8e41 | RobertMcNiven/Vector-Calculator | /vector_calculatorV2.py | 1,483 | 4.3125 | 4 | import math
try:
amount_of_vectors = int(input('How many vectors would you like to add?' + '\n'))
except:
print('Please enter an integer greater than 0')
exit()
def vector_physics():
x_component = 0
y_component = 0
for numbers in range(1, amount_of_vectors+1):
vector_direct... | true |
a76aaecaa2de87366eda6112aa83609b61711d1f | standrewscollege2018/2020-year-12-python-code-CeeRossi | /Book store/yee.py | 2,073 | 4.15625 | 4 | #This program is designed so that a user can add/ delete book titles from a list of books
print("Designed and built by Caleb Rossiter")
print("Version 1")
#User login that retains usser account after program closed
welcome = input("Do you have an acount? y/n: ")
if welcome == "n":
while True:
username = ... | true |
b25911f0ff7e94c38b08bdc0eb3895e597f4753c | Phoenix795/learn-homework-1 | /3_for.py | 1,865 | 4.25 | 4 | """
Домашнее задание №1
Цикл for: Оценки
* Создать список из словарей с оценками учеников разных классов
школы вида [{'school_class': '4a', 'scores': [3,4,4,5,2]}, ...]
* Посчитать и вывести средний балл по всей школе.
* Посчитать и вывести средний балл по каждому классу.
"""
from random import randint
def mea... | false |
c1fc96e1ddbfa31ed8fb09dc65468ccfa6c3b8c0 | ozmaws/Chapter-3 | /Project3.8.py | 626 | 4.21875 | 4 | first = int(input("Enter a positive number: "))
second = int(input("Enter a second positive number: "))
if first > second:
larger = first
smaller = second
else:
larger = second
smaller = first
while smaller != 0:
print("")
remainder = larger % smaller
print("The remainder of dividing " + str(la... | true |
c6d30d97e6d14df2e0862bf5d3e7928e20c310a4 | terchiem/Cracking-the-Coding-Interview-Python | /01 - Arrays and Strings/1-8 zero_matrix.py | 915 | 4.28125 | 4 | """
Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0,
its entire row and column are set to 0.
"""
def zero_matrix(matrix):
"""Returns the input matrix where if an element is 0, its entire row and
column are set to 0.
>>> zero_matrix([[1,1,0],[1,1,1],[1,1,1]])
[[0, 0, 0], ... | false |
bbf0fd898240ed567e7139516076256428059ec1 | terchiem/Cracking-the-Coding-Interview-Python | /01 - Arrays and Strings/1-4 valid_palindrome.py | 985 | 4.25 | 4 | """
Palindrome Permutation: Given a string, write a function to check if it is a
permutation of a palindrome. A palindrome is a word or phrase that is the same
forwards and backwards. A permutation is a rearrangement of letters. The
palindrome does not need to be limited to just dictionary words.
"""
def valid_palind... | true |
40c5ae75c684ee80cb4f881f91feed0304471a4e | acwajega2/googlePythonInterview | /app1.py | 628 | 4.3125 | 4 | #### MAKING A CHANGE APP
#----GET THE NUMBER OF COINS GIVEN CHANGE AS 31 CENTS
#---- 1 quarter ==>>>>>>(25 cents)
#---- 1 nickel ==>>>>>>(5 cents)
#-----1 pennies ==>>>>>(1 cent)
#------1 dime ==>>>>>(10 cents)
#EXAMPLE--GIVEN 31 cents-----you give back 3 coins in (1 quarter, 1 nickel and i pennies)
def num_coins(ce... | true |
3917f66cba10e3cf97376fcffcae00f0847db0d8 | AndreiR01/Sorting-Algorithms | /QuickSort.py | 2,404 | 4.375 | 4 | from random import randrange, shuffle
#https://docs.python.org/3/library/random.html#random.randrange <-- Documentation
#QuickSort is a recursive algorithm, thus we will be having a base case and a recursive function
#We will sort our list in-place to keep it as efficient as possible. Sorting in-place means that we kee... | true |
9875a570ed15b9f49ce8a719cc4f50cbd6dc5cc8 | TiarahD18/cs | /week3/test.py | 1,539 | 4.15625 | 4 | #!/usr/bin/env python
#print ("Hello CSSI")
#print ("also Hello CSSI")
#print ("also also Hello CSSI")
# print("Hello CSSI")
#name = "Bill"
#name = 55
#print(name)
#name = raw_input("Enter your name: ")
#print("Hi there...")
#print(name)
#print("na " * 16)
#print("BATMAN")
#print("Pow!" * 3)
#user_input = raw_input(... | false |
bc09d6da5d27ac66704fa42eedbc9e48ff596698 | chavisam/PythonListExercies | /exercises/04.1-count_on/app.py | 222 | 4.125 | 4 |
my_list = [42, True, "towel", [2,1], 'hello', 34.4, {"name": "juan"}]
#your code go here:
hello = []
for i in my_list:
print(type(i))
if type(i) == list or type(i)== dict:
hello.append(i)
print(hello)
| false |
a3cbf087fda96dbaa949661214f09e47f66e06f2 | AmanCSE-1/Operating-System | /CPU Scheduling Algorithm/Shortest Job First Algorithm (SJF).py | 2,048 | 4.125 | 4 | # Shortest Job First Program in Python
# Function which implements SJF algorithm.
def SJF(process, n):
process = sorted(process, key=lambda x:x[1]) # Sorting process according to their Burst Time
wait= 0
waitSum, turnSum = 0,0 # Initializng Sum of Wait-Time -> 0... | true |
268adf46f20f4a00e337be101af038282406a9fc | RakshithHegde/python-basics | /stringMethods.py | 1,181 | 4.4375 | 4 | #strings can sliced and we can return a range of characters by using slice
#specify the start index and end, seperated by a colon, to return part of a string
b="Hello,World!"
print(b[3:6])
c="Hello,World!"
print(c[:6])
#negative indexing
b = "Hello,World!"
print(b[-3:-1])
#modifying Strings
#Uppercase
a= "abcdoncw... | true |
9398f22588002160b3bc6ae7d680075e2bd0f7c0 | GokulShine12/PYTHON-INTERN | /TASK 8.py | 1,602 | 4.3125 | 4 | # 1. List down all the error types - using python program
#Syntax error
print "True"
#Division by zero error
try:
print(10/0)
except ZeroDivisionError:
print("Division by zero error")
#Key error
try:
a={'cse-a':'65','cse-b':'60'}
a['cse-c']
except KeyError:
print("Key not found err... | true |
241aff3e501418a3d0e87aa39432435709828362 | JaceTSM/Project_Euler | /euler003.py | 742 | 4.21875 | 4 | # !/Python34
# Copyright 2015 Tim Murphy. All rights reserved.
# Project Euler 003 - Largest Prime Factor
'''
Problem:
What is the largest prime factor for a given number N.
Input:
First line contains T, and then the following T lines contain N
for the given test case.
Constraints:
1 <= T <= 10
1 <= N <= 10**1... | true |
303f564f40fec53155e280186fb58ca0c16e8e53 | calvin0123/sc-projects | /stanCode_Projects/weather_master/quadratic_solver.py | 947 | 4.28125 | 4 | """
File: quadratic_solver.py
Name: Calvin Chen
-----------------------
This program should implement a console program
that asks 3 inputs (a, b, and c)
from users to compute the roots of equation
ax^2 + bx + c = 0
Output format should match what is shown in the sample
run in the Assignment 2 Handout.
"""
import math... | true |
fd10cfead6759ac05de9cb364acb40e527649d04 | liuyonggg/learning_python | /leetcode/hindex.py | 1,506 | 4.25 | 4 | '''
For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3.
Note: If t... | true |
2fc8c5777310146e6f92201945718056baa30eeb | PrajjwalDatir/CP | /CodeChef/ExamCodechef/3Q.py | 2,190 | 4.1875 | 4 | # Python3 program to find minimum edge
# between given two vertex of Graph
import queue
import sys
INT_MAX = sys.maxsize
# function for finding minimum
# no. of edge using BFS
def minEdgeBFS(edges, u, v, n):
# u = source
# v = destination
# n = total nodes
# visited[n] for keeping track
# of visit... | true |
d6bb4126ee3fd4376a9c61bb0fa05abce3f5b9f8 | PrajjwalDatir/CP | /gfg/mergesort.py | 529 | 4.1875 | 4 | # merge sort
# so we need two functions one to break and one to merge
# divide and conqeror
def merge():
pass
def mergeSort(arr):
if len(arr) <= 1:
return arr
L =
def printList(arr):
for i in range(len(arr)):
print(arr[i], end =" ")
print()
# driver code to test the above code
... | true |
c4ce8cb096120452a9e25f7d1fb86f9a4ffb2570 | PrajjwalDatir/CP | /gfg/jug1.py | 2,795 | 4.1875 | 4 | # Question 1
"""
so we have linked list with data only equal to 0 , 1 or 2 and we have to sort them in O(n) as I think before prajjwal knows the answer of this question
"""
#so first we need linked list to start withs
class Node:
"""docstring for Node"""
def __init__(self, data):
self.data = data
self.next = Non... | true |
0b4e4d3f7fdcf1d6cd0f172a91df737821231149 | tzvetandacov/Programming0 | /n_dice.py | 347 | 4.125 | 4 | #dice = input ("Enter a digit")
#from random import randint
#result = randint (1, 6) + int(1)
#print (result)
from random import randint
n = input ("Enter sides:")
n = int (n) # This can be done as shown below
result1 = randint(1, n) # Option: result = randint (1, int(n))
result2 = randint (1, n)... | true |
b4955b561872e3174004ffc19fb0325288874766 | dennohpeter/Python-Projects | /sleep.py | 769 | 4.34375 | 4 | #!/usr/bin/python
##display a message based to the user based on
##the number of hours of sleep the user enters for the previous night.
##Use the following values as the basis for the decisions:
##0-4 hours of sleep- Sleep deprived!,
##more than 4 but less than 6- You need more sleep,
##6 or more but less than 8- Not q... | true |
d42d87509e567f4917fdac8a420a0594a1bbfb89 | riteshrky/DAY-2 | /DAY 5.py | 2,966 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
def say_hello(name):
print("hello",name)
print ("how are you ")
# In[2]:
say_hello("Jam")
# In[3]:
# write a function to print sum of three numbers
def sum_of_num(x,y,z=10):#x,y are positional argumnets, and z is kerywords
print(x+y+z)
# In[4]:
s... | false |
67371e37e8ffeb9588ff24f5249b0da36af0cf55 | wjingyuan/QuickStart | /Python开发入门14天集训营_练习题/02_19.py | 1,583 | 4.125 | 4 | '''
写代码,有如下元祖,请按照功能要求实现每一个功能。
tu = ('alex', 'eric', 'rain')
1. 计算元祖长度并输出
2. 获取元祖的第2个元素并输出
3. 获取元祖的第1-2个元素并输出
4. 请使用for输出元祖的元素
5. 请使用for、len、range输出元祖的索引
6. 请使用enumerate输出元祖元素和序号(序号从10开始)
'''
tu = ('alex', 'eric', 'rain')
print(tu)
# 1. 计算元祖长度并输出
print('第1题:计算元祖长度并输出')
length = len(tu)
print('元祖的长度为:%d \n' % length)
... | false |
9ae5fe36a1421a9676dcd12a84348039f03a42e6 | juliandunne1234/benchmarking_g00267940 | /bubbleProject.py | 540 | 4.25 | 4 | def bubbleSort(arrays):
n = len(arrays)
for outer in range(n-1, 0, -1):
#inner loop runs one less time for each iteration to stay within loop boundaries
for inner in range(0, outer, 1):
#if the inner value is greater than value to the right then swap
if arrays[inner] > ar... | true |
3f1bd879d5b85a6d7f23b292eae0bf359697f047 | stayhungry-cn/-Python | /04 数据类型之数字.py | 1,218 | 4.34375 | 4 | #4.1 整型与浮点型
# (1) 整型:整数,包括正整数与负整数
a = 5
b = -5
# (2) 浮点型: 带小数点的数
c = 3.14
d = 0.618
# 4.2 算术运算符
# (1) 加 : +
#print(3+2)
# (2) 减 : -
#print(5-3)
# (3) 乘 : *
#print(6*3)
# (4) 除: /
#print(5/3)
# (5) 取模(取余数) : %
#print(5%2)
#print(97%3)
#print(4%2)
# (6) 取整(向下取整) //
#print(5//2)
#print(9//2... | false |
6fa110d87c9e35ff278d4ea190fbac15b85a2594 | Jay206-Programmer/Technical_Interview_Practice_Problems | /Uber/Count_Invalid_parenthesis.py | 581 | 4.5 | 4 |
#* Asked in Uber
#? You are given a string of parenthesis. Return the minimum number of parenthesis that would need to be removed
#? in order to make the string valid. "Valid" means that each open parenthesis has a matching closed parenthesis.
#! Example:
# "()())()"
#? The following input should return 1.
# ")"... | true |
5d7a2b7f00bc02d494f1c55d6eb3263d3022ddae | Mitterdini/Learning-The-Hard-Way | /Python/Scripts/string_formatting.py | 455 | 4.1875 | 4 | float = 12.5
inte = 6
strinly = "ight"
#the 3 ways of placing a variable in a string
print(f"float: {float} ; integer: {inte}; string: {strinly}") #method 1: using 'f' before the string
print("\n\nfloat: %f ; integer: %d; string: %s" % (float,inte,strinly)) #method 2: using '%' signs
words = "lets check mul... | true |
6d96b0e936f1a8037f50b4a766a44b81fc82905e | Tarundatta-byte/PrintingShapes.py | /main.py | 1,393 | 4.3125 | 4 | import turtle
#this assigns colors to the design
#example: col=('red','blue','green','cyan','purple')
col=('red','blue','yellow','green')
#creating canvas
t=turtle.Turtle()
#here we are defining a screen and a background color with printing speed.
screen=turtle.Screen()
screen.bgcolor('black')
t.speed(50)
#this range ... | true |
cdbd0ef66589e14f6999d45dab55b6ef9bdb9356 | NikhilCodes/DSA-Warehouse | /Algorithms/Sort/Bubble Sort/src.py | 512 | 4.25 | 4 | """
ALGORITHM : Bubble Sort
WORST CASE => {
PERFORMANCE: O(n^2)
SPACE: O(1)
}
"""
def bubble_sort(arr):
size = len(arr)
if size < 2:
return arr
for i in range(size-1, 0, -1):
for j in range(len(arr[:i])):
if arr[j] > arr[j+1]:
... | false |
df4658ae9d91eb1e7456a4d750081fa04f9f7b9b | WilAm1/Python-Beginner-Projects | /GuessTheNumber/main.py | 1,219 | 4.125 | 4 | """What’s My Number?
Between 1 and 1000, there is only 1 number that meets the following criteria:
The number has two or more digits.
The number is prime.
The number does NOT contain a 1 or 7 in it.
The sum of all of the digits is less than or equal to 10.
The first two digits add up to be odd.
... | true |
d8e84e1b4c4222be341e3c4fdb54314272b62cf6 | semihPy/Class4-PythonModule-Week2 | /assignment1Week2.py | 2,676 | 4.25 | 4 | # 1.lucky numbers:
# Write a programme to generate the lucky numbers from the range(n).
# These are generated starting with the sequence s=[1,2,...,n].
# At the first pass, we remove every second element from the sequence, resulting in s2.
# At the second pass, we remove every third element from the sequence s2, re... | true |
6393fe1c68f00f2c4e5dfb79d0b56ea80ca6d486 | nachonavarro/RSA | /rsa.py | 1,531 | 4.4375 | 4 | """
RSA is a public cryptosystem that relies on number theory.
It works for both encryption of messages as well as digital
signatures.
The main two functions to encrypt and decrypt a message.
For simplicity, we will assume that the message is already
transformed into a number ready for RSA.
It should be the case that... | true |
03317e6ab31f0821ececa4b0d41189df166162ee | RyanGoh83/flask-blog | /sql.py | 710 | 4.125 | 4 | # sql.py- Script to create db and populate with data
import sqlite3
#creates a new db if it doesn't already exist
with sqlite3.connect("blog.db") as connection:
#get a cursor obj used to execute SQL commands
c = connection.cursor()
#create the table
c.execute("""CREATE TABLE posts (title TEXT, post... | true |
5ed05b14f3c0e05310101ac1f181cb5276ccad4c | paulngouchet/AlgoChallenge | /reverse.py | 807 | 4.125 | 4 |
''' Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
to reverse
do abs to find abs value
convert integer to string
loop through list of characters backward - append in new string
convert to number
do number * initial_number/abs_number'''
def reverse(initial):
if initial == 0 or (initial < -... | true |
b5eccdaa43cde7a48a423ec1667f553d6cc3320f | centos-zhb/PythonPractice | /字符串/Teststring.py | 766 | 4.15625 | 4 | # 0、a,b为参数。从字符串指针为a的地方开始截取字符,到b的前一个位置(因为不包含b)
var1 = "hello world"
print(var1)
# 1、如果a,b均不填写,默认取全部字符。即,下面这两个打印结果是一样的
print(var1[: ]) # hello world
print(var1) # hello world
# 2、如果a填写,b不填写(或填写的值大于指针下标),默认从a开始截取,至字符串最后一个位置
print(var1[3: ]) # lo world
# 3、如果a不填写, b填写,默认从0位置开始截取,至b的前一个位置
print(var1[: 8]) # hello w... | false |
b565ba88ac04a611d00e8b8c8746da09a1b14b66 | nakuyabridget/pythonwork | /docstrings.py | 802 | 4.21875 | 4 | def print_max(x, y):
'''prints the maximum of two numbers.
The two values must be integers.'''
#conver to integers, if possible
x = int(x)
y = int(y)
if x > y:
print(x, 'is maximum')
else:
print(y, 'is maximum')
print_max(3,5)
print(print_max.__doc__)
#Autor: Nakuya bridget, a young aspiring software e... | true |
fcd6a113f571de3429020150f1003dfc4a9f73ff | Hadirback/python_algorithms_and_data_structures | /homework_3_pads/task_7.py | 846 | 4.125 | 4 | '''
7. В одномерном массиве целых чисел определить два наименьших элемента.
Они могут быть как равны между собой (оба минимальны), так и различаться.
'''
import random
start = 0
end = 10
num_array = [random.randint(start, end) for _ in range(5)]
first_min_value = end
second_min_value = end
for num in num_array:
... | false |
de1424f155303ecd939704f73098f122dfe7a366 | Hadirback/python_algorithms_and_data_structures | /homework_1_pads/task_8_python.py | 487 | 4.21875 | 4 | '''
8. Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого).
'''
a = int(input('Введите 1 число: '))
b = int(input('Введите 2 число: '))
c = int(input('Введите 3 число: '))
mid_value = None
if b < a < c or c < a < b:
mid_value = a
elif a < b < c or c < b < a:
mid... | false |
ca6476ab024b7003fcbc0b7180b38437fc4e7388 | shwarma01/Projects | /Dynamic Programming/Memoization/Fibonacci/main.py | 628 | 4.15625 | 4 | """
Calculate nth fibonacci number using recursion
"""
# Brute force method
def fib(n):
if n == 1 or n == 2:
return 1
return fib(n - 1) + fib(n - 2)
print("Brute force method")
print(fib(3))
print(fib(5))
print(fib(7))
# print(fib(100)) # Takes too long
# Memoization method
def fib(n):
memo =... | false |
f6c3d01cca78c2fcd4d5841d712e4d1773d6da4b | vadlamsa/book_practice | /8_5.py | 553 | 4.40625 | 4 | Write a function which removes all punctuation from the string, breaks the string into a list of words, and counts the number of words in your text that contain the letter “e”.
import string
def remove_punct(s):
s_without_punct=""
print(string.punctuation)
for letter in s:
if letter not in string.... | true |
e3a0fadad25c29f8d93f0985d137aef083add085 | ZhangYajun12138/unittest | /work_hard/ex40.py | 488 | 4.1875 | 4 | # coding:utf-8
# 40.字典
cities = {"CA":"Francisco","MI":"Detroit","FL":"Jacksonville"}
cities["NY"] = "New York"
cities["OR"] = "Portland"
def find_city(themap,state):
if state in themap:
return themap[state]
else:
return "Not found."
cities["_find"] = find_city
while True:
print("State?(... | false |
c6adeec162ad6951525a469599a89f78777caad7 | cklwblove/python-100-days-source-code | /ls5/demo2.py | 331 | 4.28125 | 4 | """
可变参数函数定义
"""
# 在参数名前面的*表示args是一个可变参数
# 即在调用 add 函数时,可以传入 0 个或多个参数
def add(*args):
total = 0
for val in args:
total += val
return total
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
| false |
d8ece86d297203d15d4eb5dc2d13679142d3c8b3 | DK2K00/100DaysOfCode | /d16_string_reversal.py | 248 | 4.375 | 4 | #Function to reverse string using recursion
def reverse(s):
#To determine length of string
length = len(s)
if(length <= 1):
return(s)
#Recursion
return(s[length-1] + reverse(s[0:length-1]))
reverse("helloworld")
| true |
d6bc4d7b875d10e316da2c8ceecc15266b0e0873 | DK2K00/100DaysOfCode | /d28_quick_sort.py | 855 | 4.15625 | 4 | #Function to perform quick sort
def quick_sort(arr):
sort_help(arr,0,len(arr)-1)
def sort_help(arr,first,last):
if(first < last):
splitpt = partition(arr,first,last)
sort_help(arr,first,splitpt-1)
sort_help(arr,splitpt+1,last)
def partition(arr,first,last):
pivot = arr[first]
... | true |
e3ee965a1e35069eaa7b73ce79a2a324fe3ff381 | kesarb/leetcode-summary-python | /practice/a/min_cost_to_connect_ropes.py | 1,786 | 4.125 | 4 | """ Min Cost to Connect Ropes
https://leetcode.com/problems/minimum-cost-to-connect-sticks (premium)
Given n ropes of different lengths, we need to connect these ropes into one rope.
We can connect only 2 ropes at a time. The cost required to connect 2 ropes is
equal to sum of their lengths. The length of this conn... | true |
a6537888abbcc6264728190fc6f35619dce2c5fb | kesarb/leetcode-summary-python | /practice/solution/0380_insert_delete_getrandom_o1.py | 1,597 | 4.1875 | 4 | import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.value_list = []
self.value_dict = {}
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already... | true |
9d3b7d788120939cdb2f03fa05f60232d4ccbe23 | sideris/putils | /python/putils/general.py | 1,267 | 4.34375 | 4 | import collections
from math import factorial
def binomial_coefficient(n, m):
"""
The binomial coefficient of any two numbers. n must always be larger than m
:param n: Upper coefficient
:param m: Lower coefficient
:returns The number of combinations
:rtype integer
"""
assert n > m
return fac... | true |
105602746fbb314cf0a7f8864fabc64e1822ab05 | Zaela24/CharacterCreator | /Gear/MiscItems/Items.py | 959 | 4.28125 | 4 | class Items:
"""Creates general class to contain miscelaneous items"""
def __init__(self):
self.name = "" # name of item
self.description = "" # description of item
self.price = 0 # assumed in gold piece
self.weight = 0
## THE FOLLOWING IS A DANGEROUS METHOD AND THUS HAS A P... | true |
d0b342dd97167f07e2d39c6ff9fd68aa960890cf | luiscape/hdxscraper-wfp-mvam | /collector/utilities/item.py | 828 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
ITEM:
-----
Utility designed to print pretty things to the
standard output. It consists of a dictionary
that is called as a function with a key. A
string is then returned that helps format
terminal output.
'''
from termcolor import colored as color
def item(key='bullet')... | true |
39beb68ff4681ae4037796c2bc7f60dc9db1e0a7 | Delmastro/Cryptography | /decryptAffine.py | 1,373 | 4.125 | 4 | def decrypt_affine(a, b, ciphertext):
"""Function which will decrypt an affine cipher.
Parameters:
a (int): A random integer given by "a" between 0 and the length of the alphabet
b (int) : A random integer given by "b" between 0 and the length of the alphabet
ciphertext (str): The ... | true |
bf379b22b2da3257d520c2bbd1d9ead801bee46b | kaixiang1992/python-learning | /codes/26-tuple_demo.py | 2,657 | 4.25 | 4 | '''
@description 2019/09/11 22:53
'''
# 什么是元祖:
# 元祖的使用与列表相似。不同之处在于元祖是不可修改的,元祖使用圆括号,而列表使用中括号。
# 定义元祖
# 1.使用逗号的方法:
# a_tuple = 1,2,3
# print(a_tuple) # (1, 2, 3)
# print(type(a_tuple)) # tuple
# 2.使用圆括号的方式
# a_tuple = (1,2,3)
# print(a_tuple) # (1, 2, 3)
# print(type(a_tuple)) # tuple
# 3.使用tuple函数
# list => tupl... | false |
a78ee6d38a07bdaa1a66dc000a39bbbc144b346e | amalageorge/LearnPython | /exercises/ex16.py | 637 | 4.125 | 4 | from sys import argv
script, filename = argv
print "we are going to erase %r" %filename
print "if u dont want that hit CTRL-C(^C)"
print "if u do want that, hit RETURN"
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye"
target.truncate()
print "Now i'm going to ... | true |
cb26fd3648f924a405f910dd8a846b650001d79c | kumailn/Algorithms | /Python/Reverse_Only_Letters.py | 1,002 | 4.21875 | 4 | #Question: Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
#Solution: Remove all non letter chars and then reverse string, then traverse original string inserting non letter chars back into original indexes
#Time ... | true |
f024a120ea0b7d5d54cb63c1b7b50e960a88b9cf | kumailn/Algorithms | /Python/Merge_Linked_List.py | 1,024 | 4.28125 | 4 | from _DATATYPES import ListNode
#Question: Given two sorted linked lists, join them
#Solution: Traverse through both lists, swapping values to find smallest, then working backwards
#Difficulty: Easy
def mergeList(a, b):
#If the first node is null, or the second node exists and is smaller than the first node, swap... | true |
90a09a889737795e14a2fdf6def2b8e1732e3e01 | 0siris7/LP3THW | /swap.py | 324 | 4.125 | 4 | def swap_case(s):
a = list(s)
b = []
for i in a:
if i.isupper():
b.append(i.lower())
elif i.islower():
b.append(i.upper())
return(''.join(b))
if __name__ == '__main__':
s = input("Enter the string: ")
result = swap_case(s)
print(f"The result: {result... | true |
532fb9eb334f2b0876775bf002cde6ac8c69bc75 | r6047736/UAPython | /root/a5tests/students/lmzbonack-assignment-5/puter-1.py | 1,826 | 4.125 | 4 | #
# Author: Luc Zbonack
# Description:
# This is a simple version of a question/answer AI. It takes question in through standard input and prints out answers
# through standard output. The AI will exit after 10 questions or it will exit when the user tells it to. At this time the
# AI only responds to cer... | true |
4efe57cc938192a12b13c5e90bd27ea8962545d5 | r6047736/UAPython | /root/a5tests/students/pwilkeni-assignment-5/puter-1.py | 1,456 | 4.15625 | 4 | #!/usr/bin/env python
#
# Author: Patrick Wilkening
# Description:
# a puter program that can answer some basic questions
# (up to 10 questions) before exiting.
#
import sys
import datetime
qCount = 0
color = 0
manual_exit = False
# Questions PUTER will answer
Q1 = "how are you?"
Q2 = "how goes it?"
Q3 = "what is y... | true |
c3c5099c4c4e283bbf0d0046ea4f5eee939747c4 | Rohan506/Intership-task0 | /6th Question.py | 904 | 4.3125 | 4 | #Write a python program to print the Fibonacci series and
#also check if a given input number is Fibonacci number or not.
def fib(n):
a=0
b=1
if n==1:
print(a)
else:
print(a)
print(b)
for i in range(2,n):
c=a+b
a=b
b=c
pri... | true |
58e41f38f598ba54cacc09cceaa1b3d4ca241c42 | Rutuja-haridas1996/Basic-python-problems | /sphere_volume.py | 388 | 4.25 | 4 | '''
Problem Statement:
Write a function that computes the volume of a sphere when passed the radius.
Use an assert statement to test the function.
'''
def sphere_volume(radius):
try:
assert isinstance(radius,int) or isinstance(radius,float)
return ((4/3)*(3.14))*(radius**3)
except AssertionEr... | true |
f951d79de2d71ab3f3748e5fb15daae60e2aaf93 | Brijesh1990/python-core-adv-framwork | /string/string_operator.py | 602 | 4.125 | 4 | #operators in string
#concatenate oeprator +
# name="brijesh"
# name1="parth"
# name3="jinesh"
# print(name+" "+name1+name3)
# new line \n
# name="brijesh"
# name1="parth"
# name3="jinesh"
# print(name+"\n"+name1+"\n"+name3)
#\\ backslash
# name="brijesh"
# name1="rajesh"
# print(name+"\\"+na... | false |
ebb97404d93a3f987ef0dfe68f6acf43950f5d3c | cafpereira/python-crash-course | /chapter10/exceptions.py | 1,328 | 4.25 | 4 | try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
# print("Give me two numbers, and I'll divide them.")
# print("Enter 'q' to quit.")
#
# while True:
# first_number = input("\nFirst number: ")
# if first_number == 'q':
# break
# second_number = input("Second numbe... | true |
af8c6cc19a947764e43fff904e154627ef2aaf83 | minyun168/programing_practice | /practice_of_python/formatted_name.py | 558 | 4.125 | 4 |
def formatted_name(first_name, last_name, middle_name = ""): #when we use default value just like middle_name="", we should make sure middle_name is the last variable when we define function
"""return formatted name""" # middle_name = "" not middle = " "
if middle_name:
full_name = first_name + " " +... | true |
c17615c48fb2c2c603b7a272fd7d46090f894af2 | LipsaJ/PythonPrograms | /X003PythonList/List.py | 744 | 4.375 | 4 | parrot_list = ["Blue", "Green", "Very beautiful", "is annoying"]
parrot_list.append("Red at the beak")
for state in parrot_list:
print("Parrot is " + state)
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7, 9]
numbers = even + odd
# numbers.sort is a method which applies on the object it never creates it
# Below... | true |
3005c9e712bf8e6d187e95677d3cd2109a889e2a | LipsaJ/PythonPrograms | /X011dFunctions/functionsAsPrint.py | 1,104 | 4.125 | 4 | def python_food():
width = 80
text = "Spams and Eggs"
left_margin = (width - len(text)) // 2
print(" " * left_margin, text)
def centre_text(*args, sep=' ', end= '\n', file=None, flush=False):
text = ''
for arg in args:
text += str(arg) + sep
left_margin = (80 - len(text)... | true |
810b7962e5883f95abba2813b6e68ab41fe032c0 | LipsaJ/PythonPrograms | /createDB/contacts3.py | 488 | 4.1875 | 4 | import sqlite3
db = sqlite3.connect("contacts.sqlite")
name = input("Please enter the name: ")
#
# select_sql = "SELECT * FROM contacts WHERE name = ?"
# select_cursor = db.cursor() # we have used the cursor to update so that we can see how many rows were updated
# select_cursor.execute(select_sql, name)
# ... | true |
507100b7c21da627444ca046d13603ac64bb8b94 | Ashma-Garg/Python | /decoraterAndSortedFunction.py | 1,622 | 4.21875 | 4 | import operator
def person_lister(f):
def inner(people):
# people.sort(key=lambda x:x[2])
# sorted(people,key=lambda x:x[2])
#{sorted function can not be implemented directly on function because functions are not iterable.
#To iterate through functions we use map function.
... | true |
bd34d57a1a7d43d24d1c35a4479ef1f331f29e4f | Ashma-Garg/Python | /listSortingOnTheBssisOfIndexing.py | 1,791 | 4.3125 | 4 | # You are given a spreadsheet that contains a list of N athletes and their details (such as age, height, weight and so on). You are required to sort the data based on the Kth attribute and print the final resulting table. Follow the example given below for better understanding.
# Note that K is indexed from ) to M-1, w... | true |
da56da8848e09466f831b6498e843f79fc670ecd | Ashma-Garg/Python | /SameElements.py | 934 | 4.21875 | 4 |
# Karl has an array of integers. He wants to reduce the array until all remaining elements are equal. Determine the minimum number of elements to delete to reach his goal.
# For example, if his array isarr=[1,2,2,3] , we see that he can delete the 2 elements 1 and 3 leaving arr=[2,2]. He could also delete both twos an... | true |
68fada0c38510aee5000ab801c61d5cb20bc4553 | bfernando1/codewars | /playing_with_digits.py | 540 | 4.28125 | 4 | #! python3
def dig_pow(n, p):
"""Finds a positive integer k, if it exists, such as the
sum of the digits of n taken to the successive powers
of p is equal to k * n.
Args:
Integer and a exponent
Returns:
A positive integer if found
Examp... | true |
e80fb64c73aac67e3b843c45d192d3029c4eef50 | SakyaSumedh/dailyInterviewPro | /pascals_triangle.py | 878 | 4.4375 | 4 | '''
Pascal's Triangle is a triangle where all numbers are the sum of the two numbers above it. Here's an example of the Pascal's Triangle of size 5.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Given an integer n, generate the n-th row of the Pascal's Triangle.
Here's an example and some starter code.
def pascal_triangle_... | true |
6c9d1bb06bee92dcf146f4c01fba2ae6921025ef | ann-peterson/hackbrightcodeappetizers | /CA1115.py | 692 | 4.4375 | 4 | # Your job is to write a Python program that converts the percentage
# grade to a letter grade. (Download the file as a .txt)
# read class_grades.txt
with open('class_grades.txt') as my_file:
grades = my_file.readlines()
for num in grades:
num = int(num)
if num >= 90:
print num, "A"
el... | true |
0853b01337648980e0cd46b2dba9298145dbba44 | Just-A-Engineer/TextOnlyGames | /hangman.py | 1,390 | 4.15625 | 4 | import random
words = ("python", "hangman", "xylophone", "watch", "king", "dog", "animal", "anomaly", "hospital", "exit", "entrance", "jeep", "number", "airplane", "crossing", "tattoo")
lives = None
game_won = False
print("WELCOME TO HANGMAN!!!")
print("You have three lives!")
print("Choose wisely!")
play = input("... | true |
1f87d6e40dd6710e2dbb5cb8d96828997af9adbd | LuuckyG/TicTacToe | /model/tile.py | 1,091 | 4.1875 | 4 | import pygame
class Tile:
"""Class to create the seperate tiles of the tictactoe board."""
def __init__(self, x, y, size, state='empty'):
"""Initialization of the tile.
Args:
- x: the horizontal coordinate (in px) of the tile (top left)
- y: the vertical coordinate (in... | true |
9a7e9bd46e734193a71ffdd69c27240dc231afe5 | Apostol095/gotham | /hw_3_2.py | 710 | 4.21875 | 4 | """Пользователь вводит порядковый номер Числа Фибоначчи - n
Программа вычисляет этот элемент ряда Фибоначчи и выводит его на экран (с вразумительным сообщением)."""
def main ():
n = input("порядковый номер элемента ряда Фибоначчи: ")
n = int(n)
res = get_fibonachi(n)
print('Элемент {} ряда Чис... | false |
ccd95a8298c34bf5322bace6770fd7558f352740 | scottwedge/40_python_projects | /FibonacciCalculator_ForLoops_Challenge_4.py | 2,050 | 4.25 | 4 | #!/usr/bin/env python3
# Print welcome header.
# Calculate the first n terms of the Fibonacci sequence.
# Then calculate the ratio of consecutive Fibonacci numbers.
# Which should approach 1.618
# Functions
def header():
print("Welcome to the Fibonacci Calculator App.")
print() # blank line
def fib(last, sec... | true |
3e23862314e32d5c519a1df22c463debf51b4e3f | scottwedge/40_python_projects | /CoinToss_Conditionals_Challenge_2.py | 2,173 | 4.28125 | 4 | #!/usr/bin/env python3
# Welcome user
# Get number of coin flip attempts to do
# Ask if want to see results of each flip, or not
# Display when number of heads = number of tails
# Display summary of all results for each side: count and percentage
# Imports
import random
# Functions
def header():
print("Welcome t... | true |
d9882c848dd09b65f97fb84d4d704492a419d1e6 | scottwedge/40_python_projects | /LetterCounter_Project_1.py | 2,069 | 4.5625 | 5 | #!/usr/bin/env python3
# Project 1:
# - prompts for user name and capitalizes it if needed
# - prompts for a line of text to be entered
# - prompts for which letter count is desired.
# - prints letter and count for that letter
# Instructions are that both upper case and lower case are counted for the same letter.
#... | true |
9f45813b8077ccc5aabe9ce353a654acc9cbe9fe | connorS119987/CNA267-Spring-Semester-2020 | /CH02/23Lab2-2.py | 652 | 4.34375 | 4 | # Will determin the minimum length of runway an aircraft needs to take off
print("This program will determin the minimum length of runway an aircraft needs\n") # Prints introduction statement
v = eval( input("Please enter the take-off speed of the aircraft: ") ) # Obtaining the velocity of the aircraft
a = eval( inp... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.