blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
96ca7424d8a8ff29dc1a2e6d8441db738b690c8d | s-razaq/sketchbook | /python/rock_paper_scissors.py | 1,109 | 3.734375 | 4 | __author__ = 'Saqib Razaq'
from random import choice as randchoice
from time import sleep
"""
Simple implementation of Rock Paper Scissors in Python
"""
players = "XY"
ai_players = "Y"
moves = ['r', 'p', 's']
wins = ("rp", "sr", "ps")
status = "%5s %3d %5s %3d moves: %s %s"
pause_time = 0.3
class RockPaperScisso... |
04d9ad9a91bcbe466b6ee667d0d05d96a2fc7172 | NIMESHYADAV/Edureka_DataScience_Certification | /Module_4/Module_4 practice files/Module_4/3. pandas_examples/slide_61.py | 217 | 3.84375 | 4 | # creating a data frame
# Method2: from a list of dictionaries.
import pandas
data = [{'a': 1, 'b': 2}, {'a': 2, 'b': 4, 'c': 8}]
table = pandas.DataFrame(data) # dict keys would be the column names
print(table)
|
49f8c82ee1cb054f6426a7121ce8860354d47919 | NIMESHYADAV/Edureka_DataScience_Certification | /Module_4/Module_4 practice files/Module_4/4. MatplotLib/slide_93.py | 377 | 4 | 4 | # Multiline plots: Line plots
# multiple functions can be drawn on the same plot in single plot() call.
import matplotlib.pyplot as plt
x = range(5)
# plots multiple figures using a single plot() function call.
plt.plot(x, [elem for elem in x], x, [elem*elem for elem in x], x, [elem*elem*elem for elem in x])
plt.sho... |
55730a4fc82e600fb568af4c61bd418c7ff006bb | NIMESHYADAV/Edureka_DataScience_Certification | /Module_4/Module_4 practice files/Module_4/4. MatplotLib/slide_98.py | 323 | 3.703125 | 4 | # Limiting the Axes 2:using xlim() and ylim()
import matplotlib.pyplot as plt
x = range(5)
# plots multiple figures using a single plot() function call.
plt.plot(x, [elem for elem in x],
x, [elem*2 for elem in x],
x, [elem*4 for elem in x])
plt.grid(True)
plt.xlim(-1, 5)
plt.ylim(-1, 10)
plt.show... |
ac18d156b72c10aff1c7e9c5a8238e4055fd901b | NIMESHYADAV/Edureka_DataScience_Certification | /Module_4/Module_4 practice files/Module_4/2. numpy_examples/slide 33.py | 139 | 3.609375 | 4 | import numpy as np
arr = np.zeros(8)
print(arr)
arr3d = arr.reshape((2, 2, 2))
print(arr3d)
arr = arr3d.ravel() # flattens it
print(arr)
|
48a18a45c32e551e7323321a887add71d2b7a8eb | NIMESHYADAV/Edureka_DataScience_Certification | /Module_5/Module_5_d9uk1k/Module_5/gyan_slide_code/slide_18_20.py | 498 | 3.6875 | 4 | import pandas as pd
world_cup = {'Team': ['West Indies','West indies','India','Australia','Pakistan','Sri Lanka','Australia','Australia','Australia','India','Australia'],
'Rank': [7,7,2,1,6,4,1,1,1,2,1],
'Year': [1975,1979,1983,1987,1992,1996,1999,2003,2007,2011,2015]}
df = pd.DataFrame(world_cup... |
7185fee56ce7c6cab9c444514ee88d2c71010af9 | AndreyArguedas/Data-Science-Course | /IV Lecture/Task/Tarea3_andrey_arguedas.py | 9,120 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 12:13:00 2019
@author: Andrey
"""
"""
Ejercicio 1. Ver notebook
"""
from abc import ABCMeta, abstractmethod
# Clase Abstracta, ABC Class
class Base(metaclass = ABCMeta):
@abstractmethod
def __str__(self):
pass
@abstractmethod
def Cap... |
1883ec18a6dce6f142749ff4f3568cd16c106814 | AndreyArguedas/Data-Science-Course | /II Lecture/FirstTask/Tarea1_andrey_arguedas.py | 10,579 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Tarea #1 Minería de Datos
# ## Autor : Andrey Arguedas Espinoza
# ### 1. Dado x = (3,−5,31,−1,−9,10,0,18) y dado y = (1,1,−3,1,−99,−10,10,−7) realice lo siguiente:
# #### • Introduzca x y y como listas en Python.
# In[1]:
x = [3,-5,31,-1,-9,10,0,18]
y = [1,1,-3,1,-99,-1... |
6b1ee53ec76a41326f06ddc524f1343db8eb35eb | python-bonobo/bonobo | /bonobo/util/collections.py | 3,200 | 3.921875 | 4 | import bisect
import functools
from collections import Sequence
class sortedlist(list):
"""
A list with an insort() method that wan be used to maintain sorted lists. The list by itself is not sorted, it's
up to the user to not insert unsorted elements.
"""
def insort(self, x):
"""
... |
b6c2ccd6995579420371354ee04c0e7fc0dbf0ae | gonchandrei/stepic_python | /Module3/Lesson2/Step6.py | 174 | 3.65625 | 4 | s = input()
a = input()
b = input()
ans = 0
if a in s and a in b:
print('Impossible')
else:
while a in s:
s = s.replace(a, b)
ans += 1
print(ans)
|
ed1cf8869b5c8067f3430f9a8efb307cc2401516 | OsmiumDust/classwork | /for to while loop.py | 722 | 3.984375 | 4 | # 1
my_str = "hello"
i = 0
while i < len(my_str):
"""For every character in the string my_str, print the character"""
char = my_str[i]
print(char)
i += 1
# 2
numbers = [7, 7, 2, 7, 11]
i = 0
while i < len(numbers):
"""For every number in the list of numbers, print the number."""
num = numbers[... |
9a27ef6d62ef518fb4a2f81c6247c1a38b087fb6 | OsmiumDust/classwork | /Bottle Deposits.py | 398 | 3.984375 | 4 | while True:
try:
size1 = int(input("How many 1 liter or less bottles do you have: "))
size2 = int(input("How many more than 1 liter bottles do you have: "))
value = (size1 * 0.1) + (size2 * 0.25)
value = ("%.2f" % value)
print(f"Your bottle totals comes up to ${value}. \nThank you for recycli... |
eb1500739449cbf1d0abac8e60899e9ecb886ca4 | yuanliu3/CodePathInterviewPrep | /w2s1_design_stack_min_O(1).py | 2,238 | 3.90625 | 4 | '''Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. These are the operations you should implement for this data structure.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
get_min() -- Retrieve the min... |
6943532f72e83f2b3f819cb16e0209449d22a468 | rohanstomar11/DataStructures-Algorithms-Python | /Data Structures/5. Graphs/1 - Graph using Dict.py | 796 | 3.75 | 4 | class Graph(dict):
def __init__(self):
self.graph = dict()
self.edges = []
def add(self, data1, data2):
self.edges.append(str(data1)+str(data2))
try:
graph[data1] = graph[data1] + ',' + data2
except KeyError:
graph[data1] = data2
try:
... |
9064ad29ba3f7a3b4a1130b1d517ac423cd3fb59 | rohanstomar11/DataStructures-Algorithms-Python | /Data Structures/4. Trees/1 - Binary Tree.py | 1,204 | 4 | 4 | class Node:
def __init__(self, data):
self.left = None
self.data = data
self.right = None
class Tree:
def __init__(self, node):
self.root = node
def preOrderTraversal(self, node):
if node == None:
return
else:
print(node.data)
... |
26e362fd49027e6f2edc8d8f5521b594af550859 | rohanstomar11/DataStructures-Algorithms-Python | /Algorithms/1. Searching/2 - Binary Search.py | 592 | 4.03125 | 4 | def binarySearch(numbers, size, element):
low = 0
mid = 0
high = size-1
while(low <= high):
mid = int((low+high)/2)
if(numbers[mid] == element):
return mid
elif(numbers[mid] >= element):
high = mid-1
elif(numbers[mid] <= element):
low =... |
02f7cb2112f0cfee89379fd63ff4fd6a71f58a86 | estefano10/act_7 | /clases.py | 1,002 | 3.75 | 4 | class Alquiler:
def __init__(self,marca,modelo, año, precio_por_kilometro, seguro, dni_del_arrendatario, kilometros_recorridos, nombre):
self.marca = marca
self.modelo = modelo
self.año = año
self.precio_por_kilometro = precio_por_kilometro
self.seguro = seguro
... |
bc2733978d3af54e49e4d4e5bdd2424d3c20f099 | scb-am/Fractals | /checkio/on_same_path.py | 880 | 3.734375 | 4 | def iterate(tree):
while tree:
if type(tree[0]) is str or type(tree[0]) is int:
yield tree[0]
tree = tree[1]
else:
yield tree[0][0]
tree = tree[0][1]
def on_same_path(tree, pairs):
tree_list = []
while tree:
res = [x for x in iterate(t... |
6ebc2cf19a628eca922693083794695a27a33fb0 | scb-am/Fractals | /Map/programming_types/OOP_application.py | 2,579 | 3.703125 | 4 | from abc import ABC, abstractmethod
from itertools import zip_longest
DEFAULT_KEY = '11'
class Map_point(ABC):
@property
@abstractmethod
def point_value(self):
"""get point value"""
@staticmethod
def factory(cell_coordinates, clue):
if len(clue) != 2:
raise ValueError... |
7a30fabc93c13fdf157237c5d0eca3d6bccd5918 | scb-am/Fractals | /checkio/rotate_hole.py | 2,949 | 3.5 | 4 | def rotate(holes, cannons):
return [i for i in range(len(holes)) if all([(holes[-i:] + holes[:-i])[x] == 1 for x in cannons])]
"""OMG"""
# # Creates a node which contains data and has a pointer to the next and previous node.
# class Node:
# def __init__(self, contents, last_node, next_node):
# self.co... |
705e9679adbb0a1d4afc08d96456b332e4991bca | scb-am/Fractals | /checkio/300_symbols.py | 4,332 | 3.59375 | 4 | # You have to write a function named davasaan (division with all vowels a) which calculates integer division by 10.
# The vowels "eiou" are disallowed as are the slash "/", asterisk "*", and period "." characters.
#
# We have one more rule for this univocalic challenge. This is a code golf mission and your main goal i... |
8b11919096e6dc143c145b1a31291959afa22879 | scb-am/Fractals | /most_frequent_characters.py | 1,923 | 3.515625 | 4 | import unittest
from collections import Counter
class TestStringMethods(unittest.TestCase):
def test_dif_cases(self):
self.assertEqual(most_frequent_characters('ccacccdaababBBBccccdd', 3),
'cba')
def test_characters_count(self):
self.assertEqual(most_frequent_characte... |
f75c2d0337ced40977bfecfe44cc1697363ec802 | fenshitianyue/design-pattern | /decorator_logging_class.py | 1,075 | 3.578125 | 4 | #!/usr/bin/python2
# -*- coding:UTF-8 -*-
from functools import wraps
class log_it(object):
def __init__(self, logfile='out.log'):
self.logfile = logfile
def __call__(self, f):
@wraps(f)
def wrapped_func(*args, **kwargs):
log_string = '[ ' + f.__name__ + ' ] was called...'... |
bb1c7fd1bd6a18b117c48d35499da4e199e45f08 | cwangED/AByteO-PythonCodingPrac | /pyCharmProjs/func_nest.py | 717 | 4.21875 | 4 | #!/usr/bin/python
# Filename:func_nest.py
# define functions that nested with another
def func1():
x1 = 'func1'
print("func1's variable: ", x1)
def func2():
x2 = 'func2'
print("func1's variable: ", x1)
print("func2's variable: ", x2)
def func3():
... |
e75b56de04b1d2335591205ae7f63dd572b34cf3 | cwangED/AByteO-PythonCodingPrac | /pyCharmProjs/lambda.py | 353 | 3.640625 | 4 | #!/usr/bin/python
# Filename: lambda.py
def make_repeater(n):
return lambda s:s*n
twice = make_repeater(2)
print twice('word')
print twice(5)
a = [(1, 'aa'), (2, 'bb')]
b = dict(a)
c = ([1, 'aa'], [2, 'bb'])
d = dict(c)
e = ((1, 'aa'), (2, 'bb'))
f = dict(e)
g = [[1, 'aa'], [2, 'bb']]
h = dict... |
79996556c1beac8dcdd31da0cab2f067d55f7043 | cwangED/AByteO-PythonCodingPrac | /pyCharmProjs/decoratorEx_para.py | 651 | 3.546875 | 4 | #coding=utf-8
#/usr/bin/python
# Filename: decoratorEx_para.py
# bold装饰器
def makebold(fn):
def wrapper(param="hello"):
# 在前后加入标签
return "<b>" + fn(param) + "</b>"
return wrapper
# italic装饰器
def makeitalic(fn):
def wrapper(param="hello"):
# 加入标签
return "<i>" + fn(param) + "<... |
caaaa10b883545de58bf1d88e48118cbc81981e2 | guiambros/hackerrank | /implementation/cut_the_sticks/cut_sticks.py | 2,254 | 3.65625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# --- Cut the Sticks
# You are given N sticks, where each stick is of positive integral length. A
# cut operation is performed on the sticks such that all of them are reduced by
# the length of the smallest stick.
#
# Suppose we have 6 sticks of length
# 5 4 4 2 2 8
#
# the... |
b8db5496ca46fc03ba340b69fa1a39d72d75d6c3 | guiambros/hackerrank | /arrays_and_sorting/3. insertion_sort2/insertion2.py | 1,070 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#
import sys
DEBUG = True
if (DEBUG): fp=open('input-b.txt')
def print_debug(str):
if (DEBUG): print "DEBUG: " + str
return
def read_input():
if (DEBUG):
ret=map(int, fp.readline().split(' '))
else:
ret=map(int, sys.stdin.readline().split(' ... |
19edbb4772e8dba518e777e74b600891e2efb958 | afeefebrahim/Think_python | /chap6/ex1.py | 196 | 3.890625 | 4 | #Write a compare function that returns 1 if x > y, 0 if x == y, and -1 if x < y
def compare(x,y):
if x>y:
return 1
if x<y:
return -1
if x==y:
return 0
print compare(21,1)
|
776b50819c91bc452b132a2810abfbfa9b3d07fd | mrcmillington/Python | /46 Layout.py | 583 | 4.28125 | 4 | # Demo ( Copy the code below )
from tkinter import *
root = Tk()
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(topFrame,text="Click me",fg="blue")
button2 = Button(topFrame,text="Hit me",fg="red")
button1.pack(side=LEFT)
button2.pack()
root.mainloop()
#... |
dd881e16fdcab41d89675e23d24c34d8c8d62e81 | chiru-20/chiru_20 | /Rock Paper Scissors | 8,540 | 4.28125 | 4 | #Generalized Python3 Program for Stone Paper Scissors Game(Single and Multiplayer Game).
import random
def MainMenu():
print("\nWelcome To Stone Paper Scissor Game : ")
choice = int(input("\nEnter 1. for Single Player Game \nEnter 2. for Multiplayer Game \nEnter 9. for Exit \n"))
if(choice == 1):
single_player()... |
bb73927b137f914008a2b2ee442af262a2724119 | autekroy/Yelp-Data-Challenge | /Word2VecUtility.py | 2,811 | 3.984375 | 4 | #!/usr/bin/env python
import re # use regular expression to remove non-alphabet
import nltk #for stop words
import pandas as pd
import numpy as np
from nltk.corpus import stopwords
class Word2VecUtility(object):
"""Word2VecUtility is a utility class for processing raw text into segments for further learning"""... |
86cc55280cfadf1f17da0d2d1a588636dd32f6c5 | wesleyakon/ExerciciosPython | /054.py | 603 | 3.96875 | 4 | from datetime import date
at = date.today().year
totmaior = 0
totmenor = 0
for pess in range(1,8):
ano = int(input('Em que ano a {}° pessoa nasceu? '.format(pess)))
idade = at - ano
if idade >= 21:
totmaior += 1
else:
totmenor += 1
print('ao todo tivemos {} pessoas maiores de idade'.form... |
aee25c2df7e67e7e54394f3408cbd9b211e48a87 | wesleyakon/ExerciciosPython | /029.py | 300 | 3.859375 | 4 | km = float(input('qual a velocidade atual do carro?'))
mu = (km - 80) * 7
if km <= 80:
print('tenha um bom dia!! dirija com segurança ')
else:
print('multado você exedeu o limite de 80km/h vc deve paga uma multa de R$ {}! '.format(mu))
print('tenha um bom dia!! dirija com segurança ') |
c0fbed8b51181aece087ea560dc88f8e3dd4499a | wesleyakon/ExerciciosPython | /035.py | 368 | 3.984375 | 4 | print('-=-'*20)
print(' Analisador triangulo')
print('-=-'*20)
a = float(input(' primeiro segmento?'))
b = float(input(' segundo segmento?'))
c = float(input(' terceiro segmento?'))
if a < b + c and b < a + c and c < a + b:
print('os segmentos acima PODEM FORMA TRIANGULO')
else:
print(... |
652d35cb884514a3e20acf7fe52d5eea1106876c | wesleyakon/ExerciciosPython | /034.py | 285 | 3.609375 | 4 | p = float(input('informe o valor do seu salario :$'))
des = 15
au = 10
if p <= 1250:
print('seu salario de $$',p,' com aumento de ',des,'% de aumento é $:',p + (p * des / 100))
else:
print('seu salario de $$',p,' com aumento de ', au, '% de aumento é $:', p + (p * au / 100)) |
4c3148c6082f91e16fb93700355de5c7ccdc91e1 | al3xi0escu/LPTHW | /ex22.py | 1,154 | 4.15625 | 4 | # print = a variable that writes something in the code
# # = this symbol let's you comment
# + = plus; adds
# - = minus; subtracts
# / = slash
# * = asterisk; multiplies
# % = percent; modulus operator
# < = less-than
# > = greater-than
# <= = less-than-equal
# >= = greater-than-equal
# "" = string
# '' = string
# () =... |
31bf307cd2d03f04c776fbaaa2909494a73a2ee2 | RichStone/circle-triangles-riddle | /CircleTriangle.py | 2,176 | 4.34375 | 4 | from math import ceil
class CircleTriangle:
"""
"""
def __init__(self, bottom_row_size):
if bottom_row_size < 2:
raise Exception('A triangle of circles cannot consist of less than 2 circles in the bottom row.')
self.bottom_row_size = bottom_row_size
# You can place (... |
a70133e0f1caf255a8b964be9ccc2d50df418b53 | nikhillondhe9/CS6112017 | /PythonExercise/exercise7c.py | 205 | 4.03125 | 4 | # implementation of len function
def len_function(list):
list_len = 0
for element in list:
list_len += 1
return list_len
print(len_function([1, 2, 3, 4, 5, 'six', 'seven', 'eight']))
|
3c43edcaee6ad476c78d46505b630ec657f7cbcf | devtosxn/web-scraper | /main.py | 400 | 3.671875 | 4 | from scrape_panel import attempt_website_scrape
def get_user_choice():
option = str(input('Would you like to scrape a website (y/n)? ').lower())
return option
while True:
answer = get_user_choice()
if answer == 'n':
print('Thank you for visiting, Goodbye!!!')
break
elif answer !=... |
b25ea40e1b73098c9916cc0e04465192caf68572 | lewis267/CS_390 | /rttt.py | 1,241 | 3.703125 | 4 | #!\bin\python3
line = input()
tree = list(map(str.strip, line.split(',')))
def read_right(num_to_read, index):
stars = 0
for i in range(num_to_read):
#check if done
if index >= len(tree):
return
#check for star
if tree[index] == '*':
stars += 1
... |
dad5dce6960090c8a4a1b88c9b6b3462a1d2b352 | ShreyChachra/PYTHON | /file extension.py | 132 | 4.15625 | 4 | filename=input("Enter the file name")
f_extension=filename.split(".")
print("The extension of the file is: "+repr(f_extension[-1]))
|
e4a4b75e7d95dc7540a29f85aa066a7b82a41545 | lumaherr/python_fundamentals | /04_conditionals_loops/03_01_divisible.py | 366 | 4.4375 | 4 | '''
Write a program that takes a number between 1 and 1,000,000,000
from the user and determines whether it is divisible by 3 using an if statement.
Print the result.
'''
input1 = int(input("Type a number between 1 and 1000000000: "))
if input1 % 3 == 0 :
print("Yeees its divisible by 3:", input1/3)
else :
pri... |
5db26d847134378434b76884de3c8661411dd739 | lumaherr/python_fundamentals | /02_basic_datatypes/02_06.py | 190 | 3.640625 | 4 | a = int(input("investment amount: "))
b = int(input("interest rate in percentage: "))
c = int(input("number of years to invest: "))
print("future value:", round(a * (1 + b / 100) ** c, 3))
|
bead0b58c527a91c181a840b1ddd012ff37499df | lumaherr/python_fundamentals | /08_exceptions/08_03_else.py | 323 | 4.0625 | 4 | '''
Write a script that demonstrates a try/except/else.
'''
try:
a = int(input("Type a number here: "))
b = int(input("Type a second number: "))
print(a / b)
except ValueError:
print("No other values than numbers are allowed")
except ZeroDivisionError:
print("No zeros allowed")
else:
print(a... |
5fd5ee35b647acb014c62a97ce23540302cdde58 | lumaherr/python_fundamentals | /03_more_datatypes/3_tuples/04_14_list_of_tuples.py | 526 | 4.25 | 4 | '''
Write a script that takes a string from the user and creates a list of tuples with each word.
For example:
input = "hello world"
result_list = [('h', 'e', 'l', 'l', 'o'), ('w', 'o', 'r', 'l', 'd')]
'''
#try with a loop
string1 = "hello world"
list1 = string1.split(" ")
print(type(list1))
print(list1)
tuple1 = tu... |
47c2577308f0d0a393c320ed7b0a11558dd68f29 | lumaherr/python_fundamentals | /05_functions/05_01_tasks.py | 1,141 | 4.125 | 4 | '''
Write a script that completes the following tasks.
'''
# takes in a number from the user between 1 and 1,000,000,000
input1 = int(input("Write number between 1 and 1000000000: "))
# calls a function that determines whether the number is divisible by both 4 and 7
def divisibility_4_and_7(x):
if x % 4 == 0 a... |
4f1dd3f2f47ab7a95bb3f4e44b78644c61675211 | Cl0/demo-repo-1 | /demo1.py | 610 | 3.84375 | 4 | # types
def multiply(a, b):
return a * b
# a = input('number a: ')
# b = input('number b: ')
# take an integer, and only a integer
# accept input
# if it is an integer, move on
# if not an integer, give the user another chance
def validate_input(num_digit):
user_input = input('number ' + num_digit + ':' ... |
2e1558080d0d24eeb6996c57a6c224dd3c2e2300 | ishaan19/PythonAssignments | /DataTypes2.py | 885 | 4.09375 | 4 | #1
tuple1 = ('ishaan','bharti','aryan')
print(tuple1)
print(len(tuple1))
#2
tuple1=('ishaan','55','coder')
tuple2=('geek','1','python')
print(max(tuple1))
print(min(tuple1))
print(max(tuple2))
print(min(tuple2))
#3
tuple1=(1,2,3,4,5)
product=1
for x in tuple1:
product *= x
print(product)
#4
#difference
set... |
596197fbbb9d4e3429de7c5113a8c9a1ba99af5d | ishaan19/PythonAssignments | /introToPythonassignment.py | 482 | 4.1875 | 4 | #1
print("Hello World")
#2
a="acad"
b="view"
string=" "+" "
print (string,a,b)
#3
x=int(input("enter 1st number"))
y=input("enter name")
z=input("enter course")
print("number entered",x)
print("name entered",y)
print("course entered",z)
#4
print("let's get started")
#5
s="acadview"
course="python"
fees=5000... |
03141a82296aec59438fab05b1d76f9a8ca6d24a | lightbitbird/python-playground | /test1.py | 223 | 3.78125 | 4 | print("Hello World!")
2 + 2
width = 30
height = 2 * 6
print(width + height)
word = "character word"
print(word[0: 5])
print(word[3: 6])
print(word[:8])
print(word[7:])
print(word[7:] + word[:7])
print(word[:7] + word[7:])
|
b75e790712c9d4d3031bdb5e9c2537caa90febb2 | TylerTempleton/Python_Exercises | /01_HelloWorld/01_HelloWorld/_01_HelloWorld.py | 372 | 4.5625 | 5 |
#The purpose of this program is to create a Hello World application that Prints Hello World and askes the users name and prints it
#Create multiline string variable
HelloWorld = """
-------------------------
Hello World
-------------------------
"""
#Print string
print(HelloWorld)
#User Input
name = i... |
2cab9c8cddbcc4748ba159d800391eb65ba597c4 | Hejmat/AdventOfCode | /Task15_part1.py | 649 | 3.625 | 4 | ## https://adventofcode.com/2020/day/15
file = 'No15_input.txt'
with open(file, 'r') as f:
data = f.read()
data = [int(d) for d in data.split(',')][::-1] #Reverse input data
f.close()
iterations = 2020 #Number of maximum iterations
while len(data) < iterations: #Loop until reach the limit of iterations
... |
ea1c3e8c3d0766d20ed7dd48cbb6e3fbab1a3304 | KIMKIHWAN55/Test | /HomeWork/turtle.py | 270 | 3.765625 | 4 | import turtle as t
t.screen.setup(width=400, height=300)
t.penup()
t.goto(-100,-50)
t.pendown()
radius = 50
t.color("red")
t.circle(radius)
t.color("blue")
t.forward(30)
t.circle(radius)
t.color("green")
t.forward(30)
t.circle(radius)
turtle.mainloop()
turtle.bye()
|
a159c3d3a0e825ca71974c5e9ede05a03c476670 | vincecharming/hacker_rank | /python/tools/string_calculator.py | 7,174 | 3.78125 | 4 | #
# Vincent Charming (c) 2019
#
'''
Task: Design a calculator to compute an arithmetic string, i.e. '1 + 1' => 2
1. What are the primary components that a system like this needs in order
to function correctly? Think about this in terms of simple classes or
functions that can break up the problem space int... |
efa14a0767993936ab33ba963e57a419937d08c7 | lewis426/Wizard-Game | /program.py | 3,205 | 3.8125 | 4 | import random
import time
from creatures import Creature, Wizard, SmallAnimal, Dragon
def main():
print_header()
game_loop()
def print_header():
print('------------------------------')
print(' WIZARD GAME')
print('------------------------------')
print()
def game_loop():
creatu... |
655e74440ce5b93b4ec582119600009ac4f19439 | WebProject-STT/Algorithm | /prev/baekjoon/8주차/12100/12110_sb.py | 4,363 | 3.5 | 4 | # 2048 (Easy)
import sys
def up(board) : # 위로 이동
for c in range(N) : # N번 반복을 통해 모든 열에 대해 수행
stack = []
check = 0
for r in range(N) :
if board[r][c] > 0 :
if len(stack) > 0 and stack[-1] == board[r][c] and check == 0 :
stack.append(stack.pop()... |
9d3e5b68f68ebaf6fc02293151bad0b46e25919f | WebProject-STT/Algorithm | /prev/programmers/10주차/방금그곡_sb.py | 1,024 | 3.609375 | 4 | def music_check(m, music, time) : # 악보 확인
m = m.replace('C#', 'X').replace('D#', 'Y').replace('F#', 'Z').replace('G#', 'W').replace('A#', 'P')
music = music.replace('C#', 'X').replace('D#', 'Y').replace('F#', 'Z').replace('G#', 'W').replace('A#', 'P')
musiclen = len(music)
music = time//musiclen*(m... |
1d6d22935cd99c0a9fc6c57e3c30e1da74940c92 | WebProject-STT/Algorithm | /prev/baekjoon/21주차/11559/11559_sj.py | 2,344 | 3.75 | 4 | def remove_group(map_, group):
# 연쇄반응 제거
for x, y in group:
map_[y][x] = '.'
def reposition(map_):
stack = []
for x in range(w): # 한 열씩 검사
for y in range(h):
if map_[y][x] != '.': # 아래에서 위로 올라가면서 .이 아닌경우에 stack에 저장
stack.append(map_[y]... |
a3cc4fbe3726a3e7f409bf0fab0bc837ae1c13b7 | WebProject-STT/Algorithm | /prev/baekjoon/18-19주차/1759/1759_jy.py | 766 | 3.671875 | 4 | # 암호 만들기
def make_word(cur_string, idx, count1, count2): # count1 = 자음, count2 = 모음
if len(cur_string) == L:
if count1 < 2 or count2 < 1: return
print(cur_string)
return
for i in range(idx, C):
if not visited[i]:
visited[i] = 1
if alpha[i] =... |
b739b06374f88cf0a90b01e2cf8a8872fa977770 | poornimaramesh/fluent_python_exercises | /ch12/ch12_problem.py | 1,771 | 4.03125 | 4 | ## Q1: Here are a bunch of classes. Refactor them taking into account the 8 principles
## under "Coping with Multiple Inheritance" on page 362. You are welcome to change
## anything you like and add additional classes etc. - I'm hoping this
## makes for a healty discussion on inheritance and design choices.... |
be380f6402603d1e4b1f00ae1695d04053b1fdcc | grantsrb/tokenizer | /tokenizer/tokenizer.py | 16,488 | 3.6875 | 4 | import string
import torch
def tokenize(main_string, delimeters={" "},
special_tokens={"\\newline",'\n'},
split_digits=False,
lowercase=False):
"""
Returns a list of tokens delimeted by the strings contained in the
delimeters set... |
3f642af56b2577321e7a41a86de0f774fa508d63 | patrick473/TCIT-V1PROG-15 | /6.11.py | 274 | 3.796875 | 4 | def easyCrypto(word) :
new = ''
for i in word :
if ord(i) % 2 == 0 :
char = chr(ord(i) + 1)
new = new + str(char)
else :
char = chr(ord(i)-1)
new = new + str(char)
print(new)
easyCrypto(input())
|
a557e31b94de8fd9f0aebdacbae935b4f43df8f7 | patrick473/TCIT-V1PROG-15 | /3.23.py | 335 | 3.8125 | 4 | print('-----a-----')
for a in range(0,2):
print(a)
print('-----b-----')
for b in range(0,1):
print(b)
print('-----c-----')
for c in range(3,7):
print(c)
print('-----d-----')
for d in range(1,2):
print(d)
print('-----e-----')
for e in range(0,4,3):
print(e)
print('-----f-----')
for f in range(5,22,4)... |
b5811feaf9fedfb46e84ad803a2a67392e7ae45b | patrick473/TCIT-V1PROG-15 | /5.23.py | 421 | 3.8125 | 4 | def pay(hours,wage) :
if 40 < hours > 60 :
hours -= 40
pay = wage * 40
pay = pay + (hours * (wage * 1.5))
elif hours > 60 :
hours -=60
pay = wage * 40
pay = pay +((wage * 1.5) * 20)
pay = pay + (hours * (wage * 2))
else: # hours <40
pay = ... |
9d9a32f98c7b0decbd2901f8b428cfbc3414ecc0 | patrick473/TCIT-V1PROG-15 | /2.18.py | 272 | 4.03125 | 4 | flowers = ['rose', 'bougainvillea', 'yucca','marigold', 'daylilly', 'lilly of the valley']
print('potato' in flowers)
thorny = [flowers[0], flowers[1], flowers[2]]
poisonous = [flowers[-1]]
dangerous = thorny + poisonous
print(thorny)
print(poisonous)
print(dangerous)
|
c22930572ee367f88598c944594cd9bad0e00d52 | patrick473/TCIT-V1PROG-15 | /5.26.py | 512 | 3.90625 | 4 | def rps():
victory = False
while victory == False :
a = input('Player 1: R, P or S: ')
b =input('Player 2: R, P or S: ')
if (a == 'R' and b == 'S') or (a == 'S' and b == 'P') or (a == 'P' and b == 'R'):
victory = True
print('Player A has won')
elif (b == ... |
6a8d920b0ba97520d8545fa041c36fe6b35f66cb | patrick473/TCIT-V1PROG-15 | /5.19.py | 230 | 3.609375 | 4 | def inBoth(a,b) :
for i in a :
for u in b :
if i !=u :
continue
else :
both.append(int(i))
print(both)
both = []
inBoth([1,2,3,4,10,9,7],[1,2,3,4,5,6,7])
|
b911abf1a10322c48f810e76329b945bc360ae56 | patrick473/TCIT-V1PROG-15 | /final assignment 6.py | 193 | 3.765625 | 4 | def code(invoerString):
new = ''
for i in invoerString :
char = chr(ord(i) + 3)
new = new + str(char)
print(new)
return new
code(input('Voer een woord in: '))
|
b163727de7b06bb17e5d974c0fa881f469ca038e | hakukata/python-basic | /codes/204-1.py | 387 | 3.9375 | 4 | #! /usr/bin/env python
#coding:utf-8
print "请输入字符串,然后按下回车键:"
user_input = raw_input()
result = user_input.isdigit()
if not result:
print "您输入的不完全是数字"
elif int(user_input)%2==0:
print "您输入的是一个偶数"
elif int(user_input)%2!=0:
print "您输入的是一个奇数"
else:
print "您没有输入什么呢吧"
|
8d1df32b10b6976373e3f646b94fa28506d9ac4e | hakukata/python-basic | /codes/204-2.py | 349 | 3.953125 | 4 | #!/usr/bin/env python
#coding:utf-8
import random
numbers = [random.randint(1,100) for i in range(20)]
"""
odd = []
even = []
for x in numbers:
if x%2==0:
even.append(x)
else:
odd.append(x)
"""
odd = [x for x in numbers if x%2!=0]
even = [x for x in numbers if x%2==0]
print numbers
print "... |
4e6cf1d9510a223daf588fd3e247724c5d38be59 | AdmiralAckbar13/nmt_python_labs | /word_count.py | 1,556 | 4.15625 | 4 | #Word_count.py (lab 6) [Shane Roeseberg]
print("== Word Count ==")
print("\n")
print("------------------------------------------------------------------------------")
print("When entering the filename be sure to include the extension (such as .txt)")
print("-------------------------------------------------------------... |
a8242c11ce67de41d1fa47bed91da46a5927fbe8 | AdmiralAckbar13/nmt_python_labs | /peasants(b).py | 813 | 4.15625 | 4 | #Peasants b.).py (Lab 3) [Shane Roeseberg]
# b.) Recursive function implementing Russian peasant multiplication. Call function expo()
def main(): #main input script
while True:
print("Type stop at any point to exit the program.")
x = input("Please enter a number: ")
y = input("Enter a number to multiply by... |
f4136261c36896707643637af5c4dea17ad59e79 | AdmiralAckbar13/nmt_python_labs | /spiral.py | 300 | 3.859375 | 4 | #Spiral.py (Lab 4) [Shane Roeseberg]
import turtle
print("== Spiral ==")
def main():
distance = 11
angle = 10
for i in range(250):
turtle.forward(distance)
turtle.left(angle)
distance = distance + .20
if i == 249:
print("== Program Completed ==")
if __name__ == '__main__':
main() |
b3ce613b9f64c19cfbe68bafc4493434776ab6b4 | AdmiralAckbar13/nmt_python_labs | /navigate.py | 808 | 4.21875 | 4 | #Navigate.py (Lab 2) [Shane Roeseberg]
import turtle
def main():
stored = []
while True:
direction = input('Please enter a direction: ')
if direction == 'forward':
stored.append(turtle.forward(100))
elif direction == 'left':
degrees = input('How many degrees? ')
if int(de... |
6b4b6fcdebd8d3931c90df06230f4b923eca0fb7 | AdmiralAckbar13/nmt_python_labs | /rpn.py | 931 | 3.84375 | 4 | #RPN.py (lab 8) [Shane Roeseberg]
import math
def rpn(string):
array = []
operators = {"+": lambda x,y: x + y, "-": lambda x,y: x - y, "*": lambda x,y: x * y, "/": lambda x,y: x / y,"sin": lambda y: math.sin(y),"cos": lambda x: math.cos(x)}
numb = None
for i in string.split():
if i in "+-*... |
66527d85168ad1937392466baea240be1e987bef | HovhannesMkrtchyan2004/Python_Homewhork | /Lesson 41.py | 2,777 | 3.53125 | 4 | # Ruben
class Weapon:
def __init__(self, name, damage, range):
self.name = name
self.damage = damage
self.range = range
def hit(self, actor, target):
if not target.is_alive():
print("the enemy is already defeated")
elif actor.get_cords()[0] + self.r... |
085d3bb5e61f99153503c71a15d226f7b580a4cf | kiilkim/book_duck | /pythonPractice/0518/test1.py | 3,970 | 3.703125 | 4 | #지난시간 복습
#람다 함수 한줄에 표현하고 싶을 때
#함수이름 = lambda 매개변수, 매개변수 : 실행문
#1교시
#클래스 183p
# 클래스 정의 (사물,객체,업무...) 특징 저장하는 변수, 특징을 처리하는 기능(함수)
# class 클래스이름:
# 주제 변수1
# 주제 변수2
# 주제 처리 함수1
# 주제 처리 함수2
result = 0
def add(num):
global result
result +=num
return result
print(add(3))
print(add(4))
cl... |
21cbc6922758c76dac842a084bc7febe6a0652ba | kiilkim/book_duck | /pythonPractice/pnuPY/0710/07101B.py | 1,699 | 3.734375 | 4 | #0710 1교시
# if문
pocket = ['paper','cellphone']
card = 1
if 'money' in pocket:
print('택시를 타고 가라')
elif card:
print('택시를 타고 가라')
else:
print('걸어가라')
#while
treehit = 0
while treehit < 10:
treehit +=1
print("나무를 %d번 찍었습니다." %treehit)
if treehit == 10 :
print("나무가 넘어갑니다.")
... |
fb80a559841c3bc8980d006bf89e72a8eeb8a9e7 | kiilkim/book_duck | /pythonPractice/pythonMath/0625.py | 4,263 | 3.5 | 4 | #연습문제.
#1. 숫자를 받으면 몇째자리 수인지 돌려주는 코딩함수
def indexNum(a):
return len(str(a))
print(indexNum(1234))
#2. 숫자를 받으면 공통된 숫자를 출력하라
# 근데 공통 숫자를 출력하는게 아니라, 문자다.
# 숫자를 받는건 함수(숫자,숫자)로 되는데
# 그 받은 숫자를 숫자로 인식하고 공통의 수를 찾아내야한다.
#숫자에 인덱스가부여되나? no 다만 정수형 자료는 index로 접근할 수 없습니다.
a = '12345'
print(a[0])
def sameNum(a,b):
c... |
7d188480f61b0e1bf628fa3b9305bc9824444c51 | LarryHu0217/python-AI | /puzzle.py | 10,242 | 4.0625 | 4 | import sys
import math
import time
import queue as Q
import resource
import heapq
#### SKELETON CODE ####
## The Class that Represents the Puzzle
class PuzzleState(object):
"""
The PuzzleState stores a board configuration and implements
movement instructions to generate valid children.
"""
... |
4a2c1d56de89c352efde0b7c4ce19a39f59f4fb2 | Suchandana/Bungee-Tech | /Answer1.py | 1,123 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[9]:
import pandas as pd
from pathlib import Path
import numpy as np
# In[10]:
df=pd.read_csv('C:/Users/sucha/Downloads/internship-test2-master/internship-test2-master/input/question-1/main.csv')
# In[4]:
df_grouped = df.groupby((df.Year//10)*10)
# In[11]:
df.hea... |
cc3aa1e54b45140be177246bde2c0aa62be152d8 | VoTonggg/nguyenvanhung-fundamental-c4e18 | /Session05/sokoban.py | 2,762 | 3.578125 | 4 | map_sokoban = {
"size_x" : 5,
"size_y" : 5
}
player = {
"x" : 4,
"y" : 0
}
boxes = [
{"x": 1, "y" : 1},
{"x": 2, "y" : 2},
{"x": 3, "y" : 3},
]
destinations = [
{"x": 2, "y" : 1},
{"x": 3, "y" : 2},
{"x": 4, "y" : 3},
]
playing = True
while playing:
for y in range(map_sokob... |
6da5222d4585d8add67d7e6e9a6f88f875897018 | VoTonggg/nguyenvanhung-fundamental-c4e18 | /Session02/sum-n.py | 145 | 4.0625 | 4 | n = int(input("Enter a number? "))
# sum = 0
# for i in range(n+1):
# sum += i
# print(sum)
#pythonic
total = sum(range(n+1))
print(total) |
b4b296fa360ecfc7a44fcf2fdec1ca887cba4d76 | VoTonggg/nguyenvanhung-fundamental-c4e18 | /Session03Homework/infiniteloop.py | 89 | 3.875 | 4 | count = 0
while True:
print("Hello")
count += 1
if count == 5:
break |
d575351c762e94f1375a305ded14a0fc47234465 | VoTonggg/nguyenvanhung-fundamental-c4e18 | /Session03/updatefavslist.py | 395 | 4.03125 | 4 | favs = ["deadth note", "netflix", "teaching"]
print("Hi there, here your favorite things so far")
for index, item in enumerate(favs):
print("{0}. {1}".format(index+1, item))
position = int(input("Position you want to upade? "))
replace_fav = input("Your replacing favorite? ")
favs[position-1] = replace_fav
for ... |
08866c23ae868cb1905aaa40b2c6eeced70278c0 | kenziehong/CodeCademy_Sept2018 | /ComputerSience/Test_LinkedList.py | 7,820 | 4.4375 | 4 | #Introduction
from linked_list import LinkedList, Node
# initializing linked list with NO head node to start
linked_list_1 = LinkedList()
linked_list_1.add('hey!')
linked_list_1.add('ho!')
linked_list_1.add("let's go!")
linked_list_1.traverse()
# The last added node is the head using .add()!
# We can als... |
0e5d003faabc7c3f19fa06b42f76348306ede1bd | kenziehong/CodeCademy_Sept2018 | /ComputerSience/Hong_Review_Data Structures.py | 994 | 4.03125 | 4 | class TreeNode:
def __init__(self, value):
self.value = value
self.children = []
def __repr__(self, level=0):
# HELPER METHOD TO PRINT TREE!
ret = "--->" * level + repr(self.value) + "\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
def add_chil... |
7bd3758b0ece0f55c761b24d3562f5385b3aa804 | kenziehong/CodeCademy_Sept2018 | /ComputerSience/SORTING ALGORITHMS_A Sorted Tale_Project.py | 4,494 | 4 | 4 | #books_large.csv
#books_small.csv
title,author
Adventures of Huckleberry Finn,Mark Twain
Best Served Cold,Joe Abercrombie
Dear Emily,Fern Michaels
Collected Poems,Robert Hayden
End Zone,Don DeLillo
Forrest Gump,Winston Groom
Gravity,Tess Gerritsen
Hiromi's Hands,Lynne Barasch
Norwegian Wood,Haruki Muraka... |
44134c4e67a78fe12578d78b5912cc586d628f6d | kenziehong/CodeCademy_Sept2018 | /ComputerSience/Choose Your Own Adventure- Wilderness Escape_Project_LEARN TREES.py | 3,001 | 4.3125 | 4 | LEARN TREES
Choose Your Own Adventure: Wilderness Escape
Welcome to Wilderness Escape, an online Choose-Your-Own-Adventure. Our users get a unique story experience by picking the next chapter of their adventure. We use the tree data structure to keep track of the different paths a user may choose. Let's get started!
... |
d5c338e237cc4c17548307e31ecba3f6d919654e | b-ark/lesson_24 | /Task2.py | 1,461 | 4.21875 | 4 | # Write a program that reads in a sequence of characters,
# and determines whether it's parentheses, braces, and curly brackets are "balanced."
class Stack:
def __init__(self):
self._items = []
def is_empty(self):
return not bool(self._items)
def push(self, item):
self._items.appen... |
d0ca7de78e010d948b8c787dc26fa93c767cf7e8 | haelannaleah/autoturtle | /obstacle_detection.py | 5,827 | 3.75 | 4 | """ Detect obstacles before we collide with them.
Author:
Annaleah Ernst
"""
import cv2
import numpy as np
import rospy
from logger import Logger
class ObstacleDetector():
""" Detect obstacles.
Attributes:
obstacle (bool): True if there is an obstacle that needs attention, False otherwis... |
64ca7ab687b24e2d2162f7010cb7ebbdf58b017a | Saphyel/life | /features/steps/step_rules.py | 1,492 | 3.515625 | 4 | """
Check if applies the rules of the game
"""
# @mark.steps
# ----------------------------------------------------------------------------
# STEPS:
# ----------------------------------------------------------------------------
from behave import given, then, when
from life.universe import Universe
from life.cell impor... |
4a4181245dbe27c07b8a1ba11b6662028d235d20 | NicGiannone/week3-review-part2-NicGiannone-master | /sales-totaler.py | 607 | 3.515625 | 4 | inputFileName = input('Enter sales: ')
totalFileName = input('Enter name for sales file')
inputFile = open(inputFileName, 'r')
outputFile = open(totalFileName, 'w')
for sales in inputFile:
sumTotal = 0.0
sales = sales.strip()
sales = sales.split(' ')
for sale in sales:
sale = sale.replace(... |
0a0dbc6d9c53f6f18f441ace853ba8955fe84c57 | bopopescu/geosci | /sage/src/sage/calculus/desolvers.py | 62,357 | 3.5625 | 4 | r"""
Solving ordinary differential equations
This file contains functions useful for solving differential equations
which occur commonly in a 1st semester differential equations
course. For another numerical solver see the :meth:`ode_solver` function
and the optional package Octave.
Solutions from the Maxima package ... |
faa5fb4d996728c602ea873f3f1627b4ec90a714 | bopopescu/geosci | /sage/src/sage/groups/braid.py | 82,060 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Braid groups
Braid groups are implemented as a particular case of finitely presented groups,
but with a lot of specific methods for braids.
A braid group can be created by giving the number of strands, and the name of the generators::
sage: BraidGroup(3)
Braid group on 3 strands
... |
4a4588767e2311371fb797ba71bbb739bff8174b | bopopescu/geosci | /sage/src/sage/geometry/linear_expression.py | 24,869 | 3.609375 | 4 | """
Linear Expressions
A linear expression is just a linear polynomial in some (fixed)
variables (allowing a nonzero constant term). This class only implements
linear expressions for others to use.
EXAMPLES::
sage: from sage.geometry.linear_expression import LinearExpressionModule
sage: L.<x,y,z> = LinearExp... |
744bcd60d450c0d916f486395abbc2a411ac9b07 | bopopescu/geosci | /sage/src/sage/categories/category.py | 119,948 | 3.609375 | 4 | r"""
Categories
AUTHORS:
- David Kohel, William Stein and Nicolas M. Thiery
Every Sage object lies in a category. Categories in Sage are
modeled on the mathematical idea of category, and are distinct from
Python classes, which are a programming construct.
In most cases, typing ``x.category()`` returns the category ... |
6f66dbf3aef4ab6fba5978a793998988a0c1443e | bopopescu/geosci | /sage/src/sage/modules/tensor_operations.py | 20,350 | 3.609375 | 4 | """
Helper Classes to implement Tensor Operations
.. warning::
This module is not meant to be used directly. It just provides
functionality for other classes to implement tensor operations.
The :class:`VectorCollection` constructs the basis of tensor products
(and symmetric/exterior powers) in terms of a chose... |
0b8b84ab52b9b00f5c16655639617b53ba7e8175 | bl3ck/pdsnd_github | /bikeshare.py | 8,383 | 4.4375 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.