blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
d1d844be30625c6e2038e0596b19c05cf9a489fa | DarioBernardo/hackerrank_exercises | /recursion/num_decodings.py | 2,241 | 4.28125 | 4 | """
HARD
https://leetcode.com/problems/decode-ways/submissions/
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mappi... |
668c5cda04ba409fcad5811fbbe85594be6b3c57 | elenaborisova/Softuniada-Hackathon | /softuniada_2021/06_the_game.py | 573 | 4.0625 | 4 | def get_minimum_operations(first, second):
count = 0
i = len(first) - 1
j = i
while i >= 0:
while i >= 0 and not first[i] == second[j]:
i -= 1
count += 1
i -= 1
j -= 1
return count
shuffled_name = input()
name = input()
if not len(shuffled_name)... |
a58d108cc4b7729d8345250fb6b3fbc7e067b38b | srushti-maladkar/python_methods | /lists.py | 342 | 3.71875 | 4 | # import __hello__
li = [1, 2, 3, 4, 5, 6,"S"]
li.append(7) #takes 1 value to append
print(li)
li.append((8, 9, 10))
print(li)
li.clear()
print(li)
li = [1, 2, 3, 4, 5, 6]
li2 = li.copy()
li.append(6)
print(li, li2)
print(li.count(6))
print(li.index(4))
li.insert(2, 22)
print(li)
li.pop(1)
print(li)
li... |
5d792080e230b43aa25835367606510d0bb63af7 | feynmanliang/Monte-Carlo-Pi | /MonteCarloPi.py | 1,197 | 4.21875 | 4 | # MonteCarloPi.py
# November 15, 2011
# By: Feynman Liang <feynman.liang@gmail.com>
from random import random
def main():
printIntro()
n = getInput()
pi = simulate(n)
printResults(pi, n)
def printIntro():
print "This program will use Monte Carlo techniques to generate an"
print "experimental... |
5251c5a37c2fbd8d4298810bf4b1ecb818fcda07 | jambompeople/jambompeople.github.io | /pythonclass.py | 238 | 3.859375 | 4 | class people:
def __init__(self, name, age):
self.name = name
self.age = age
def print(self):
print(self.name,self.age)
Jackson = people("Jackson", 13)
Jackson.name = "JD"
Jackson.age = 12
Jackson.print()
|
119122c529770f37325bd9e50a3c7e5a9bfa4004 | saridha11/python | /count sapce beg.py | 112 | 3.71875 | 4 | string =input()
count = 0
for a in string:
if (a.isspace()) == True:
count+=1
print(count)
|
a7a45dbf67baf4b430ff38fbb50854ab8f01fa75 | saridha11/python | /interval.positive.py | 123 | 3.671875 | 4 | def main():
a=7
b=9
for num in range(a,b+1):
if num%2==0:
print(num,end=" ")
main()
|
c38ad0e4f85157fae49fbc5e86efde52e8542dbe | saridha11/python | /anagrampro.py | 160 | 3.90625 | 4 | def check(str1,str2):
if(sorted(str1)==sorted(str2)):
print("yes")
else:
print("no")
str1=input()
str2=input()
check(str1,str2)
|
fb2117ab2600331a2f94a09c5b3c3412bcdb0cb3 | saridha11/python | /swap ch.py | 130 | 3.671875 | 4 | def swap():
s = 'abcd'
t = list(s)
t[::2], t[1::2] = t[1::2], t[::2]
x=''.join(t)
print("badc")
swap()
|
b52bb5f53ee3842e205131242bb3ef13df5fc8d6 | shuklaham/spojpractice | /ALICESIE.py | 155 | 3.671875 | 4 |
def main():
tc = int(raw_input())
for i in range(tc):
num = int(raw_input())
if num%2 ==0:
print num//2
else:
print (num+1)//2
main()
|
5db532b280a6b04d302432c29e7d83f76c75e485 | shuklaham/spojpractice | /samer08f.py | 271 | 3.5625 | 4 | #spoj solutions
known = {1:1}
def nsquares(n):
if n in known:
return known[n]
else:
c = n**2 + nsquares(n-1)
known[n] = c
return known[n]
num = int(raw_input())
while num != 0:
print nsquares(num)
num = int(raw_input())
|
dcb748b79f6f897f88430352c0a53b873592435b | ztwu/python-demo | /classdemo.py | 261 | 3.578125 | 4 | class ztwu:
p = 0
def __init__(self,p1):
ztwu.p = p1
return
def m1(self):
print("m1",ztwu.p)
return
def m2(self, p1, p2):
print(p1+p2)
return
def m3(self):
print("m3")
return |
876d3e79b2c05a6e0495a27b24268d966784018d | Drishti-Jain/ai_exp | /exp1 toy problem.py | 318 | 3.5 | 4 | x=int(input("No. of bananas at the beginning: "))
y=int(input("Distance to be covered: "))
z=int(input("Max capacity of camel: "))
lost=0
start=x
for i in range(y):
while start>0:
start=start-z
if start==1:
lost=lost-1
lost=lost+2
lost=lost-1
start=x-lost
if start==0:
break
print(start)
|
83c601b56a12f48a2ad1c73646eab2f9a9c71a03 | c2lyh/leetcode | /longest_common_prefix.py | 843 | 4.0625 | 4 | '''
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input str... |
cbfd4dde0f5203f05c73fc790b93d7c4a10edcd6 | jsbarbosa/MonitoriaMetodosComputacionales | /Ejercicios/derivadas.py | 2,668 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 17 19:43:58 2016
@author: Juan
"""
# imports required modules
import matplotlib.pyplot as plt
import numpy as np
# sets the functions and their derivatives
functions = [np.cos, np.exp] # example functions
derivatives = [np.sin, np.exp] # exact derivatives, m... |
adf1a8f9da44ef3590068589a9e68d5413e354c9 | karthikBalasubramanian/MapReduceDesignPatterns | /code/mapper_inverted_index.py | 1,359 | 4.03125 | 4 | #!/usr/bin/python
# in Lesson 3. The dataset is more complicated and closer to what you might
# see in the real world. It was generated by exporting data from a SQL database.
#
# The data in at least one of the fields (the body field) can include newline
# characters, and all the fields are enclosed in double quotes.... |
9e7d64fbc8fd69a5d56e3f65a057a2a3ce08da27 | revanth465/Algorithms | /Searching Algorithms.py | 1,403 | 4.21875 | 4 | # Linear Search | Time Complexity : O(n)
import random
def linearSearch(numbers, find):
for i in numbers:
if(i==find):
return "Found"
return "Not Found"
numbers = [1,3,5,23,5,23,34,5,63]
find = 23
print(linearSearch(numbers,find))
# Insertion Sort | Time Complex... |
18d8ac2957545f1c72ddb30ce917fa52be6f3b81 | OlegZhdanoff/python_basic_07_04_20 | /lesson_1-1.py | 553 | 3.9375 | 4 | var_str = 'hello'
var_int = 5
var_float = 3.2
print('String = ', var_str, '\nInteger = ', var_int, '\nFloat = ', var_float)
random_str = input('Введите произвольную строку\n')
random_int = input('Введите произвольное целое число\n')
random_float = input('Введите произвольное дробное число\n')
print('Ваша строка = ', ... |
b6125617c91172dc3fb3b4c784e30d03d472eaeb | OlegZhdanoff/python_basic_07_04_20 | /lesson_7/lesson_7_3.py | 1,963 | 3.515625 | 4 | """3. Реализовать программу работы с органическими клетками. Необходимо создать класс Клетка. В его конструкторе
инициализировать параметр, соответствующий количеству клеток (целое число). В классе должны быть реализованы методы
перегрузки арифметических операторов: сложение (add()), вычитание (sub()), умножение (mul()... |
e9c965347e640a3dc9c568f854d7840faa5ff31a | OlegZhdanoff/python_basic_07_04_20 | /lesson_2_2.py | 809 | 4.21875 | 4 | """
2. Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами
0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка
элементов необходимо использовать функцию input().
"""
my_list = []
el = 1
i = 0
while el:
... |
a1e6886e32335718cb3de5274dc0380f28c01c0b | OlegZhdanoff/python_basic_07_04_20 | /lesson_1_3.py | 198 | 3.671875 | 4 | n = int(input('Введите число n\n'))
nn = int(str(n) + str(n))
nnn = int(str(n) + str(n) + str(n))
result = n + nn + nnn
print('Сумма чисел', n, nn, nnn, 'равна', result)
|
d4488bb782387cd7a639961df403754416a1022f | MigrantJ/sea-c34-python | /students/MaryDickson/session04/exceptions.py | 709 | 3.984375 | 4 | # questions about the exceptions section in slides 4
list = [0, 1, 4, 8, 100, 1001]
def printitem(list, num):
"""
Can I throw a warning message if number not in range?
"""
try:
return list[num]
except:
return(u"oops not long enough")
finally:
list.append(34)
print lis... |
1fe9ccebdbd43d3542d2b84d40aff034a96eb035 | danevd-TCD/leetcode | /Medium/2-Add Two Numbers.py | 2,276 | 3.8125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
list1 = [] #array for linked list 1
li... |
c31b9941a741feb5f72068044ec410b1ff11532e | KevinFrankhouser/PythonProjects | /Encapsulation.py | 509 | 3.734375 | 4 | class Car:
def __init__(self, speed, color):
self.__speed = speed
self._color = color
def set_speed(self, value):
self.__speed = value
def get_speed(self):
return self.__speed
def set_color(self, value):
self._color = value
def get_color(self... |
ed2837d7ad12ce569757025fbb8e849d5d9914bd | YoonKiBum/programmers | /Level1/68644.py | 302 | 3.6875 | 4 | from itertools import combinations
def solution(numbers):
answer = []
for combination in combinations(numbers, 2):
x = int(combination[0])
y = int(combination[1])
answer.append(x+y)
answer = set(answer)
answer = list(answer)
answer.sort()
return answer
|
6265b2b09f6ce1fa39701aa34d95723dd69c310f | abhnvkmr/hackerRank | /algorithms/anagram.py | 682 | 3.640625 | 4 | # HackerRank - Algorithms - Strings
# Anagrams
def shifts_required(input_str):
shifts = 0
if len(input_str) % 2:
return -1
a, b = input_str[: len(input_str) // 2], input_str[len(input_str) // 2 :]
dict = {}
dicta = {}
for i in b:
if i in dict.keys():
dict[i] += 1
... |
c7bb7446021d6d43b02e561dd4e663248e76f79a | abhinavchinna/complex--number-calculator | /code.py | 1,802 | 3.5 | 4 | # --------------
import pandas as pd
import numpy as np
import math
#Code starts here
class complex_numbers:
def __init__(self,a,b):
self.real=a
self.imag=b
def __repr__(self):
if self.real == 0.0 and self.imag == 0.0:
return "0.00"
if self.real == 0:... |
6c82627929fa81cdd0998309ec049b8ef4d7bc86 | Helen-Sk-2020/JtBr_Arithmetic_Exam_Application | /Arithmetic Exam Application/task/arithmetic.py | 2,032 | 4.125 | 4 | import random
import math
def check_input():
while True:
print('''Which level do you want? Enter a number:
1 - simple operations with numbers 2-9
2 - integral squares of 11-29''')
x = int(input())
if x == 1 or x == 2:
return x
break
else:
... |
c123ff4f0b25cab5630f2b7fb6cb3243cd9abbe0 | Helen-Sk-2020/JtBr_Arithmetic_Exam_Application | /Topics/Writing files/Theory/main.py | 225 | 3.765625 | 4 | names = ['Kate', 'Alexander', 'Oscar', 'Mary']
name_file = open('names.txt', 'w', encoding='utf-8')
# write the names on separate lines
for name in names:
name_file.write(name + '\n')
name_file.close()
print(name_file) |
f35a379b82ba3181da4dbfeda3df222ae24d1370 | zenefits-brody/liaoxuefeng-python | /lambda-function.py | 220 | 3.921875 | 4 | """
https://www.liaoxuefeng.com/wiki/1016959663602400/1017451447842528
请用匿名函数改造下面的代码
"""
def is_odd(n):
return n % 2 == 1
L = list(filter(lambda x: x % 2 == 1, range(1, 20)))
print(L)
|
fc09097d3be62c80b2072cba63db8e4fbb5650d3 | Qasim-Habib/Rush-Hour | /rush_hour.py | 27,924 | 3.828125 | 4 | import sys
from queue import PriorityQueue
import copy
import time
def list_to_string(arr): #convert list to string
str_node=''
for i in range(0, Puzzle.size_table):
for j in range(0, Puzzle.size_table):
str_node += arr[i][j]
return str_node
def print_array(ar): #print the array in the ... |
b513eaa39db2de8aab8d3e3b99d2d4f342d26b14 | Gi-lab/Mathematica-Python | /07-Mate.py | 351 | 4.3125 | 4 | lista_numeros = []
quantidade = int(input('Quantos numeros voce deseja inserir? '))
while len(lista_numeros) + 1 <= quantidade:
numero = int(input('Digite um numero '))
lista_numeros.append(numero)
maior_numero = max(lista_numeros)
print(f'O maior número da lista é {maior_numero}')
input('Digite uma t... |
0a52989a5efd0d95afbd0b5d2d213834ecbb3505 | AnkitaPisal1510/dictionary | /dic_Q10.py | 309 | 3.671875 | 4 | #
#q10
d={
"alex":["sub1","sub2","sub3"],
"david":["sub1","sub2"]
}
# l=[]
# for i in d:
# # print(y[i])
# # print(len(y[i]))
# j=len(d[i])
# l.append(j)
# print(sum(l))
#second method
list1=[]
for i in d.values():
for j in i:
list1.append(j)
print(len(list1))
print(list1) |
30437b421a5e77cea639d04f38b77d6e94c62c2f | AnkitaPisal1510/dictionary | /dic_Q7.py | 273 | 3.5625 | 4 | #q7 ["2","7",'9','5','1']
d=[
{"first":"1"},
{"second":"2"},
{"third":"1"},
{"four":"5"},
{"five":"5"},
{"six":"9"},
{"seven":"7"}
]
# a=[]
# for i in d:
# for j in i:
# if i[j] not in a:
# a.append(i[j])
# print(a)
|
ad503eddaa5c4a00adab20760850c56e7710ee13 | etallman/backend-numseq | /numseq/fib.py | 307 | 4.03125 | 4 | # Fibonacci
'''Within the numseq package, creates a module named fib. Within the fib module, defines a function fib(n) that returns the nth Fibonacci number.'''
def fib(n):
fib_list = [0,1]
for i in range(2, n+1):
fib_list.append(fib_list[i-2] + fib_list[i-1])
return fib_list[n] |
c3d6fa2e65ece7d2cc4c04e2aa815e142bf25306 | Artengar/Drawbot | /Letters_overlay/Letters_overlay.py | 396 | 3.984375 | 4 | #This script put letters on top of each other, comparing which parts of the letters are similar in all typefaces installed on your computer
presentFonts = installedFonts()
fill(0, 0, 0, 0.2)
for item in presentFonts:
if item != item.endswith("egular"):
print(type(item))
print(item)
font(it... |
760cff566ac1cf331b44d84a449fb5da9eb2b3e9 | Artengar/Drawbot | /Rolling_eyes_3/Rolling_eyes_3.py | 1,717 | 3.921875 | 4 | #Rolling eyes on the number 3.
#Free for use and modify, as long as a reference is provided.
#created by Maarten Renckens (maarten.renckens@artengar.com)
amountOfPages = 16
pageWidth = 1000
pageHeight = 1000
#information for drawing the circle:
midpointX = 0
midpointY = 0
ratio = 1
singleAngle = 360/amountOfPages
#So... |
bcc0887e2fc2dadab69e061cf0ebb7771acb7145 | techmexdev/Networking | /tcp_client.py | 663 | 3.53125 | 4 | from socket import *
server_name = 'localhost'
server_port = 3000
# SOCK_STREAM = TCP
while True:
client_socket = socket(AF_INET, SOCK_STREAM)
# connection must be established before sending data
client_socket.connect((server_name, server_port))
message = input(f'\nSend letter to {server_name}:{ser... |
91c93f60046efb049315fb5bb439f0629e079325 | dwightr/ud036_StarterCode | /media.py | 1,186 | 3.609375 | 4 | import webbrowser
class Video():
"""
Video Class provides a way to store
video related information
"""
def __init__(self, trailer_youtube_url):
# Initialize Video Class Instance Variables
self.trailer_youtube_url = trailer_youtube_url
class Movie(Video):
"""
M... |
cedb0a8cbf50d11ab70ab10be53e0892ca290bd3 | drsantos20/python-concurrency | /algorithms/test_binary_search.py | 349 | 3.59375 | 4 | import unittest
from algorithms.binary_search import binary_search
class TestBinarySearch(unittest.TestCase):
def test_binary_search(self):
array = [3, 4, 5, 6, 7, 8, 9]
find = 8
result = binary_search(array, find, 0, len(array)-1)
self.assertEqual(result, 1)
if __name__ == '__... |
8c81bbc51967ddf5ab6e0d6d40cdea1e0a2dfbd3 | renanpaduac/LP_ATIVIDADE_4 | /create_db.py | 338 | 3.59375 | 4 | # -*- coding: latin1 -*-
import sqlite3
con = sqlite3.connect("imc_calc.db")
cur = con.cursor()
sql = "create table calc_imc (id integer primary key, " \
"nome varchar(100), " \
"peso float(10), " \
"altura float(10), " \
"resultado float(100))"
cur.execute(sql)
con.close()
print ("DB Cria... |
129123b7825f07aa303dad36c1b93fd5c27329c6 | forwardslash333/PythonPractice | /10. Add Pattern.py | 398 | 3.9375 | 4 | '''
Write a Python program that accepts an integer (n) and computes the value of n+nn+nnn
Sample value of n is 5
Expected Result : 615
'''
n = input ('Enter an integer\n')
n1 = int('%s' % n) # single digit integer
n2 = int('%s%s' % (n,n)) # second digit number
n3... |
b7d148d07dedf887d3b750bd29238f7852060f02 | Yaraslau-Ilnitski/homework | /Class/Class7/7.08.py | 323 | 3.65625 | 4 | from math import sqrt
def func(mean_type, *args):
acc = 0
count = 0
if mean_type:
for item in args:
acc += item
count += 1
return acc / count
acc = 1
for item in args:
acc += item
count += 1
return acc ** (1 / count)
func(False, 1, 2, ... |
54469d6f0b99a60f520db6c0b159891a8bddc45c | Yaraslau-Ilnitski/homework | /Homeworks/Homework1/task_1_3.py | 198 | 3.59375 | 4 | a = float(input("Ребро куба = "))
V_cube = a ** 3
V_cube_side = 4 * V_cube
print('Площадь куба =', V_cube, 'Площадь боковой поверхности =', V_cube_side)
|
90e3af08fb0b5b7cc753583416b5a3927da92f5b | Yaraslau-Ilnitski/homework | /Class/Class3/3.07.py | 189 | 3.9375 | 4 | stroka = input("Введите предложение\n")
if len(stroka) > 5 :
print(stroka)
elif len(stroka) < 5:
print("Need more!")
elif len(stroka) == 5:
print("It is five") |
e04141931c38d8747c39a4a00ff527725b6e6fa9 | Yaraslau-Ilnitski/homework | /Homeworks/Homework3/task_3_1.py | 250 | 3.578125 | 4 | a = int(input("Введите число делящееся на 1000:\n"))
while True:
if a % 1000 == 0:
print('millenium')
break
else:
a = int(input("...\nВведите число делящееся на 1000:\n"))
|
af1751ce022c930e5b09ba0332f4eb16d39d9b02 | Yaraslau-Ilnitski/homework | /Class/Class7/7.02.py | 1,098 | 3.78125 | 4 | from random import randint
def create_matrix(length, height):
rows = []
for i in range(length):
tnp = []
for i in range(height):
tnp.append(randint(0, 10))
rows.append(tnp)
return rows
matrix = create_matrix(2, 2)
def view(matrix):
for vert in matrix:
fo... |
24a0de5ae6d529277c7770ba74537acf5ae23f3b | Yaraslau-Ilnitski/homework | /Class/Class11/Test.py | 445 | 3.78125 | 4 | class main:
self.x = x
self.y = y
class Line:
point_a = None
point_b = None
def __init__(self, a: Point, b: Point):
self.point_a = a
self.point_b = b
def length(self):
diff = self.point_a.y - self.point_b.y
if diff < 0:
diff = -diff
return ... |
848b8f6dc9767fe4be22982f73a76e8e376bdbb9 | wan-si/pythonLearning | /nowcoder/countUpper.py | 252 | 3.78125 | 4 | # 找出给定字符串中大写字符(即'A'-'Z')的个数
while True:
try:
string = input()
count =0
for i in string:
if i.isupper():
count+=1
print(count)
except:
break |
7e2470a00ba8544adad824e27f443cf6aeea842a | wan-si/pythonLearning | /nowcoder/stepSquar 2.py | 729 | 3.53125 | 4 | # 描述
# 请计算n*m的棋盘格子(n为横向的格子数,m为竖向的格子数)沿着各自边缘线从左上角走到右下角,总共有多少种走法,要求不能走回头路,即:只能往右和往下走,不能往左和往上走。
# 本题含有多组样例输入。
# 输入描述:
# 每组样例输入两个正整数n和m,用空格隔开。(1≤n,m≤8)
# 输出描述:
# 每组样例输出一行结果
# 示例1
# 输入:
# 2 2
# 1 2
# 复制
# 输出:
# 6
# 3
# 复制
def steps(n,m):
if n==0 or m==0:
return 1
else:
return steps(m,n-1)+steps(n,... |
875f5cfd880c495fd2daa4a4285492bbd9176681 | chyko67/- | /200528p56.py | 599 | 3.515625 | 4 | import re
def maketext(script):
written_pattern = r':'
match = re.findall(written_pattern, script)
for writtenString in match:
script = script.replace(writtenString, 'said,')
return script
s = """mother : My kids are waiting for me. What time is it? What time is it? What time ... |
832f2065b6df66978a435e81418a8458472ea4b8 | ajwake97/Weather-App | /Weather Program.py | 1,352 | 3.765625 | 4 |
import requests
import json
import time
#This is the API Key
API_KEY = "10b3ff178d347bb5e10cfee10deb2b63"
#This is the base URL
baseUrl = "https://api.openweathermap.org/data/2.5/weather?"
#This prompts the user for the desired zipcdoe
def zipInput():
zipCode = input("Enter the zipcode: ")
#Sends a request t... |
b3fac7fac215201441c828afbecfd522e043a42c | shruti0/guvi-1 | /leap.py | 109 | 3.765625 | 4 | year = int(input())
if ((year%4==0 and year%100 !=0) or (year%400 == 0)):
print('yes')
else:
print('no')
|
f0b85958acc09ea92cbf9a995aa24311241efb09 | Jrjh27CS/Python-Samples | /practice-python-web/listLessThanTen.py | 735 | 4.0625 | 4 | #Challenge given by https://www.practicepython.org
#Jordan Jones Apr 16, 2019
#Challenge: Write a program that prints out all of the elements in given list a less than 5
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for x in a:
if x < 10:
print(x)
#Extra 1: Instead of 1 by 1 print, make a new list that has al... |
0a6b38b73eea3f054edadbf5dc5f08ee4c524cb1 | Jrjh27CS/Python-Samples | /practice-python-web/fibonacci.py | 690 | 4.21875 | 4 | #Challenge given by https://www.practicepython.org
#Jordan Jones Apr 16, 2019
#Challenge: Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
# Take this opportunity to think about how you can use functions.
# Make sure to ask the user to enter the num... |
b87ed85c70fab6268ef65915778bbed612ba6f0a | C4st3ll4n/Cods_Py | /aleatorio/PouI.py | 874 | 3.625 | 4 | from random import randint as rr
v = 0
d = 0
while True:
jogador = int(input("Digite um valor: "))
pc = rr(0,11)
t = jogador + pc
tipo = ' '
while tipo not in 'PI':
tipo = input("Par ou Impar? [P/I]\n ").strip().upper()[0]
print(f'Deu {t}')
if tipo == "P":
if t % ... |
d2e4e3492046a7fb161d10ee63db46deab2862d5 | C4st3ll4n/Cods_Py | /aleatorio/ex62.py | 532 | 3.8125 | 4 | pri = int(input("Primeiro termo: "))
razao = int(input("Razão: "))
termo = pri
cont = 1
total = 0
mais = 10
while mais != 0:
total = total + mais
while cont <= total:
print(termo, " ", end="")
termo = termo + razao
cont += 1
print("\nWait for it....")
decisao = input... |
38a1b18e152c1156560e74d62f3b826e04c1adbc | CarsonP25/sic_xe-assembler | /symtab.py | 442 | 3.515625 | 4 | class Symtab:
"""Symbol tables containing labels and addresses"""
def __init__(self):
"""Init table"""
self.table = {}
def addSym(self, label, value):
"""Add an entry to the SYMTAB"""
self.table[label] = value
def searchSym(self, label):
for name in self.t... |
3ec773ad3e28f8538c0d76a12d6062df0d30014e | mohan2005mona/python | /regularexpression 1.py | 5,799 | 4.0625 | 4 | import re
email=input('enter valid email address')
result=re.search(r'[\w\.-]+@google.com',email)
if result:
print("its a valid google id")
else:
print('Your email id is invalid')
result=re.sub(r'[\w\.-]+@google.com','\2\1@gmail.com',email)
print(result)
import re
str= '808-1234 #athis is my phone number ... |
63b47daca4a17690bf29270996835298782b1659 | Rodo2005/bucles_python | /ejemplos_clase.py | 6,647 | 4.125 | 4 | #!/usr/bin/env python
'''
Bucles [Python]
Ejemplos de clase
---------------------------
Autor: Inove Coding School
Version: 1.1
Descripcion:
Programa creado para mostrar ejemplos prácticos de los visto durante la clase
'''
__author__ = "Inove Coding School"
__email__ = "alumnos@inove.com.ar"
__version__... |
99fb47e8d7b77982b52335e4d53ef5f5a05b6dc8 | nicolascordoba1/PythonIntermedio | /hangman.py | 943 | 3.5 | 4 | from random import randint
import os
def run():
with open("./archivos/data.txt", "r", encoding= "utf-8") as f:
contador = 0
palabras = []
for line in f:
palabras.append(line.rstrip())
contador +=1
numero = randint(0, contador-1)
palabra = pa... |
6bf2e38a0c09451811be3e0f0d17b5d172b839e5 | Arselena/higher-school | /Level_0_8.py | 662 | 3.71875 | 4 | def SumOfThe(N, data):
try:
assert type(N) is int and N >= 2 and N == len(data)
for i in range(len(data)):
assert type(data[i]) is int # Проверяем Элемент массива
DATA = list(data)
SUM = None
for i in range(1, N):
if DATA[0] == sum(DATA[1:N]):
... |
66a860394ed31f2c6c821d93b5ccebefe40742be | Arselena/higher-school | /Level_0_11.py | 474 | 3.875 | 4 | def BigMinus(s1, s2):
try:
assert type(s1) is str and type(s2) is str
assert s1 != '' and s2 != ''
def modul(x): # Возвращает модуль x
if x < 0:
x = x * (-1)
return x
a = int(s1)
b = int(s2)
assert 0 <= a <= (10**16) and 0 <=... |
57d1ca01b8dde421ca7f9e9fc001725a516febb3 | rdiazrincon/PytorchZeroToAll | /5_Linear_Regression.py | 3,039 | 4.0625 | 4 | import torch
from torch import nn
from torch import tensor
# x_data is the number of hours studied
x_data = tensor([[1.0], [2.0], [3.0], [4.0]])
# y_data is the number of points obtained
y_data = tensor([[3.0], [5.0], [7.0], [9.0]])
# e.g: 1 hour of study -> 2 points. 2 hours of study -> 4 points usw
# hours_of_study ... |
f7011fc9cd0a66c35e67f3440e67aff78ca813f6 | LeoKnox/kanji_app_a | /tree.py | 1,514 | 3.75 | 4 | class Tree:
def __init__(self, info):
self.left = None
self.right = None
self.info = info
def delNode(self, info):
if self.info == info:
print('equal')
if not self.left and not self.right:
print('a')
self.lef... |
5c9720ba0f06dc339f3d3054cc59a9ae573e8093 | brammetjedv/PYTAchievements | /ifstatements.py | 275 | 3.71875 | 4 | varA = 6
if ( varA == 5 ):
print("cool")
elif ( varA > 5 ):
print("kinda cool")
elif ( varA == 69 )
pass
else :
print("not cool")
varW = True
varX = True
varY = True
varZ = True
if ( (varW and varX) or (varY and varZ) ):
print("flopje")
print("end")
|
7620b60fd16105ff63f2738573db92dc2d8f3fd5 | tegupta/fulltopractice | /OOPs/using_init_method.py | 281 | 3.84375 | 4 |
class Emp(object):
def __init__(self,name,salary):
self.name=name
self.salary=salary
return None
def display(self):
print(f"The name is: {self.name}\nThe salary is:{self.salary}")
return None
emp1=Emp('Ramu', 54000)
emp1.display() |
61e3abf84388aa418bbbd5e32adbda69f0da9fb0 | Pod5GS/CS5785-Applied-Machine-Learning | /HW0/iris_plot.py | 2,920 | 3.59375 | 4 | #!/usr/bin/env python
"""
This script read Iris dataset, and output the scatter plot of the dataset.
Be sure the Iris dataset file is in the 'dataset' directory.
"""
from matplotlib import pyplot as plt
import numpy
# This function draw the labels
def draw_label(fig, label, index):
"""
:param fig:... |
165c2222f7e8767fc1201b609da4a4c8aabfbc6b | knotriders/programarcadegame | /pt6.2.2.py | 244 | 3.640625 | 4 | n = int(input("How many eggs?:"))
print("E.g. n: ",n)
# n = 8
for i in range(n):
for j in range(n*2):
if i in (0 , n-1) or j in (0, 2*n-1):
print("o", end = "")
else:
print(" ", end = "")
print()
|
fbbe40dbd80fa0eb0af9a22c7c1f78775dca2dca | knotriders/programarcadegame | /test2.py | 274 | 3.90625 | 4 | done = False
while not done:
quit = input("Do you want to quit? ")
if quit == "y":
done = True
else:
attack = input("Does your elf attack the dragon? ")
if attack == "y":
print("Bad choice, you died.")
done = True |
8eae2a9c399ad80545c8ac7f3d4878fcfef4285e | hmcurt01/Ivy-Plus | /printdata.py | 3,541 | 3.8125 | 4 | from data import student_dict
import pyperclip
#convert student dict into text
def printdict(value, grade):
studentamt = 0
sortednames = {}
for o in student_dict:
if student_dict[o].grade == grade:
sortednames[o] = student_dict[o].name
if value == "stats":
label = "NAME ... |
dcbe36488dc453401fb81abd4a01dd2fe29bcbbf | moribello/engine5_honor_roll | /tools/split_names.py | 1,231 | 4.375 | 4 | # Python script to split full names into "Last Name", "First Name" format
#Note: this script will take a .csv file from the argument and create a new one with "_split" appended to the filename. The original file should have a single column labled "Full Name"
import pandas as pd
import sys
def import_list():
while ... |
6ac521f4fa27b32de1192e7f2b8367ac6b86f9ea | Meet00732/DataStructure_And_Algorithms | /Breath_First_Search/BFS.py | 929 | 3.90625 | 4 | import time
graph = dict()
visited = []
queue = []
n = int(input("enter number of nodes = "))
for i in range(n):
node = input("enter node = ")
edge = list(input("enter edges = ").split(","))
graph[node] = edge
# print(graph)
def bfs(visited, graph, n):
queue.append(n)
for node ... |
50d6496496531c365527290d9d12bcf4fb1f1c5f | DanilkaZanin/vsu_programming | /Time/Time.py | 559 | 4.125 | 4 | #Реализация класса Time (из 1 лекции этого года)
class Time:
def __init__(self, hours, minutes, seconds):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def time_input(self):
self.hours = int(input('Hours: '))
self.minutes = int(input('Minutes... |
77c1a636b346eb0a29ce7010a249a0d13c375fb6 | shaikhul/scoring_engine | /parsers.py | 716 | 3.75 | 4 | import csv
from custom_exceptions import ParseError
class Parser(object):
def __init__(self, file_path):
self.file_path = file_path
def parse(self):
raise NotImplementedError('Parse method does not implemented')
class CSVParser(Parser):
def parse(self):
with open(self.file_path, ... |
89de0d0d8b5680f76b8150da9a93320b89e6a41b | summerpenguin/learning-CS | /ex16-4.py | 2,123 | 3.859375 | 4 | #将参数调入模块
from sys import argv
#在运行代码时需要输入的代码文件名称和需要调用的文件名称
script, filename = argv
#打印”我们将要擦除文件,文件名为格式化字符%r带标点映射文件名“
print "We're goint to erase %r." % filename
#打印”如果你不想这么做,可以按CERL-C键终止进程“
print "If you don't want that, hit CRTL-C (^C)."
#打印”如果你想这么做,请点击RETURN键“
print "If you do want that, hit RETURN."
#以”?“为提示符读取控制台的... |
fb43b06f60b0b73c57a7c99814e2ad1e2d6acf15 | james-prior/python-asyncio-experiments | /mylog.py | 899 | 3.8125 | 4 | import datetime
def format_time(t):
return f'{t.seconds:2}.{t.microseconds:06}'
def log(message):
'''
prints a line with:
elapsed time since this function was first called
elapsed time since this function was previously called
message
Elapsed times are shown in seconds with mi... |
0ddd1c97e6e4b0b15dcfd7f5f09fdf19c822120a | james-prior/python-asyncio-experiments | /2-sequential-waits.py | 474 | 3.78125 | 4 | #!/usr/bin/env python3
'''
Awaiting on a coroutine.
Print “hello” after waiting for 1 second,
and then print “world” after waiting for another 2 seconds.
Note that waits are sequential.
'''
import asyncio
from mylog import log
async def say_after(delay, what):
await asyncio.sleep(delay)
log(what)
async d... |
a31c0549965ec668c0009148d5a94db2bc70225f | taysemaia/basic_python | /conjuntos.py | 437 | 3.734375 | 4 | # coding: utf-8
# Programação 1, 2018.2
# Tayse de Oliveira Maia
# Conjunto com mais elementos
numero = []
soma = 0.0
while True:
numeros = raw_input()
if numeros == 'fim':
break
soma += 1
if int(numeros) < 0:
numero.append(soma)
soma = 0.0
for i in range(len(numero)):
numero[i] = nume... |
a9653885227248fd5605eb6b0fcc7ec6b2bb5cfc | taysemaia/basic_python | /avre.py | 270 | 3.75 | 4 | # coding: utf-8
# Programação 1, 2018.2
# Tayse de Oliveira Maia
# Arvore Natal
altura = int(raw_input())
larguramax = 2 * altura - 1
for alturas in range(altura + 1):
print ' ' * (larguramax - ( 2 * alturas - 1) / 2),
print 'o' * (2 * alturas - 1)
print (larguramax + 1) * " " + "o"
|
0b48be2de52b543d189741a5c5300f995adf84f2 | EssamQabel/Problem-Solving | /Codeforces/A/41A.py | 200 | 3.71875 | 4 | s = input()
t = input()
result_list = []
for i in range(len(s)):
result_list.append(s[i])
result_list.reverse()
s = ''.join(result_list)
if s == t:
print('YES')
else:
print('NO') |
6d3af464bbf9f8e9cf52f751bb66d9fde3cfbace | manankhaneja/hep-da | /programs/main.py | 2,607 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 23 18:50:07 2018 - constantly improving ever since
@author: Manan Khaneja
"""
# Master program for data extraction without damaging file format
# takes in input the directory in which all the files have to be analysed ( eg. a directory from which neutron data is ex... |
b36872d55259a67b9b0ad8ef8ce8e26e30b75cc0 | benkerns09/digital-crafts-lessons | /files/March8/phonebook.py | 2,012 | 4.0625 | 4 | class PhoneBook(object):
def __init__(self, name, phone):#in it we have the name and phone number
self.name = name
self.phone = phone
self.peopleList = []#I'm not sure what this is
def phoneBookEmpty(self):
if len(self.peopleList) == 0:#if the length of people list is zero...its... |
c6a3dc37f5d97438c3a9a3894cc82f65ec9ff35b | benkerns09/digital-crafts-lessons | /files/March6/mar307.py | 666 | 3.828125 | 4 | def drawtriangle(height, base):
for row in range(1, height + 1):
spaces = height - row
print " " * spaces + "*" * (row * 2 - 1)
drawtriangle(6, 4)
def box(height, width):
for row in range(height):
if row in[0] or row in[(height-1)]:
print("* " * (width))
else:
... |
6c51492aa5005099401d48ce50e6d84e41b59657 | KhalidOmer/Exercises | /Work_Directory/Python/lottery.py | 617 | 3.890625 | 4 | import numpy as np
"""This is a simple common game that asks you to guess a number
if you are lucky your number will match the computer's number"""
def luck_game():
print("Hello, let's check if you're lucky!'")
print("You are asked to guess a number between 0 and 10'")
luck_number = int(np.random.uniform(0,11))
... |
86773d8aa5d642f444192ecc1336560c86d718ca | siddu1998/sem6_labs | /Cloud Computing/Assignment 1/question9.py | 218 | 4.40625 | 4 | # Write a Python program to find whether a given number (accept from the user)
# is even or odd, print out an appropriate message to the user.
n=int(input("please enter the number"))
print("even" if n%2==0 else "odd") |
180256985bff15f54e150f1ff7a6cc4d86a1b365 | siddu1998/sem6_labs | /Cloud Computing/Assignment 1/question10.py | 250 | 3.984375 | 4 | # Write a Python program to count the number 4 in a given list.
length=int(input("Please enter the length"))
list_with_fours=[]
for i in range(0,length):
list_with_fours.append(int(input()))
print("number of 4's")
print(list_with_fours.count(4)) |
f0501f677535546d870b4e28283048c78fb87771 | zhh007/LearnPython | /2.List.py | 619 | 4.0625 | 4 |
x = list('Hello')
print(x)
y = "".join(x)
print(y)
x = [1, 1, 1]
x[1] = 2
print(x)
names = ['Void', 'Alice', 'Jack']
del names[1]
print(names)
name = list('Perl')
name[2:] = list('ar')
print(name)
list1 = [1, 2, 3]
list1.append(4)
print(list1)
x = [1, 2, 1, 3]
print(x.count(1))
a = [1, 2, 3]
b = [4, 5]
a.ex... |
891d590fe33896826dd3c5ce6c6e1bea06e5b980 | pink-floyd-in-venice/pink-floyd-in-venice.github.io | /resources/functions/CsvTripleCreator/main.py | 722 | 3.890625 | 4 | import csv
if __name__== "__main__":
csv_name=input("Inserire nome file csv: ")
if csv_name[-4:] !=".csv":
csv_name += ".csv"
with open(csv_name, "w", newline="") as csv_file:
writer=csv.writer(csv_file, delimiter=' ', quotechar='|')
writer.writerow(["Subject", "Predicate", "Object"... |
c03b3059a659730e6db51364c5dd5144bc5f64a6 | SandeeraDS/FYP-Codes | /After 2019-08-25/python_string/stringTest.py | 563 | 3.734375 | 4 | import re
name = " sande er " \
"dddsds sds sds sdd dsdsd ddsd dsds "
name2 = " sande er " \
"dddsds sds sds sdd dsdsd ddsd dsdsa"
name3 = " BCVFE | sande er " \
"dddsds sds sds sdd 2 .. 3 dsdsd ddsd ? dsdsA1"
newString1... |
f0d2eef82b83a98f36f2a759f585c8cf03ad0327 | SandeeraDS/FYP-Codes | /After 2019-08-25/encoding_test/test.py | 1,093 | 3.53125 | 4 | import re
import nltk
# to install contractions - pip install contractions
from contractions import contractions_dict
def expand_contractions(text, contractions_dict):
contractions_pattern = re.compile('({})'.format('|'.join(contractions_dict.keys())))
def expand_match(contraction):
# print(contracti... |
d3a2e416b3bd15607d71317808f17751667c9e0b | Jeremyreiner/DI_Bootcamp | /week5/Day4/exercise/exerciseXP.py | 3,256 | 4.46875 | 4 | # Exercise 1 – Random Sentence Generator
# Instructions
# Description: In this exercise we will create a random sentence generator. We will do this by asking the user how long the sentence should be and then printing the generated sentence.
# Hint : The generated sentences do not have to make sense.
# Download this wor... |
316aa2bdc7e255944d154ce075592a157274c9bc | Jeremyreiner/DI_Bootcamp | /week5/Day3/daily_challenges/daily_challenge.py | 2,874 | 4.28125 | 4 | # Instructions :
# The goal is to create a class that represents a simple circle.
# A Circle can be defined by either specifying the radius or the diameter.
# The user can query the circle for either its radius or diameter.
# Other abilities of a Circle instance:
# Compute the circle’s area
# Print the circle and get ... |
0cdc78355fca028bb19c771c343ae845b702f555 | Jeremyreiner/DI_Bootcamp | /week5/Day1/Daily_challenge/daily_challenge.py | 2,265 | 4.40625 | 4 | # Instructions : Old MacDonald’s Farm
# Take a look at the following code and output!
# File: market.py
# Create the code that is needed to recreate the code provided above. Below are a few questions to assist you with your code:
# 1. Create a class called Farm. How should this be implemented?
# 2. Does the Farm class ... |
7a7c944b90acd5e775968c985c9f2b58789ed4a7 | christopher-henderson/thesis | /writing.py | 1,896 | 3.53125 | 4 | '''
Wikipedia sucks...unless it doesn't. This is the N-Queens problem implemented
using the following general-form pseudocode.
https://en.wikipedia.org/wiki/Backtracking#Pseudocode
It is getting correct answers, although I am doing something wrong and also
getting duplicates.
'''
N = 8
def backtrack(P, root, accep... |
69005c262433db7d85e18bf3b770ca093533c99f | christopher-henderson/thesis | /backtrack/01knapsack.py | 1,681 | 3.8125 | 4 | from backtrack import backtrack
class KnapSack(object):
WEIGHT = 50
ITEMS = ((10, 60), (20, 100), (30, 120))
MEMO = {}
def __init__(self, item_number):
self.item_number = item_number
def first(self):
return KnapSack(0)
def next(self):
if self.item_number >= len(self.ITEMS) - 1:
return None
ret... |
9c03b56ac31edf5d0163ec4cf3a9cab915a789a4 | christopher-henderson/thesis | /nQueen0.py | 2,178 | 3.75 | 4 | import copy
N = 8
NUM_FOUND = 0
derp = list()
def backtrack(P, C, R):
if reject(P, C, R):
return
# Not a part of the general form. Should it be in 'reject'?
# That would be kinda odd, but it must appended before a call to output.
P.append([C, R])
if accept(P):
output(P)
s = fi... |
7ce103ab49574b9dcb251574c06934c9fb2b00e1 | SvenLC/CESI-Algorithmique | /listes/triParSelection.py | 439 | 3.828125 | 4 | # Ecrire la procédure qui reçoit un tableau de taille N en entrée et qui réalise un tri par sélection
exemple = [1, 3, 5, 6, 3, 2, 4, 5, 6]
def triParSelection(tableau, n):
for i in range(0, n):
for j in range(i, n):
if(tableau[i] > tableau[j]):
min = tableau[j]
... |
9693d52cc708aca038148b57c23f45976ef7ef01 | SvenLC/CESI-Algorithmique | /boucles/exercice6.py | 331 | 3.5625 | 4 | # Écrire un algorithme qui demande un nombre de départ, et qui calcule la somme des entiers jusqu’à ce nombre,
# par exemple, si on entre 5, on devrait afficher 1 + 2 + 3 + 4 + 5.
def somme(nombre):
total = 0
for i in range(0, nombre):
total = total + i
print(i)
return total
print(somme... |
6438fc05212750bb32b2ca3aecbfb970f7568071 | cran/excerptr | /inst/excerpts/excerpts/main.py | 5,131 | 3.5625 | 4 | #!/usr/bin/env python3
"""
@file
module functions
"""
from __future__ import print_function
import re
import os
def extract(lines, comment_character, magic_character, allow_pep8=True):
"""
Extract Matching Lines
Extract all itmes starting with a combination of comment_character and
magic_character... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.