blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
86e74e6b83be3976ba48f90728a50334811df18a | cycho04/python-automation | /game-inventory.py | 1,879 | 4.3125 | 4 | # You are creating a fantasy video game.
# The data structure to model the player’s inventory will be a dictionary where the keys are string values
# describing the item in the inventory and the value is an integer value detailing how many of that item the player has.
# For example, the dictionary value {'rope': 1, ... | true |
fc68579b36277493e624b0401ac7be7fdf1b4f5c | AdityaKuranjekarMYCAPTAIN/Python-Project-2-PART-1- | /Fibonacci.py | 253 | 4.125 | 4 | n = int(input("How many numbers of fibonacci series do you want to see?: "))
x = 0
y = 1
z = 0
i = 1
while (n >= i):
print (z)
x = y
y = z
z = x+y
i += 1
#>>>>>>>>>>>>>>>>>>.................HAPPY CODING....................<<<<<<<<<<<<<<<<<<<<<<<
| false |
70a3ee1c969065898bdb77d2aa0b8004a0364fbf | rajmohanram/PyLearn | /003_Conditional_Loop/06_for_loop_dict.py | 582 | 4.5 | 4 | # let's look at an examples of for loop
# - using a dictionary
# define an interfaces dictionary - items: interface names
interface = {'name': 'GigabitEthernet0/2', 'mode': 'trunk', 'vlan': [10, 20, 30], 'portfast_enabled': False}
# let's check the items() method for dictionary
interface_items = interface.items()
p... | true |
0cd762b867fbd84b8319eeb89b10c0fcb73675ef | rajmohanram/PyLearn | /004-Functions/01_function_intro.py | 758 | 4.46875 | 4 | """
Functions:
- Allows reuse of code
- To create modular program
- DRY - Don't Repeat Yourselves
"""
# def: keyword to define a function
# hello_func(): name of the function - Prints a string when called
# () - used to get the parameters: No parameters / arguments used in this function
def hello_func():
... | true |
d8d9a875d2a71f214c7041c2df0b0fcf298e4c8b | jda5/scratch-neural-network | /activation.py | 2,158 | 4.21875 | 4 | import numpy as np
class ReLU:
def __init__(self):
self.next = None
self.prev = None
def forward(self, inputs):
"""
Implements Rectified Linear Unit (ReLU) function - all input values less than zero are replaced with zero.
Finally it sets two new attributes: (1) the i... | true |
ad0394942b9f519406945e58c72e7da25dda27eb | BigNianNGS/AI | /python_base/class2.py | 1,562 | 4.3125 | 4 |
class Dog():
"""构造方法"""
def __init__(self,name,age,weight=5):
self.name = name
self.age = age
self.weight = weight
# ~ return self 不需要,程序已经内设
def set_weight(self,weight):
self.weight = weight
def eat_bone(self):
print(self.name + 'is eating bone')
def bark(self):
print(self.name+' is ba... | false |
594edacffdac059e2f6b34a514d402659b9ed4a1 | leon-lei/learning-materials | /binary-search/recursive_binary_search.py | 929 | 4.1875 | 4 | # Returns index of x in arr if present, else -1
def binarySearch(arr, left, right, x):
# Check base case
if right >= left:
mid = int(left + (right - left)/2)
# If element is present at the middle itself
if arr[mid] == x:
return mid
# If element is smaller than mid... | true |
70b705fc1378b524560ac03c727748133b8919bd | Lipones/ScriptsPython | /estruturas de repetição2.py | 293 | 4.15625 | 4 | # -*- coding: utf-8 -*-
lista1 = [1,2,3,4,5]
lista2 = ["olá", "mundo", "!"]
lista3 = [0, "olá", "biscoito", "bolacha", 9.99, True]#comando for é utilizado para percorrer listas e exibir resultados
for i in lista1:
print(i)
for i in lista2:
print(i)
for i in lista3:
print(i)
| false |
1421aac5bb5d2864179392ec3580146803b0dc22 | signalwolf/Algorithm | /Chapter2 Linked_list/Insert a node in sorted linked list.py | 1,244 | 4.28125 | 4 | # https://www.geeksforgeeks.org/given-a-linked-list-which-is-sorted-how-will-you-insert-in-sorted-way/
# insert by position
class LinkedListNode(object):
def __init__(self, val):
self.val = val
self.next = None
def create_linked_list(arr):
dummy_node = LinkedListNode(0)
prev = dummy_node... | true |
cc2ca652d4ef4f7b5b6f4198f1e92a6f3a85ad63 | YSreylin/HTML | /1101901079/list/Elist10.py | 289 | 4.21875 | 4 | #write a Python program to find the list of words that are longer than n from a given list of words
a = []
b = int(input("Enter range for list:"))
for i in range(b):
c = input("Enter the string:")
a.append(c)
for j in a:
d = max(a, key=len)
print("\n",d,"is the longest one")
| true |
97d96de1162239c5e135bc9ce921625b5c88a080 | YSreylin/HTML | /1101901079/Array/array.py | 242 | 4.40625 | 4 | #write python program to create an array of 5 integers and display the array items.
#access individual element through indexes.
import array
a=array.array('i',[])
for i in range(5):
c=int(input("Enter array:"))
a.append(c)
print(a)
| true |
7d6b9fc6ddd4a6cc4145d1568965666b48b030ed | YSreylin/HTML | /1101901079/0012/04.py | 204 | 4.125 | 4 | #this program is used to swap of two variable
a = input('Enter your X variable:')
b = input('Enter your Y variable:')
c=b
d=a
print("Thus")
print("The value of X is:",c)
print("The value of Y is:",d)
| true |
1a1d300c97c45ce4e321530f3a30d296fe165bf2 | YSreylin/HTML | /1101901079/0012/Estring6.py | 394 | 4.25 | 4 | '''write a Python program to add 'ing' at the end of a given string (length should be at least 3).
If the given string already ends with 'ing' then add 'ly' instead.
if the string lenth of the given string is less then 3, leave it unchanged'''
a = input("Enter the word:")
x = a[-3:]
if len(a)>3:
if x=='ing':
... | true |
4373addc9af220054ff54a7d6abb1073bf7a602d | TaviusC/cti110 | /P3HW2_MealTipTax_Cousar.py | 1,327 | 4.25 | 4 | # CTI-110
# P3HW2 - MealTipTax
# Tavius Cousar
# 2/27/2019
#
# Enter the price of the meal
# Display tip choices
# Enter the tip choice
# Calculate the total price of meal (price of meal * tip + price)
# Calculate the sales tax (charge * 0.07)
# Calculate the total (charge + sales tax)
# if tip == '0.15', '0... | true |
59c807425fc3d05a2492fd09fdd09b70b2ff82a7 | ImayaDismas/python-programs | /boolean.py | 622 | 4.125 | 4 | #!/usr/bin/python3
def main():
boo = (5 == 5)
print(boo)
print(type(boo))
print('logical operator AND')
#logical operator AND
a = (True and True)
print(a)
b = (True and False)
print(b)
c = (False and True)
print(c)
d = (False and False)
print(d)
print('logical operator OR')
#logical operator OR
... | false |
09e2ea08b77fa1a4e33180cac2ed46e872f281fb | ImayaDismas/python-programs | /variables_dict.py | 455 | 4.3125 | 4 | #!/usr/bin/python3
def main():
d = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
for k in sorted(d.keys()): #sorted sorts the alphabetically
print(k, d[k])
#using a different definition of the dictionaries
a = dict(
one=1, two = 2, three = 3, four = 4, five = 'five'
)#usually are mutable
a['seven'... | true |
278144e8d19ad06065719defc62f8b4c2e29c786 | Mansalu/python-class | /003-While/main.py | 1,093 | 4.34375 | 4 | # While Loops -- FizzBuzz
"""
Count from 1 to 100, printing the current count. However, if the count is
a multiple of 3, print "Fizz" instead of the count. If the count is a
multiple of 5 print "Buzz" instead. Finally, if the count is a multiple of both print
"FizzBuzz" instead.
Example
1, 2, Fizz, 4, Buzz, Fizz, 7,... | true |
d741d285f023ad8223a5c095775a8d0b225f4b4a | cabhishek/python-kata | /loops.py | 1,045 | 4.3125 | 4 | def loop(array):
print('Basic')
for number in array:
print(number)
print('Basic + Loop index')
for i, number in enumerate(array):
print(i, number)
print('Start from index 1')
for i in range(1, len(array)):
print(array[i])
print('Choose index and start position')
... | true |
a1d66f9acca5ecd0062f9842e07a5158b109587b | cabhishek/python-kata | /word_break.py | 1,280 | 4.28125 | 4 | """
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
"""
def word_break_2(word, dict):
for ... | true |
ec077fa4521bd2584b13d15fe3b3866dd4ff4fde | rtyner/python-crash-course | /ch5/conditional_tests.py | 337 | 4.34375 | 4 | car = 'mercedes'
if car == 'audi':
print("This car is made by VW")
else:
print("This car isn't made by VW")
if car != 'audi':
print("This car isn't made by VW")
car = ['mercedes', 'volkswagen']
if car == 'volkswagen' and 'audi':
print("These cars are made by VW")
else:
print("Not all of these cars... | true |
89573fb8b24671dd322e22c6dfcfabea58d578ed | UWPCE-PythonCert-ClassRepos/Python210_Fall2019 | /students/kclark75/assignment07/untitled0.py | 570 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 1 18:43:13 2019
@author: kenclark
Class: Python 210A-Fall
Teacher: David Pokrajac, PhD
Assignment -
"""
from math import pi
class Circle(object):
def __init__(self, r):
self.radius = r
def area(self):
return se... | false |
0c04919a425328f8a1dfcf7e612a6d8f1780e61d | UWPCE-PythonCert-ClassRepos/Python210_Fall2019 | /students/matthew_denko/lesson03/slicing_lab.py | 1,731 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 28 15:08:38 2019
@author: matt.denko
"""
"""Write some functions that take a sequence as an argument, and return a copy of that sequence:
with the first and last items exchanged.
with every other item removed.
with the first 4 and the last 4 items... | true |
51cf6b8c764ffef5e24eede476fff19f76d66df4 | UWPCE-PythonCert-ClassRepos/Python210_Fall2019 | /students/jraising/lesson02/series.py | 2,261 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 17 17:09:09 2019
@author: jraising
"""
def fibo(n):
fib = [0,1]
for i in range(n-1):
fib.append(fib[i] + fib[i+1])
return (fib[n])
ans = fibo(5)
print (ans)
def lucas(n):
luc = [2,1]
for i in range(n-1):
lu... | true |
e1f1be756bda5a8452dd18deec0c7e936c17f673 | UWPCE-PythonCert-ClassRepos/Python210_Fall2019 | /students/jammy_chong/lesson03/list_lab.py | 1,919 | 4.3125 | 4 | def create_list():
global fruit_list
fruit_list = ["Apples", "Pears", "Oranges", "Peaches"]
#Seris 1
create_list()
print(fruit_list)
new_fruit = input("Add another fruit to the end of the list: ")
fruit_list.append(new_fruit)
print(fruit_list)
user_number = input(f"Choose a number from 1 to {len(fruit_list)}... | true |
45e749325dc2d163416366a6a3046a83d97bbd76 | UWPCE-PythonCert-ClassRepos/Python210_Fall2019 | /students/matthew_denko/lesson02/fizz_buzz.py | 603 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 20:51:19 2019
@author: matt.denko
"""
"""Write a program that prints the numbers from 1 to 100 inclusive.
But for multiples of three print “Fizz” instead of the number.
For the multiples of five print “Buzz” instead of the number.
For numbers wh... | true |
45f3e57a623f550857bb4261f6bb66287c7203ce | UWPCE-PythonCert-ClassRepos/Python210_Fall2019 | /students/bishal_gupta/lesson03/list_lab.py | 2,041 | 4.25 | 4 | #!/usr/bin/env python3
"""
Created on Mon Oct 28 18:25:04 2019
@author: Bishal.Gupta
"""
#Series 1
fruitlist = ['Apples','Pears','Oranges','Peaches']
print("The list has following fruit", len(fruitlist), "fruits:", fruitlist)
new_fruit = input("What fruit would you like to add? ")
fruitlist.append(new_fruit)
print... | false |
dda29cfb852c6093c19b19bbb8a3f4d74b5d6450 | Rupesh2010/python-pattern | /pattern1.py | 245 | 4.125 | 4 | num = 1
for i in range(0, 3):
for j in range(0, 3):
print(num, end=" ")
num = num + 1
print("\r")
num = 0
for i in range(0, 3):
for j in range(0, 3):
print(num, end=" ")
num = num + 1
print("\r")
| false |
000a7bafb0c973ba1869c322e84efb75ee41e6f1 | mohamedamine456/AI_BOOTCAMP | /Week01/Module00/ex01/exec.py | 249 | 4.125 | 4 | import sys
result = ""
for i, arg in enumerate(reversed(sys.argv[1:])):
if i > 0:
result += " "
result += "".join(char.lower() if char.isupper() else char.upper() if char.islower() else char for char in reversed(arg))
print(result) | true |
dffcce747fb2c794585df237849517bd8b637d9f | data-pirate/Algorithms-in-Python | /Arrays/Two_sum_problem.py | 1,690 | 4.21875 | 4 | # TWO SUM PROBLEM:
# In this problem we need to find the terms in array which result in target sum
# for example taking array = [1,5,5,15,6,3,5]
# and we are told to find if array consists of a pair whose sum is 8
# There can be 3 possible solutions to this problem
#solution 1: brute force
# this might not be the bes... | true |
aa990f7844b6d49bc9eb2c019150edbc65b32833 | oskar404/code-drill | /py/fibonacci.py | 790 | 4.53125 | 5 | #!/usr/bin/env python
# Write a function that computes the list of the first 100 Fibonacci numbers.
# By definition, the first two numbers in the Fibonacci sequence are 0 and 1,
# and each subsequent number is the sum of the previous two. As an example,
# here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13... | true |
959cd3062b855c030b92cfe0f2edbbe141018508 | kctompkins/my_netops_repo | /python/userinput.py | 220 | 4.125 | 4 | inputvalid = False
while inputvalid == False:
name = input("Hey Person, what's your name? ")
if all(x.isalpha() or x.isspace() for x in name):
inputvalid = True
else:
inputvalid = False
print(name)
| true |
920db86935bce4a965494006d2e4bb255183dbc5 | rvaccari/uri-judge | /01-iniciante/1008.py | 1,259 | 4.21875 | 4 | """
Salário
Escreva um programa que leia o número de um funcionário, seu número de horas trabalhadas,
o valor que recebe por hora e calcula o salário desse funcionário. A seguir, mostre o
número e o salário do funcionário, com duas casas decimais.
Entrada
O arquivo de entrada contém 2 números inteiros e 1 número com ... | false |
3759abcbab3aff89acc59fe4228f0146ee2eaa56 | HSabbir/Design-pattern-class | /bidding/gui.py | 1,717 | 4.1875 | 4 | import tkinter as tk
from tkinter import ttk
from tkinter import *
from bidding import biddingraw
# this is the function called when the button is clicked
def btnClickFunction():
print('clicked')
# this is the function called when the button is clicked
def btnClickFunction():
print('clicked')
# this is the funct... | true |
cd79e3b1ce72569bb62b994695e4483798346a0c | Luke-Beausoleil/ICS3U-Unit3-08-Python-is_it_a_leap_year | /is_it_a_leap_year.py | 926 | 4.28125 | 4 | #!/usr/bin/env python3
# Created by: Luke Beausoleil
# Created on: May 2021
# This program determines whether inputted year is a leap year
def main():
# this function determines if the year is a leap year
# input
year_as_string = input("Enter the year: ")
# process & output
try:
year = ... | true |
322be9bbf093725a12f82482cd5b9d0ffdf98dcc | bgschiller/thinkcomplexity | /Count.py | 1,966 | 4.15625 | 4 | def count_maker(digitgen, first_is_zero=True):
'''Given an iterator which yields the str(digits) of a number system and counts using it.
first_is_zero reflects the truth of the statement "this number system begins at zero" It should only be turned off for something like a label system.'''
def counter(n):
... | true |
a8f2158fe199c282b8bdc33f257f393eb70e6685 | iamaro80/arabcoders | /Mad Libs Generator/06_word_transformer.py | 737 | 4.21875 | 4 | # Write code for the function word_transformer, which takes in a string word as input.
# If word is equal to "NOUN", return a random noun, if word is equal to "VERB",
# return a random verb, else return the first character of word.
from random import randint
def random_verb():
random_num = randint(0, 1)
if ra... | true |
7c017d73da7b2e702aecf6fa81114580389afe09 | Numa52/CIS2348 | /Homework1/3.18.py | 862 | 4.25 | 4 | #Ryan Nguyen PSID: 180527
#getting wall dimensions from user
wall_height = int(input("Enter wall height (feet):\n"))
wall_width = int(input("Enter wall width (feet):\n"))
wall_area = wall_width * wall_height
print("Wall area:", wall_area, "square feet")
#calculating gallons of paint needed
#1 gallon of paint covers 3... | true |
f5540eb90b304d519809c8c010add05fc11e491f | sindhumudireddy16/Python | /Lab 2/Source/sortalpha.py | 296 | 4.375 | 4 | #User input!
t=input("Enter the words separated by commas: ")
#splitting words separated by commas which are automatically stored as a list.
w=t.split(",")
#sorting the list.
w1=sorted(w)
#iterating through sorted list and printing output.
for k in w1[:-1]:
print(k+",",end='')
print(w1[-1])
| true |
9791dc9cb5195fba0fd7b3237a6d8d39b089a20e | GreatHayat/Sorting_Data_Structures | /insertion_sort.py | 382 | 4.28125 | 4 | # Insertion Sort Algorithm
def insertionSort(array):
n = len(array)
for i in range(1, n):
key = array[i]
j = i - 1
while j >= 0 and array[j] > key:
array[j + 1] = array[j]
j = j - 1
array[j + 1] = key
# Calling the function
array = [5,4,3,2,1]
inserti... | false |
b9cf4f68c2bcb975561600f6504248a832b565a2 | letwant/python_learning | /learn_liaoxuefeng_python/函数式编程/高阶函数/高阶函数介绍.py | 912 | 4.25 | 4 | # -*- coding: utf-8 -*-
# 高阶函数英文叫Higher-order function。什么是高阶函数?我们以实际代码为例子,一步一步深入概念。
print(abs(-10)) # 10
print(abs) # <built-in function abs>
# abs(-10)是函数调用,而abs是函数本身
# 函数本身也可以赋值给变量,即:变量可以指向函数
# 如果一个变量指向了一个函数,那么,可以通过该变量来调用这个函数
f = abs
value = f(-10)
print(value) # 10
# 【函数名也是变量】
abs = 10
# abs(-10) # TypeError: ... | false |
263387b1a516c9558c26c0d6fd2df142ff9edcc6 | muondu/caculator | /try.py | 528 | 4.40625 | 4 | import re
def caculate():
#Asks user to input
operators = input(
"""
Please type in the math operation you will like to complete
+ for addition
- for subtraction
* for multiplication
/ for division
""" )
#checks if the opertators match with input
if not re.match("^[+,-,*,/]*$", operators)... | true |
1edd3809d431ece230d5d70d15425bd2fa62e43a | jabhij/DAT208x_Python_DataScience | /FUNCTIONS-PACKAGES/LAB3/L1.py | 445 | 4.3125 | 4 | """
Instructions --
Import the math package. Now you can access the constant pi with math.pi.
Calculate the circumference of the circle and store it in C.
Calculate the area of the circle and store it in A.
------------------
"""
# Definition of radius
r = 0.43
# Import the math package
import math
# Calculate C
C ... | true |
c82f373f42c0124c42d3ec8dd89184a0897998a1 | jabhij/DAT208x_Python_DataScience | /NUMPY/LAB1/L2.py | 614 | 4.5 | 4 | """
Instructions --
Create a Numpy array from height. Name this new array np_height.
Print np_height.
Multiply np_height with 0.0254 to convert all height measurements from inches to meters. Store the new values in a new array, np_height_m.
Print out np_height_m and check if the output makes sense.
"""
# height is a... | true |
1c0357c5d25156eb2b9024fa411639ad0ff2aec9 | Atrociou/Saved-Things | /todo.py | 619 | 4.1875 | 4 | print("Welcome to the To Do List")
todoList = ["Homework", "Read", "Practice" ]
while True:
print("Enter a to add an item")
print("Enter r to remove an item")
print("Enter p to print the list")
print("Enter q to quit")
choice = input("Make your choice: ")
if choice == "q":
exit()
break
elif choi... | true |
7ca8bdfb4b5f89ec06fb494a75413184f153401d | NISHU-KUMARI809/python--codes | /abbreviation.py | 522 | 4.25 | 4 | # python program to print initials of a name
def name(s):
# split the string into a list
l = s.split()
new = ""
# traverse in the list
for i in range(len(l) - 1):
s = l[i]
# adds the capital first character
new += (s[0].upper() + '.')
# l[-1] gives last it... | true |
6c8e860f0ac34f6199c71ba0b528622dc980e61a | xdc7/pythonworkout | /chapter-03/01-extra-02-sum-plus-minus.py | 1,155 | 4.15625 | 4 | """
Write a function that takes a list or tuple of numbers. Return the result of alternately adding and subtracting numbers from each other. So calling the function as plus_minus([10, 20, 30, 40, 50, 60]) , you’ll get back the result of 10+20-30+40-50+60 , or 50 .
"""
import unittest
def plus_minus(sequence):
sum... | true |
182bc373458a808387825084a7927ff50288e270 | xdc7/pythonworkout | /chapter-02/05-stringsort.py | 984 | 4.25 | 4 | """
In this exercise, you’ll explore this idea by writing a function, strsort, that takes a single string as its input, and returns a string. The returned string should contain the same characters as the input, except that its characters should be sorted in order, from smallest Unicode value to highest Unicode value.
... | true |
92188bb3349159b96640692939e9b784426ee41d | xdc7/pythonworkout | /chapter-04/03-restaurant.py | 1,383 | 4.28125 | 4 | """
create a new dictionary, called menu, representing the possible
items you can order at a restaurant. The keys will be strings, and the values will be prices (i.e.,
integers). The program will then ask the user to enter an order:
If the user enters the name of a dish on the menu, then the program prints the price a... | true |
a265236d9b35352de75c292cd30b2b66301aae55 | xdc7/pythonworkout | /chapter-02/01-pig-latin.py | 987 | 4.25 | 4 | """write a Python program that asks the user to enter an English word. Your program should then print the word, translated into Pig Latin. You may assume that the word contains no capital letters or punctuation.
# How to translate a word to pig latin:
* If the word begins with a vowel (a, e, i, o, or u), then add way... | true |
476c3f377be42a32630992fd0fbbc18bce1c9288 | xdc7/pythonworkout | /chapter-05/5.2.2-factors.py | 1,054 | 4.28125 | 4 | """
Ask the user to enter integers, separated by spaces. From this input, create a dictionary whose keys are the factors for each number, and the values are lists containing those of the users' integers that are multiples of those factors.
"""
def calculateFactors(num):
factors = []
for i in range (1, num + 1... | true |
bfdc1168bf7bbbf621d41de4efb479b1bf4a11fe | xdc7/pythonworkout | /chapter-01/05-extra-01-hex-to-dec.py | 1,737 | 4.25 | 4 | """
Write a program that takes a hex number and returns the decimal equivalent. That is, if the user enters 50, then we will assume that it is a hex number (equal to 0x50), and will print the value 80 on the screen. Implement the above program such that it doesn’t use the int function at all, but rather uses the builti... | true |
38a591219f2e390385353788fa8c1eb969e4d253 | maurice-gallagher/exercises | /chapter-5/ex-5-6.py | 2,004 | 4.5 | 4 | # Programming Exercise 5-6
#
# Program to compute calories from fat and carbohydrate.
# This program accepts fat grams and carbohydrate grams consumed from a user,
# uses global constants to calculate the fat calories and carb calories,
# then passes them to a function for formatted display on the screen.
# Glo... | true |
667c668af92cafa7af07828df395d4d43b948b75 | nazariyv/leetcode | /solutions/medium/bitwise_and_of_numbers_range/main.py | 554 | 4.3125 | 4 | #!/usr/bin/env python
# Although there is a loop in the algorithm, the number of iterations is bounded by the number of bits that an integer has, which is fixed.
def bit_shift(m: int, n: int) -> int:
shifts = 0
while m != n:
m >>= 1
n >>= 1
shifts += 1
return 1 << shifts
# if n... | true |
bc33ce706a85ee11b4aeb822256b4c23bf7f1a5e | karina-chi/python-10-2020 | /Lesson2/task2.py | 716 | 4.21875 | 4 | # Для списка реализовать обмен значений соседних элементов, т.е.
# Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
items = input("Укажите значения спи... | false |
e305999659409116a695be650da868d41cad775c | sandeepbaldawa/Programming-Concepts-Python | /recursion/regex_matching_1.py | 1,453 | 4.28125 | 4 | '''
Implement a regular expression function isMatch that supports the '.' and '*' symbols.
The function receives two strings - text and pattern - and should return true if the text
matches the pattern as a regular expression. For simplicity, assume that the actual symbols '.'
and '*' do not appear in the text string... | true |
96a0bc369ee2198c2bc03d5d555d6449a4339693 | sandeepbaldawa/Programming-Concepts-Python | /recursion/cryptarithm.py | 2,093 | 4.28125 | 4 | Cryptarithm Overview
The general idea of a cryptarithm is to assign integers to letters.
For example, SEND + MORE = MONEY is “9567 + 1085 = 10652”
Q. How to attack this problem?
-Need list of unique letters
-Try all possible assignments of single digits
-Different arrangemen... | true |
d39cf9c6a416f7678bf3b98e36ab52b6ac17997a | sandeepbaldawa/Programming-Concepts-Python | /recursion/crypto_game.py | 2,243 | 4.34375 | 4 | '''
Given a formula like 'ODD + ODD == EVEN', fill in digits to solve it.
Input formula is a string; output is a digit-filled-in string or None.
Where are we spending more time?
if we run CProfile on CProfile.run('test()')
we see maximum time is spent inside valid function,
so how do we optimize the same?
In valid ... | true |
16494f0438fe6af0cfc369187fa8c8708bda7925 | sandeepbaldawa/Programming-Concepts-Python | /lcode/amazon/medium_sort_chars_by_freq.py | 504 | 4.25 | 4 | '''
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input:
"tree"
Output:
"eert"
'''
from collections import defaultdict
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
res = defaultdict(int... | true |
4fcf4d2382a0222c93bcd328383399ea292ea031 | isrishtisingh/python-codes | /URI-manipulation/uri_manipulation.py | 1,173 | 4.125 | 4 | # code using the uriModule
# the module contains 2 functions: uriManipulation & uriManipulation2
import uriModule
# choice variable is for choosing which function to use for manipulating the URL/URI
choice = -1
try:
choice = int(input(" \n Enter 1 to parse given URL/URIs \n Enter 2 to enter your own URI/U... | true |
89ea463ab59b1aa03b14db54ec8d86a8a4168fcf | iriabc/python_exercises | /exercise3.py | 2,082 | 4.46875 | 4 | from collections import deque
def minimum_route_to_treasure(start, the_map):
"""
Calculates the minimum route to one of the treasures for a given map.
The route starts from one of the S points and can move one block up,
down, left or right at a time.
Parameters
----------
the_map: list of... | true |
a3c232a6c220ad1a72284e764c9e70f19fc672b8 | NoName3755/basic-calculator | /calculator.py | 1,108 | 4.21875 | 4 | calculate = True
while calculate:
try:
x = int(input("Enter your first number: "))
y = int(input("Enter your second number: "))
except(ValueError):
print("not an integer")
else:
o = input("enter your operator in words :")
if o == "addition" or o == "+":
... | false |
19d10ffc36a71b8e662857b9f83cbdecdb47114e | TnCodemaniac/Pycharmed | /hjjj.py | 567 | 4.125 | 4 |
import turtle
num_str = input("Enter the side number of the shape you want to draw: ")
if num_str.isdigit():
s= int(num_str)
angle = 180 - 180*(10-2)/10
turtle.up
x = 0
y = 0
turtle.setpos(x,y)
numshapes = 8
for x in range(numshapes):
turtle.color("red")
x += 5
y += 5
turtle.forward(x)
tur... | true |
653c0e75c90f2f607eb46df5a885b47cbbd8d107 | Prolgu/PyExamples | /Diccionario-For_menu.py | 1,605 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Diccionario-For_menu.py
#
#
#
import os
salir = False
dic={'1': '0', '2': '0', '3': '0', '4': '0'}#defino mi diccionario
def menu(): #mi memu principal
os.system('clear')
print("Esto parece un menu:")
print("\t1 - Ingresar val... | false |
2d5a337a4cef68a85705c164d5dcdfbd4edb5e17 | nembangallen/Python-Assignments | /Functions/qn10.py | 384 | 4.15625 | 4 | """
10. Write a Python program to print the even numbers from a given list.
Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result : [2, 4, 6, 8]
"""
def get_even(my_list):
even_list = []
for item in my_list:
if (item % 2 == 0):
even_list.append(item)
else:
pass
... | true |
8a872760535ef1b17100bdd9faee4ff6609c1b8d | nembangallen/Python-Assignments | /Functions/qn13.py | 395 | 4.21875 | 4 | """
13. Write a Python program to sort a list of tuples using Lambda.
"""
def sort_tuple(total_student):
print('Original List of tuples: ')
print(total_student)
total_student.sort(key=lambda x: x[1])
print('\nSorted:')
print(total_student)
total_student = [('Class I', 60), ('Class II', 53),
... | true |
040902675356f5d842d290c5b0570546bc83c9cb | nembangallen/Python-Assignments | /Functions/qn8.py | 387 | 4.28125 | 4 | """
8. Write a Python function that takes a list and returns a new list with unique
elements of the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
"""
def unique_list(my_list):
unique_list = []
for x in my_list:
if x not in unique_list:
unique_list.append(x)
... | true |
ecedcca7da6cd799acc1bce8c0e2b4361c9652a4 | BlaiseMarvin/pandas-forDataAnalysis | /sortingAndRanking.py | 1,820 | 4.34375 | 4 | #sorting and ranking
# to sort lexicographically, we use the sort_index method which returns a new object
import pandas as pd
import numpy as np
obj=pd.Series(range(4),index=['d','a','b','c'])
print(obj)
print("\n")
print(obj.sort_index()) #this sorts the indices
#with a dataframe, you can sort by index on either ... | true |
7d44b3978280fed567e2422c24f0d2488c28d89d | vandent6/basic-stuff | /elem_search.py | 893 | 4.15625 | 4 |
def basic_binary_search(item, itemList):
"""
(str, sequence) -> (bool)
Uses binary search to split a list and find if the item is in the list.
Examples:
basic_binary_search(7,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90, 100, 600]) -> True
basic_binary_search(99,[1, 4, 6, 7, 8, 9, 11, 15, 70, 80, 90... | true |
2817f68fa0dc08ba61921f04a3c4ea5eccc31b38 | ltrii/Intro-Python-I | /src/cal.py | 1,702 | 4.6875 | 5 | # """
# The Python standard library's 'calendar' module allows you to
# render a calendar to your terminal.
# https://docs.python.org/3.6/library/calendar.html
# Write a program that accepts user input of the form
# `calendar.py month [year]`
# and does the following:
# - If the user doesn't specify any input, you... | true |
4d726618926c5e8d18a6f6a1f6b69fe670c46ad5 | JayVer2/Python_intro_week2 | /7_dictionaries.py | 469 | 4.125 | 4 |
#Initialize the two dictionaries
meaningDictionary = {}
sizeDictionary = {}
meaningDictionary["orange"] = "A Fruit"
sizeDictionary["orange"] = 5
meaningDictionary["cabbage"] = "A vegetable"
sizeDictionary["cabbage"] = 10
meaningDictionary["tomato"] = "Widely contested"
sizeDictionary["tomato"] = 5
print("What defi... | true |
b019d0cd997e8c94e5af01ff7f05f0ff8496ba70 | avyartemis/UoPeople.CS1101.PythonProgrammingAssignments | /RainbowColors (Inverted Dictionary).py | 1,544 | 4.28125 | 4 | # CS1101(Intro To Python). Chapter 11: Dictionaries. Week 7. By Avy Artemis.
# Theme: Creating an Artistic Inverted Dictionary
RainbowColors = {'C1': ['Red', 'Rose', 'Sangria', 'Scarlet', 'Warm Colours'],
'C2': ['Orange', 'Carrot', 'Sandstone', 'Warm Colours'],
'C3': ['Yellow', 'Bu... | false |
b56bdb3019523f776ca7e6078a04ca14f9a2bd92 | mohitsharma98/DSA-Practice | /queue.py | 563 | 4.125 | 4 | class queue:
def __init__(self):
self.s = []
def enqueue(self, x):
self.s.append(x)
def dequeue(self):
if len(self.s)>=1:
self.s = self.s[1:]
else:
print("Queue is empty!")
def show(self):
print(self.s)
if __name__ == "__main__"... | false |
4207246674a228f5ab87bf29c41ef6677a1165fc | jaclynchorton/Python-MathReview | /Factorial-SqRt-GCD-DegreeAndRadians.py | 556 | 4.15625 | 4 | #------------------From Learning the Python 3 Standard Library------------------
#importing math functions
import math
#---------------------------Factorial and Square Root---------------------------
# Factorial of 3 = 3 * 2* 1
print(math.factorial(3))
# Squareroot of 64
print(math.sqrt(64))
# GCD-Greatest Common Den... | true |
d0c7bab49992c2e2fc6dbd76104d6846183eb51a | pilihaotian/pythonlearning | /leehao/learn104.py | 746 | 4.125 | 4 | # 继承、派生
# 继承是从已有类中派生出新类,新类具有原类的行为和属性
# 派生是从已有类中衍生出新类,在新类中添加新的属性和行为
# 基类、超类、父类、派生类、子类
# 单继承
class Human:
def say(self, what):
print("说", what)
def walk(self, distance):
print("走了", distance, "公里")
class Student(Human):
# 重写父类
def say(self, what):
print("学生说", what)
def ... | false |
b582d0dced5a0303819dd5a8a3cb3b7d50fbe648 | sevkembo/code_examples | /dice.py | 1,094 | 4.21875 | 4 | from random import randint
class Dice:
def __init__(self, sides=6):
self.sides = sides
def roll_dice(self):
if self.sides == 6:
print(randint(1, 6))
elif self.sides == 10:
print(randint(1, 10))
elif self.sides == 20:
print(randint(1, 20))
w... | false |
0eacae023b58e7727bcfcec37684d47ab49ddfbb | Jabed27/Data-Structure-Algorithms-in-Python | /Algorithm/Graph/BFS/bfs.py | 1,508 | 4.25 | 4 | # https://www.educative.io/edpresso/how-to-implement-a-breadth-first-search-in-python
from collections import defaultdict
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
#initializing a default dictionary with list
graph=defaultdict(list)
parent=[]
dist=[]
def init(n):
for ... | true |
a4a2e639b8c672ebfdb7f8b67f1f567c1ebc704e | Programmer7129/Python-Basics | /Functions.py | 444 | 4.25 | 4 | # For unknown arguments in a function
def myfunc(**name):
print(name["fname"]+" "+name["lname"])
myfunc(fname="Emily", lname="Scott")
def func(*kids):
print("His name is: "+ kids[1])
func("Mark", "Harvey", "Louis")
# Recursion
def recu(k):
if(k > 0):
result = k + recu(k-1)
... | true |
79072e55960b5de9f56486db34748bfaa55c08b9 | FayazGokhool/University-Projects | /Python Tests/General Programming 2.py | 2,320 | 4.125 | 4 | def simplify(list1, list2):
list1_counter,list2_counter = 0,0 #This represents the integer in each array that the loop below is currently on
list3 = [] #Initialise the list
list1_length, list2_length = len(list1), len(list2) #Gets the length of both lists and stores them as varibales so they don't have to be called... | true |
39fdd0263563f932f80ce91303ba69e74bf67259 | leilii/com404 | /1-basics/3-decision/4-modul0-operator/bot.py | 214 | 4.375 | 4 | #Read whole number UserWarning.
#work out if the number is even.
print("Please enter a number.")
wholenumber=int(input())
if (wholenumber%2 == 0):
print("The number is even")
else:
print("The number is odd")
| true |
b7d81a61e20219298907d2217469d74539b10ac4 | fwparkercode/Programming2_SP2019 | /Notes/RecursionB.py | 806 | 4.375 | 4 | # Recursion - function calling itself
def f():
print("f")
g()
def g():
print("g")
# functions can call other functions
f()
def f():
print("f")
f()
g()
def g():
print("g")
# functions can also call themselves
#f() # this causes a recursion error
# Controlling recursion with depth
def c... | true |
21f141bbd269f85b302c1950cc0f2c8705f97854 | tejasgondaliya5/advance-python-for-me | /class_variable.py | 615 | 4.125 | 4 | class Selfdetail:
fname = "tejas" # this is class variable
def __init__(self):
self.lname = "Gondaliya"
def printdetail(self):
print("name is :", obj.fname, self.lname) # access class variable without decorator
@classmethod # access class va... | true |
298c5f852cc317067c7dfcceb529273bbc89ec66 | tejasgondaliya5/advance-python-for-me | /Method_Overloding.py | 682 | 4.25 | 4 | '''
- Method overloding concept is does not work in python.
- But Method ovrloding in diffrent types.
- EX:- koi ek method ma different different task perform thay tene method overloading kehvay 6.
'''
class Math:
# def Sum(self, a, b, c):
def Sum(self, a = None, b=None, c=None): # this one method b... | true |
08421cdc822d1ee9fb6a906927bb4836f1bc691f | YuanchengWu/coding-practice | /problems/1.4.py | 605 | 4.1875 | 4 | # Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palin drome.
# 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 palindrome_... | true |
767b3239ad235c29906cc7f903713ac0c67712c7 | laboyd001/python-crash-course-ch7 | /pizza_toppings.py | 476 | 4.34375 | 4 | #write a loop that prompts the user to enter a series of pizza toppings until they enter a 'quit' value. As they enter each topping, print a message saying you'll add that to their pizza.
prompt = "\nPlease enter the name of a topping you'd like on your pizza:"
prompt += "\n(Enter 'quit' when you are finished.) "
... | true |
77a0cf7be579cd67bf2f9a449d8615c682924d6f | dipeshdc/PythonNotes | /loops/for.py | 782 | 4.125 | 4 | """
For Loop
"""
sentence = "the cat sat on the mat with"# the rat cat and rat were playing in the mat and the cat was happy with rat on the mat"
'''
print("Sentence is: ",sentence)
print("Length of sentence:", len(sentence))
print("Number of Occurrences of 'cat': ", sentence.count('t')) #3
'''
count=0
for char in s... | true |
014db87928669d171b65f3c43c09aca9345843bc | MrLVS/PyRep | /HW5.py | 621 | 4.15625 | 4 | print("Введите неотрицательные целые числа, через пробел: ")
answer = input("--> ")
def find_min_int_out_of_string(some_string):
""" A function to find the minimum number outside the list. """
int_list = list(map(int, some_string.split()))
for i in range(1, max(int_list)+1):
if i not in int_list:
... | true |
35d0fce23734caccf4dc22ddec7175a2230b3c5d | MrLVS/PyRep | /HW10.py | 496 | 4.21875 | 4 | # Solution of the Collatz Hypothesis
def сollatz(number):
""" A function that divides a number by two if the number is even,
divides by three if the number is not even, and starts a new loop.
Counts the number of cycles until the number is exactly 1. """
i = 0
while number > 1:
if numbe... | true |
4dc8fcf6c516ca8bf19c652eef0ab235aa0dc1c4 | frederatic/Python-Practice-Projects | /palindrome.py | 509 | 4.3125 | 4 | # Define a procedure is_palindrome, that takes as input a string, and returns a
# Boolean indicating if the input string is a palindrome.
def is_palindrome(s):
if s == "": # base case
return True
else:
if s[0] == s[-1]: # check if first and last letter match
return is_palin... | true |
6a141c1e62a9565c54b544ea6ec058d650d03e0d | olimpiojunior/Estudos_Python | /Section_9/list_comprehension_p1.py | 1,062 | 4.1875 | 4 | """
list Comprehension
Utilizadando list comprehension nós podemos gerar ovas listas com dados processados a partir de outro iterável
#Parte 01
#1
num = [1,2,3,4,5]
res = [i * 10 for i in num if i%2 != 0]
print(res)
#2
print([i**2 for i in [1,2,3,4,5]])
#3
nome = 'olimpio'
print([l.upper() for l in nome])
#4
lista... | false |
2c8aaddc8adb1e71d2d44161c44e2842a686354e | olimpiojunior/Estudos_Python | /testes/Teste4.py | 1,376 | 4.28125 | 4 | """
mypy só funciona quando se utiliza o type hinting
type hinting é a utilização de atributos com os tipos sendo passados dentro da função, como abaixo
"""
import math
def cabecalho(texto: str, alinhamento: bool = True) -> str:
if alinhamento:
return f"{texto.title()}\n{'-'*len(texto)}"
else:
... | false |
da3d214c93118d4ba3947536ca5dd7163298b59a | olimpiojunior/Estudos_Python | /Section 8/funcoes_com_parametros.py | 1,002 | 4.34375 | 4 | '''
Funções com parametros
funções que recebem dados para serem processados dentro da função
entrada -> processamento -> saida
A função é feita com parametros, Ao usar essa funão é passado os argumentos
-----------------------------------------------------
def quadrado(x):
return x**2
print(quadrado(2))
print(qu... | false |
9f6e71d2b6edee357d69aef795a686b0ce85e1ff | olimpiojunior/Estudos_Python | /Section_10/map.py | 1,110 | 4.5 | 4 | """
map - função map realiza mapeamento de valores para função
function - f(x)
dados - a1, a2, a3 ... an
map object: map(f, dados) -> f(a1), f(a2), f(a3), ...f(an)
-------------------------------------------------------------------
import math
def calc(r):
return math.pi * (r**2)
raios = [1, 2.2, 3., 4, 5.7, 8]
l... | false |
ed9f95a6170b0477fa4ea6a336b336735a452702 | abidtkg/Practices | /python/json.py | 680 | 4.3125 | 4 | # full_name = input("Enter your name: ")
# birth_year = int(input("Enter your age: "))
# print(f'Hi, {full_name}. How are you today?')
# feeling = input("Type: ")
# print(f'Hey {full_name}, your birth year is {birth_year} ? is it true?')
# age_confirm = input("y/n? :")
# print(f'you are {feeling} tody so, it\'s a good ... | false |
916c450d31f5c5cc27f4aa1158f53be1ae761e2b | AlanEstudo/Estudo-de-Python | /aula17a.py | 905 | 4.1875 | 4 | # Variáveis Compostas (Listas)
# .append(' ') => adiciona um elemento no final da lista
# .insert(0, ' ') => adiciona um elemento no inicio ou no indice da lista
# del variavel[3] => apaga o elemento na indice 3
# variavel.pop(3) => apaga o elemento no indice 2, caso não passa o indici apaga o ultimo elemento
# variav... | false |
b6fe10e17b9e4aa330841cb6a82c5719d85bc2b9 | AlanEstudo/Estudo-de-Python | /ex075.py | 768 | 4.1875 | 4 | # Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla.No final mostre:
# quantas vezes apareceu o valor 9.
# Em que posição foi digitado o primeiro valor 3.
# Quais foram os números pares.
numeros = (
int(input('Digite um número: ')),
int(input('Digite outro númeror: ')),
i... | false |
50558d02725abf9c04eff5efe7806cca7510bfc2 | ukrduino/PythonElementary | /Lesson02/Exercise2a1.py | 553 | 4.15625 | 4 | # Write a bubble-sort function
def bubble_sort(un_list):
"""
Bubble-sort function
>>> unsorted_list = [54, 26, 93, 17, -77, 31, 44, 55, 200000]
>>> bubble_sort(unsorted_list)
>>> print unsorted_list
[-77, 17, 26, 31, 44, 54, 55, 93, 200000]
"""
for pass_number in range(len(un_list) - 1... | false |
9185f60dee9625d663bcecea816da0255507f7a3 | ukrduino/PythonElementary | /Lesson02/Exercise2_1.py | 724 | 4.65625 | 5 | # Write a recursive function that computes factorial
# In mathematics, the factorial of a non-negative integer n, denoted by n!,
# is the product of all positive integers less than or equal to n. For example,
# 5! = 5 * 4 * 3 * 2 * 1 = 120.
def factorial_rec(n):
"""
Computing factorial using recursio... | true |
a273d9b05d584d3818c2cfbd2a020d11c8d927f9 | rootzilopochtli/python-notes | /programming_in_python/classes.py | 1,205 | 4.1875 | 4 | # 15. Classes
# class
class Car:
def __init__(self,name,gear,miles):
self.name = name
self.gear = gear
self.miles = miles
def drive(self,miles):
self.miles = self.miles + miles
def shift_gear(self,gear):
self.gear = gear
car = Car("Tesla", 0, 0)
car.shift_gear(6)
de... | false |
4c289536721da7f0aacf1d7a09483102add0d98d | rootzilopochtli/python-notes | /programming_in_python/comparison_operators.py | 590 | 4.125 | 4 | # 10. Comparison operators
# compare
n1 = 5
n2 = 10
# greater than
n1_gt_n2 = n1 > n2 # return a boolean
#print(n1_gt_n2)
# less than
n1_lt_n2 = n1 < n2
#print(n1_lt_n2)
#print(83 < 120)
# greater than eqal
#print(n1 >= n2)
#print(99 >= 99)
# less than eqal
#print(5 <= 5)
# not eqal to
#print( 5 != 9 )
# eqal to
#print... | false |
ec90fa2fe745ef77be5573534260e1261f3a0d87 | Anku-0101/Python_Complete | /String/03_StringFunction.py | 329 | 4.15625 | 4 | story = "once upon a time there lived a guy named ABC he was very intelliget and motivated, he has plenty of things to do"
# String Function
print(len(story))
print(story.endswith("Notes"))
print(story.count("he"))
print(story.count('a'))
print(story.capitalize())
print(story.find("ABC"))
print(story.replace("ABC", ... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.