blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
22afc903d5165e253d50a10862ba8f994f6b5081 | johnnymcodes/cs131b_python_programming | /5_iteration/print_backwards.py | 275 | 4.15625 | 4 |
string = input('enter a string ')
print(string)
print(type(string))
backwardsString = ''
def print_backwards(string):
n = len(string)-1
while n > -1:
backwardsString += string[i]
n = n-1
print(backwardsString)
print_backwards(string)
| false |
ba5f177e8ed7dff0164f72206401d5dd35ab690a | johnnymcodes/cs131b_python_programming | /4_functions/w10exhand.py | 1,504 | 4.21875 | 4 | # Write a program that expects numeric command line arguments and calls
# functions to print descriptive statistics such as the mean, median,
# mode, and midpoint.
# Week 9 : Severance 4
import sys #expects numeric command line arguments
cmarg = sys.argv[1:] #returns a list of cmd arguments
numlist = list(... | true |
87f7b24055a392eb6a29a2a72b8b9395b4c083fe | johnnymcodes/cs131b_python_programming | /6_strings/sortuserinput.py | 944 | 4.5625 | 5 | #intro to python
#sort user input
#write a program that prints out the unique command line arguments
#it receives, in alphabetical order
import sys
cmdarg = sys.argv[1:]
cmdarg.sort()
delimiter = ' '
if len(cmdarg) > 1:
joinstring = delimiter.join(sys.argv[1:])
print('this is your command argument '... | true |
ff6e1c1d4887494c8ae8513f0f3b3e66dd895181 | MaximChernyak98/LP_homework | /lesson2/compare_str_if.py | 1,789 | 4.1875 | 4 | '''
Практика: Сравнение строк
Написать функцию, которая принимает на вход две строки
Проверить, является ли то, что передано функции, строками. Если нет - вернуть 0
Если строки одинаковые, вернуть 1
Если строки разные и первая длиннее, вернуть 2
Если строки разные и вторая строка 'learn', возвращает 3
Вызвать функцию н... | false |
8d88e73998d7d8bdfb3d323a963369c44aee27db | aliyakm/ICT_task1 | /3.py | 521 | 4.28125 | 4 | print("Please, choose the appropriate unit: feet = 1, meter = 2.")
unit = int(input())
print("Please, enter width and length of the room, respectively")
width = float(input())
length = float(input())
if unit == 1:
area = width*length
result = "The area of the room is {0} feets"
print(result.fo... | true |
92827541e986f956574b4c50ae27ba757dc6a9a1 | tarcisiocsn/4epy | /dictionaries02.py | 1,774 | 4.25 | 4 | #Counting Pattern
#the general pattern to count the words in a line of the text is to split the line
#into words, then loop through the words and use a dictionary to track the count of
#each word independently
counts=dict()
print('Enter a line of text: ')
line=input('') #se não colocar a definição de line essa porra d... | false |
2f91d697437a7ae3ffb51c07443634f68505566b | androidgilbert/python-test | /ex33.py | 514 | 4.1875 | 4 |
def test_while(a,b):
numbers=[]
i=0
while i<a:
print "At the top is %d"%i
numbers.append(i)
i=i+b
print "numbers now:",numbers
print "at the bottom i is %d"%i
return numbers
def test_for(a):
numbers=[]
for i in range(0,a,3):
print "at the top is %d"%i
numbers.append(i)
print "numbe... | true |
00cf375c449164d643f12c421ffc3fbbde8a789e | androidgilbert/python-test | /ex30.py | 410 | 4.15625 | 4 | people=30
cars=40
buses=15
if cars>people:
print "we should take the cars"
elif cars<people:
print "we should not take the cars"
else:
print "we can't decide"
if buses>cars:
print "that is too many buses"
elif buses<cars:
print "maybe we could take the buses"
else:
print "we still can not decide"
if people>buse... | true |
3391a8aed49e4335f75ad4b18ac26639b9752b6e | JenySadadia/MIT-assignments-Python | /Assignment2/list_comprehension(OPT.2).py | 714 | 4.125 | 4 | print 'Exercise OPT.2 : List comprehension Challenges(tricky!)'
print '(1)'
print 'find integer number from list:'
def int_element(lists):
return [element for element in lists if isinstance(element, int)]
lists = [52,53.5,"grp4",65,42,35]
print int_element(lists)
print '(2)'
print 'Here the y = x*x + ... | true |
860251764c96cccf6db12d1695ae1774d9332dc4 | Tanner0397/LightUp | /src/chromosome.py | 2,288 | 4.125 | 4 | """
Tanner Wendland
9/7/18
CS5401
Missouri University of Science and Technology
"""
from orderedset import OrderedSet
"""
This is the class defintion of a chromosome. A chromosome has genetic code that ddetermines the phenotype of the population member (the placement of the bulbs).
The genetic code is a li... | true |
3d66b0c6593a83435e0df5d2e132e8b504136e6c | antondelchev/Python-Basics | /Conditional-Statements-Advanced---Exercise/06. Operations Between Numbers.py | 877 | 4.21875 | 4 | number_one = int(input())
number_two = int(input())
action = input()
result = 0
if action == "+" or action == "-" or action == "*":
if action == "+":
result = number_one + number_two
elif action == "-":
result = number_one - number_two
elif action == "*":
result = number_one * numbe... | false |
a221f1dd62fc93c85c1329c670fe4d330df35caa | imthefrizzlefry/PythonPractice | /DailyCodingChallenge/Hard_Problem004.py | 1,069 | 4.125 | 4 | import logging
'''This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the ... | true |
79dacd2b79eb76486bfcb0ad860b01eced6ff016 | imthefrizzlefry/PythonPractice | /DailyCodingChallenge/Hard_Problem012.py | 1,032 | 4.53125 | 5 | '''This problem was asked by Amazon.
There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, ... | true |
b075eaa1eb0118a9f0fd0e112b91f318e4a98a20 | Aifedayo/Logic | /palindrome.py | 346 | 4.375 | 4 | def palindrome(string):
'''
Python function that checks whether a word
or phrase is palindrome or not
'''
new_string = string.replace(' ','')
if new_string == new_string[::-1]:
print(f'{string} is a palindrome')
else:
print(f'{string} is not a palindrome')
palindrome(input(... | true |
2b288e37ceb0c00528623ce6c863597d09aebfb8 | ish-suarez/afs-200 | /week5/function/function.py | 481 | 4.1875 | 4 | def step1():
user_input = []
print(f'I will be asking you for 3 numbers')
for i in range(3):
num = int(input(f'Give me a number: '))
user_input.append(num)
input_max = max(num for num in user_input)
input_min = min(num for num in user_input)
print(f'Your Numbers are: {user... | true |
affa4eda6861fe0c5a2e31f232d3714fa15d84e8 | ish-suarez/afs-200 | /week2/evenOrOdd/evenOrOdd.py | 1,078 | 4.28125 | 4 | # Getting input to determine if numbers are even or odd
def user_input_eve_or_odd():
number = int(input('Give me a number and I will tell you if it is even or odd? '))
check_if_even_or_odd = number % 2
if check_if_even_or_odd == 0:
print(f"{number} is Even")
else:
print(f"{number} is Od... | true |
4f22ae3685a8024e3a70f7721495510c0ca139db | maayan20-meet/meet2018y1lab5 | /fun2.py | 1,111 | 4.28125 | 4 | import turtle
turtle.goto(0,0)
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
direction = None
def up():
global direction
print("You pressed the up key.")
direction = UP
on_move()
def down():
global direction
print("you pressed the down key")
direction = DOWN
on_move()
def left():
global di... | false |
1ee69b4669c48ad85dd511ae57d7d4125cf6f645 | VimleshS/python-design-pattern | /Strategy pattern/solution_1.py | 2,021 | 4.125 | 4 | """
All the classes must in a seperate file.
Problems in this approch.
Order Class
It is not adhering to S of solid principles
There is no reason for order class to know about shipper.
Shipping Cost
Uses a default contructor.
Uses the shipper type stored in a shipper class to ca... | true |
3947858a10bb6fe6e1f0549d39c60f70de70a696 | UmberShadow/PigLatin | /UmberShadow_Pig Latin.py | 989 | 4.5 | 4 | #CJ Malson
#March 6th, 2021
#Intro to Python Programming
#Professor Wright
#I don't understand pig latin at all. What is this??
#Program requests a word (in lowercase letters) as input and translates the word into Pig Latin.
#If the word begins with a group of consonants, move them to the end of the word and ... | true |
693aa7a983a83814395518f00d68d6345502694b | luqiang21/Hackerrank.com | /Cracking the Coding Interview/Davis'_Staricase.py | 1,891 | 4.1875 | 4 | '''
Davis' staircase, climb by 1, 2 or 3 steps when given n stairs
in a staircase
'''
import numpy as np
def staircase(n):
# this function is written based on discussion of this problem on
# the website
A = [1,2,4]
A.append(sum(A))
A.append(A[1] + A[2] + A[3])
M = np.array([[1,1,0],[1,0,1],[1,0,0]])
An = np.arr... | true |
e5822481483705f34f2af0672ada9d3e81ed8af7 | jlesca/python-booleans | /values-booleans.py | 633 | 4.125 | 4 | # VALORES BOOLEANOS EN PYTHON
# En Python podemos usar operadores relacionales para comparar dos valores.
print(10 > 9) # Mostrará True
print(10 == 9) # Mostrará False
print(10 < 9) # Mostrará False
# Podemos hacer uso de un IF para comparar dos valores y ejecutar una instrucción si ese IF se cumple.
a = 10 # Creo ... | false |
4bd415c085f450727517e81170243dac251f4643 | danilvr/python-practice | /extra_practice05/part1/doctest/doctest_example.py | 1,154 | 4.1875 | 4 | def p1(a, b, c):
"""
Установление по сторонам (a, b, c) треугольника его типа:
равносторонний, разносторонний, равнобедренный.
Примеры:
>>> p1(1, 1, 1)
'равносторонний'
>>> p1(3, 4, 5)
'разносторонний'
>>> p1(5, 5, 3)
'равнобедренный'
>>> p1(1, 0, -1)
'сторона не может б... | false |
321cb60befeebd95889763e272177d7cdfd9f1a0 | sureshrmdec/algorithms | /app/dp/knapsack.py | 1,105 | 4.1875 | 4 | """
Given a weight limit for a knapsack, and a list of items with weights and benefits, find the optimal knapsack
which maximizes the benefit, whilee the total weight being less than the weight limit
https://www.youtube.com/watch?v=ipRGyCcbrGs
eg -
item 0 1 2 3
wt 5 2 8 6
benefit 9 3 1 4
wt limit = 10
soln: ... | true |
f45faa385782d01190945ab84805c8c3eabb9ad4 | martin-kar/project_euler | /p19_counting_sundays.py | 2,061 | 4.125 | 4 | """
Counting sundays
Problem 19
How many sundays fell on the first of the month during the twentieth
century (1 Jan 1901 to 31 Dec 2000)?
"""
DAYS_PER_WEEK = 7
SUNDAY = 7
DAYS_PER_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
MONTHS_PER_YEAR = 12
def get_days_this_month(month, year):
if is_leap_day(mo... | false |
28d24e0531c3f15a5f79fd0501f8f58662452f0b | joaolrsarmento/university | /courses/CT-213/lab3_ct213_2020/hill_climbing.py | 1,841 | 4.1875 | 4 | from math import inf
import numpy as np
def hill_climbing(cost_function, neighbors, theta0, epsilon, max_iterations):
"""
Executes the Hill Climbing (HC) algorithm to minimize (optimize) a cost function.
:param cost_function: function to be minimized.
:type cost_function: function.
:param... | true |
95bf38eccb1a70731cc9cc4602a440fdb98043dd | ranjanlamsal/Python_Revision | /file_handling_write.py | 1,891 | 4.625 | 5 | '''In write mode we have attributes such as :
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a f... | true |
3867392dee2e78d71c9a8bf99e1372a46a0eb726 | beyondvalence/thinkpython | /tp.05.py | 1,537 | 4.15625 | 4 | #! Thinking Python, Chp05, conditionals and recursion
#5.1 modulus operator
print("5.1")
print("156%100=")
print(156%100)
#5.9 E2 stack diagrams for recursive functions
print("5.9 E2")
def do_n(f,n):
if n<=0:
return
f()
do_n(f, n-1)
def print_now(s='now'):
print(s)
do_n(print_now,6)
#5.11 keyboard input
prin... | true |
d59b573a9bc93897e130ad223c08f0b22b99bf0b | ankarn/groupIII_twintrons | /groupIII_3'_motif_search.py | 2,605 | 4.125 | 4 | ################################################################################
#
# Search for Group III twinton 3' motifs
# ______________________________________
#
# A program to to find 3' motifs for group III twintrons, given the external
# intron in FASTA format.
#
# ** Prog... | true |
ca55b480b5735b4bc0bcb9feb1bb810de93a1007 | andrewrisse/Exercises | /ArrayAndStringProblems/URLify.py | 1,727 | 4.1875 | 4 | """
URLify.py
Creator: Andrew Risse
Drew heavily from example 1.3 in "Cracking the Coding Interview" in attempt to understand and
write their Java version in Python.
This program replaces spaces in a string with '%20'.
Assumptions: the string has sufficient space at the end to hold the additional characters and ... | true |
ac4be20f003f5e94d72f2251cc53f7ef384d02f0 | chunhuayu/Python | /Crash Course/06. Operators.py | 616 | 4.3125 | 4 | # Multiply 10 with 5, and print the result.
>>> print(10*5)
# Divide 10 by 2, and print the result.
>>> print(10/2)
# Use the correct membership operator to check if "apple" is present in the fruits object.
>>> fruits = ["apple", "banana"]
>>> if "apple" in fruits:
print("Yes, apple is a fruit!")
# ... | true |
0d303b898e689b0460aecb8d16248106d3a0073e | chunhuayu/Python | /Crash Course/0702. Tuple.py | 2,436 | 4.78125 | 5 | # Tuple is immutable
# A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
# Create a Tuple:
>>> thistuple = ("apple", "banana", "cherry")
>>> print(thistuple)
('apple', 'banana', 'cherry')
# Access Tuple Items: You can access tuple items by referring to the ind... | true |
57c29ce26289441922f017c49a645f8cbe9ce17f | rajatpachauri/Python_Workspace | /While_loop/__init__.py | 260 | 4.25 | 4 | # while loop is mostly used for counting
condition = 1
while condition < 10:
print(condition)
condition += 1
# condition -= 1
# to create out own infinite loop
while True:
print('doing stuff')
# for breaking use control+c | true |
1aa840435f3eaabb240f81d193c62b3381f52110 | Aminaba123/LeetCode | /477 Total Hamming Distance.py | 1,306 | 4.1875 | 4 | #!/usr/bin/python3
"""
The Hamming distance between two integers is the number of positions at which
the corresponding bits are different.
Now your job is to find the total Hamming distance between all pairs of the
given numbers.
Example:
Input: 4, 14, 2
Output: 6
Explanation: In binary representation, the 4 is 010... | true |
0674b8d7de1b0a1f417b11be2eac016d459c8be5 | Aminaba123/LeetCode | /063 Unique Paths II.py | 1,948 | 4.1875 | 4 | """
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0... | true |
a8e56295e5b3d81fc6b63eb549d4a4d4f51dd7ea | Aminaba123/LeetCode | /433 Minimum Genetic Mutation.py | 2,041 | 4.15625 | 4 | #!/usr/bin/python3
"""
A gene string can be represented by an 8-character long string, with choices
from "A", "C", "G", "T".
Suppose we need to investigate about a mutation (mutation from "start" to
"end"), where ONE mutation is defined as ONE single character changed in the
gene string.
For example, "AACCGGTT" -> "A... | true |
64ebeedfbf3d242316451493e0407916896c2f77 | Aminaba123/LeetCode | /403 Frog Jump.py | 2,164 | 4.28125 | 4 | """
A frog is crossing a river. The river is divided into x units and at each unit there may or may not exist a stone. The
frog can jump on a stone, but it must not jump into the water.
Given a list of stones' positions (in units) in sorted ascending order, determine if the frog is able to cross the river
by landing o... | true |
24ba1fb74133913ff4642b3168f44b775cf64b7c | Aminaba123/LeetCode | /384 Shuffle an Array.py | 1,372 | 4.28125 | 4 | """
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array ba... | true |
13684394a6e93a3c95c3c7916fcb88113a22e7a0 | Aminaba123/LeetCode | /088 Merge Sorted Array.py | 1,122 | 4.125 | 4 | """
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The
number of elements initialized in A and B are m and n respectively.
"""
__author__ = 'Danyang'
class... | true |
36bd7b053f22dbde6145ee948b168bb114a1bcfe | Aminaba123/LeetCode | /225 Implement Stack using Queues.py | 1,673 | 4.28125 | 4 | """
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Notes:
You must use only standard operations of a queue -- which means only push to back, p... | true |
85068b845fc62bc3ca6b9307072225de0f5d380f | Aminaba123/LeetCode | /353 Design Snake Game.py | 2,043 | 4.4375 | 4 | """
Design a Snake game that is played on a device with screen size = width x height.
"""
from collections import deque
__author__ = 'Daniel'
class SnakeGame(object):
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@par... | true |
0f0c2b71165908b69143488b544ec20e7192961b | jiankangliu/baseOfPython | /PycharmProjects/02_Python官方文档/一、Python初步介绍/03_Python控制流结构/3.2判断结构.py | 1,030 | 4.125 | 4 | #3.2.1 if-else语句
#例1 求较大值
num1=eval(input("Enter the first number: "))
num2=eval(input("Enter the second number: "))
if num1>num2:
print("The larger number is:",num1)
else:
print("The larger number is: ",num2)
#3.2.2 if语句
firstNumber=eval(input("Enter the first number: "))
secondNumber=eval(input("E... | true |
3ba28ea233a3f3736bbcd8d520b3369f33ee379b | chaofan-zheng/tedu-python-demo | /month01/all_code/day09/demo07.py | 819 | 4.46875 | 4 | """
面向对象:软件编程思想
找谁 干嘛?
现实事物 -抽象-> 类(模板) -具体-> 对象
车 class Car: Car(xx,xx,xx)
车牌 京E0001
品牌 奔驰
颜色 白色
"""
# 创建类(抽象化)
class Wife:
"""
自定义类 - 老婆
"""
# 数据
def __in... | false |
a04882c6e51ff77d30d39c8f234e46d6f0ae9d75 | chaofan-zheng/tedu-python-demo | /month01/all_code/day04/demo13.py | 873 | 4.21875 | 4 | """
切片:定位多个元素
for number in range(开始,结束,间隔)
"""
message = "我是花果山水帘洞美猴王孙悟空"
# 写法1:容器名[开始: 结束: 间隔]
# 注意:不包含结束
print(message[2: 5: 1])
# 写法2:容器名[开始: 结束]
# 注意:间隔默认为1
print(message[2: 5])
# 写法3:容器名[:结束]
# 注意:开始默认为头
print(message[:5])
# 写法4:容器名[:]
# 注意:结束默认为尾
print(message[:])
message = "我是花果山水帘洞美猴王孙悟空"
# 水帘洞... | false |
727b4ee599937e2177ffb98ca6ffe9ed13ae116d | chaofan-zheng/tedu-python-demo | /month01/all_code/day06/demo01.py | 1,504 | 4.34375 | 4 | """
笔试题:
请叙述元组与列表的区别.
答:内存存储机制不同.
元组采用按需分配的存储机制,节省内存.
列表 预留空间 + 自动扩容,操作灵活
面试题:
为什么要有元组(为什么要有不可变).
答:任何数据本质都可以理解为不可变,元组就是不可变数据.(计算机世界)
但是在实际应用中,需要不断存储新数据,所以Python提供了列表.
Python语言有哪些数据类型
答:只可变与不可变2种类型
常用的可变数据:列表...
... | false |
4ea129f839988825cb63b8fbb294dd8edadcb662 | chaofan-zheng/tedu-python-demo | /month01/all_code/day07/exercise09.py | 267 | 4.21875 | 4 | # 练习2:创建函数,在终端中打印矩形.
def print_rectangle(number):
for row in range(number):
if row == 0 or row == number - 1:
print("*" * number)
else:
print("*%s*" % (" " * (number - 2)))
print_rectangle(8) | false |
d2bdd6b93d56863575896542acf8995db880c5f4 | chaofan-zheng/tedu-python-demo | /month01/all_code/day11/exercise06.py | 645 | 4.4375 | 4 | """
练习:
创建子类:狗(跑),鸟类(飞)
创建父类:动物(吃)
体会子类复用父类方法
体会 isinstance、issubclass与type的作用.
"""
# 从思想层面讲:先有子再有父,从子 -泛化-> 到父
# 从编码层面讲:先有父再有子,从父 -特化-> 到子
class Animal:
def eat(self):
print("吃")
class Dog(Animal):
def run(self):
print("跑")
class Bird(Animal):
de... | false |
52d27a07d787975725603b50590605b7463fe380 | chaofan-zheng/tedu-python-demo | /month01/all_code/day12/homework/exercise02.py | 645 | 4.125 | 4 | """
需求:小明使用手机打电话
划分原则:
数据不同使用对象区分 -- 小王/小孙...
行为不同使用类区分 -- 手机/卫星电话...
识别对象:
人类 手机
分配职责:
打电话 通话
建立交互:
人类 调用 手机
"""
class Person:
def __init__(self, name=""):
self.name = name
def call(self, communication):
pr... | false |
be3e780e2aa09537a6a6df9e65bc5c15eb4da166 | chaofan-zheng/tedu-python-demo | /month01/all_code/day11/homework/exercise03.py | 1,351 | 4.15625 | 4 | """
5. 创建电脑类,保护数据在有效范围内
数据:型号, CPU型号, 内存大小, 硬盘大小
不超过10个字符 大于0 元组长度大于等于1
"""
class Computer:
def __init__(self, model_number="", cpu="", memory=0, hard_disk=()):
self.model_number = model_number
self.cpu = cpu
self.memory = memory
self.hard_... | false |
5a391b6015b94af3800dba89cf6ed07e94d1f445 | daniyaniazi/Python | /COLLECTION MODULE.py | 2,510 | 4.25 | 4 | """COLLECTION MODULE IN PYTHON """
#LIST TUPLE DICTIONARY SET ARE CONTAINER
#PYTHON HAS COLLECTION MODULE FOR THE SHORTCOMMING OF DS
#PRVIDES ALTERNATIVES CONTAINER OF BUILTIN DATA TYPES
#specializex collection datatype
"""nametupele(), chainmap, deque, counter, orderedDict, defaultdic , UserDict, UserList,UserString""... | true |
6f6a30c997764bad22985c0a8053c88241f4f499 | themorsten/DataStructures | /DoublyLinkedList/DoublyLinkedList.py | 1,290 | 4.125 | 4 | class DoublyLinkedListNode:
def __init__(self,value):
self.value = value
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, value): # добавить в конец
newNode = DoublyLinkedListNode(value)
if self.head: ... | false |
aca916cd7150ccdc1dc3ddad48f5b41d53007f7f | StealthAdder/SuperBasics_Py | /functions.py | 2,101 | 4.46875 | 4 | # function is collection of code
# they together work to do a task
# they are called using a function call.
# to create a function we use a keyword called "def"
# --------------------------------------------------
# create a function.
def greetings():
print("Hello Dude!")
greetings() #calling the functi... | true |
89edd52a8e28902a6331f7d939e3a369e3e14e69 | Aravind-2001/python-task | /4.py | 242 | 4.15625 | 4 | #Python program to divided two numbers using function
def divided_num(a,b):
sum=a/b;
return sum;
num1=int(input("input the number one: "))
num2=int(input("input the number one :"))
print("The sum is",divided_num(num1,num2))
| true |
bf2443eb20578d0e4b5765abc5bd6d3c46fabdc6 | leelaram-j/pythonLearning | /com/test/package/lists.py | 1,231 | 4.125 | 4 | """
List in python
written inside []
sequence type, index based starts from 0
mutable
"""
a = [1, 2, 3, 4, 5]
print(a)
print(type(a))
print(a[1])
# array slicing
print("Slicing")
print(a[0:3])
print(a[2:])
print(a[:3])
print("-------------")
a = [1, "sample", True, 10.45, [1, 2, 3, 4]]
print(a)
print(type(a))
prin... | true |
934f9b2581ab5fa583aaf274d068448b9cc4f0de | sharpchris/coding352 | /8.py | 2,259 | 4.375 | 4 | # Codebites URL: https://codechalleng.es/bites/21/
cars = {
'Ford': ['Falcon', 'Focus', 'Festiva', 'Fairlane'],
'Holden': ['Commodore', 'Captiva', 'Barina', 'Trailblazer'],
'Nissan': ['Maxima', 'Pulsar', '350Z', 'Navara'],
'Honda': ['Civic', 'Accord', 'Odyssey', 'Jazz'],
'Jeep': ['Grand Cherokee', '... | true |
037920de71306887635d46953eb21890f00d9593 | yeri96/AlgoritmicaBasica_2018 | /Mayor_Menor/mayor_menor.py | 1,617 | 4.4375 | 4 | # coding: utf-8
numero1 = input("Introduce el primer número: ")
numero2 = input("Introduce el segundo número: ")
numero3 = input("Introduce el tercer número: ")
if numero1 == numero2 and numero1 == numero3:
print "Ha escrito 3 veces el mismo número"
else:
if numero1 == numero2 and numero1 != numero3:
p... | false |
a017de5cb43b53b1f7c796ab015b91a68f09efdf | abhishekratnam/Datastructuresandalgorithmsinpython | /DataStructures and Algorithms/Recursion/Reverse.py | 445 | 4.1875 | 4 | def reverse(S, start, stop):
"""Reverse elements in emplicit slice S[start:stop]."""
if start < stop - 1:
S[start], S[stop-1] = S[stop - 1], S[start]
reverse(S, start+1, stop - 1)
def reverse_iterative(S):
"""Reverse elements in S using tail recursion"""
start,stop = 0,len... | true |
e03f40711cfe8a26b38de0c63faaee30e1b0e336 | pragatishendye/python-practicecode | /FahrenheitToCelsius.py | 338 | 4.40625 | 4 | """
This program prompts the user for a temperature in Fahrenheit and returns
the Celsius equivalent of it.
Created by Pragathi Shendye
"""
tempInFahrenheit = float(input('Enter a temperature in Fahrenheit:'))
tempInCelsius = (tempInFahrenheit - 32) * (5 / 9)
print('{} Fahrenheit = {:.2f} Celsius'.format(tempI... | true |
23a9baab1b0308bde129e6d01894f56ea79e3c64 | iresbaylor/codeDuplicationParser | /engine/utils/printing.py | 921 | 4.1875 | 4 | """Module containing methods for pretty-printing node trees."""
def print_node_list(node_list):
"""
Print a list of TreeNodes for debugging.
Arguments:
node_list (list[TreeNode]): a list of tree nodes
"""
for node in node_list:
if node.parent_index is None:
print_node... | true |
f29ca346f0977a08234ceeb742e13ff1ec31fb11 | upputuriyamini/yamini | /al.py | 211 | 4.15625 | 4 | al=int(input())
if al == 0:
exit();
else:
if((al>='a' and al>='z') or (al>='A' and al>='Z')):
print(al, "is an alphabet.")
else:
print(al,"is not an alphabet")
| false |
433453e34c036cf7b04079f06debd27ba3c31e69 | amarish-kumar/Practice | /coursera/coursera_data_structures_and_algorithms/course_1_algorithmic_toolbox/Week_4/binarysearch/binary_search.py | 2,180 | 4.15625 | 4 | #python3
'''Implementation of the binary search algoritm.
Input will contain two lines. First line will
have an integer n followed by n integers in
increasing order. Second line will have an
integer n again followed by n integers. For
each of the integers in the second line, you
have to perform bi... | true |
a58e51493d43ad0df89b3836366ef7b729223d57 | jnoriega3/lesson-code | /ch6/printTableFunctions.py | 2,680 | 4.59375 | 5 | # this is the printTable function
# parameter: tableData is a list of lists, each containing a word
# we are guaranteed that each list is the same length of words
# this function will print our table right-justified
def printTable( tableData ):
#in order to be able to right-justify each word, we'll... | true |
72218d09cd2c9a05bae3d9a2f22eccba436a554d | jnoriega3/lesson-code | /ch4/1-list-print.py | 638 | 4.46875 | 4 | #this defines a function with one parameter, 'theList'
def printList( theList ):
# this for loop iterates through each item in the list, except the last item
for i in range( len(theList)-1 ): #can you remember what this line does?
#this will add a comma after each list item
print( str(theList[i]... | true |
db8cc0d6b26b66a57b5db9b2478bedb0b463e5a6 | burakdemir1/BUS232-Spring-2021-Homeworks | /hw7.py | 407 | 4.21875 | 4 | names = ("Ross","Rachel","Chandler","Monica","Joey","Phoebe")
friends_list = set()
for name in names:
names_ = input(f'{name}, enter the names of the friends you invited: ')
name_list = names_.split()
for name in name_list:
friends_list.add(name)
print('This is final list of people invite... | true |
18290bee33c550d52f7b3133320f40f1f43296ff | edersonlucas/Calculadora_IMC_Python | /calculadoraIMC.py | 2,272 | 4.15625 | 4 | '''
Calculadora IMC
Autor: Ederson Lucas
'''
#Entrada do Nome
nome = input('Qual seu nome? ')
# Laço ano
while True:
idade = input('Qual sua idade? ')
if idade.isdigit() == False or int(idade) <= 0:
print('Digite uma idade valida!')
continue
else:
idade = int(idade)
if i... | false |
e0c8f24b3fd76f748f8aff3e31c04ec314ab6bba | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/IntroToObjects_List.py | 741 | 4.53125 | 5 | #Lists - An unordered sequence of items
groceryList = ['Greens', 'Fruits', 'Milk']
print("My Grocery list is ", groceryList)
#You can iterate over lists. What's Iterate?
#Iterate means go one by one element traverssing the full list
#We may need to iterate the list to take some action on the given item
#e.g. what is ... | true |
19a636342dcb726c0a3c1ac89dab78319e4ca0c7 | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/Files_Reading.py | 1,152 | 4.28125 | 4 | #Opening a file using the required permissions
f = open("data/drSeuss_green_eggs_n_ham.txt","r")
#Reading a file using readline() function
print("== Using for loop to read and print a file line by line ==")
#Default print parameters
for line in f:
print(line)
#Extra new lines after the every line. Why?
#Specify... | true |
01dc63ff29161279ab8cb689d375895180efc241 | skoolofcode/SKoolOfCode | /The Geeks/modules/IntroToModule.py | 780 | 4.15625 | 4 |
#introduction to Modules
#Let's create a module hello that has 2 function helloWorld() and helloRedmond()
#Diffirent ways of importing the module
#1. Import module as is with its name. Note the usage <module>.<function>
import hello
hello.helloIssaquah()
hello.helloRedmond()
hello.helloSeattle()
hello.helloBangal... | true |
fac14e0cfee5d22b65ca14fce29909c03c5a4f83 | skoolofcode/SKoolOfCode | /TrailBlazers/LiveClass/Class_3_2_Live.py | 820 | 4.15625 | 4 | #Print a decimal number as binary
#"{0:b}".format(number)
j = 45
print("The number j in decimal is ",j)
print("{0:b}".format(j))
#Use ord() to get Ascii codes for a given character
storeACharacter = 'a'
print("I am printing a character ", storeACharacter)
print("The ASCII code for a is ", ord(storeACharacter))
#Lets ... | true |
83e14b2a1a0b7d360c9ef3b979b5ac1c6fff630f | skoolofcode/SKoolOfCode | /CodeNinjas/SimplifiedHangMan.py | 1,441 | 4.46875 | 4 | #Simplified Hangman
#Present a word with only first 3 characters. Rest everything is masked
#The user would be asked to guess the word. He/She wins if the word is correctly guessed.
#A user get a total of 3 tires. At every try a new character is shown.
#Let's have a global word list.
worldList = ["batman","jumpsui... | true |
dbf8ea3834665ffc7df5953b5974455849501e16 | skoolofcode/SKoolOfCode | /The Geeks/list_methods.py | 1,042 | 4.59375 | 5 | # This file we'll be talking about Lists.
#Create a list
print("\n *** printing the list ***")
groceryList = ['Milk', 'Oranges', "Cookies", "Bread"]
print(groceryList)
#Append to the list. This also means add a item to the list
print("\n*** Add pumpkin to the list")
groceryList.append("pumpkin")
print(groceryList)
#... | true |
ac998b57fae60f1088db024c902ec8a9994b00d3 | skoolofcode/SKoolOfCode | /TrailBlazers/maanya/practice/caniguessyourage.py | 1,024 | 4.125 | 4 | def thecoolmathgame ():
print("Hello. I am going to guess your age today! I promise I will not cheat :)")
startnum = int(input("Pick a number from 1-10:"))
print("Now I will multiply your chosen number by 2.")
age = startnum * 2
print ("Now I will add 5 to the new number.")
age = age + 5
print("Now I will multip... | true |
315e47a3d80ac5835bb40dcc890b7bc924c08c1e | martyav/algoReview | /pythonSolutions/most_frequent_character.py | 878 | 4.1875 | 4 | # Frequency tables, frequency hashes, frequency dictionaries...
#
# Tomayto, tomahto, we're tracking a character alongside how many times it appears in a string.
#
# One small optimization is to update the most-frequently-seen character at the same time as
# we update the dictionary.
#
# Otherwise, we'd have to write ... | true |
07482b5f7f8b1ba25dbedc9a1f4398bb66ebd04a | SamuelNgundi/programming-challenges-with-python | /3.11. Book Club Points.py | 1,264 | 4.21875 | 4 | """
11. Book Club Points
Serendipity Booksellers has a book club that awards points to its customers
based on the number of books purchased each month.
The points are awarded as follows:
- If a customer purchases 0 books, he or she earns 0 points
- If a customer purchases 2 books, he or she earns 5 points
- If a cust... | true |
bb5d1cdeede1ec0a878ad5ee0f023e331f75d2dd | SamuelNgundi/programming-challenges-with-python | /3.2. Areas of Rectangles.py | 1,179 | 4.46875 | 4 | """
2. Areas of Rectangles
The area of a rectangle is the rectangles length times its width.
Write a program that asks for the length and width of two rectangles.
The program should tell the user which rectangle has the greater area,
or if the areas are the same.
Reference:
(1) Starting out with Python, Third Editi... | true |
afe32f4de9c73b431f8e20694a975a45ae993b34 | SamuelNgundi/programming-challenges-with-python | /3.1. Day of the Week.py | 1,136 | 4.46875 | 4 | """
1. Day of the Week
Write a program that asks the user for a number in the range of 1 through 7.
The program should display the corresponding day of the week, where 1 = Monday,
2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday,
and 7 = Sunday.
The program should display an error message if the u... | true |
7e1205f5489688438da50bb992c737eaaf9504fa | rickydhanota/Powerset_py | /powerset_med.py | 1,006 | 4.15625 | 4 | #Powerset
#Write a function that takes in an array of unique integers and returns its powerset.
#The powerset P(X) of a set X is the set of all the subsets of X. for example, the powerset of [1, 2] is [[], [1], [2], [1, 2]]
#Note that the power sets do not need to be in any particular order
#Array = [1, 2, 3]
#[[], [... | true |
9b010ff1877e1ef42db1fe2f8d630dff72b2c544 | JakobHavtorn/algorithms-and-data-structures | /data_structures/stack.py | 1,975 | 4.1875 | 4 | class Stack(object):
def __init__(self, max_size):
"""Initializes a Stack with a specified maximum size.
A Stack incorporates the LIFO (Last In First Out) principle.
Args:
max_size (int): The maximum size of the Stack.
"""
assert type(max_size) is int and max_si... | true |
0cac7a90f5b2e66b12400a09cb98a0028eda2883 | Utkarsh016/fsdk2019 | /day4/code/latline.py | 426 | 4.15625 | 4 | """
Code Challenge
Name:
Last Line
Filename:
lastline.py
Problem Statement:
Ask the user for the name of a text file.
Display the final line of that file.
Think of ways in which you can solve this problem,
and how it might relate to your daily work with Python.
"""
file_name=input("ent... | true |
e5a23142c19ef32b8bd5afc36370fc733be83284 | gagande90/Simple-Gui-Programs-Python | /Simple/2_adding_widgets.py | 789 | 4.34375 | 4 | import tkinter as tk # alias tkinter as "tk"
from tkinter import ttk # ttk == "themed tk"
gui = tk.Tk() # create Tk() instance and assign to variable
ttk.Label(gui, text="Hello Label").\
... | false |
1afcc2281ee5a21f3fc4b7327582d5fb96dd4dcb | Harguna/Python | /calc.py | 1,335 | 4.21875 | 4 | print("Press: 1 for even-odd ")
print("Press: 2 for prime number ")
print("Press: 3 for factorial ")
print("Press: 4 for average ")
print("\n")
opt= int( input ("Enter your option: "))
def even_odd(num1):
if num1==0:
print("Number is neither even nor odd")
if num1%2==0:
print("Number is even")
e... | false |
8662bda8ca8c11a857c90048e588861d7eb475c7 | rshandilya/IoT | /Codes/prac2d.py | 1,523 | 4.3125 | 4 | ############# EXPERIMENT 2.D ###################
# Area of a given shape(rectangle, triangle, and circle) reading shape and
# appropriate values from standard input.
import math
import argparse
import sys
def rectangle(x,y):
"""
calculate area and perimeter
input: length, width
output: dict - area, p... | true |
7bf6f58e13b0f780d83aeadd9893382d68762ab5 | veyu0/Python | /les_6/les_6_task_4.py | 2,470 | 4.1875 | 4 | class Car:
''' Автомобиль '''
_speed = None
_color = None
_name = None
_is_police = False
def __init__(self, name, color):
self.name = name
self.color = color
print(f'Новая машина: {self.name} (цвет {self.color}) {type(self)}')
def go(self):
pri... | false |
7ad247c561871ac54719ae32ad42be206364b6b5 | veyu0/Python | /les_2/les_2_task_2.py | 655 | 4.46875 | 4 | '''Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input().'''
list = list(input('Введите число: '))
... | false |
405b6b42a5524fab2960666eafa33887d7b8447f | antigravitybird/pynet_test | /ex_17_callfunc.py | 888 | 4.25 | 4 | #!/usr/bin/env python
def my_func(x, y, z=20):
return x + y + z
def my_func2(x, y, z=20):
return x, y, z
print
print "Calling with three positional arguments: "
print "Value: ", my_func(10, 20, 30)
print
print "Calling with two named arguments: "
print "Value: ", my_func(x=10, y=20)
print
print "Calling with... | false |
3d120963e6082fc867cb0b2266e0f4aa63ff458e | wensheng/tools | /r2c/r2c.py | 1,795 | 4.25 | 4 | #!/bin/env python
"""
Author: Wensheng Wang (http://wensheng.com/)
license: WTFPL
This program change change rows to columns in a ASCII text file.
for example:
-----------
hello
world
!
-----------
will be converted to:
-----------
h w!
e o
l r
l l
o d
-----------
If you specify '-b', vertical bars will be added to... | true |
0b44b64de6e6b1c1e58b40b4d793d4e5bb14cbc2 | zertrin/zkpytb | /zkpytb/priorityqueue.py | 2,082 | 4.25 | 4 | """
An implementation of a priority queue based on heapq and
https://docs.python.org/3/library/heapq.html#priority-queue-implementation-notes
Author: Marc Gallet
Date: 2018-01
"""
import heapq
import itertools
class EmptyQueueError(Exception):
pass
class PriorityQueue:
"""Based on https://docs.python.org/... | true |
c73cf61e5a79744a8aaa15c9545bddc5b3b47692 | programmersteven/python_exercise | /prac_05/hex_colours.py | 496 | 4.3125 | 4 | COLOR_TO_CODE = {"AliceBlue": "#f0f8ff","blue1": "#0000ff","black":"#000000","brown":"#a52a2a",
"coral": "#ff7f50","DarkGoldenrod": "#b8860b","DarkOrchid": "#9932cc","DarkSeaGreen": "#8fbc8f",
"DimGray": "#696969","firebrick": "#b22222"}
color = input("Enter the color's name: ")
while ... | false |
ccb58c3b3faee4d0b2a14e600c2881a3d5ecb362 | atravanam-git/Python | /DataStructures/tuplesCodeDemo_1.py | 1,133 | 4.6875 | 5 | """tuples have the same properties like list:
#==========================================================================
# 1. They allow duplicate values
# 2. They allow heterogeneous values
# 3. They preserve insertion order
# 4. But they are IMMUTABLE
# 5. tuple objects can be used as keys in Dictionaries
#=========... | true |
0160126d1a2e614c95b844adb1524a6982f50493 | atravanam-git/Python | /FunctionsDemo/globalvarDemo.py | 902 | 4.53125 | 5 | """
#==========================================================================
# 1. global vs local variables in functions
# 2. returning multiple values
# 3. positional args vs keyword args
# 4. var-args, variable length arguments
# 5. kwargs - keyword arguments
#======================================================... | true |
397cf4e1582b4f6e5f30a51a5ef531231fdba1b2 | javatican/migulu_python | /class2/if3.py | 220 | 4.125 | 4 | x=-101
if x%2 and x>0:
print(x,"是正奇數")
elif x%2 and x<0:
print(x,"是負奇數")
elif x%2==0 and x>0:
print(x,"是正偶數")
elif x%2==0 and x<0:
print(x,"是負偶數")
else:
print(x,"是0") | false |
964c6e0588f5e3ca4aabb1cd861357f6d935a595 | cuongdv1/Practice-Python | /Python3/database/create_roster_db.py | 2,652 | 4.125 | 4 | """
Create a SQLite database using the data available in json stored locally.
json file contains the users, courses and the roles of the users.
"""
# Import required modules
import json # to parse json
import sqlite3 # to create sqlite db
import sys # to get coomand line arguments
# G... | true |
b0436a9cd1ab679ac92b3fa3bd75786a3cb52067 | spectrum556/playground | /src/homework_1_additional/h_add.7.py | 566 | 4.25 | 4 | __author__ = 'Ihor'
month_num = int(input('enter the number of month\n'))
def what_season(month_num):
if month_num == 1 or month_num == 2 or month_num == 12:
return 'Winter'
elif month_num == 3 or month_num == 4 or month_num == 5:
return 'Spring'
elif month_num == 6 or month_num == 7 or m... | true |
c1e0a3c70cfd90f4753bc9b46c101c2e7ad1227d | wardk6907/CTI110 | /P5T2_FeetToInches_KaylaWard.py | 520 | 4.3125 | 4 | # Feet to Inches
# 1 Oct 2018
# CTI-110 P5T2_FeetToInches
# Kayla Ward
#
# Constant for the number of inches per foot.
inches_per_foot = 12
# Main Function
def main():
# Get a number of feet from the user.
feet = int(input("Enter a number of feet: "))
# Convert that to inches.
print(f... | true |
55accbf96df3236d8b55ada121259a0cf95daf99 | PraveenMut/quick-sort | /quick-sort.py | 783 | 4.15625 | 4 | # QuickSort in Python using O(n) space
# tester array
arr = [7,6,5,4,3,2,1,0]
# partition (pivot) procedure
def partition(arr, start, end):
pivot = arr[end]
partitionIndex = start
i = start
while i < end:
if arr[i] <= pivot:
arr[i],arr[partitionIndex] = arr[partitionIndex],arr[i]
partitionInd... | true |
ed4bf2d14601305473a0e708b7933c28c679aed5 | bscott110/mthree_Pythonpractice | /BlakeScott_Mod2_TextCount.py | 1,366 | 4.3125 | 4 | import string
from string import punctuation
s = """Imagine a vast sheet of paper on which straight Lines, Triangles, Squares, Pentagons, Hexagons, and other figures,
instead of remaining fixed in their places, move freely about, on or in the surface,
but without the power of rising above or sinking below it, v... | true |
b54d309379486f336fcd189b81a9a1df5fba77d0 | AnirbanMukherjeeXD/Explore-ML-Materials | /numpy_exercise.py | 2,818 | 4.28125 | 4 | # Student version : https://tinyurl.com/numpylevel1-280919
# Use the numpy library
import numpy as np
def prepare_inputs(inputs):
# TODO: create a 2-dimensional ndarray from the given 1-dimensional list;
# assign it to input_array
n = len(inputs)
input_array = np.array(inputs).reshape(1,n)
... | true |
183c214562494a3c9ade3e285d5a68dc8f0ba856 | MikeDiaz93/Problems_VS_Algorithms | /Dutch_National_Flag_Problem/Dutch_National_Flag_Problem.py | 1,949 | 4.15625 | 4 | def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
if input_list == None:
return None
if input_list == []:
return []
aux1 = 0
aux2 = 0
middle ... | false |
f7754142cebe7e721ca0cd13187d4025a625cdba | cbira353/buildit-arch | /_site/writer1.py | 445 | 4.15625 | 4 | import csv
from student import Student
students = []
for i in range(3):
print('name:', end='')
name = input()
print('dorm:', end='')
dorm = input()
students.append(Student(name, dorm))
for student in students:
print("{} is in {}.".format(student.name, student.dorm))
file =open("students.cs... | true |
94908555a5067b29f51bc69eb397cb1f3aace887 | onizenso/College | /classes/cs350/wang/Code/Python/coroutines.py | 1,990 | 4.5 | 4 | #!/usr/bin/env python
# demonstrate coroutines in Python
# coroutines require python 2.5
"""
this simple example is a scheduler for walking dogs
the scheduler subroutine and main() act as coroutines
yield hands off control, next() and send() resumes control
"""
def printdog(name): # a... | true |
2696488fbf8a0c27b5c410bdca8fab666eeaa213 | BeniyamL/alx-higher_level_programming | /0x0A-python-inheritance/9-rectangle.py | 1,166 | 4.34375 | 4 | #!/usr/bin/python3
"""
class definition of Rectangle
"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Rectangle(BaseGeometry):
"""
class implementation for rectangle
"""
def __init__(self, width, height):
"""initialization of rectangle class
Arguments:
w... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.