blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3b624f3f2cfcfeebe3126fc16f5442e731a0429c | derrida/shmuppy | /projectiles.py | 2,768 | 3.84375 | 4 | from math import degrees, atan2
from pygame import transform
from sprite import Sprite
class Projectile(Sprite):
"""The base that other projectiles inherit."""
def __init__(self, scene, size, color, power, speed, range):
Sprite.__init__(self, scene, size, color)
self.power = power
self... |
869997ca17d20abb13f7cdf81b4dee07167b8400 | betty29/code-1 | /recipes/Python/577264_Random_numbers_arbitrary_probability/recipe-577264.py | 1,220 | 3.921875 | 4 | # Generating N random numbers that probability distribution
# fits to any given function curve
# FB - 201006137
import math
import random
# define any function here!
def f(x):
return math.sin(x)
# f(x) = 1.0 : for uniform probability distribution
# f(x) = x : for triangular probability distribution
# (math.sqrt(... |
4eaebccef82b49147049e56186146d7f03ea6445 | jaymzsocool/Intro-Python | /src/day-1-toy/fileio.py | 373 | 4.375 | 4 | # Use open to open file "foo.txt" for reading
f = open("foo.txt")
# Print all the lines in the file
for line in f:
print(line)
# Close the file
f.close()
# Use open to open file "bar.txt" for writing
b = open("bar.txt", "w")
# Use the write() method to write three lines to the file
b.write("""A new Line
Anothe... |
206dd1e649e2f3977b04d5820b7c2a3fa902cdbd | bilinmezgelecek/ilkcag | /taskagitmakas.py | 1,053 | 3.6875 | 4 | ''' bu kendime not '''
''' not2 bunu yeni ekledim 14/05/2020'''
import random
ihtimaller = ['taş','kağıt','makas']
def zar():
a = random.choice(ihtimaller)
return a
while True:
print(' 1 - Taş \n 2 - Kağıt \n 3 - Makas \n Seçiminizi yapın?')
secim = int(input())
if secim == 1:
osecim = 'taş'
elif s... |
77ffe8e229b4f8166309866be406c2a9e65016bc | Tilia-amurensis/python_tasks | /Coursera_task3.10.py | 201 | 4 | 4 | word = input()
first = word.find("f")
last = word.rfind("f")
if first != -1 and last == first:
print(first)
elif first != -1 and last != -1 and first != last:
print(first, last)
else:
pass
|
29ddc838c803fcb0c3e6b1702402630310a26191 | b166er-droid/Algorithms-Coding | /Random Questions/findNumberOfWaysForDice.py | 754 | 3.859375 | 4 | #! https://www.geeksforgeeks.org/dice-throw-dp-30/
# Input: d = 2, f = 6, target = 7
# Output: 6
# Explanation:
# You throw two dice, each with 6 faces. There are 6 ways to get a sum of 7:
# 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
def numberWays(face, dices, target):
table = [[0] * (target + 1) for dice in range(dices + 1... |
dac3c40e66c2ae3daa42fa7fc7fd20943964ec4a | julianascimentosantos/cursoemvideo-python3 | /Desafios/Desafio087.py | 649 | 3.765625 | 4 | matrizes = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
pares = soma = maior = 0
for l in range(0, 3):
for c in range(0, 3):
matrizes[l][c] = int(input(f'Digite um valor para [{l}, {c}]: '))
if matrizes[l][c] % 2 == 0:
pares += matrizes[l][c]
soma += matrizes[l][2]
maior = matrizes[... |
6da7b5027f14c0966cca70fda2561e7d6628a106 | sarkarChanchal105/Coding | /Leetcode/python/Medium/replace-words.py | 1,439 | 4.15625 | 4 | """
https://leetcode.com/problems/replace-words
In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another".
Given a diction... |
a8bc10225fad98e2199192ac79291b8b4e1995ad | AM-Myrick/LeetCodeSolutions | /Easy Questions/Intersection of Two Arrays II/solution.py | 954 | 3.828125 | 4 | # https://leetcode.com/problems/intersection-of-two-arrays-ii/
from typing import List
from collections import Counter
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
# create a function to ensure the array with less elements is iterated over
def find_intersects(first_num... |
b153bba856ad0fa0468f72ab22d6cc1e1b21347c | granth19/Old-Python-Stuff | /Kairos Cross.py | 876 | 3.546875 | 4 | import turtle
t= turtle.Turtle()
t.speed(30)
def T():
for x in range(4):
t.forward(80)
t.left(90)
t.forward(20)
t.right(90)
t.forward(15)
t.right(90)
t.forward(80)
t.right(90)
t.forward(15)
t.right(90)
t.forward(2... |
9dd678e9a52569d0e1c0d9a3c70abb46498b0b5e | rlarabel/parenthesis-matcher | /Stack_exercises.py | 2,079 | 4 | 4 | # To create a custom exception class (must extend Exception)
# class EmptyStackException(Exception):
# pass
# Note: 'pass' is a stub used for a class or method that does nothing;
# in this case, the class only exists to be raised and caught.
class Stack:
def __init__(self):
self.__stack = []
# Sta... |
a0e92c3c22c53eca5c91d251c8fb8b64a123834c | yomihiko/listen | /chapter12/fileRead.py | 199 | 3.59375 | 4 | file = open('hello.txt', 'r', encoding='utf-8')
src = file.read()
print(src)
file.close()
with open('hello.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line, end='')
|
e506a7126bd291c290e22cd2df15aa81a587ffb8 | bneb/dotfiles | /pyfunk.py | 1,776 | 3.828125 | 4 | # python functions to be aliased in .alias and called as needed
from math import sqrt
def factor(n, factors=[]):
""" This function returns the prime factorization.
Args:
n: the number to be factored
"""
n = int(n)
if n < 1: print('invalid input')
while not n%2:
factors.app... |
1d2afe01ab436482447d53406f50d8b09649b67b | BrendaTatianaTorres/TrabajosPython | /py2_retos1/reto28.py | 336 | 3.921875 | 4 | def tabla (numero1, numero2):
for i in range(1,numero2+1,1):
multi = numero1*i
print (numero1, '*' ,i, '=' , multi)
numero1 = input ('Escriba el número del que quiere ver la tabla ')
numero2 = input ('Escriba el número hasta el que quiere ver la tabla ')
numero1=int(numero1)
numero2=int(numero2)
tabla(nu... |
970130036674baae56cec508d290d1fc9d0c1ff4 | anermika/PythonForEverybody | /Python Data Structures/Week 5 - Dictionaries/Assignement9_1.py | 405 | 3.546875 | 4 | name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts=dict()
bigcount= None
bigword= None
for line in handle:
if not line.startswith('From '): continue
words=line.split()
mail=words[1]
counts[mail]=counts.get(mail, 0) +1
for mail,count in counts.items():
if bigcount is... |
48b4f9f473eb25b4c1e3ca53d733c18e1e2b82f7 | jdbr827/ProjectEuler | /ProjectEulerProblem112.py | 4,567 | 3.90625 | 4 |
def is_increasing(n):
string = str(n)
for i in range(len(string)):
if string[i] != min(string[i:]):
return False
return True
def is_decreasing(n):
string = str(n)
for i in range(len(string)):
if string[i] != max(string[i:]):
return False
return True
def is_bouncy(n):
return (not is... |
bfdd60c409a89bba9262ebb4b673008f92a09c36 | nhungtlu/nguyenthihongnhung-fundamentals-c4e01 | /BTN/Cuahang.py | 695 | 3.765625 | 4 | price = {
'chuoi' : 4,
'tao' : 2,
'cam' : 1.5,
'le' : 3,
}
stock = {
'chuoi' : 6,
'tao' : 0,
'cam' : 32,
'le' : 15
}
a = ['chuoi','tao','cam','le']
for i in price (len(a)):
print([a[i]])
print("price:",prices [a[i]])
print("stock:",stock [a[i]])
# prices = {"banana" : 4 , ... |
2237be85b8d81a5c96a5b470f22ba8bc653f561b | duynii/hackerrank_python | /collections/ordereddict.py | 315 | 3.578125 | 4 | from collections import OrderedDict
n = int(input())
sold = OrderedDict()
for i in range(n):
l = input().split()
item = ' '.join(l[:-1]) # Could also use l.pop()
price = int(l[-1])
total = sold.get(item, 0) + int(price)
sold[item] = total
for key, sum in sold.items():
print(key, sum)
|
7758aec73078917644ba6d8a947959a307762a02 | Demondul/python_algos | /functionIntermediateI.py | 207 | 3.578125 | 4 | import random
def randInt(min=0,max=100):
return int(random.random()*max)+min
print(str(randInt()))
print(str(randInt(max=50)))
print(str(randInt(min=50)))
print(str(randInt(min=50,max=500)))
|
363ac50d6350bebfaae0706bed6f719751d809cb | TaoKeC/sc-projects | /stanCode_Projects/my_photoshop/green_screen.py | 1,350 | 3.90625 | 4 | """
File: green_screen.py
-------------------------------
This file creates a new image that uses
MillenniumFalcon.png as background and
replace the green pixels in ReyGreenScreen.png
"""
from simpleimage import SimpleImage
def combine(background_img, figure_img):
"""
:param background_img: (SimpleImage) the... |
36ca948cdf19633c2fc65dab5f336acb055bea91 | MilletMorgan/morpion-python | /morpion.py | 11,304 | 3.5 | 4 | # A FAIRE :
#
# - CREER IA
# import pour pouvoir nettoyer le terminal
import os
#Nettoie le terminal
os.system('clear')
#Déclaration des variables
horiBar = "----------"
vertBar = "|"
space = " "
circle = "O"
cross = "X"
scoreJoueur1 = 0
scoreJoueur2 = 0
case1 = space
case2 = space
case3 = space
case4 = space
c... |
d9ea90ef6093689ddd473d1dd901ad36ddd0db44 | alessandrothea/t3tools | /python/findDuplicates.py | 9,569 | 3.625 | 4 | #!/usr/bin/env python
import optparse
import sys, re
import os, subprocess
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
... |
0d047b1c5d4dc7f6493e9054e796663ce563a585 | samadhan563/Python-Programs | /Chapter_03/03_String_Function.py | 1,165 | 4.34375 | 4 | # Program for string function in python
'''
Author : Samadhan Gaikwad.
Software Developer
Location: Pune.
'''
#Concat string two string
string1="Welcome to Python World !!!"
print("String length : ",len(string1))
print("String end with : ",string1.endswith("!!!"))
print("Check count of o :",string1.count("... |
073e82269bc12b1491f8ddb8f94657dc2a09f742 | stungkit/Leetcode-Data-Structures-Algorithms | /12 BFS + DFS/490. The Maze.py | 5,894 | 4.46875 | 4 | # Problem: Return if there is a path from A to B.
# There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right,
# but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
# Given the ball's start p... |
39f76e14a6b32e6beb9c115cd49c4220a5ce1e56 | SatishKohli18/SudokuSolver | /Sudoku.py | 1,539 | 3.5625 | 4 | class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
row,col = -1,-1
for i in range(9):
for j in range(9):
if board[i][j] == ".":
... |
2d3847452799d50b7c2f511154f2fbd462930e30 | alejogonza/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 466 | 3.96875 | 4 | #!/usr/bin/python3
"""
2-read_lines
"""
def read_lines(filename="", nb_lines=0):
"""
reads n lines of a text file and prints it to stdout
"""
linecount = 0
with open(filename, "r", encoding='utf-8') as my_file:
if nb_lines <= 0:
print(my_file.read(), end="")
else:
... |
cc98807679a8b2aafa5f18dbbf95798b3a5868b4 | Adem54/Python-Tutorials | /sinav/4.py | 598 | 4.09375 | 4 | """
Kullanıcıdan alınan 2 basamaklı bir sayının okunuşunu bulan bir fonksiyon yazın.
Örnek: 97 ---------> Doksan Yedi
Not: kullanıcıdan alınan sayı her zaman iki basamaklı olacak
"""
birler = ["", "Bir", "İki", "Üç", "Dört", "Beş", "Altı", "Yedi", "Sekiz", "Dokuz"]
onlar = ["", "On", "Yirmi", "Otuz", "Kırk", "Elli", "... |
18d076bf7bad0fd72ab04f09886b27e32ad07afe | niwanshu16/FDSP2019 | /Day11/day11.py | 1,007 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 20 16:01:41 2019
@author: KIIT
"""
import matplotlib.pyplot as plt
# Reshaping an array
import numpy as np
l = list(map(int,input().split()))
x = np.array(l)
x = x.reshape(3,3)
print(x.ndim)
print(x)
# using normal
# mean,sd,no.of entries
inc... |
f14e5c755b4e41ee68082dd1731d2c778cefa444 | dariasolaire/Python_ex | /Lab1/Lab1_2.py | 717 | 4.25 | 4 | """2. Торговая фирма в первый день работы реализовала товаров на P тыс. руб.,
а затем ежедневно увеличивала выручку на 3%.
Какой будет выручка фирмы в тот день, когда она впервые превысит заданное значение Q?
Сколько дней придется торговать фирме для достижения этого результата?"""
count=0
p=int(input("Введите ч... |
62249d3fbb7879d1b93a3ae53b38591b31f247f4 | yroslaw55555/Khasanov-6.10-1-4- | /10,4.py | 677 | 3.6875 | 4 | # 10.3
class Volunteer:
def __init__(self, name, city):
self.name = name
self.city = city
def get_info(self):
print(f'{self.name}, г. {self.city}')
class StatusVol(Volunteer):
def __init__(self, name, city, status):
super().__init__(name, city)
self.... |
d38a992b24226103e0e20ed7254c0d2da0887cb8 | moses12345/python_stuff | /powerpuff2.py | 1,118 | 3.609375 | 4 | # #10 4
# import time
# test_cases=5
# steps=0
# t1=time.time()
# def count(a,b):# 10 4
# if a % b != 0:
# a+=1
# global steps
# steps+=1
# count(a,b)
# return 'TOTAL STEPS: {}'.format(steps)
# else:
# return 'TOTAL STEPS {}'.format(steps)
# t2=time.time()
# a,b=int(inp... |
d9a44feaefe408c8606d0093855b47b07c2b7860 | cfarrow/diffpy.srfit | /diffpy/srfit/fitbase/profileparser.py | 5,734 | 3.609375 | 4 | #!/usr/bin/env python
"""This module contains classes for parsing profiles from files.
ProfileParser is a base class for parsing data. It can interact with a Profile
object to automatically set the Profile's data and metadata. Each specific file
format must be encapsulated in a ProfileParser subclass.
See the class d... |
fb1655d0df3681444269fb7ff462a8625d1f3b8d | duocang/python | /Genomik/homework2/1.py | 1,202 | 3.640625 | 4 | #- *- coding: UTF-8 -*-
import sys
inputNum = int(sys.argv[1])
print "The number for the SAM bit flag is ", inputNum
brinaryinputNum = bin(inputNum)
print "The brianry is ", brinaryinputNum
bits = 0
temp = inputNum
while(inputNum != 0):
inputNum = inputNum >> 1
bits += 1
inputNum = temp
flagBits = []
for i in ... |
4e9ad1b3d497f5ae077406a5b76a548b0c559e33 | shoeless0x80/100_Python_Exerciese | /63.py | 265 | 3.984375 | 4 | import time
counter = 0
while counter < 4:
print("Hello")
time.sleep(counter)
counter += 1
print("End of the Loop")
'''
i = 0
while True:
print("Hello")
i = i + 1
if i > 3:
print("End of loop")
break
time.sleep(i)
'''
|
9a2cb715286de8b237e4c5c84581cee6bc35afbd | luccaportes/Solitaire | /estruturas.py | 601 | 3.53125 | 4 | import random
class Fila:
def __init__(self, fila=[]):
self.fila = fila
def insert(self, e):
self.fila.insert(0, e)
def pop(self):
if len(self.fila) == 0:
return None
return self.fila.pop()
class Pilha:
def __init__(self, pilha=[]):
self.pilha = ... |
2e5345e30dad6bb9ee6ce12c6f94c324d63e1525 | george21-meet/meetyl1 | /ooppt2.py | 1,310 | 4.125 | 4 | import turtle
from turtle import Turtle
a=0
class Ball(Turtle):
def __init__(self,r,colour,dx,dy):
Turtle.__init__(self)
self.penup()
self.r=r
self.colour=colour
self.dx=dx
self.dy=dy
self.shape("circle")
self.color(colour)
self.turtlesize(r/10)
def move(self,screen_width,screen_length):
current_x... |
7338bd3d0f531b92c949bce86ee88d2c46aebf93 | miftaunnoor/Hangman | /Stage_7.py | 1,332 | 3.953125 | 4 | import random
print("H A N G M A N")
types= ['python', 'java', 'kotlin', 'javascript']
r= random.choice(types)
guess = len(r)*["-"]
lives= 8
correct_letters = []
incorrect_letters = []
alphabets= "abcdefghijklmnopqrstuvwxyz"
while lives>0:
print("")
print("".join(guess))
letter= input("Input a letter: ... |
5d1329fa6be4ed97be8abfbf12b7e15236c51552 | vishista-135/Internship-review-analysis-proj | /Day18.py | 1,125 | 3.5 | 4 | list1 = [1,2,3,4,5,6,7,8,9,10]
list1*10
list1 = [0]*10
list2 = []
for item in list1:
list2.append (item*10)
[item*10 for item in list1]
list1 = [1,2,3,4,5,6,7,8,9,10]
import numpy as np
x = np.array(list1)
#df.values -> ndarray
x.shape
x.ndim
y = 10 #scaler value
y = np.array... |
53203ade25a394a73ee15a78a23b85c8224f006a | lorbichara/100-days-of-code | /Python/CharacterInput.py | 1,216 | 4.40625 | 4 | # Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
# Extras:
# Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint... |
dfac652566853639b4474859abadb4fa756796fd | florias/TNO-RU-Lane-detection-project | /Tools/Generator.py | 1,335 | 3.90625 | 4 | import numpy as np
class Generator(object):
"""Generates mock-up data for lane positions.
Generates a matrix consisting of lanes with 100 pairs of coordinates indicating the lanes' position. All lanes are
straight and the purpose is to test the visualiser.
Attributes:
width: width of the lan... |
77526ff6de709ddf359f6bec5459dbbb47c11b4c | MariaGabrielaReis/Python-for-Zombies | /List-01/L1-ex001.py | 260 | 3.984375 | 4 | #Exercise 01 - List 01
#Faça um programa que peça dois números inteiros e imprima a soma desses dois números
print("Soma de dois números")
n1 = int(input('Digite um nº: '))
n2 = int(input('Digite outro nº: '))
print(f'A soma dos números é {n1+n2}') |
8a53c53d3878f3a0c079f7b43fa34955420e30a0 | SteffanySympson/BLUE-MOD-1 | /Desafios/Desafio Sena Melhorado.py | 905 | 4.125 | 4 | # Faça um programa que ajude um jogador da MEGA SENA a criar
# palpites.O programa vai perguntar quantos jogos serão gerados e vai sortear 6
# números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta.
from random import randint
from time import sleep
print(" Roleta da Sorte Blue - JOGA ... |
09938accee657c2f96f213ff71ce7f73ada06708 | egregori3/MachineLearningExperiments | /DataAnalysis1/egregori3/VisualizeWiFi.py | 665 | 3.859375 | 4 | # http://www.apnorton.com/blog/2016/12/19/Visualizing-Multidimensional-Data-in-Python/
import numpy as np
import pandas
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
# Load data into Numpy array
data = np.loadtxt(fname="wifi_localization.txt", delimiter="\t")
columns=['x1', 'x2', '... |
0be8989176c7ddf363b267402c494e00c09ce928 | pastorcmentarny/DomJavaKB | /python/test/test_trading_calculate_daily_limit.py | 831 | 3.6875 | 4 | import unittest
from src.tools.trading import calculate_daily_limit
class MyTestCase(unittest.TestCase):
def test_test_trading_calculate_daily_limit_acceptance_test(self):
# given
expected_result = """With your balance £2000.0.
You aim is to get profit of £22.00 and dont play more if you reach £6... |
69663b4c7c6c1e42463591ddc48cd1fbe96df960 | captainjack331089/captainjack33.LeetCode | /LeetCode_Hash_Table/705_Design_HashSet.py | 1,502 | 3.9375 | 4 | """
705. Design HashSet
Category: Hash Table
Difficulty: Easy
"""
"""
Design a HashSet without using any built-in hash table libraries.
To be specific, your design should include these functions:
add(value): Insert a value into the HashSet.
contains(value) : Return whether the value exists in the HashSet or not.
rem... |
bfa801ec7dbb3ef5f6ac41d8d5ebab326660c42a | alextimofeev272/rosalind | /mmch.py | 568 | 3.6875 | 4 | #coding: utf_8
#найти размещения - упорядоченный набор к - элеменов из n
#что равно C(n,k)*k! - число сочетаний умноженное на число перестановок
#число размещений учитывает порядок
#пример: AUGCUUC
from math import factorial
rna = 'AUGCUUC'
a, u, g, c = map(rna.count, ["A", "U", "G", "C"])
a = factorial(max(a, u)) ... |
8d61123d1a4de5a25bdfca41ac306ca74f1f8df5 | Reikenzan/Some-Python | /SomeWork/reviewWhileNotLoop.py | 368 | 4.21875 | 4 | """ask the user if they want to play again(y/n). If user enters 'y'
or 'n' print it to the screen. If Not, tell them if was invalid &
and keep asking for a valid input until they enter 'n' or 'y'. then
print it to the screen"""
ans = input("Do you want to play again? (y/n)")
while not(ans == 'y' or ans =='n'):
... |
e7dd32fc109808608cc3f92cf13d9463cdd915e7 | pedrokarneiro/Python_MongoDB_Study | /0702_Python_MongoDB_Sort_DESCending.py | 882 | 4.25 | 4 | # Python MongoDB Sort
# 0702_Python_MongoDB_Sort_DESCending.py
#
# Sort the Result
# ===============
# Use the sort() method to sort the result in ascending or descending order.
# The sort() method takes one parameter for "fieldname" and one parameter for "direction" (ascending is the default direction).
#
# Sort Desc... |
038716701b848ec7f43f49191f01db0e19a0f200 | kradical/ProjectEuler | /p22.py | 933 | 3.859375 | 4 | # Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
# containing over five-thousand first names, begin by sorting it into
# alphabetical order. Then working out the alphabetical value for each name,
# multiply this value by its alphabetical position in the list to obtain a name
# score. Fo... |
833bad4102e4fd41e25d933ed40d67d9976e8442 | holzschu/Carnets | /Library/lib/python3.7/site-packages/networkx/algorithms/euler.py | 7,254 | 4.0625 | 4 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2010 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
#
# Authors:
# Nima Mohammadi <nima.irt@gmail.com>
# Aric Hagberg <hagberg@lanl.gov>
# Mike Trenfield <will... |
d38977b91675bc88b283585f8b57fc64c4c35643 | mattheww22/COOP2018 | /Chapter06/U06_Ex_07_fibonacci.py | 1,129 | 4.5625 | 5 | # U06_Ex_07_fibonacci.py
#
# Author: Matthew Wiggans
# Course: Coding for OOP
# Section: A3
# Date: 06 Feb 2018
# IDE: PyCharm
#
# Assignment Info
# Exercise: 07
# Source: Python Programming
# Chapter: 6
#
# Program Description
#
# This program computes the "n"th fibonacci number that is specified b... |
4ff16e082353450d1081c02fa1c15e3ef4ebddd5 | ManuelPalermo/SudokuSolver | /SudokuEngine.py | 10,393 | 3.796875 | 4 | from copy import deepcopy
class Sudoku:
'''
self.sudoku = sudoku 2D array (9x9)
self.options = dictionary( (pos): (options) ) where every pos has all the numbers which could fit, for a determinate state
'''
def __init__(self, sudoku):
self.options = {}
self.sudoku = sudoku
s... |
348fbccc21bb615401a2dad4f4768e7db7f80c19 | GokoshiJr/algoritmos2-py | /src/datos-abstractos/cuenta/Cuenta.py | 1,204 | 3.8125 | 4 | class Cuenta():
def __init__(self, titular: str, cantidad = 0.0):
self.__titular = titular
if (cantidad <= 0.0):
self.__cantidad = 0
else:
self.__cantidad = cantidad
def getTitular(self):
return self.__titular
def getCantidad(s... |
2af8f636a2250cf784b0e97bab2b45baf40fc24c | hyolin97/bigdata_web | /python/ne6.py | 277 | 3.546875 | 4 | sem=int(input("이수학기를 입력하시오:"))
sco=int(input("이수학점를 입력하시오:"))
if (sem==8) and (sco>=150):
print("정상졸업자입니다.")
elif (sco>=150):
print("조기졸업자입니다.")
else:
print("졸업대상자가 아닙니다.")
|
76cf324a337c449f9860bdd78c7d12345eeb9676 | RazielSun/cppclasshelper-sublime-text-plugin | /method_generator/klass/datatype.py | 371 | 4.15625 | 4 | class Datatype:
"""
represents a datatype
"""
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
def __str__(self):
"""
renders datatype name
... |
4d5734808eff4cabde439ce66301147e41f73d6d | Blaze20014/01-Guessing | /main.py | 1,828 | 3.625 | 4 | import sys, random
import sys, time
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
compRandom = random.randint(1, 100)
correctGuess = False
guesses = 0
print("Running GLaDOS_Installer_V1.14.2")
time.sleep(1)
print("GLaDOS booting up...")
time.sleep(1)
print("GLaDOS: Hello player; I see ... |
004c95741d9ecb7d1e5af1110ecb9e52c79ff153 | pjjoy/python | /study_homeworks/hyunjae/algorithm/level1/Exercise12_nobetstr.py | 775 | 3.5 | 4 | """
대문자와 소문자가 섞여있는 문자열 s가 주어집니다. s에 'p'의 개수와 'y'의 개수를 비교해
같으면 True, 다르면 False를 return 하는 solution를 완성하세요.
'p', 'y' 모두 하나도 없는 경우는 항상 True를 리턴합니다.
단, 개수를 비교할 때 대문자와 소문자는 구별하지 않습니다.
예를 들어 s가 pPoooyY면 true를 return하고 Pyy라면 false를 return합니다.
제한사항
문자열 s의 길이 : 50 이하의 자연수
문자열 s는 알파벳으로만 이루어져 있습니다.
입출력 예
s answer
"pPoooyY" true... |
84ded68bfc326d56db7b9efabb3aa25ba8014396 | jonfang/cmpe273-fall17-ChatBot | /roommanager.py | 1,265 | 3.75 | 4 | from hotel import Hotel
class RoomManager:
"""
Manage and calculate date/time
"""
def __init__(self):
pass
def book_hotel(self, receipt, s):
arr = s.split(" ")
receipt["hotel_type"] = arr[1]
msg = "Thank you! You will be staying at " + arr[1]
return msg
... |
461830baf58d27c7794649c30046f64ab7ad56af | ZCKaufman/python_programming | /ValidPalindrome.py | 1,564 | 4.21875 | 4 | import unittest
class MyString:
def isPalindrome(self, s: str) -> bool:
mainString = ""
startPoint = 0
endPoint = 0
for i in s:
if i.isalnum():
mainString += i
mainString = mainString.lower()
endPoint = len(mainString) - 1
while(... |
df0765903ccb28e8e30ffd317e90a4a99b0a9a5a | AnderX003/Algorithms-with-Python | /algorithms_computation_3.py | 3,676 | 3.5625 | 4 | def _01(n):
if n == 1:
return 1
elif n < 1:
return 0
array = range(1, int(n) + 1)
size = len(array)
left = 0
right = size - 1
while left <= right:
m = left + (right - left) // 2
if ((array[m]) ** 2) <= n < ((array[m + 1]) ** 2):
return array[m]
... |
be93df22c8cb919daf5d9ec8e168aea7f393ecc9 | todorovventsi/Software-Engineering | /Programming-Fundamentals-with-Python/final-exam-preparation/03.Programming-fundamentals-final-exam/03.Need-for-speed-3.py | 1,967 | 3.859375 | 4 | n_cars = int(input())
cars_collection = {}
for _ in range(n_cars):
car_name, mileage, fuel = input().split("|")
car_mileage = int(mileage)
car_fuel = int(fuel)
cars_collection[car_name] = {"mileage": car_mileage, "fuel": car_fuel}
command = input()
while not command == "Stop":
data = command.spli... |
110ba9cc562ed1ee5126321581f58162def5bf8a | VasilicaMoldovan/AI | /lab6/Problem.py | 872 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 12:46:19 2020
@author: Vasilica
"""
from math import floor
from random import shuffle
class Problem:
def __init__(self, path):
self.__path = path
def readData(self):
dataSet = []
with open(self.__path, 'r') as f:
fo... |
15d5fcc8c5f9d882c9f697387a02e82ad0fb4879 | annarob/testing | /christopher's programming/Welcome To Night Vale.py | 4,889 | 3.71875 | 4 | import time
import random
import pickle
class ForTechMus():
def House():
print('You have entered the Museum of Forbidden Technologies.')
Obj1 = ['bookcase', 'Cthulu Statue', 'bloodstone', 'shelf']
Obj2 = ['a cat.', 'a dog.', 'The Faceless Woman Who Secretely lives in your home.', 'Old woman ... |
5c4bcbbe054a93d0e9cbb4520bca870a1d659410 | 610yilingliu/leetcode | /Python3/530.minimum-absolute-difference-in-bst.py | 721 | 3.59375 | 4 | #
# @lc app=leetcode id=530 lang=python3
#
# [530] Minimum Absolute Difference in BST
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def getMinimumDifference(self, root):
... |
29ff40b4869a028e09f64826ec37c1c488a545a9 | MayLSantos/Atividade-de-Revis-o | /QUESTAO 2.py | 581 | 3.9375 | 4 | lista = []
class Pilha():
lista= []
def push (self, valor):
self.lista.append(valor)
def pop (self):
if (not(self.isEmpty())):
return self.lista.pop()
def isEmppty(self):
return len(lista.lista) == 0
def length (self):
return len (self.lista)
... |
448470e4825801690e33878cfce960acefd10f41 | priyanka0708/python0708 | /hangman.py | 544 | 4 | 4 | import random
name = input("What is your name? ")
print("Good Luck ! ", name)
words = ['rainbow', 'computer', 'science', 'programming']
word = random.choice(words)
print("Guess the characters")
guesses = ''
turns = 4
while turns > 0: -
failed=0
for char in word:
if char in guesses:
... |
d41ddf43efc44a2a17be21ef92f56173e531dda4 | mikekrieger/dev-challenge | /chapter2_exercises.py | 738 | 3.8125 | 4 | #Name: Michael Krieger
# Exercise 2.1 The number is expressed in octal form. 02492 is not recognized in octal
# because 9 is not recognized as a valid number. 1114 is the decimal equivalent of
# 02132 octal (2*8^3 + 1*8^2 + 3*8^1 + 2*8^0).
#
# Exercise 2.2 Responses are 5; nothing; 6 respectively. When they are prin... |
837b5c2250bed3279a23ee017ea63bc1e013a088 | lishulongVI/leetcode | /python/18.4Sum(四数之和).py | 2,257 | 3.5625 | 4 | """
<p>Given an array <code>nums</code> of <em>n</em> integers and an integer <code>target</code>, are there elements <em>a</em>, <em>b</em>, <em>c</em>, and <em>d</em> in <code>nums</code> such that <em>a</em> + <em>b</em> + <em>c</em> + <em>d</em> = <code>target</code>? Find all unique quadruplets in the array which ... |
ba92a4070b0e260d27a53a0fc2dfacc07860f241 | Artur30/Algorithms-and-data-structures | /bfs.py | 2,076 | 3.859375 | 4 | """ Здесь представлен поиск графа в ширину """
from collections import deque
import unittest
class Node:
def __init__(self, key):
self.key = key
self.d = float('inf') # расстояние
self.visited = False
def bfs(adj, start_node):
""" Функция для поиска графа в ширину """
result = []... |
028d025a98849d50cc4330384bba7e084eac78e2 | Mohamed-Hassan-Akl/Codes_YouTube | /Computer Vision/RealTime_Edge_Detection (Image_Processin_Basics_2)/edge detection.py | 740 | 3.5 | 4 | # OpenCV program to perform Edge detection in real time
# import libraries
import cv2
cap = cv2.VideoCapture("motion.mp4") # capture frames from a video
while(1): # loop runs if capturing has been initialized
ret, frame = cap.read() # reads frames from a camera
hsv =... |
ce08bdd193ad3c0002c61b4eac0a91483f679f5b | saabii/HW-lession-03 | /2.2.py | 84 | 3.5625 | 4 | s = 'Hello!Anthony!Have!A!Good!Day!'
up=s.upper()
l =up.split('!')
print(l[:6])
|
052ae5a92219d1e0c8a6abc02732fdc7b7ea4590 | toanphamcao/22 | /PhamCaoToan_IT19A1B/project_05_page99.py | 828 | 4.125 | 4 | """
Author: Phạm Cao Toàn
Date: 24/07/2021
Program: project_05_page99.py
Problem:
Explain how to check for an invalid input number and prevent it being used in a program.
You may assume that the user enters a number.
Solution:
....
"""
P0 = -1
while (float(P0)<=0):
P0 = input(" How many initial... |
510b3e1836bc4b57b28398df5e8a9f76780ba36a | leiannedang/MP_PYTHON | /MP4FINAL.py | 1,916 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Machine Problem 4 (Python Solution)
By Group 1 of 2ECE-A
Michael Jeffrey Carlos and Lei-Ann Edang
ProjMotion Function accepts values for the constant-velocity motion in the
horizontal direction and free-fall motion in the vertical direction such
as the initial height, magnitude ... |
a2157f0d264f08db0fe64df6e5e18f781a153a67 | Azumait/grammar1-1 | /back_python_3_dataprocess1/2_python_pandas_x_matplotlib1/1.py | 1,954 | 4.03125 | 4 | # 데이터분석 라이브러리 판다스 x 맷플롭립
# 참조자료:
# https://ordo.tistory.com/34?category=732886 (Python 데이터프레임 만들기 블로그 시작점)
import pandas as pd # pip install pandas
from pandas import DataFrame as df
# 1. Pandas를 활용해 DataFrame 만들기
# DataFrame을 간단히 df로 정의하기 : df(data={'key':[value]})
df1 = df(data={'Num':['1', '2', '3'], 'Name':['Kim'... |
6b4bdf34cac57c0ed78a6b800bbeea89cc17f645 | rdsrinivas/python | /sort.py | 130 | 3.609375 | 4 | #!/usr/local/bin/python
animals = ["cat", "ant", "bat"]
animals.sort()
#for animal in animals:
# print animal
print animals
|
4fee7270b1c9031a55e7fe44eb077dd78f362745 | git4rajesh/python-learnings | /Decorators/Demo/advanced/bar.py | 305 | 3.8125 | 4 | from Decorators.Demo.advanced.foo import Foo
class Bar:
foo = Foo()
param = 'test'
@foo.decorate1(param)
@foo.decorate2(param)
def func(self, number):
print('Inside func')
print(Bar.foo.new_param)
if __name__ == '__main__':
bar_obj = Bar()
bar_obj.func(3)
|
fd6b466abb90fbb80eee20ce0ba869998573a44e | Cliffcoding/python-the-hard-way | /ex9.py | 212 | 3.796875 | 4 | days = 'Mon Tues Weds Thurs Fri Sat Sun'
months ='\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'
print('Here are the days: ', days)
print("Here are the months:",months)
print("""
3 Quotes
equals
Multiple lines
""")
|
3861bc4e8ca8721bf6a0e649c3c132fed6a30d2e | martincsumner/issieshomework | /01_variables/variables.py | 1,097 | 4.5625 | 5 | #this is our constant values...
import constant
import math
#this is a VARIABLE - its value can be changed.
THIS_YEAR_VARIABLE = '2005'
#here we are printing the value of the christmas day constant (this gets imported in the line 'import chrimbo').
print('Christmas day is on the : ' + constant.CHRISTMAS_DAY_CONSTANT... |
8b8951a9abda5c6d0580b9238dd0f39502b47553 | Azalius/TpOnlineJudge | /Balance/main.py | 614 | 3.6875 | 4 | import sys
def valide(stri):
index = 0
cars = []
while index <= len(stri) -1:
if stri[index] == "(" or stri[index] == "[":
cars.append(stri[index])
elif not cars:
return False
if stri[index] == ")":
if cars.pop() != "(":
return Fal... |
15a69ecb35cec652121faaf582966f25ea7dad8b | gaoyangthu/leetcode-solutions | /004-median-of-two-sorted-arrays/median_of_two_sorted_arrays.py | 1,815 | 4.28125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3... |
5f524237681639824924912e87877cb1ccf143ea | ivanjankovic16/pajton-vjezbe | /Comprehensions.py | 906 | 3.609375 | 4 | nums = [1,2,3,4,5,6,7,8,9,10]
##my_list =[]
##for letter in 'abcd':
## for num in range(4):
## my_list.append((letter, num))
#my_list = [(letter, num) for letter in 'abcd' for num in range(4)]
#my_list = [n*n for n in nums]
#my_list = filter(lambda n: n%2 == 0, nums)
##names = ['Bruce', 'Clark', 'Peter',... |
d34522e633f8883770f2de5b9e069f0af2cc2bc3 | austindflatt/RobotsVsDinosaurs | /robot.py | 501 | 3.578125 | 4 | from weapon import Weapon
from dinosaur import Dinosaur
class Robot:
def __init__(self, name, health, power_level, robot_weapon):
self.name = name
self.health = health
self.power_level = power_level
self.weapon = robot_weapon
def attack(self, name):
if self.health > 0:... |
d922b9ef73b67fd7f5f97198877391923a825695 | gsib/cryptography_laboratory | /VigenereCipher.py | 673 | 3.84375 | 4 | def VigenereCipher(plaintext, key):
l = len(plaintext)
while(len(key) < len(plaintext)):
key = key + key
Matrix = [['0' for x in range(26)] for x in range(26)]
for i in range(26):
for j in range(26):
Matrix[i][j] = chr((j + i) % 26 + ord('A'))
Ciph... |
03cc776a0e02d780d491566beaf0e9e7bef6e1fc | Kayalvizhi12/FirstProject | /set5.py | 114 | 3.671875 | 4 | a=input()
b=input()
c=input()
if (a>b) and (b>c):
print (a)
elif (b>c) and (b>a):
print (b)
else:
print (c)
|
a891764b23f0baeff57b6e88a89b26f00d1f5a12 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/mntsbo001/question1.py | 719 | 4.0625 | 4 | """Program to check if string is a palindrome
Sbonelo Mntungwa
9 May 2014"""
def palndrm(string): #Defining function
if len(string) == 1 or len(string) == 0: #When there is only one or no character left in string
print( "Palindrome!") #output result
else:... |
12e28b6df95f1ac247c41c5e8fec49096a18fd86 | happiness11/Twitter_Api | /stats.py | 386 | 3.921875 | 4 | def show_menu():
print("menu")
print()
print("1. Add a person")
print("2. View People")
print("3. Stats")
print("4. Exit")
option = input("Enter Option\n")
return option
show_menu()
def program_loop():
while True:
option = show_menu()
if option == 4:
br... |
1b39cc716135b19ed77d0971a4933f53cf0cb42f | ChuaCheowHuan/web_app_DPTH | /CS50_web_dev/src/src3/passengers.py | 1,174 | 3.515625 | 4 | import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
def main():
# List all flights.
flights = db.execute("SELECT id, origin, destination, duration FROM flights"... |
f53eca9fc44040ce4ccb4144a3d55b17e2b31231 | sahithipala1/python_tutorial_with_mosh | /example5.py | 201 | 3.96875 | 4 | print(5 ** 4)
print ((10+3)* 8)
# If else Statements
temperature = 34
if temperature > 30:
print("It's a hot day")
print("Drink water")
elif temperature > 20:
print("It's a nice day")
|
7da0b6aa57f7d175f971967319c599b4b5414a4b | Nagajothikp/Nagajothi | /s52.py | 65 | 3.53125 | 4 | n=input("Enter a num:")
k=input("Enter a num:")
z=min(k)
print(z) |
9e7e4b38c6964c10b9d271b40cd3623b6bdeae86 | bikiranguha/Thesis_project | /ExpCostFn.py | 904 | 3.5625 | 4 | # Function to generate the expected benefit of a classifier, as detailed here:
# http://www.svds.com/the-basics-of-classifier-evaluation-part-1/
def ExpCost(y_true,y_pred,benefit_tP,cost_fN, benefit_tN, cost_fP):
confArray = confusion_matrix(y_true, y_pred)
tN = float(confArray[0][0]) # true negative (0)... |
4a880335fd2fb23124cbae5082284e25b399ac36 | fbakalar/pythonTheHardWay | /exercises/ex38.py | 1,896 | 4.53125 | 5 | #---------------------------------------------------------|
#
# Exercise 38 Doing things to Lists
#
# a "data Structure" is just a formal way to structure or
# organize some data (facts)
#
# just a way to store facts (data) in a program in an
# an organized way so that you can access them in
# differ... |
9f11229d9a35d423b11d53e0beab06a2f0d9d3c6 | avncharlie/flashlight-battery-saver | /BatterySaver.py | 6,188 | 3.625 | 4 | '''
BatterySaver.py
Author: Alvin Charles, https://github.com/avncharlie
Description: This is a program that toggles on and off a 'battery-saving'
mode, which, by default, turns off bluetooth, wifi, the keyboard backlight
and dims the screen to save battery. It can also read off given default
values through a JSON f... |
f6e65f9f0acd096f5372e230920fb8b456520676 | nicolemhfarley/short-challenges | /IQ_numbers.py | 1,039 | 4.46875 | 4 | """
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given numbers finds one that is di... |
b92d753d2923d658e1ad1ea9fa2aca21788d052e | LucianoCassarini/Tripletes | /main.py | 3,553 | 3.734375 | 4 |
#===========================Auxiliares=================================
#devuelve nombre del usuario
def name(line):
posicion = line.find(",")
return line[0:posicion]
#devuelve página visitada
def pag(line):
posicion1 = line.find(",")
aux = line[(posicion1+1):]
pos2 = aux.find(",")
return aux... |
901e8c3529decc7a240748acf64aa973c958caf5 | Ryujongwoo/python1910 | /1016/04_stringFunction.py | 2,999 | 3.90625 | 4 | string = 'We are the champoins, My friend!'
# len() : 인수로 지정된 문자열을 구성하는 문자의 개수를 얻어온다.
print(string)
print(len(string)) # 32
print(string[-1]) # !
print(string[len(string) - 1]) # !
print('*' * 50)
# count() : 인수로 지정된 문자열의 출연 횟수를 얻어온다.
print(string.count('e')) # 4
print(string.count('we')) # 0
print(string... |
f133a17bb2e55d558ffdb96382c3546afdb740fb | jlyang1990/LeetCode | /334. Increasing Triplet Subsequence.py | 727 | 3.65625 | 4 | class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
first = float("inf") # smallest (valid) first element in triplet
# or (potential) first element in triplet (for searching for better "second")... |
013b53bcf2d92a7b328a8731eaa7a20fd8fbb9eb | gcardosov/PythonAprendeOrg | /UsoDeFor.py | 317 | 3.828125 | 4 | #Tabla del 7 usando FOR
print 'Tabla del 7 usando FOR'
#in range
#in palabra o cadena
for j in range (1,11):
print "7x"+str(j),"="+str(j*7)
j = j+1
print 'Uso del for para contar elementos en listas'
print 'Por ejemplo las letras de una palabra'
for letras in 'Tiempo':
print letras;
|
3875638b90344c9bff0feb81dea36b6f090ee97e | codeMacha/TitleTransfer | /Block.py | 1,192 | 3.5625 | 4 | #!/usr/bin/env python
#title :Block.py
#description : block class for the blockchain class
#author : Pasang Sherpa
#usage :python Block.py
#notes :has getter and setter to change the block features
#python_version :3.6.8
#======================================================... |
cd2badde32d471ee6280de8c2b94542733af3b16 | jukilove/Python_ProgrammingPractice- | /Dictionaries and Structuring Data/ticTacToe_1.py | 2,314 | 4.53125 | 5 | #Using Data Structures to Model Real-World Things.
#A Tic-Tac-Toe Board
#To move, the Tic-Tac-Toe Board space are called:
#top-L | top-M | top-R
#------+-------+------
#mid-L | mid-M | mid-R
#------+-------+------
#low-L | low-M | low-R
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L... |
57e27e15f532c07b7e2878b85ac9d240616040cd | desl0451/pythonbase | /python2/python2_1.py | 1,061 | 4.21875 | 4 | # coding=utf-8
# python包含6种内建的序列
edward = ['Edward Gumby', 42]
john = ['John Smith', 50]
database = [edward, john]
print database
# 索引
greeting = 'Hello' # 从0开始
print greeting[0]
print greeting[-1] # 从后面提取
# fourth = raw_input('Year: ')[3] # 2001
# print fourth # 1 0开始
# 索引示例
# 据根给定的年月日以数字形式打印出日期
months = [
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.