blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
533b8da62de65025cbb71c981eade387bf694d68 | chanshik/codewars | /dragon_curve.py | 1,783 | 4.53125 | 5 | """
The dragon's curve is a self-similar fractal which can be obtained by a recursive method.
Starting with the string D0 = 'Fa', at each step simultaneously perform the following operations:
replace 'a' with: 'aRbFR'
replace 'b' with: 'LFaLb'
For example (spaces added for more visibility) :
1st iteration: Fa -> F ... | true |
a56d602738b04e9e1aafc27f2aeff127da7a82a5 | emretokk/codeforces | /800/word.py | 719 | 4.15625 | 4 | """
that would change the letters' register in every word
so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones.
( tersine )
input :
The first line contains a word s — it consists of uppercase and lowercase Latin letters and possesses the length from 1 to 100.
... | true |
8c093593ac10bc378c7c897fcfdf60d65cd7011c | Zzz-ww/Python-prac | /python_Project/Day_08/test_1.py | 1,366 | 4.40625 | 4 | """
在Python中可以使用class关键字定义类,
然后在类中通过之前学习过的函数来定义方法,
这样就可以将对象的动态特征描述出来,
代码如下所示。
"""
class Student(object):
# __init__是一个特殊方法用于在创建对象时进行初始化操作
# 通过这个方法我们可以为学生对象绑定name和age两个属性
def __init__(self, name, age):
self.name = name
self.age = age
def study(self, course_name):
print('%s正在学习... | false |
2a1fc488fef69bace682aa04094d77cd028fb993 | vrednyydragon/ProjectEuler | /py_src/Problem001_2.py | 815 | 4.25 | 4 |
class Sum():
def SumMultiplues(self, input_data):
assert 0 < int(input_data), "Вводимые данные должны быть числами больше 0 числами и целыми!!!"
numb = int(input_data)
iterator=0
sum_ = 0
for i in range (numb):
iterator=i
if (iterator%3==0 or iterator%5==0):
print("кратное 3 или 5: " + str(iter... | false |
355421abb31a6d13fa52ed315082c92ce25e5272 | Deepanshu276/AlgorithmToolbox | /Array/2D-array/creatingArray.py | 281 | 4.25 | 4 | import numpy as np
arr1=np.array([[1,2,3],[4,5,6],[7,8,9]])
"""Time complexity in thios is O(1) as we are simultaneously giving the value in the array
but if we insert the value one by one in the array then the time complexity will be O(m*n)
where m=row and n=column"""
print(arr1) | true |
f51c20b97fc016f582163475675042b425a394b1 | 18516264210/MachineLearning | /sorts/select_sort.py | 1,602 | 4.28125 | 4 | """
使用选择排序法进行数据的排序
什么是选择排序,通过内层循环,找到值最大的索引,然后将最大值放在最后面;
或者是通过内层循环,找到值最小的索引,然后将最小值放在最前面。
正序和逆序无所谓
"""
def select_sort_1():
"""对数组进行从小到大排序,先排小值到最前"""
data = [9,3,7,6,5,4,8,2,1]
for i in range(len(data)):
index = i
# 从index开始遍历,与下一个元素进行比较,获取到值为最大的index
for j in range(i,... | false |
d84a72df4fd58fba1a1aedfe016ebdb18b33705d | ProProgrammer/asyncio-rp | /theory.py | 1,567 | 4.1875 | 4 | from typing import Generator
from random import randint
import time
import asyncio
def odds(start, end) -> Generator:
"""
Produce a sequence of odd values starting from start until end including end
Args:
start:
end:
Returns: Yield each value
"""
for odd in range(start, end ... | true |
071429abd45ee187f732a3cd50c13088eb94f720 | knparikh/IK | /LinkedLists/clone_arbit_list/clone.py | 2,428 | 4.15625 | 4 | #!/bin/python
class Node:
def __init__(self, node_value):
self.val = node_value
self.next = None
self.arbit = None
# Given a doubly linked list with node having one pointer next, other pointer arbit, pointing to arbitrary node. Clone the list.
# Approach 1: Uses extra space O(n) in hash t... | true |
f8eb3b6c2dc76f5a4c18e962b994df7219510308 | knparikh/IK | /Recursion/class_learnings.py | 2,970 | 4.25 | 4 | def fibo(n):
if (n == 0) or (n == 1):
return n
return fibo(n-1) + fibo(n-2)
# Tips to write recursive functions
# Define function meaningfully
# Think about base cases, what's already defined
# Think about the typical case
# Example:
# Merge sort
# Recurrence relationship
# Define function: merge (a ... | true |
b314f7c064518604957fc677897c33f51afc584e | knparikh/IK | /LinkedLists/median/median.py | 1,741 | 4.125 | 4 | #!/bin/python3
import sys
import os
class LinkedListNode:
def __init__(self, node_value):
self.val = node_value
self.next = None
def _insert_node_into_singlylinkedlist(head, tail, val):
if head == None:
head = LinkedListNode(val)
tail = head
else:
node = LinkedList... | true |
ccaee08097c8797bd374e374e9936f174142fd3d | walkrrr/110-L3-Soft-Build-A-Birthday-Reminder-App-Starter-1 | /main.py | 300 | 4.25 | 4 | user_input = input("Enter a person's name: ")
if user_input == "Walkrrr":
print("Birthday is 12/26/1983!")
elif user_input == "Missy":
print("Birthday is 05/03/2006!")
elif user_input == "DeVon":
print("Birthday is 06/23/1983")
else:
print("Can't find a birthday for this person")
| false |
25450a5f381210b30eff26600fdf9377b7762cd4 | joepark92/students_and_grades | /students_n_grades.py | 1,741 | 4.15625 | 4 | studentinfo = []
course_dict = {
1: 'Math',
2: 'Science',
3: 'History'
}
while True:
numStudents = input("How many students do you have: ")
try:
numStudents = int(numStudents)
except:
print('Invalid entry... Try using digits, ex. 1, 2, 3, etc.')
continue
if numStuden... | true |
85490c42ce849d03911999af97526f3dc1ef6c75 | TSantosFigueira/Python_Data-Structures | /Data Structures - Array/ReverseString.py | 456 | 4.34375 | 4 | strings = "Hi, my name is Thiago!"
# approach 01
print(strings[::-1])
# approach 02
def reverseString(strings):
for i in range(len(strings) - 1, -1, -1):
print(strings[i], end='')
#approach 03
def reverseStringWithList(strings):
newStrings = []
for i in range(len(strings) - 1, -1, -1):
newStrings... | true |
a1c101827947b2ebc854c39bcda7bed452c54aa9 | sebastianhlaw/tensorflow-benchmark | /python/playground/get_started_contrib_learn.py | 1,466 | 4.15625 | 4 | # Getting started with TensorFlow
# https://www.tensorflow.org/get_started/get_started
import tensorflow as tf
import numpy as np
# Declare list of features. We only have one real-valued feature. There are many other types of columns that are more
# complicated and useful.
features = [tf.contrib.layers.real_valued_co... | true |
64f2ec55e0ab9699b5d20eb1bb9408e8757f4050 | pedrocambui/exercicios_e_desafios | /python/cursoemvideo/ex075.py | 1,086 | 4.15625 | 4 | tupla = (int(input('Digite um número: ')),
int(input('Digite um número: ')),
int(input('Digite um número: ')),
int(input('Digite um número: ')))
par = False
print(f'O valor 9 apareceu {tupla.count(9)} vezes.')
if 3 in tupla:
print(f'O valor 3 apareceu na {tupla.index(3)+1}º posição.')
els... | false |
6bd1ef758a24b491de6487685bdba70f50859418 | timsergor/StillPython | /008.py | 283 | 4.125 | 4 | #Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
odd = []
even = []
for i in range(len(A)):
if A[i] % 2 == 0:
even.append(A[i])
else:
odd.append(A[i])
print(even+odd)
| true |
99774c11dcd328634fdfe51602b7453bf243a610 | timsergor/StillPython | /105.py | 1,582 | 4.25 | 4 | #1042. Flower Planting With No Adjacent. Easy. 47.7%.
#You have N gardens, labelled 1 to N. In each garden, you want to plant one of 4 types of flowers.
#paths[i] = [x, y] describes the existence of a bidirectional path from garden x to garden y.
#Also, there is no garden that has more than 3 paths coming into or lea... | true |
4be06146f86619793040004e9139480283895ba7 | Skippi-engineer/Console-Games | /Rock paper scissors.py | 1,207 | 4.15625 | 4 | #
# Simple console game rock paper scissors:
#
from random import*
game = True
while game:
player = (input("rock/paper/scissors: ")).lower()
rand = randint(1, 3)
if rand == 1:
print("rock")
if player == "rock":
print("Tie!")
elif player == "paper":
... | true |
65779d0cd88f215d09e94b49567fe0ebdec5c83c | donaq/scramblecheatpy | /scramblecheat.py | 1,524 | 4.21875 | 4 | #!/usr/bin/python
import sys
import readline
from scheathelpers import *
if len(sys.argv)!=2:
print "Usage: scramblecheat.py <dictionary file>"
exit()
words = read_dictionary(filename=sys.argv[1])
if not words:
exit()
print "\nFor instructions, type 'help'. To exit the program, press the Enter key.\n"
instructio... | true |
be0404d73463c30014cddb01f3ba109e5c04b94d | chaitan64arun/algo-ds | /array_element_appearance.py | 623 | 4.34375 | 4 | #!/usr/bin/python
"""
https://www.careercup.com/question?id=5664477329489920
You have given an array of integers. The appearance of integers vary (ie some integers appears twice or once or more than once)
How would you determine which integers appeared odd number of times ?
a[] = { 1,1,1, 2,5,10000, 5,7,4,8}
as you... | true |
bb5a6198910d5e8cb45c4e0ac03002e33b5c3cbb | Elvis-IsAlive/python | /printDirectory.py | 1,901 | 4.15625 | 4 | #! /usr/bin/python3
"""List the content of a directory to the depth of -directory"""
import os
import sys
import argparse
def printDir(directory, depth, lvl = 0):
"""prints the directories and files of a directory"""
os.chdir(directory)
for e in sorted(os.listdir()):
#only non-hidden elements
... | true |
c0f083cbddfb27401321e3d95d30056d42d0e81a | m2mathew/learn-python-in-one-day | /03_variables.py | 730 | 4.25 | 4 | # Chapter 3: The World of Variables and Operators
userAge = 0
userAge, userName = 30, 'Peter'
'''
Variable names can contain letters, numbers, or underscores
But they cannot start with a number
Can only start with a letter or underscore
'''
# Here we go
x = 5
y = 10
# x = y
y = x
print ('x = ', x)
print ('y = ', ... | true |
36b7c19b65d70daf224f1f10e07986107572ab00 | dconn20/labs.2020 | /student.py | 609 | 4.1875 | 4 | # A Program that reads in students
# until the user enters a blank
# and then prints them all out again
students = []
firstname = input("Enter first name (blank to quit): ").strip()
while firstname != "":
student = {}
student ["firstname"] = firstname
lastname = input ("Enter lastname: ").strip()
stud... | true |
0cd0946d99ab89504458e247982945c91fdeeebf | jmanndev/41150-Exercises | /Tutorial2/calculator-with-tax.py | 775 | 4.375 | 4 | # 1. Write a python program that act as a cashier which will prompt the user
# for numbers that can be either integers or floats until the user enters 0.
# The program should accumulate all the entered numbers up until the 0
# and provide the total before and after tax. Tax is 0.05
def inputNumber(prompt):
while ... | true |
85fdc56db8157d1a346840760d4084f2b4d366e0 | Coditya0809/CodersPack | /Python/Task5.py | 291 | 4.21875 | 4 | months=["january","february","march","april","may","june","july","august","september","october","november","december"]
month_days=[31,28,31,30,31,30,31,31,30,31,30,31]
month=input("Enter the month: ")
for i in range (12):
if(month.lower()==months[i]):
print(month_days[i])
| false |
477b7094c6ee99f09ac6d61a4d571f06b570bacf | Xenom-msk/Exercises-from-Teach-Your-Kids-to-Code-by-Bryson-Payne | /Exercises-for Teach Your Kids to Code by Bryson Payne/What_to_wear.py | 473 | 4.28125 | 4 | # What to wear?
rainy=input("How's the weather? Is it raining? (y/n)").lower()
cold=input("Is it cold today? (y/n)").lower()
if (rainy=='y' and cold=='y'):
print("You'd better wear a raincoat.")
elif (rainy=='y' and cold!='y'):
print("Carry an umbrella with you.")
elif (rainy!='y' and cold=='y'):
pr... | true |
a2ac7d561a73a8d5ed225aa1e9385b01b85c9f01 | Xenom-msk/Exercises-from-Teach-Your-Kids-to-Code-by-Bryson-Payne | /Exercises-for Teach Your Kids to Code by Bryson Payne/Pizza_calculator.py | 663 | 4.34375 | 4 | # Pizza cost calculator
# How many pizzas they want
number_of_pizzas=eval(input("how many pizzas do you want? "))
# Cost of each pizza
cost_per_pizza=eval(input("how much does each pizza cost? "))
# Calculate the total cost of the pizzas as our subtotal
subtotal=number_of_pizzas*cost_per_pizza
# Calculat... | true |
bd4e1edd47f082abe6726aab34a9741e71f991b9 | KolienPleijsant/assignment | /assignment_2_Kolien.py | 2,241 | 4.34375 | 4 | #open the csv file
politicians = open("politicians.csv")
#make a multidimensional list and set indext to 0
newlist = []
index = 0
#strip the csv and make it a multidimensional list
for info in politicians:
infosplit = info.strip().split(",")
newlist.append(infosplit)
firstname = infosplit[0]
lastname = infosplit[... | true |
890a2648b66de9c0746fb84e17d227f4569e1044 | maddurivenkys/trainings | /AI_ML/training/Day1/home_work/median.py | 487 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 21:55:07 2019
@author: e1012466
"""
# is a floor division operator which will round the result to nearest integer
# Python program to print
# median of elements
# list of elements to calculate median
n_num = [1, 2,7, 8, 9,3, 4, 5,6]
n = len(n_num)
n_num.sort()
... | true |
ed71969d9316cc5e19d9a2e706eed432c499af66 | freena22/Python-Practice-Book | /09_function_design.py | 2,861 | 4.4375 | 4 |
# Functions and Function Design
def readable_timedelta(days):
"""Print the number of weeks and days in a number of days."""
#to get the number of weeks we use integer division
weeks = days // 7
#to get the number of days that remain we use %, the modulus operator
remainder = days % 7
return "... | true |
26749abc649c1667a32bc15e118615cf5aa7ea90 | nicsins/PLDC1150 | /week3/practice.py | 323 | 4.3125 | 4 | from datetime import date
from datetime import time
from datetime import datetime
print(f"Todays date is {date.today()}")
print(f"The time is {datetime.time(datetime.now())}")
print(f"Todays date and time is {datetime.today()}")
city="Minneapolis"
date=date.today()
print(f'in the city of {city} and the date is {date... | true |
69353e9ee5e34e7ea82bc96ca05e5a4c7465b623 | nicsins/PLDC1150 | /Week5/texbook.py | 2,395 | 4.28125 | 4 | ''' texbook program
author =__DomiNic__
this is an example program of ways to
use data validation for integers and floats
along with presenting a solid example of nested loops
**improved from lab notes***'''
print('Welcome to the book shop')
#start with getting user input and defining variables
head="*"*40#simple deco... | true |
28ccf0700be7b1acdcb4faace4b4b85c26ee6c20 | nicsins/PLDC1150 | /Week2/practice.py | 643 | 4.15625 | 4 | def getInput():
return [int(input(f'enter score for test # {i+1}'))for i in range( int (input('How many test scores would you like to enter')))]
def print_Output(nums):
print('the values entered are ',end='')
[print(i,' ',end='')for i in nums]
print()
print(f'The highesty score was {max(nums)}')
... | true |
00cd83ab8506bfd32b82aa0998e845273df415ee | nicsins/PLDC1150 | /Week4/apollo.py | 525 | 4.125 | 4 | ''' author=-nic_
asks user what year we landed on the moon and
tells you if you got it right
09/18/2018'''
#get user input establish var
right_year=1969
year = input('What year did Apollo 11 land on the moon? ')
while year== '' or year.isalpha():
year = input('What year did Apollo 11 land on the moon? ')
year=int... | false |
07e258168dc94bf9a5f50ff74a3d15270ee86785 | tessam30/Python | /examples/katrina.py | 1,005 | 4.125 | 4 | # Answering questions about Katrina text using Python text handling abilities
f = open("katrina_advisory.txt")
text = f.read()
f.close()
print 'Content of "katrina_advisory.txt"'
print '-' * 51
print
print text
# Q1. Strip leading spaces and make everything lowercase
text_clean = text.lower().strip()
print text_clean... | true |
72b9ddc4835863a9d492f7164d30dcb70dc5be1e | caspian2012/Wang_Ke_python | /HW1_12.py | 1,595 | 4.25 | 4 | """ Question 12"""
# Import defaultdict function.
from collections import defaultdict
def ana_finder(file_name):
# Open the file, read it and add the raw stripped words into a list.
words = []
with open(file_name, 'r') as f:
for line in f:
words.append(line.rstrip())
# We find wo... | true |
14e196f86efa736320d4cbadae7ae7356813f13c | caspian2012/Wang_Ke_python | /HW1_2.py | 739 | 4.53125 | 5 | """ Question 2"""
# Construct a funtion to find semordnilap that finds semordnilap pairs of a
# list of words.
def semordnilap(file):
# Access a file, read its content and split the list of words into
# individual ones.
file = open ('sample.txt').read()
words = file.split()
# Set the default... | true |
52eddb29c7f0432d6837f9871af6fe604db1e06c | Jack-Sh/03_Higher_Lower | /03_secret_compare.py | 1,847 | 4.125 | 4 | # HL component 3 - compare secret and users guess
# To Do
# If users guess is below secret print too low
# If users guess is above secret print too high
# If users guess is the secret print congratulations
# Function to check low, high, guess, and round numbers
def int_check(question, low=None, high=None):
sit... | true |
4429b8da21d51288c7d4a9edd88568c7712cfb51 | mdsksadi/python | /List_in_Python.py | 2,377 | 4.53125 | 5 | '''
In a variable we can assign only one value. But if we assing multiple values into the variable,
we need to use a list.
For diclaring a list, we need to use box bracket "[]"
We can assign both number and string type values.
List is mutable (We can chagne the values).
'''
nums= [2,4,20,54,120] #We diclear a lis... | true |
df20b2381136f21dd85ab4316491e8d9f90c619f | mdsksadi/python | /Dictionary.py | 2,416 | 4.15625 | 4 |
'''
List: It's orderd. It's mantain the sequence.
Set: It does not maintain the sequence.
Dictionary: Differenty key for different element.
Example: Phone book. If we search a name, we get a number against that name.
Every value has a different key given by me.
But in list, the key... | true |
c48c13d876895eafa0724f5d6b9000e8208708a7 | saida93522/HelloPython | /birthday.py | 586 | 4.28125 | 4 | import datetime
date = datetime.datetime.now() # date class.
# formatting date to string. %B returns full month name.
currMonth = date.strftime("%B").lower()
def birthday():
name = input('What is your name?\t').capitalize()
month = input(f'Hi {name}!, what month were you born in?\t').lower()
# check if... | true |
77746a97fcceca80de494fb8ff0765df5fba6c0d | ToscaMarmefelt/CompPhys | /PS3Q1.py | 1,494 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 11 09:26:27 2018
@author: Tosca
"""
import random
import numpy as np
# Decide on number of columns and rows for test matrices A and B
col_a = random.randint(1,10) #Range 1-10 for simplicity
row_a = random.randint(1,10)
col_b =... | true |
37e4a5af48a708dbbf381bc7189e500cf9aa35bf | SolidDarrama/Python | /area_calculation.py | 1,203 | 4.3125 | 4 | #Billy Leager
#10/1/2014
#Practice Program - Menu
def rectangle_area():
side1 = int(input('Enter the value of the first side:'))
side2 = int(input('Enter the value of the second side:'))
print('The area of the rectangle is', (side1 * side2))
def triangle_area():
height = int(input('Enter the... | true |
68ea74d5b245e9d3df91c79e5fa7ba55a1b4be3a | SolidDarrama/Python | /Ch3 Ex/Chapter 3 Exercises 7.py | 977 | 4.15625 | 4 | #Jose Guadarrama
#9/20/2014
#CH3 EX7
#user input 1
primary1=str(input('Enter the 1st Primary Color: '))
#if else 1
while primary1 != "red" and primary1 != "blue" and primary1 != "yellow":
primary1 = input("\nerror message")
#user input 2
primary2=str(input('Enter the 2nd Primary Color: '))
#if els... | true |
c3edbfd23f522eef4534fd2feb11d6a6c9bb0b68 | dheerajdbaudb22/Devops21 | /Treasure_island.py | 609 | 4.125 | 4 | print("Welcome to Treasure island.")
print("Your mission is to find the treasure.")
task1 = input("Do you want to take left or right? \n")
t1 = task1.lower()
if ( t1 == "right" ):
print("Your game is over !")
else:
t1 == "left"
task2 = input("Do you want to swim or wait? \n")
t2 = task2.lower()
if ... | true |
45a110c28232c1b28e8a8cabb1695979e8848c8f | rageshm110/python3bootcamp | /lists.py | 1,100 | 4.65625 | 5 |
# Lists are ordered sequences that can hold a variety of object types
# they use [] and , to separate objects in list
# ex: [1,2,3,4] | ["Ragesh","TechM", 4] | ["Adhik", [2007, 20, 05]]
# lists supports indexing and slicing. Lists can be nested
# and also have a variety of useful methods that can be called
# off of ... | true |
1580c6aab9ceffbc8f12a68a82723d291357dccd | BrunoCAF/CES22 | /Lista 2/methods.py | 1,586 | 4.53125 | 5 | #55-70
# Lets illustrate the use of static, class and abstract methods by modelling Polygons
import abc, turtle
from math import sqrt
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
@staticmethod
def distance(A, B):
return sqrt((A.x - B.x)**2 + (A.y - B.y)**2)
def norm(s... | false |
63dad4f2c002647474a4d418ac17578744dac437 | AlanMalikov777/Task1_Python | /first.py | 695 | 4.3125 | 4 |
def toSwap(listToEnter,x,y):#swaps two variables
listToEnter[x],listToEnter[y]=listToEnter[y],listToEnter[x]
# toPermute uses a heap's algorithm
def toPermute(list, current, last):#takes a list, starting index and last index
if last<0:
print("")
elif current == last:# if starting and last indexes w... | true |
272ff75f4d102f291fbd318b92937d8f1b5c2b45 | tkern0/misc | /School/guessNum.py | 1,430 | 4.125 | 4 | import random
# Gets the user's name, allowing only letters, spaces and hyphens
letters = "qwertyuiopasdfghjklzxcvbnm- "
while True:
try:
name = input("What is your name? ")
for i in name:
if i.lower() not in letters: raise ValueError
except ValueError: print("Please use only... | true |
27a866921ee473a17cc635df89e44c516e6cbff5 | devashishtrident/progressnov8 | /scope.py | 1,742 | 4.25 | 4 | '''x =25
def my_func():
x = 50
return x
"/the only x the program is aware of is global variable"
#print(x)
"this is looking at the myfunc scope only"
#print(my_func())
"what confuses the people most is calling the function first and getting the very next value we get x will be called but a global variab... | true |
2eb5448693f0b2567dda1b14f81135df988ed3f9 | devashishtrident/progressnov8 | /Dictionaries.py | 310 | 4.25 | 4 | #dictionary do not return any sorted order
my_stuff = {"key1":123,'key2':'value2','key3':{'123':[1,2,'grabme']}}
print(my_stuff['key3']['123'][2].upper())
my_stuff = {'lunch':'pizza','bfast':'eggs'}
my_stuff['lunch']='burger'
my_stuff['dinner'] = 'pasta'
print(my_stuff['lunch'])
print(my_stuff)
| false |
5d5aa60886dd4729e839956378ab1e9575f5b8a2 | ChristinaEricka/LaunchCode | /unit1/Chapter 09 - Strings/Chapter 09 - Studio 8 - Bugz - Bonus Mission.py | 1,851 | 4.25 | 4 | # Bonus Mission
#
# Write a function called stretch that takes in a string and doubles each
# of the letters contained in the string. For example,
# stretch("chihuahua") would return “cchhiihhuuaahhuuaa”.
#
# Add an optional parameter to your stretch function that indicates how
# many times ea... | true |
5991435ff06a5927e9d0e5c7d92a6973e1b1982d | ChristinaEricka/LaunchCode | /unit1/Chapter 08 - More About Iteration/Chapter 08 - Exercise 06.py | 628 | 4.1875 | 4 | # Write a program to remove all the red from an image.
#
# For this and the following exercises, use the luther.jpg photo
import image
img = image.Image("luther.jpg")
win = image.ImageWin(img.getWidth(), img.getHeight())
img.draw(win)
img.setDelay(1, 15) # setDelay(0) turns off animation
for row in range(img.get... | true |
62c17fd1f2fd0dcccf78a7ce41dbf87ab3ce075e | ChristinaEricka/LaunchCode | /unit1/Chapter 09 - Strings/Chapter 09 - Exercise 02.py | 554 | 4.125 | 4 | # Write a function that will return the number of digits in an integer
import string
def num_digits(n):
"""Return number of digits in an integer"""
count = 0
for char in str(n):
if char in string.digits:
count += 1
return count
def main():
"""Cursory testing of num_digits"... | true |
783fa5014f0e5df887b967f03de35622ebf59417 | ChristinaEricka/LaunchCode | /unit1/Chapter 07 - Exceptions and Problem Solving/Chapter 07 - Exercise 10.py | 1,039 | 4.28125 | 4 | # Write a function triangle(n) that returns an upright triangle of height n.
#
# Example:
# print(triangle(5))
#
# Output:
#
# #
# ###
# #####
# #######
# #########
def line(n, str):
"""Return a line consisting of <n> sequential copies of <str>)"""
return_value = ''... | true |
4b2c398683572555cb7fae39882fe1e648b7b217 | ChristinaEricka/LaunchCode | /unit1/Chapter 11 - Dictionaries and Tuples/Chapter 11 - Studio 10 - Yahtzee.py | 2,598 | 4.1875 | 4 |
import random
# The roll_dice function simulates the rolling of the dice. It
# creates a 2 dimensional list: each column is a die and each
# row is a throw. The function generates random numbers 1-6
# and puts them in the list.
def roll_dice(num_dice, num_rolls):
# create a two-dimensional (num_dice by num_rol... | true |
1dedaceb98c59184781af863a5a44540a832bb9e | ChristinaEricka/LaunchCode | /unit1/Chapter 09 - Strings/Chapter 09 - Exercise 09.py | 1,185 | 4.65625 | 5 | # Write a function called rot13 that uses the Caesar cipher to encrypt a
# message. The Caesar cipher works like a substitution cipher but each
# character is replaced by the character 13 characters to “its right” in the
# alphabet. So for example the letter “a” becomes the letter “n”. If a letter
# is past the mi... | true |
46e0b03dec67ab8b34ebeeb96ae2a4a52c500e9f | ChristinaEricka/LaunchCode | /unit1/Chapter 08 - More About Iteration/Chapter 08 - Exercise 03.py | 1,818 | 4.3125 | 4 | # Modify the turtle walk program so that you have two turtles each with a
# random starting location. Keep the turtles moving until one of them leaves
# the screen.
import random
import turtle
def is_in_screen(screen, t):
left_bound = - screen.window_width() / 2
right_bound = screen.window_width() / 2
... | true |
2feef2a3a3c2438b0acf31bf8df33a3f65485d4e | EvanKaeding/datacamp | /Python for R Users/Control Structures.py | 390 | 4.125 | 4 | # Assign 5 to a variable
num_drinks = 5
# if statement
if num_drinks < 0:
print('error')
# elif statement
elif num_drinks <= 4:
print('non-binge')
# else statement
else:
print('binge')
num_drinks = [5, 4, 3, 3, 3, 5, 6, 10]
# Write a for loop
for drink in num_drinks:
# if/else statement
if drink... | false |
dd81c3c278398a8bea81d19dad23fca4fca0ca9d | sravyaysk/cracking-the-coding-interview-solutions | /LeetCode/searchInRotatedArray.py | 2,629 | 4.1875 | 4 | '''
She asked for binary search functionality which tells no exists in array or not. Generally we find mid element through (low+high)/ 2 so she asked to change that and use random function to decide mid. Binary search is performed on sorted array but here unsorted array is given.
Two modifications are performed on ... | true |
cb8d29bd928f567faf99e220423b583aab63cb97 | ajay946/python-codes | /PrimeNum.py | 328 | 4.125 | 4 | # To find prime number in a given range
start = int(input("Start: "))
end = int(input("End: "))
for i in range(start, end +1):
# if number is divisible by any number between 2 and i it is not prime
if i >1 :
for j in range(2,i):
if(i%j)==0:
break
else:
p... | true |
30b51090fcc64881051a00b755a8111d6482d28d | atafs/BackEnd_Python-language- | /language/americoLIB_006_VARIABLES.py | 1,249 | 4.21875 | 4 | #!/usr/bin/python
#**************************
#IMPORTS
import sys
#VARIABLES
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
#MULTI ASSIGNMENT
multi1 = multi2 = multi3 = 1
multi4, multi5, multi6 = 1, 2, "john"
#PRINT
print("")
print("PYTHON:... | true |
4007832db5961a1f4dd5107a901c7a571b60763b | shubham264693/project | /proga.py | 1,663 | 4.15625 | 4 | text="Where are you? Meet me near the play station"
test_list = text.split()
index_list1 = [0, 3, 6]
index_list2 = [1, 4, 7]
index_list3 = [2, 5, 8]
# printing original lists
print ("Original list : " + str(test_list))
print()
print ("Original index list : " + str(index_list1))
print()
# using li... | false |
baafacd76c43bc5077924f822d32bab2a933aad5 | kevincdurand1/Python-Data-Science-Examples | /Normalization.py | 623 | 4.125 | 4 | #Normalization
#Data normalization is used when you want to adjust the values in the feature vector
#so that they can be measured on a common scale. One of the most common forms of normalization
#that is used in machine learning adjusts the values of a feature vector so that they sum up to 1.
#Add the following lin... | true |
7063ed0f8969fdfc8e5998ce83473afedea34160 | anhnh23/PythonLearning | /src/theory/control_flow/functions/__init__.py | 2,196 | 4.28125 | 4 | '''
Syntax:
def function-name(parameters):
statement(s)
Explaination:
+ parameter - can be indentifier=expression
'''
# be keys into a dictionary
dic = {'a':10, 'b':20, 'c':30}
inverse = {}
for f in list(dic):
inverse[dic[f]] = f
print(dic)
print(inverse)
"""This is case parameter is indentifier=expre... | true |
e58a6f27c032f2a349dbd6c95c674ad8807df85d | anhnh23/PythonLearning | /src/theory/io/io_module.py | 2,080 | 4.125 | 4 | #str() returns representations of value which are fairly human-readable
#repr() generate representation which can be read by the interpreter
s = 'Hello,\n world.'
print(str(s))
print(repr(s))
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
'''str()
1. rjust right justifies
2... | true |
4fb27d914ed56b2ce789e9cc45152f90520390b7 | perzonas/euler | /Euler_1.py | 318 | 4.15625 | 4 | # If we list all the natural numbers below 10 that are
# multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
sum = 0
for i in range(3, 1000, 3):
if i % 5 != 0:
sum += i
for i in range(5, 1000, 5):
sum += i
print(sum) | true |
571018d26e98b054e6fee8d204d4b124f262f6a5 | mhhg/acm | /1_array_string/two_pointers/1_two_sum/two_sum/two_sum.py | 764 | 4.21875 | 4 | from typing import Dict, List
"""
TwoSum Given an array of integers, find two numbers such that they add up to
a specific target number.
The function twoSum should return indices of the two numbers such that they add
up to the target, where index1 must be less than index2.
Please note that your returned answers (bo... | true |
60d931a8ac4ea9d4b4047d68903ef8c50328a300 | crazyAT8/Python-Projects | /While Loop.py | 2,373 | 4.25 | 4 |
# i = 1 # Initialization
# while i<=5: # Condition
# print("william")
# i = i + 1 # Increment/Decrement
# the objective here is to print my name 5 times in a row
# without the Increment/Decrement the loop would go on forever
# when using ... | true |
e6045dc8607f166a7d9ea877b0e3af73fb0303a3 | Absurd1ty/Python-Practice-All | /problems_py7/power_of_3.py | 598 | 4.25 | 4 | """Given an integer n, return true if it is a power of three.
Otherwise, return false. An integer n is a power of three,
if there exists an integer x such that n == 3x."""
class Solution:
def isPowerOfThree(self, n: int) -> bool:
if n==0:
return False
if n==3 or n==1... | true |
9a9fdc10a372dad407a03275064b54508d07dff4 | Raj-Madheshia/Datastructure | /Dynamic Programming/multipleMatrixMultiplication.py | 620 | 4.15625 | 4 | """
The logic behind multiple matrix mutiplication is as given below
A = 10*30
B = 30*5
C = 5*60
ABC = (AB)C || A(BC)
ABC = (AB)C
= 10*30*5 + 10*5*60 operations
= 4500 operation
----OR----
ABC = A(BC)
= 30*5*60 + 10*30*60 operations
= 27000 operation
So to get which combination will requir... | true |
443256679bd1828e82113c8635ce04d9d75efe14 | iiepobka/3_lesson_pythons_algorithms | /task_5.py | 742 | 4.125 | 4 | # В массиве найти максимальный отрицательный элемент. Вывести на экран его значение и
# позицию (индекс) в массиве.
from random import randint
COUNT_ITEMS = 10
START_ITEMS = -100
STOP_ITEMS = 100
my_list = [randint(START_ITEMS, STOP_ITEMS) for x in range(COUNT_ITEMS)]
print(my_list)
max_negative_item = -1
stop = 0
... | false |
35b52d6776d6a4ab71caa79644f614a569f39ef5 | tchrlton/Learning-Python | /HardWay/ex20.py | 1,683 | 4.3125 | 4 | #from the module sys, import the function or paramater argv
from sys import argv
#The two arguments in argv so it has the script (ex20.py) and
#input_file (test.txt or whatever file you input).
script, input_file = argv
#The function that will print the whole txt file after it reads it
def print_all(f):
print(f.read... | true |
6b18af9ead2fc973094c40dab143633e9be352dd | SDSS-Computing-Studies/006b-more-functions-bonhamer | /task3.py | 461 | 4.46875 | 4 | #!python3
"""
Create a function that determines the length of a hypotenuse given the lengths of 2
shorter sides
2 input parameters
float: the length of one side of a right triangle
float: the length of the other side of a right triangle
return: float value for the length of the hypotenuse
Sample assertions:
assert hyp... | true |
8e7611672fde651757c3ea869cf9b6e9980b4018 | mmveres/pyPrj06_02_2021 | /ua/univer/lesson02/cycle/tasks_cycle.py | 487 | 4.15625 | 4 | def print_10_positive():
i = 0
while i < 10:
value = int(input("enter positive value"))
if value >= 0:
i += 1
print("count=", i, "value =", value)
else:
print("not positive")
def pow(x,n):
value = 1
for i in range(n):
value *= x
re... | false |
bd5487e173f2eb396eff5d2929288c9894e70896 | WhaleJ84/com404 | /1-basics/ae1-mock-paper/q2-decision.py | 254 | 4.28125 | 4 | # Q2) Decision
print("Please enter a whole number:")
num = int(input())
# an if statement that divides the input number by 2 and checks to see if it has a remainder; if so it is odd.
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
| true |
e68b1523babc3f2820dae5d89fa90efa7bf8c1c4 | WhaleJ84/com404 | /1-basics/4-repetition/1-while-loop/bot.py | 484 | 4.15625 | 4 | # Ask user for number of robots
print("How many ascii robots should I draw?")
number_robots = int(input())
ROBOT = """
#########
# #
# O O #
| V |
| --- |
|_______|
"""
robots_displayed = 0
MAX_ROBOTS = 10
# Display robots
if number_robots <= MAX_ROBOTS:
while robots_displayed < (number_robots):
... | true |
8c7a480827e7924c2ce43947e0c22e1823d0e39b | WhaleJ84/com404 | /1-basics/6-review/1-input-output/3-interest.py | 449 | 4.15625 | 4 | # Read current amount from user
print("What is your current amount in savings? (£)")
current_amount = float(input())
# Read interest rate from user
print("What is your interest percentage rate? (%)")
interest_rate = float(input())
# Calculate new amount
interest_amount = (interest_rate / 100) * current_amount
new_amo... | true |
e76c97c6168cbfe2da5b8bd215e9645afe1a5156 | ZhenyaBardachina/Python_start | /les_1.2.py | 402 | 4.3125 | 4 | '''Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
Используйте форматирование строк.'''
time = int(input('Enter time in seconds: '))
h = time // 3600
m = time // 60 % 60
s = time % 60
print(f'{h:02d}:{m:02d}:{s:02d}') | false |
4ffbc088793baeeddb2804c4645acf276a46ceb8 | syoliveira/sirleyoliveira | /main.py | 1,038 | 4.3125 | 4 | """numero = int(input("digite um numero:"))
print(numero)
#numero = str (numero)
print(numero)
boleano = True
if numero % 2 == 0:
print("numero par")
if numero < 5:
print("numero menor")
elif numero == 5:
print("numero igual")
else:
print("numero maior")"""
"""numeroA = int(input("digite o 1ª numero... | false |
b2d50fa5197a9e4906ec9ecc6c5339cd1dc9c14d | rkc98/Python_100_days_challenge | /day_10/fisrt_word_capital.py | 347 | 4.1875 | 4 |
first_name=input("what is your first name ?\n")
last_name=input("what is your last name ?\n")
def format_name(first,last):
if first=='' and last=='':
return "check your inputs"
f_name=first.title()
l_name=last.title()
return f_name+" "+l_name
fullname=format_name(first=first_name,last=last_na... | true |
6d44e6b86da192c3afae09ed13c5b507b15eadd8 | mve17/SPISE-2019 | /Day 1/Choose Your Own Adventure 6.py | 2,084 | 4.125 | 4 | name=input("Please Enter Your Name: ")
intro_text='''
You've woken up with a splitting headache. Fumbling in the dark, your hand brushes against a cold metallic object in the sand.
Maybe it will be useful. Would you like to take it with you? [y/n] '''
intro_response=input("\nBad news, "+name+". "+intro_text)
... | true |
e3b34d927246002048c1b992eb6af41dbb7c68f1 | mve17/SPISE-2019 | /Day 6/testing.py | 588 | 4.15625 | 4 | def reverse_digits(number):
negative=number<0
number=abs(number)
reversed_number=int(str(number)[::-1])
if negative:
reversed_number*=-1
return reversed_number
############
#TEST CASES#
############
#Test 1: 0
print("Testing 0")
if reverse_digits(0)==0:
print('passed!')
else:
prin... | true |
0932d8c4c24a6b33759f55142a466e26ba3b0ab5 | Madhan911/nopcommerceApp | /BasicPrograms/AsendingOrder.py | 765 | 4.1875 | 4 |
#In programming, a flag is a predefined bit or bit sequence that holds a binary value. Typically, a program uses a flag to remember something or to leave a sign for another program.
list_one = [1,2,3]
flag = 0
if list_one == sorted(list_one):
flag = 1
if flag:
print("list is sorted")
else:
print("list ... | true |
7ca57bbfa2bec5c1d11a4e30f1032d2987f0b6d5 | Madhan911/nopcommerceApp | /BasicPrograms/RecursionFactorial.py | 421 | 4.28125 | 4 | def fact(n):
return 1 if (n == 0 or n == 1) else n * fact(n - 1)
num = 3
print("Factorial of", num, "is", fact(num))
'''
num = int(input("enter the number : "))
factorial = 1
if num < 0:
print("number is a negative number")
elif num ==0:
print("factorial number one is 0 ")
else:
for i in range(1,... | true |
c777da622c52236d1e7dd664818824cc1fae46ff | AA-anusha/pythonclasses | /formatting.py | 448 | 4.25 | 4 | first_name = raw_input('Your first name: ')
last_name = raw_input('Your last name: ')
# Old style formatting.
print('Hello %s %s!' % (first_name, last_name))
# New Style formatting
print('Hello {} {}!'.format(first_name, last_name))
print('Hello {0} {1}!'.format(first_name, last_name))
# This is where, you will feel... | true |
2ef3ef7ea96277d3dafbd81da73dc63afd2898e2 | aoracle/hackerank | /all_domains/python/data_types/sets.py | 573 | 4.1875 | 4 | # Task
# Given sets of integers, and , print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either or but do not exist in both.
# Input Format
# The first line of input contains an integer, .
# The second line contains space-separated integers.
#... | true |
dd2547464d148487e2214804d2ff1a53c25bdd88 | DanielMafra/Python-LanguageStudies | /exercise075.py | 486 | 4.125 | 4 | number = (int(input('Enter a number:')),
int(input('Enter another number:')),
int(input('Enter one more number:')),
int(input('Enter the last number:')))
print(f'You entered the values {number}')
print(f'The value 9 appeared {number.count(9)} times')
if 3 in number:
print(f'The value... | true |
e36d10ebe0613d79cce471d872756947965708f6 | DanielMafra/Python-LanguageStudies | /exercise032.py | 345 | 4.34375 | 4 | from datetime import date
year = int(
input('What year do you want to analyze? Enter 0 to analyze the current year: '))
if year == 0:
year = date.today().year
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print('The year {} is a leap year.'.format(year))
else:
print('The year {} is not a l... | true |
e6c06ce1dbbd185c08cba48996001b3cf517e22d | pankosmas/Python-Courses | /Simple Games/tic tac toe remaster/main.py | 2,396 | 4.15625 | 4 | # This is a sample Python script.
# Tic Tac Toe game
# globals
board = [
[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "]
]
# functions
def print_board():
print(" +---+---+---+")
print("2 | " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " |")
print("1 | " + b... | false |
dfd8892f50fc1ca02b00c81f1542c157f2c5a12e | Lazaro232/pythonRoadMap | /completePythonCourse/19_GUI_Tkinter/04_frames.py | 802 | 4.53125 | 5 | import tkinter as tk
from tkinter import ttk
# Instanciando o objeto Tkinter
root = tk.Tk()
# Definindo um 'main frame'
main = ttk.Frame(root)
main.pack(side="left", fill="both", expand=True)
# Elementos DENTRO do Frame main
tk.Label(main, text="Label Top", bg="red").pack(
side="top", fill="both", expand=True)
t... | false |
dc4b0dabe8bcd545112104dc0f9985931b9cfed2 | Lazaro232/pythonRoadMap | /completePythonCourse/13_Asynchronous_Development/01_threads.py | 1,676 | 4.125 | 4 | import time
from threading import Thread
def ask_user():
start = time.time()
user_input = input('Enter your name: ')
greet = f'Hello, {user_input}'
print(greet)
print(f'aks_user, {time.time() - start}')
def complex_calculation():
start = time.time()
print('Started calculating...')
[x... | false |
4a90435d940ba7b25452972abbc8e83709c061dd | mmilade/Tic-Tac-Toe | /Problems/Plus one/task.py | 437 | 4.375 | 4 | # You are given a list of strings containing integer numbers. Print the list of their values increased by 1.
# E.g. if list_of_strings = ["36", "45", "99"], your program should print the list [37, 46, 100].
# The variable list_of_strings is already defined, you don't need to work with the input.
# list_of_strings = ["... | true |
b7af78cdca8b3e3df7e070410c229f5cdaa4908c | SVMarshall/programming-challanges | /leetcode/implement_stack_using_queues.py | 1,353 | 4.25 | 4 | # https://leetcode.com/problems/implement-stack-using-queues/
class Stack(object):
# simulating first a stack
class Queue():
def __init__(self):
self.queue_list = []
def push(self, x):
self.queue_list.append(x)
def pop(self):
return self.queue_list.p... | true |
9727529e9542a4ec8fdef1092770e5cd58db6228 | yaelBrown/pythonSandbox | /pythonBasics/decorators/decoratorz.py | 857 | 4.5 | 4 | '''
Example of python decorators
'''
# have function that returns a function
def func(aa="cookies"):
print("This is the default function")
def one():
return 1
def eleven():
return 11
if aa == "cookies":
return one()
else:
return eleven()
# print(func())
# can pass a function into a funct... | true |
70c559449bd39e24557ce664afb47ca8e7359de4 | yaelBrown/pythonSandbox | /LC/_sumProduct.py | 2,616 | 4.65625 | 5 |
def sum_product(input_tuple):
prod = 1
s = 0
for i in input_tuple:
s += i
prod *= i
return s, prod
def sum_product(t):
sum_result = 0
product_result = 1
for num in t:
sum_result += num
product_result *= num
return sum_result, pro... | true |
1aa62001f4c84e91942fa762495f0ec252bc2412 | yaelBrown/pythonSandbox | /LC/LC535-EncodeDecodeTinyURL.py | 1,524 | 4.375 | 4 | """
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL.
There is... | true |
79abaed44a11e0c6cdd108e345267a3b47b08b9b | yaelBrown/pythonSandbox | /LC/_maxProduct.py | 2,131 | 4.4375 | 4 | def max_product(arr):
# Initialize two variables to store the two largest numbers
max1, max2 = 0, 0 # O(1), constant time initialization
# Iterate through the array
for num in arr: # O(n), where n is the length of the array
# If the current number is greater than max1, update max1 and max2
... | true |
7c0aed711b26257167682c4ac1eae247abe451fe | 17hopkinsonh/RPG_Game | /file1.py | 875 | 4.34375 | 4 | """
Author: Hayden Hopkinson
Date: 15/09/2020
Description: A start screen explaining to the user how the game works
version: 1.0
improvements from last version:
"""
# libraries
# functions
def explain_game():
"""this will print out a explanation of the game to the user. Takes no ... | true |
bdb27e057539b67802ac9e2bb70182b1cd002e34 | zerowxx/doc | /python/lpython/hello.py | 1,361 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#hello.py
print 'hello, world'
print u'中文'
##list 可变长度
classmates = ['Michael', 'Bob', 'Tracy']
print classmates
print 'len:',len(classmates)
#delete last
classmates.pop()
#classmates.pop(i)
print classmates
#insert
classmates.append('Tracy')
classmates.insert(1,'Jack... | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.