blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e58e2b78b45e66a480d412af07ec8ee954230556 | BreeBot/IntroToProg-Python | /Assigment07.py | 986 | 4.40625 | 4 | #-------------------------------------------------#
# Title: Working with Dictionaries
# Dev: Breana K. Merriweather
# Date: August 26, 2019
# ChangeLog:
#-------------------------------------------------#
#1). Create a simple example of how you would use Python Exception Handling.
#Demonstrate handl... |
37e447400336b7c839e1b305b66ce5f228edf7e4 | MihirMore/Fun-Python-Projects | /Guess_the_number/user-guess.py | 789 | 4.40625 | 4 | # Guess the number is a game where user is asked to guess a number, the computer then comments if the number is high, low or the correct number.
# Here we are using the random function to generate a random number betwwen x to y.
import random
def guess(x):
random_number = random.randint(1, x)
... |
efc1f55a43fd4532c3b6cde9276d996e0faa304e | cyclades1/Python-Programs | /p11.py | 107 | 3.53125 | 4 | '''input
12
3
'''
n = int(input())
c = int(input())
if(n%c==0):
print("YES")
else:
print("No")
|
597f7f559071465f21323f205d4ec503b5efec5f | Dpalazzari/codeChallenges | /Python/basic_stack/basic_stack.py | 810 | 3.65625 | 4 | from itertools import chain
class BasicStack(object):
def push_to_array(self, arr, num):
return list(chain.from_iterable([arr, [num]]))
def push_to_array_with_append(self, arr, num):
arr.append(num)
return arr
def remove_last_element(self, arr):
arr = arr[0:-1]
return arr
def remo... |
e9479627d41cb048285a0af07494884aa295ff6b | Alex-Wei-bot/python-learning-diary | /exercise code/day3.1.py | 304 | 4.1875 | 4 | #英尺厘米换算
i=float(input('input an number'))
j=input('is it inch or centimeter?')
if j == 'inch':
inch=i
centimeter=inch*2.54
print(f'the length in centimeter is {centimeter:.2}')
else:
centimeter=i
inch=centimeter/2.54
print('the length in inch is %.2f' %inch) |
1f496a7e604f3449f03d945b34a3517741b198a0 | nikithasake/Python | /python coding(prep)/fibonnaci.py | 134 | 4.09375 | 4 | #fibonaci
def fib(n):
if n==1:
return 0
if n==2:
return 1
return fib(n-1)+fib(n-2)
n=int(input("Enter input:"))
print(fib(n))
|
38945d14315783bf445d82814180c28b7f9dfc0e | alysonla/Full-Stack | /names.py | 830 | 4.46875 | 4 | # Open names.txt file
# Write a Python script which loads the names from the file, and converts your own name to a
# superhero (or supervillain) name by picking the name corresponding to your first name's position
# in the alphabet (there are 26 superheroes in the list). For example, if your name starts with A,
# you ... |
b07323b38c4b60f7da1307ca9d870fbc059a9d51 | greend6807/cti110 | /CTI 110/P4T1A_Green/P4T1A_Green.py | 689 | 4.125 | 4 | #CTI-110
#P4T1A_Green
#Darius Green
#11/20/18
import turtle #Allows us to use turtle.
wn = turtle.Screen() #Creates a playground for turtles
blues = turtle.Turtle() #Create a turtle, assign to blues
#Display options
blues.pensize(3)
blues.pencolor("blue")
blues.shape("turtle")
#Have the ... |
d449d303b2831c9198b4018dcacd1fa7b1a9fa30 | Kapo4eso4i/CheckIO | /Home/Pawn Brotherhood.py | 363 | 3.609375 | 4 | def safe_pawns(pawns):
letters = [' ', 'a', 'b', 'c', 'd', 'e' , 'f', 'g', 'h', ' ']
safe_place = []
for pawn in pawns:
next_row = str(int(pawn[1])+1)
safe_place += [letters[letters.index(pawn[0])+1] + next_row,
letters[letters.index(pawn[0])-1] + next_row]
return ... |
e9e60f5bbaad2e4111ba98e77d0605ff628c76a8 | SeungpilHan/Python_Tutorial | /Desktop/Coding/Jump to Python/practice.py | 69 | 3.765625 | 4 | for a in [1,2,3]:
print(a)
i = 0
while i < 3:
i=i+1
print(i) |
d8355d46dc6b0aac828f6c6249e7ce07d507b28a | ZhengweiHou/python-learn-hzw | /optionSYS_test/进程同步/mutex_lock_demo_lock.py | 980 | 3.90625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import threading
lock = threading.Lock() # 定义一个互斥量-互斥锁
num = 0
def producer():
global num
times = 1000000
while times >0 :
global lock
lock.acquire() # 加锁
num += 1
lock.release() # 解锁
times -= 1
print('producer end!!... |
a60249008de805cbb06538751ceddfa93568d9d1 | oereo/Algorithm_thursday | /YounJongSu/mid_hw/quick_sort.py | 577 | 3.8125 | 4 | def partition(arr, l, h):
i = l-1
piv = arr[h]
for j in range(l, h):
if arr[j]<piv:
i+=1
arr[i],arr[j]=arr[j],arr[i]
print(arr)
arr[i+1],arr[h] = arr[h], arr[i+1]
print(arr)
print("pt end")
print(i+1)
return i+1
def quickSort(arr, l, h):
... |
ff733043a6af1f002e7fc938b53947ad137bbc94 | thomasmontoya123/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/9-Adam.py | 1,116 | 3.703125 | 4 | #!/usr/bin/env python3
"""Adam module"""
def update_variables_Adam(alpha, beta1, beta2, epsilon, var, grad, v, s, t):
"""
updates a variable in place using the Adam optimization algorithm
Parameters
----------
alpha : float
learning rate
bet... |
47e7512a8c8dec280aab01d06218cc8b5a37c808 | Marie-EveGauthier/whatIShouldWatch | /bin/tag-analysis/process_categories.py | 867 | 4.3125 | 4 | import pandas as pd
filename1 = raw_input("Enter the name of the file you want to process categories from:\n")
#Import the data in file as a pandas object
data = pd.read_csv(filename1, names = ['name', 'categories'])
#get a list of names who don't have entries in wikipedia
no_categories = data[data.categories.isnul... |
9c171f0dbca62bec644364ebb504ec5818ee3c2f | TuongTuan3T/PythonNC | /Lab05/Bai03.py | 364 | 3.75 | 4 | class Student:
def __init__(self, name:str, number: str, course:str, mail:str):
self.name = name
self.number = number
self.course = course
self.mail = mail
def __str__(self):
return ('{}\n{}\n{}\n{} '.format(self.name, self.number, self.course, self.mail))
pupil = Student('TuongTuan', '187it0701... |
95715c18eb0ec9519b481b0a667e38cb7b87e5bd | allankeiiti/Learning_Pytest | /modulo_2_validando_teste_com_erros_esperados.py | 1,087 | 3.875 | 4 | """
Aqui temos funções cujo possuem condições que caso sejam ou não atendidas, um erro é invocado e isso é esperado.
Portanto aqui é utilizado o pytest.raises(<Tipo de Erro>) para falar pro Pytest que este erro é esperado e que deve
ser invocado. Pois quando é testado um software também é necessário tentar... |
5f377bc81345db5adaa1a3a32c3170f669048194 | alters-mit/tdw_sound20k | /tdw_scene_size.py | 837 | 3.65625 | 4 | from abc import ABC, abstractmethod
from typing import Tuple
from numpy.random import RandomState
class TDWSceneSize(ABC):
"""
The size of a TDW scene room.
"""
@abstractmethod
def get_size(self) -> Tuple[int, int]:
"""
:return: The dimensions of the room.
"""
rai... |
215cd0b991f514076a58152eed8e2c2cd4839853 | hwins/triangle-puzzle-python3 | /TrianglePuzzlePython3/src/Triangle.py | 5,956 | 3.53125 | 4 | #!/usr/bin/env python3
import sys
class Node_Tree_Element(object):
"""individual element of the node tree
These objects contain node information such as left child, right child,
level on the tree and node integer value
"""
def __init__(self, node_value):
assert isinstance(node_value, int)
... |
0500416f388df1a6a047545b2e8432f7dd1ca24f | chao-ji/LeetCode | /python/string/lc49.py | 1,189 | 4.0625 | 4 | """49. Group Anagrams
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
"""
from string import ascii_lowercase
... |
a8c5e28379d9f4d8b39e6ed35b775f06d00a6e48 | xuting1108/Programas-de-estudo | /exercicios-pythonBrasil/estrutura-de-decisao/ex15.py | 997 | 4.25 | 4 | #Faça um Programa que peça os 3 lados de um triângulo. O programa deverá informar se os valores podem ser um triângulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno.
# Dicas:
# Três lados formam um triângulo quando a soma de quaisquer dois lados for maior que o te... |
965313b0c4a2748bdd1e6ede0ac8bec04b79956f | gabriellaec/desoft-analise-exercicios | /backup/user_242/ch162_2020_06_15_19_06_37_199855.py | 321 | 3.65625 | 4 | lista = [1,3,7,9]
def verifica_lista(lista):
par = True
impar = True
for i in lista:
if lista%2 == 0:
impar = False
else:
par = False
if par and not impar:
return 'par'
elif impar and not par:
return 'impar'
return 'misturado'
... |
7b7a97d7dc33fa33d73a7e3ce823a960d8432d74 | shanminlin/Cracking_the_Coding_Interview | /chapter-1/6_string_compression.py | 3,620 | 4.21875 | 4 | """
Chapter 1 - Problem 1.6 - String Compression
Problem:
Implement a method to perform basic string compression using the counts of repeated characters. For example,
the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the
original string, your method should return the... |
1dc43e7491a4f1701f4f7da8dd48e7c257e4dcb5 | adnan-mehremic/guess-phrase | /guess_phrase.py | 3,223 | 3.53125 | 4 | import random
population_size = 150
target = "Machine learning is awesome."
genes = '''qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM1234567890 ,.-_;:?!@$'''
# percente value of elitism to be performed
elitism_factor = 10
mating_percent = 50
class Individual(object):
def __init__(self, chromosome):
... |
8c60164ae99a06f82d08bb538af4449bfacdd421 | rajlath/rkl_codes | /Best_algo/Flying_with_Numbers/anagrams.py | 621 | 3.984375 | 4 | str1 = "marina"
str2 = "anaram"
def verify_anagrams(s1, s2):
'''
verify if two strings are anagram to each other
'''
dicts = {}
if len(s1) != len(s2):return False
for i in range(len(s1)):
dicts[s1[i]] = dicts.get(s1[i], 0) + 1
dicts[s2[i]] = dicts.get(s2[i], 0) - 1
return al... |
968ac463970b4f45b4d03d147e779c5246ee845f | grigorescu/Pygminion | /trunk/pygminion/utils.py | 996 | 3.671875 | 4 | import string
def cmpMoney(a, b):
try:
a = a.lower()
b = b.lower()
return cmp(int(a), int(b))
except ValueError:
# Something has a potion in the cost...
a_coins = sum([int(c) for c in a if c in string.digits])
b_coins = sum([int(c) for c in b if c in str... |
f76c559b08c7075f299f09f0af0d6fe160857508 | alexisbird/BC2repo | /madlibs.py | 1,022 | 4.625 | 5 | """Make a simple madlib, you can look one up. Ask for three words, save them in variables, fill in the madlib, then print the final madlib."""
# Create a variable for each word the user must input via input prompt
word1_person = input("Please enter a person: ")
word2_person = input("Please enter another person: ")
wor... |
f1c3d643764fc6661f4d46f044cfd179599200b9 | kiranmaipuli/DATA-STRUCTURES | /trees/binarySearchTree/leftNRightView.py | 2,718 | 3.84375 | 4 | """ finding left and right view in a binary search tree """
# inputArray = [50,30,20,40,70,60,80,10,59]
inputArray = [50,30,70,40,60,80,59]
levelDict = {}
class Node:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
# inserting nodes in a binary sear... |
be0c0eac2694290e053d394c3d83829b8ed17404 | tamoghnaaa2012/P342_Assignment-5 | /Own_library.py | 4,494 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import math
def bisection_method(f,a,b,tol,file):
step = 0 #iteration counter
for i in range(1,200):
if f(a)*f(b)<0:
continue
else:
if (abs(f(a)) < abs(f(b))):
a=a - ... |
8c5c86d9b0a165f027b8e1a7a61adcd9ad85730e | Chelton-dev/ICTPRG-Python | /temp.py | 169 | 3.8125 | 4 | mylist =["Fred:123", "Smith:475" ]
checkUser = "Smith"
for i in mylist:
arr=i.split(":")
if arr[0] == checkUser:
print("found")
|
3993e5446723b8592aa4adb1f70c3bdfd6c2018f | ipcoo43/algorithm | /lesson127.py | 176 | 3.609375 | 4 | print('행고정 열변화')
import pprint
matrix = [[0]*5 for i in range(5)]
i=0
for row in range(5):
for col in range(5):
i=i+1
matrix[row][col]=i
pprint.pprint(matrix) |
d1c54e8551de9f15f053da7e61a4d6d615de0e15 | thomashigdon/puzzles | /scratch/properties.py | 178 | 3.515625 | 4 | class A(object):
def __init__(self, foo):
self.foo = foo
@property
def bar(self):
print "returning foo"
return self.foo
print A('blah').bar
|
495ebdb2ba4cc43717338fdf255efc6ebed8e85e | 8563a236e65cede7b14220e65c70ad5718144a3/introduction-python-programming-solutions | /Chapter05/0002_palindrome.py | 348 | 4.375 | 4 | """
Program 5.1
Determine whether a Given String is a
Palindrome or not using slicing
"""
def main():
user_string = input("Enter string:\n")
if user_string == user_string[::-1]:
print("User entered string is a palindrome")
else:
print("User entered string is not a palindrome")
if __name__... |
a058ec6561d9d7dac2e7df081fd943a9bf2c77bd | elidaniel/chore-tracker | /calc.py | 612 | 3.875 | 4 |
import sys
num = raw_input('Enter the first number: ')
opr = raw_input('Enter operator + - / *: ')
den = raw_input('enter the other number: ')
try:
num = int(num)
except ValueError:
print "You did not enter a good first number"
sys.exit()
try:
den = int(den)
except ValueError:
print "You did not ent... |
a2249dc39675c8b55e4216b590683dee0cfb46a2 | mbravofuentes/Codingpractice | /python/round.py | 95 | 3.96875 | 4 | print("Enter an input: ")
x = input()
if (int(x) > 3):
print("Sup")
else:
print("hey")
|
f80a25ff7e401e7a65d2516156a047725f859cb9 | kscott94/qBio | /project_submissions/cp_upper_beginner.py | 1,625 | 3.828125 | 4 | gene1 = "gtgggagacatagtggtcaaggtccccccgagtgtggacgaaaagctggccgatttgatagcaaagactatcgcggagagactgaaaaccctcgcaaggctcaatgagatgctcaagaactccgaactctcagaagaggatgcaatagaactcggacggaaggcgaaaatgggaaggggcgagtaccttgagagaagatattcttctcgtagttaa"
gene2 = "atgagagaagatattcttctcgtagttaacacaaacgtgctattctctttcttcgggaaatcaacagtaaccagagagctcgtg... |
ad2e63d83ee9c4ef6b21a27e7ccce92afc589cab | AdamZhouSE/pythonHomework | /Code/CodeRecords/2882/58586/253698.py | 503 | 3.515625 | 4 | nums=int(input())
arr=list(map(int,input().split(" ")))
if nums==1:
print("YES")
else:
peek=-1
index=-1
for i in range(0,nums-1):
if arr[i]>=arr[i+1]:
index=i
break
if index==-1:
print("YES")
else:
flag=True
peek=arr[index]
for i in... |
4d7603a1000d64888815bbfa55176464b8aeaaad | rebekahorth/Week-Two-Assignment | /convert.py | 258 | 3.703125 | 4 | __author__ = 'Rebekah Orth'
# CIS 125 Fall 2015
# Temperature Table
def main():
F=eval(input("Please enter a temperature in Fahrenheit:"))
C= (F-32) * 5 / 9
print("The temperature ", F , " in Fahrenheit is equal to ", C , " Celsius")
main() |
dc3c6a4189b86147d9bd2629d582d31536586eb0 | lyc192130/MCTS-with-OCBA | /inventory/inventory_control.py | 8,835 | 3.65625 | 4 | """
An example implementation of the abstract Node class for use in MCTS
for the inventory control problem
"""
from numpy.random import random
from collections import namedtuple, defaultdict
from monte_carlo_tree_search import MCTS, Node
from numpy import sqrt
import os
import argparse
import dill # pip install dill
... |
c5a0b1053620d5e32705ed4b47c7710669454144 | CafeYuzuHuang/coding | /MaximumDepthofBinaryTree.py | 2,574 | 3.796875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: TreeNode) -> int:
# 2021.03.19
# Max depth ~10^4, extreme unbalanc... |
fa8741b975be7fa8adfad1ed56cc2e1812425d80 | danielzhangau/Data-Mining | /wk11_tutorial/decisiontreec/dataset.py | 6,149 | 3.8125 | 4 | from collections import Counter
class DatasetInstance:
"""
Class that represents an instance of a dataset
"""
# CONSTRUCTOR
def __init__(self, attributes_names, attributes_values, target_name, target_value):
"""
Build a new instance
Parameters:
- attributes_name... |
5fbc02eecd4c13a07780b8a0c66c42f7dd554b8e | Allen-C-Guan/Leetcode-Answer | /python_part/Leetcode/DP/Greedy Alg/1221. Split a String in Balanced Strings/Solution.py | 452 | 3.625 | 4 | '''
边走边看,凑成一对算一对,这就是贪心!!丝毫不管以后发生什么。
这里用R和L计数,其实用一个就行,遇见R, +1, 遇见L, -1
'''
class Solution:
def balancedStringSplit(self, s: str) -> int:
R = L = cnt = 0
for c in s:
if c == "R": R += 1
else:L += 1
if R == L and R != 0:
R = L = 0
cn... |
03283ef494ca975db2c4808dc73fe8440429ba6d | karoscha/python-study | /PycharmProjects/study/lecture-inheri.py | 331 | 3.875 | 4 | # -*- coding: utf-8 -*-
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def personInfo(self):
print('name={}, age={}, gender={}'.format(self.name,self.age,self.gender))
person = Person('karoscha', '36', '남')
person.perso... |
7819f16c7bc6118496d9321c3fc4c702026d03f4 | arnabs542/DS-AlgoPrac | /bitmanupulations/shops.py | 3,074 | 3.625 | 4 | """Open minimum shops
Problem Description
There are A shops numbered 1 to A and B items numbered 1 to B. Shop contains different items denoted by 2-D array C of size N x 2 where C[i][0] denotes shop number and C[i][1] denotes item number. There are D people number 1 to D which wants to buy item.
Need of the people is d... |
b24848c4cee3b4def1e7108c935d64ce6a413232 | tntterri615/Pdx-Code-Guild | /Python/lab20creditcardvalidation.py | 580 | 3.828125 | 4 | # write fn to determine if cc# is valid (as a boolean)
def check_credit_card(card):
check_digit = card.pop()
# print(check_digit)
# print(card) # list w/o check digit
card.reverse()
# print(card)
# double every other element AND sub 9 fr/nums > 9
for i in range(0, len(card), 2):
car... |
ee461243895da3bd84bfbc8551d9dc3887dcfe71 | vedant-2103/nand2tetris | /ex8/Parser.py | 2,495 | 3.53125 | 4 | __author__ = 'Itay'
class Parser:
CommandTypes = {"C_ARITHMETIC", "C_PUSH", "C_POP", "C_LABEL", "C_GOTO", "C_IF", "C_FUNCTION", "C_CALL", "C_RETURN"}
def __init__(self, file):
"""
Opens the input file/stream and gets ready
to parse it
"""
self.file = open(file)
... |
4323c1f3a05e9698f1df34c0f6b925052e544e6b | ddnimara/KTH_Projects | /Artificial Neural Networks/DD2437_Artificial_Neural_Network_Lab_3/functions.py | 17,392 | 3.765625 | 4 | # Import libraries
import numpy as np
import itertools
import load_data as ld
import matplotlib.pyplot as plt
import seaborn as sns
"""
This lab is addressed to:
- Explain the principles underlying the operation and functionality of au-
toassociative networks;
- Train the Hopfield network;
- Explain the at... |
f656e6c8eef37eff82d83c98c1352b9322d3bc53 | green-fox-academy/RudolfDaniel | /[week-02]/[day-01]/Exercise-26.py | 208 | 4.03125 | 4 | nr1 = int(input("Type in number one: "))
nr2 = int(input("Type in number two: "))
if nr2 <= nr1:
print("The second number should be bigger")
elif nr2 > nr1:
for i in range(nr1, nr2):
print(i) |
4f9bf5d5e60b078e314bb4d6008a58e1b1a18713 | BohdanLiuisk/python-course-beginner | /Solution/seqLen.py | 115 | 3.8125 | 4 | n = int(input())
len = 0
while n > 0:
len += 1
n = int(input())
if n == 0:
continue
print(len)
|
07eb56181e2314aa54c7002756290c07dc8109d5 | 6igsm0ke/Introduction-to-Programming-Using-Python-Liang-1st-edtion | /CH07/EX7.8.py | 803 | 4.34375 | 4 | # 7.8 (Stopwatch) Design a class named StopWatch. The class contains:
# ■ The private data fields startTime and endTime with get methods.
# ■ A constructor that initializes startTime with the current time.
# ■ A method named start() that resets the startTime to the current time.
# ■ A method named stop() that sets the ... |
4e50553975988dcc877118df84d9a86710261f7c | Bachatero/AKOB | /assignments/assignment10.2_last.py | 275 | 3.546875 | 4 |
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
distrib = dict()
for line in handle:
if not line.startswith("From "):
continue
lst = list()
lst = distrib.items()
lst.sort()
for key,val in lst:
print key, val
|
6a13372dcd83864ece8e00dbfd29d6af2603086a | YiwenCui/Interview_questions | /string_to_int.py | 1,179 | 3.671875 | 4 | # interview step 1: clarifying questions/High level discussion
# step 2: chooose approach, list potential solutions and approach
def add_one(given_array):
carry = 1
result = []
for i in range(len(given_array)-1,-1, -1):
total = given_array[i] + carry
if total == 10:
carry = 1
... |
8054031756b9245f7f3c2e129032f47f00c7dd29 | guojixu/interview | /leetcode/0. 树的非递归遍历.py | 1,686 | 3.953125 | 4 |
def preorder(root): # 先序
stack = []
while stack or root:
while root:
print(root.val)
stack.append(root)
root = root.lchild
root = stack.pop()
root = root.rchild
def inorder(root): # 中序
stack = []
while ... |
8e35ccb2fbb118864f471113ddb871f20ed757de | zhaoxuyan/LeetCode_Python | /058_Length_of_Last_Word.py | 515 | 3.75 | 4 | # 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
# 如果不存在最后一个单词,请返回 0 。
# 输入: "Hello World"
# 输出: 5
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if s == ' ':
return 0
elif len(s) == 1 and s != ' ':
return 1
el... |
b7fb18b1d37df291a7a7bc9a71d268ca99ea36ba | nirajan5/Demo | /TupleIndexingAndSlicing.py | 207 | 4.15625 | 4 | tuple = (1, 2, 3, 4, 5, 6, 7)
# element 1 to end
print(tuple[1:])
# element 0 to 3 element
print(tuple[:4])
# element 1 to 4 element
print(tuple[1:5])
# element 0 to 6 and take step of 2
print(tuple[0:6:2])
|
e364ac3e891692b1066ceca38079c37619abe4ee | Aru09/JangoRepo | /Week1/HackerRank/ifelse.py | 280 | 4.09375 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
if(n%2!=0):
print("Weird")
if(n%2==0 and n in range(1,6)):
print ("Not Weird")
if(n%2==0 and n in range(5,21)):
print("Weird")
if (n%2==0 and n>20):
print ("Not Weird") |
2072a01629b678332f5b02d2542744186413f162 | jaina-sunny/jsm | /a.py | 223 | 4.03125 | 4 | s = raw_input("enter a string ")
n = input("enter a key ")
st=""
def encrypt(s,n):
st=""
for i in range(0,len(s)):
char=s[i]
st=st+ chr((ord(char) + n - 97) % 26 + 97)
return st
print "the result:" + encrypt(s,n)
|
c5efd7729a34d5dcac5f1766a4f08e57092bceaa | rafaelperazzo/programacao-web | /moodledata/vpl_data/445/usersdata/323/103287/submittedfiles/matriz2.py | 900 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
z = int(input('Digite a dimensão da matriz(i=j): '))
m = []
for i in range(0,z,1):
n=[]
for j in range(0,z,1):
n.append(float(input('Digite o valor da linha%d e da coluna%d: '%((j+1),(i+1)))))
m.append(n)
if z<=2:
med1=0
med1=med1+m[0][0]+m[0][1]
... |
f79acaf2c487d74eb9c0bfbc1f16aa19a1708eed | babiswas/Tree | /test18.py | 917 | 3.90625 | 4 | class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
def inorder(node):
if node:
if node.left:
inorder(node.left)
print(node.value)
if node.right:
inorder(node.right)
def delete_full_tree(node):
if node... |
77ec9d228c98accedd08f7b9078163cd6e43273f | gabriellaec/desoft-analise-exercicios | /backup/user_374/ch28_2020_03_23_19_55_07_100940.py | 126 | 3.59375 | 4 | n = 0
calcula = 0
while n < 100:
calcula = calcula + (1/(2**n))
n = n + 1
if n == 99:
print(calcula)
|
45bc9c1e656eb9d947b90f10532b7c64d51b3f85 | BlogBlocks/jupnote | /searcH.py | 285 | 3.6875 | 4 | # Simple File Search
#import searcH
#searcH.search()
def search(filename, term):
datafile = open(filename, "r")
data = datafile.readlines()
for line in data:
if term in line:
print line,
if __name__ == "__main__":
search(filename, term) |
f6064c35bc8dbbcfff2efcc2717b91034bf9891c | yanomateus/loan-calculator | /loan_calculator/irr.py | 7,513 | 3.90625 | 4 | def newton_raphson_solver(
target_function,
target_function_derivative,
initial_point,
maximum_relative_error=0.0000000001,
max_iterations=100,
):
"""Numerical solver based on Newton-Raphson approximation method.
The Newton-Raphson method allows algorithmic approximation for the root
of... |
4c72949e80eb904540d38e66e04bbf0725084afb | cherry-wb/quietheart | /codes/trunk/codes/pythonDemo/14_queue_simple.py | 1,295 | 3.96875 | 4 | #!/usr/bin/python
from Queue import Queue
from Queue import PriorityQueue
a1='a1'
a2='a2'
a3='a3'
a4='a4'
a5='a5'
b1='b1'
b2='b2'
b3='b3'
b4='b4'
b5='b5'
q = Queue()
pq = PriorityQueue()
for i in xrange(5):
p = 5 - i
q.put("a"+str(p))
q.put("b"+str(p))
pq.put((p,"a"+str(p)))
pq.put((p,"b"+str(p))... |
4aa2258db3db6eda84e9eb2cf80f007e434a0461 | syurskyi/Algorithms_and_Data_Structure | /_temp/Python for Data Structures Algorithms/template/16 Trees/Tree Representation Implementation (Lists).py | 754 | 3.5 | 4 | # Tree Representation Implementation (Lists)
#
# Below is a representation of a Tree using a list of lists. Refer to the video lecture for an explanation and
# a live coding demonstration!
___ BinaryTree(r
r_ [r, # list, []]
___ insertLeft(root,newBranch
t _ root.p.. 1)
__ l..(t) > 1:
root.i.. ... |
65e84d6c8775c43a2046b0ad3200e97ceb5474ed | SimonSlominski/Codewars | /3_kyu/3_kyu_The Lift.py | 4,696 | 4.03125 | 4 | """ All tasks come from www.codewars.com """
"""
TASK: The Lift
Synopsis
A multi-floor building has a Lift in it.
People are queued on different floors waiting for the Lift.
Some people want to go up. Some people want to go down.
The floor they want to go to is represented by a number (i.e. when they enter the Lift t... |
43b246b5e1b9dcf1dcbdc8424581343b7d3aee12 | AlexTheKing/python-course | /classes.py | 266 | 3.71875 | 4 | class Cat:
def __init__(self, name):
self.name = name
def meow(self):
print('Meow!')
def drink(self, beverage):
print('Meow! I drink {}!'.format(beverage))
cat = Cat('Tom')
cat.color = 'black'
print(cat.name)
print(cat.color)
cat.meow()
cat.drink('milk') |
aad023c862faceb058b0dfbe3e3c9dbf2a138f9e | le-birb/advent-of-code_2020 | /day3.py | 907 | 3.71875 | 4 |
from math import prod as mult
from itertools import zip_longest, product
infile = open('day3-input', 'r')
trees = [[c == '#' for c in line.strip()] for line in infile]
infile.close()
height = len(trees)
width = len(trees[0])
def count_trees(right, down):
tree_count = 0
for i in range(0, height//down):
... |
6fca13066743f2dffe8d51ced7843dea0664cb18 | signoreankit/PythonLearn | /set.py | 556 | 4.375 | 4 | #Sets - Unordered collections of unique elements
# To Define Set
set_1 = set()
# To add element to a set
set_1.add('Ankit')
set_1.add('Ankit') # It wont take duplicate items. Try it!
set_1.add('Dell Xps 15')
set_1.add('Python 3.6')
set_1.add('Machine Learning')
print("Set_1: ", set_1)
# Casting a list with duplic... |
0ecc206f18e17e5df485c4437a10c4ee4692aae7 | gustavo621/projetos-em-python | /projetos em python/exercicio45.py | 871 | 3.8125 | 4 | import random
pc = ["pedra", "papel", "tesoura"]
pc2 = random.choice(pc)
print('''suas opções:
[ 1 ] pedra
[ 2 ] papel
[ 3 ] tesoura''')
seu = int(input("escolha uma opção: "))
if pc2 == "pedra" and seu == 3:
print("você perdeu! o pc escolheu pedra")
elif pc2 == "papel" and seu == 1:
print("você perdeu! o pc es... |
84f65c3cec5d670f35cacd817dbb9f1741e4059c | Saranya2616/hello-world | /power.py | 137 | 3.8125 | 4 | a=int(input())
b=int(input())
if a & b is int:
c=a**b
print(c)
else:
c=int(a)
d=int(b)
e=c**d
print(e)
|
9620f5ab669734e1ec5082416d09b00cd2606fc3 | anonymint/euler | /python/euler002.py | 994 | 4.03125 | 4 | """
Project Euler #2: Even Fibonacci numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first terms will be:
1,2,3,5,8,13,21,34,55,89,...
By considering the terms in the Fibonacci sequence whose values do not exceed , find the sum of the ev... |
08e33e4645bfb1716171c6fdf0f895e5eaf4e002 | zmalpq/CodeWars | /take a ten minute walk.py | 2,873 | 4.40625 | 4 | #You live in the city of Cartesia where all roads are laid out in a perfect grid.
#You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk.
#The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends y... |
cf2fb52172448eac18f83428de4e4d6cd7d6b605 | Nahidjc/python_problem_solving | /armstrong.py | 182 | 3.84375 | 4 | N= int(input())
temp=N
sum=0
while N != 0:
rem = N%10
N = N//10
sum = sum+ (rem**3)
if sum == temp:
print("the Number is armstrong")
else:
print("Not Armstrong") |
8a2041d7aee907757a2cbf5e650047ef6feaaad0 | ayushiagarwal99/leetcode-lintcode | /leetcode/depth_first_search/124.binary_tree_maximum_path_sum/124.BinaryTreeMaximumPathSum_zheyuuu.py | 1,315 | 3.828125 | 4 | # Source : https://leetcode.com/problems/binary-tree-maximum-path-sum
# Author : zheyuuu
# Date : 2020-08-05
#####################################################################################################
#
# Given a non-empty binary tree, find the maximum path sum.
#
# For this problem, a path is defined as... |
f6c3bc55ec38fefd1cf9b8dd646f6bf5135716d4 | itsanti/gbu-ch-py-algo | /hw2/hw2_task5.py | 489 | 3.6875 | 4 | """HW2 - Task 5
Вывести на экран коды и символы таблицы ASCII, начиная с символа под номером 32 и заканчивая 127-м включительно.
Вывод выполнить в табличной форме: по десять пар «код-символ» в каждой строке.
"""
i = 1
for code in range(32, 128):
end = '\n' if i % 10 == 0 else '\t'
print(f'{code:3}-{chr(code)}... |
f0122e83bce6f99185eca3ff20c799b5d5e0a09a | mkorycinski/algorithms-and-data-structures | /searching/binary_search.py | 1,175 | 3.84375 | 4 | import unittest
def binary_search(arr, ele):
first = 0
last = len(arr) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2
if arr[mid] == ele:
found = True
else:
if ele < arr[mid]:
last = mid - 1
... |
31f855cac904eea71623dd33aa6ab3ef7fb855fe | Pshinde100/Natural-language-processing | /NLP.py | 2,765 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 10:24:02 2019
@author: Pranit
"""
import nltk
nltk.download()
import re
sent1 = "this is my first sentense. this sentense has some lines and words. this is the third sentense"
# split para into words
# \s = space
re.split(r"\s", sent1)
# split at a l... |
be1b22931d637df369df2b0450eae036baebdccc | espazo/sicp-in-python | /2 使用对象构建抽象/列表和字典的实现.py | 2,678 | 4.28125 | 4 | empty_rlist = None
def make_rlist(first, rest):
"""Make a recursive list from its first element and the rest."""
return (first, rest)
def first(s):
"""Return the first element of a recursive list s."""
return s[0]
def rest(s):
"""Return the rest of the elements of a recursive list s."""
re... |
d6c668f74590864614fbe19db2d0a00dc6495003 | wly6250/Python3.6 | /Python-base/list2.py | 200 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# 从0到99的100个数中,删除所有的偶数!
r=list(range(100))
for i in range(len(r)//2):
r.pop(i)
print('循环条件i:',i)
print('处理后的list:',r)
|
09878b9c10dcf97f9b056fe97d2d7bc0bca76bf1 | Mararsh/yard | /docs/algorithms/selection_sort.py | 5,068 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Title : Selection Sorting
Objective : Show each step of comparing and movement in intuitive way
Created by: Mara
Created on: 2018/3/19 21:01
"""
import random
ODATA = []
DATA_LENGTH = 20
def generate_data(number):
while len(ODATA) < number:
data = random.randint(0, number... |
4e69f55ec7e9e0a3a870ba03bc7b0c0ebe7de417 | rajababulukka/PythonPrograms | /recursive_string_permutation.py | 446 | 3.765625 | 4 | def permutation(str_1):
if len(str_1)<=1:
return set([str_1])
all_permutations=[]
for i in range(len(str_1)):
first=str_1[i]
rest=str_1[:i]+str_1[i+1:]
permutations=permutation(rest)
for permute in permutations:
all_permutations.append(first+p... |
2f7b84480815942d4f30111de08783577c18d61a | parwez6969/fossproject | /python 786.py | 167 | 4 | 4 | a=int(input('enter the first number'))
b=int(input('enter the second number'))
addition=a+b
multipliction=a*b
print('addition=',a+b)
print('multipliction=',a*b)
|
c5027a7c2c5f14c446f6e294e309fd68e603fca8 | loxygenK/blin-tool | /scripts/lib/color.py | 655 | 3.625 | 4 | class Color:
BLACK = 0
RED = 1
GREEN = 2
YELLOW = 3
BLUE = 4
PINK = 5
CYAN = 6
WHITE = 7
@classmethod
def colored(cls, string, color, bold=False):
if type(color) == int:
return cls.__colored(string, color, bold)
elif type(color) == str:
co... |
9a29fe6f20d13d587327bf84001979425224cd9b | Aasthaengg/IBMdataset | /Python_codes/p03803/s724674653.py | 200 | 3.609375 | 4 | strength = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1]
A, B = [strength.index(n) for n in map(int, input().split())]
if A > B:
print('Alice')
elif A < B:
print('Bob')
else:
print('Draw')
|
893ae9a7901c8ce7030ca0efdb4c81dba293c3ba | nicolealdurien/Assignments | /week-02/day-1/user_address.py | 1,673 | 4.4375 | 4 | # Week 2 Day 1 Activity - User and Address
# Create a User class and Address class, with a relationship between
# them such that a single user can have multiple addresses.
class User:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.ad... |
c0e1994cf06d96f0b03dfb3c9469748bf63772d6 | rmfaber/FootballPredictions | /getgames.py | 3,521 | 3.5 | 4 | import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import pandas as pd
import time
def start_browser(url='https://www.voetbal.com/'):
browser = webdriver.Chrome()
browser.get(url)
# agree to use cookies
time.sleep(2)
browser.find... |
595cebfd880642511997f4b352e431e30b11600e | Vanid64/atbspython | /ch5/inventory.py | 1,113 | 3.859375 | 4 | def displayInventory(inventory):
if type(inventory) != dict:
print('Please pass a dictionary as an inventory.')
return
totalItems = 0
print("Inventory:")
for k, v in inventory.items():
print(str(v) + ' ' + k)
totalItems += v
print("Total number of items: " + str(total... |
95e032f227acf2e3ac2e818aaa7e38f6950095f4 | HuangPengcheng-0207/file-transfer-python | /FTPClientUsingTCP.py | 2,590 | 4.25 | 4 | """ FTPClientUsingTCP.py
[STUDENTS FILL IN THE ITEMS BELOW]
Libin Feng, Yuqi Liu
CISC-650 Fall 2014
Sep 26, 2014
This module will:
a. start a TCP control connection to the serv... |
6a822e550a8f3e51efc7bdca386b078d7f6a559f | yusif-ifraimov/TowerDefense | /source/button.py | 3,755 | 3.75 | 4 | # Button class
#
# Rectangular object that displays an image,
# can respond to mouse-overs, and
# send a message on click
#
# 2014/4/9
# written by Michael Shawn Redmond
from config import *
import pygame
import rectangle
class Button(rectangle.Rectangle):
def __init__(self, position, width, height, image, image_... |
7ad8f7dffba52c64a8bab06e8be920967d6c6d31 | apalala/exercism | /python/sublist/sublist.py | 527 | 3.9375 | 4 |
SUBLIST = 1
SUPERLIST = 2
EQUAL = 3
UNEQUAL = 4
def check_lists(alist, blist):
if alist == blist:
return EQUAL
elif _has_sublist(blist, alist):
return SUBLIST
elif _has_sublist(alist, blist):
return SUPERLIST
else:
return UNEQUAL
def _has_sublist(alist, sub):
# ... |
f72f94385f029819972e2d72d975af5d9788f538 | jcohen66/python-sorting | /questions/easy/two_sum_hash_better.py | 545 | 4.09375 | 4 | def two_sum(nums, target):
'''
Given an array of integers and a target
integer, return an array containing the
indexes of the elements that add up to
the target.
>>> two_sum([2,7,11,15], 9)
[0, 1]
>>> two_sum([3, 2, 4], 6)
[1, 2]
>>> two_sum([3,3], 6)
[0]
'''
result =... |
50783ab670ce256cb473c3cb184c5f34fee312c0 | paalso/mipt_python_course | /7_pictures_1/2/spec_figures.py | 961 | 3.59375 | 4 | import pygame
def draw_bordered_ellipsis(
screen, ellipse_rect, ellipse_color, border_color, border_width=0):
rect_topleft_x, rect_topleft_y, rect_width, rect_height = ellipse_rect
inner_rect = (rect_topleft_x + border_width,
rect_topleft_y + border_width,
... |
6b362adfd78d92e5820996ec6a4e7a269664e23f | ernie0423/introprogramacion | /practico2/practico2_ejercicio2.py | 246 | 4.125 | 4 | def numeroMax (num1, num2, num3):
MAX = max(num1,num2,num3)
print("El mayor es:", MAX)
num1 = int(input("ingrese un numero: "))
num2 = int(input("ingrese un numero: "))
num3 = int(input("ingrese un numero: "))
numeroMax(num1, num2, num3) |
adc2f4ac9d674fd85ffe2fe225e3102e5096345e | imdangodaane/tetris | /test.py | 242 | 4.125 | 4 | #!/usr/bin/env python3
def rotate(m):
b = list(zip(*reversed(m)))
for i in range(len(b)):
b[i] = list(b[i])
for i in b:
print(i)
return b
rotate([
[0, 1, 1],
[1, 1, 0]
])
rotate([
[0, 1],
[0, 1],
[1, 1]
])
|
77d9f49b82e3bbdf949e70339d893fe17f77111d | DKanyana/PythonProblems | /4_UniqueOne.py | 218 | 3.953125 | 4 | def find_one_uniq(numbers):
uniq =0
for num in numbers:
uniq ^= num
return uniq
numbers= [1,2,2,3,3,4,4,5,5,1,7]
print(find_one_uniq(numbers))
#Time complexity - O(n)
#Space complexity - O(1) |
1e48a33617e37c016b85b40d94355c74e54abe3c | Ayesha116/piaic.assignment | /q7.py | 230 | 4 | 4 | #Write a Python program to get the difference between a given number and 17, difference cannot be negative
a = int(input("enter any number: "))
if a>=17:
print("difference is ",a-17)
elif a<17:
print("difference is ",17-a) |
09769295bee9a4c84307241bd8a0b1932d94d621 | eronekogin/leetcode | /2022/cinema_seat_allocation.py | 939 | 3.6875 | 4 | """
https://leetcode.com/problems/cinema-seat-allocation/
"""
from collections import defaultdict
class Solution:
def maxNumberOfFamilies(
self,
n: int,
reservedSeats: list[list[int]]
) -> int:
# Build seats.
seats = defaultdict(int)
for r, c in reservedSeats:... |
9f35dadd26f47c77978f42018a9d7f73326b1c5b | elvisliyx/python-learn | /learn-day3/encode.py | 212 | 3.796875 | 4 | #-*- coding:utf-8 -*-
import sys
print(sys.getdefaultencoding())
s = '你好'
print(s.encode())
s_gbk = s.encode('gbk')
print(s_gbk)
s_to_utf = s_gbk.decode('gbk').encode('utf-8')
print('utf-8',s_to_utf)
|
9e61dd627bb4ba4fc285271eadd0fd599854561e | sunil10000/outlab7 | /prep_stmt.py | 3,220 | 3.578125 | 4 | import sqlite3
table_no = int(input())
def insert_team():
team_id = int(input())
team_name = input()
conn = sqlite3.connect('ipl.db')
crsr = conn.cursor()
crsr.execute("INSERT INTO TEAM (team_id, team_name) VALUES (?, ?);", (team_id, team_name))
conn.commit()
conn.close()
def insert_match():
match_id = int(i... |
8d32ec8f4c75c6eb1436122c45aa5680391dfef5 | Ian100/Curso_em_Video-exercicios- | /desafio_49.py | 372 | 4.0625 | 4 | # Refaça o desafio 09, mostrando a tabuada de um número que o usuário escolher,
# só que agora utilizando um laço for.
n = int(input('Digite um número inteiro para ver sua tabuada: '))
print('=' * 40, end='\n\t\t\t\t')
print('TABUADA DO {}'.format(n))
print('=' * 40)
for i in range(1, 11):
print('{} x {:... |
55a1fe608743ef248e9b6e7b0691571784640cb9 | liqueur/leetcode | /sol_Add_Two_Numbers.py | 1,017 | 3.59375 | 4 |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
_sum = 0
l1stk = []
l2stk = []
while l1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.