blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
29edaded65d4d82474ef0f5c5b048c688f4ca0d4 | ddemetriadou/Quantum-Computing-Project | /Circuit5.py | 12,821 | 3.609375 | 4 | '''
Quantum Computing Project
Author: Petros Zantis
'''
import matplotlib.pyplot as plt
from Tensor import *
from Gate import *
from State import *
import copy
plt.rcParams['figure.figsize'] = (12, 6)
plt.rcParams['font.size'] = 13
class Circuit(object):
def __init__(self, name):
'''... |
b67658c1674eaf756a4140efeadcd6bd4944e0b8 | riderflo85/OpenFoodFacts | /config/DataBase.py | 3,229 | 3.5625 | 4 | #! /usr/bin python3
# conding: utf-8
import mysql.connector
class DataBase():
"""Class that manages SQL queries with the database"""
def __init__(self, name_BDD):
"""Constructor of the class that defines basic variables"""
self.name_BDD = name_BDD
self.conn = None
self.curso... |
e73b2286e0258ed961c01eb10c2f5df7513777fa | trishacjames/MyFirstPython | /coins.py | 185 | 3.53125 | 4 | print("You have 0 coins.")
input("Do you want another?")
print("You have 1 coins")
input("Do you want another?")
print("You have 2 coins.")
input("Do you want another?")
print("Bye") |
341d6401d39a8fc1854f0d204bd7d28b6492ac9a | 77rtoip/SPOJ | /PRIME_T/python3.7/app.py | 735 | 3.625 | 4 | """
PRIME_T - Liczby Pierwsze
https://pl.spoj.com/problems/PRIME_T/
Sprawdź, które spośród danych liczb są liczbami pierwszymi
Input
n - liczba testów n<100000, w kolejnych liniach n liczb z przedziału [1..10000]
Output
Dla każdej liczby słowo TAK, jeśli liczba ta jest pierwsza, słowo: NIE, w przeciwnym wypadku.
E... |
f74b07ab17f082dd200b2abcd93fe9623163631c | szharas/python-project-lvl1 | /brain_games/games/prime.py | 593 | 3.921875 | 4 | from random import randint
DESCRIPTION = 'Answer "yes" if given number is prime. Otherwise answer "no".'
def is_prime(num):
if num > 1:
if num % 2 == 0 or num % 3 == 0:
return False
# Iterate from 2 to n / 2
for i in range(2, num // 2):
if (num % i) == 0:
... |
543314f4c374dd17aee189358dbe7c6983ed6a84 | lukeymyuan/coding_interview_challenges | /triangle.py | 233 | 3.671875 | 4 | def solution(A):
if(len(A)<3):
return 0
A.sort()
for i in range (0, len(A)-2):
# check adjacent values as they provide the highest value
if A[i] + A[i+1] > A[i+2]:
return 1
return 0
|
a4fadf4fbae4083114e0b7b34d2d6bb3a24eb39c | lukeymyuan/coding_interview_challenges | /longestConsecutiveCharacters.py | 405 | 3.640625 | 4 | def longestConsecutiveCharacters(string):
prev=None
maxCount=0
count=1
maxChar=None
for curr in string:
if curr == prev:
count+=1
else:
count = 1
if count>maxCount:
maxCount=count
maxChar=curr
prev=curr
return {maxCh... |
079859c3fc5bfdfb95db6f625e015088d28e1ab8 | thetwoj/qlearning | /world.py | 1,644 | 3.78125 | 4 | #!/usr/bin/python3
import random
from pprint import pprint
class Node:
def __init__(self, name):
self.name = name
self.neighbors = []
self.goal_node = False
make_set(self)
def __repr__(self):
return ('<Node name: {}, neighbors: {}, goal: {}'.format(
self.n... |
62f4473d326733e451c31b9ed796bfdb6de5bf34 | marcosmcp/Hello_World | /Python/Lotofácil/lotofacil.py | 2,856 | 3.90625 | 4 | import random
totalnum = 25
faltantes = 0
escolhidos= []
matriz = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
sorteio =[]
novalista = []
nova_matriz=[]
choisen = 0
while choisen != 5:
print('''
>>>>>>>> $ PROGRAMA Sortear LOTOFÁCIL $ <<<<<<<<<<<<<
... |
25df2944d457743cacf7770ef0026664446b5e53 | jhee514/Algorithms | /SWEA_problems/1231_중위순회.py | 1,105 | 3.734375 | 4 | import sys
sys.stdin = open("input_1231.txt", "r")
def inorder_traverse(node):
global inorder
# parent = find_p(node)
if node:
inorder_traverse(tree[node][0])
inorder += data[node-1][1]
inorder_traverse(tree[node][1])
def postorder_traverse(node):
global postorder
if nod... |
c37c888ce17ce5be73ea43e3434adf27139e20a3 | Avogar/Snake | /Snake.py | 40,369 | 3.53125 | 4 | import pygame, random, os, sys
pygame.init()
def draw_snake():
for i in range(len(x)-1, -1,-1):
if i == 0:
if dx[i] == a:
screen.blit(snake_head_right,[x[i],y[i]-1])
elif dx[i] == -a:
screen.blit(snake_head_left, [x[i], y[i]-1])
... |
60215280c6fbe48b2b175cfbf6b3efe7bac6f2b6 | nischalp8l/python101 | /asi3.py | 533 | 3.921875 | 4 | import random
def findOTP(num1,num2):
x =random.randint(1,20)
print(x)
for i in range(3):
n = int(input("Enter number in range 1 to 20 "))
if (n>20):
print("Wrong input try again!")
elif x==n:
return "OTP SUCCESSFULLY MATCHED"
else:
print(... |
2fc8bfd4530c5c3c842792dec7109ff53a56740c | JuliyShulaeva/TPG | /2sem/laba1/laba4/laba4.py | 2,038 | 3.59375 | 4 | import sqlite3
import csv
class Student(object):
def __init__(self, data, curs):
for key, value in data.items():
object.__setattr__(self, key, value)
object.__setattr__(self, 'cursor', curs)
def __setattr__(self, key, value):
object.__setattr__(self, key, value)... |
ccedc799b70151dbe08557098586f1525d0c32dd | JuliyShulaeva/TPG | /1sem/Q1/Q.py | 406 | 3.515625 | 4 | class Tree:
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo # груз(данные)
self.left = left # левый узел
self.right = right # правый узел
def __str__(self):
return str(self.cargo)
def total(tree):
if tree is None:
return 0
r... |
2afbfc51b60ce357cc677647cb95a4314c92dde6 | JuliyShulaeva/TPG | /2sem/laba1/laba3/laba3.py | 1,140 | 3.90625 | 4 | import sys
import sqlite3
import csv
conn = sqlite3.connect(":memory:") # или :memory: чтобы сохранить в RAM
cursor = conn.cursor() # взаимодействие с базой
kol = 0
# Создание таблицы
tb_create = cursor.execute("""CREATE TABLE student
(id int, first_name char, middle_name char, last_name ... |
d325c6030594201b60e045f45f2f68206f3a0bbf | NyanWunna/cp1404practicals | /prac_02/files.py | 444 | 3.6875 | 4 | def main():
NAME_FILE = "name.txt"
name_file = open(NAME_FILE, "w")
name = input("Enter name: ")
print(f"{name}", file=name_file)
name_file.readline(2)
name_file.close()
NUMBER_FILE = "numbers.txt"
number_file = open(NUMBER_FILE, "r")
first_line_str = input_file.readline()
seco... |
2f72f900e73e4e0ddc9cff63346e221139707e6b | NyanWunna/cp1404practicals | /prac_05/emails.py | 486 | 3.96875 | 4 | def main():
email = input("Email: ")
data = {}
while email != "":
name_part = email.split("@")[0]
email_part = name_part.split(".")
name = "".join(email_part).title()
name_confirm = input(f"Is your name {name}? y/n").lower()
if name_confirm == "n" or name_confirm == ... |
af800a84a2887a6cc0561a74b3a44215ac9e8457 | jhglick/comp120-sp21-lab09 | /longest_increasing_subsequence.py | 467 | 4.125 | 4 | """
File: longest_increasing_subsequence.py
Author: COMP 120 class
Date: March 23, 2021
Description: Has function for longest_increasing_subsequence.
"""
def longest_increasing_subsequence(s):
"""
Returns the longest substring in s. In case of
ties, returns the first longest substring.
"""
pass
i... |
5793b9577d5d35f04e955f40595d1e5e0def80b2 | phyuthinzarmg/python-exercises | /ex19.py | 731 | 3.8125 | 4 | def cheese_and_crackers(cheese_count, boxes_of_crackers):
2 print(f"You have {cheese_count} cheeses!")
3 print(f"You have {boxes_of_crackers} boxes of crackers!")
4 print("Man that's enough for a party!")
5 print("Get a blanket.\n")
6
7
8 print("We can just give the function numbers directly:")
9 cheese_and_crackers(20... |
371e64af5e5451f34e28ac8764d18f3c6d82abb8 | phyuthinzarmg/python-exercises | /ex24.py | 791 | 4.0625 | 4 | print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do:')
print('\n newlines and \t tabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there i... |
25a51d4bfc145b1a6c8f0a907ccd8a30caddeb73 | lukegil/test | /retrieve/crawler.py | 7,764 | 3.984375 | 4 | import urllib2
import re
import string
import pprint
import connect
#remove all html tags from a string
def remove_html_tags(text):
strip_text = ''
flag = ''
last_character = ''
count = 0
#look through every character
for character in text:
#if it has a <, it mig... |
0ead192ad5b4d5d7d2200c26a78eaed348933274 | rachit-mishra/Hackerrank | /String 10 formatting.py | 793 | 4.21875 | 4 | '''
def print_formatted(number):
for i in range(1,number+1):
binlen = len(bin(i)[2:])
print(str(i).rjust(binlen,' '),end=" "),
print(str(oct(i)[2:]).rjust(binlen,' '),end=" ")
print(str(hex(i)[2:].upper()).rjust(binlen,' '),end=" ")
print(str(bin(i)[2:]).rjust(binlen,' '), s... |
ae32662ce0b4d3b4c778d934aa0f84ae0fa46a2b | rachit-mishra/Hackerrank | /Sets 3 No idea.py | 588 | 3.78125 | 4 | '''
********No idea python sets hackerrank*****
Set A - Like all integers
Set H - Dislike all integers
'''
n, m = input().split()
happiness = 0
happinessA = 0
happinessB = 0
arr = (set([int(x) for x in input().split()]))
A = set([int(y) for y in input().split()])
B = set([int(z) for z in input().split()])
count = [1 ... |
5b17d6216a339ee9642c7d826ff468a2bdd99139 | rachit-mishra/Hackerrank | /Sets 1 intro.py | 681 | 4.25 | 4 | # Set is an unordered collection of elements without duplicate entries
# when printed, iterated or converted into a sequence, its elements appear in an arbitrary order
# print set()
# print set('HackerRank')
# sets basically used for membership testing and eliminating duplicate entries
array = int(input())
sumlist = ... |
2b481e16167b0473f5cf618b1284c099436555ea | rachit-mishra/Hackerrank | /Algorithms Plus Minus.py | 345 | 3.5 | 4 | n = int(input().strip())
arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]
countplus = 0
countzero = 0
countneg = 0
for values in arr:
if values==0:
countzero+=1
elif values>0:
countplus+=1
elif values<0:
countneg+=1
print(countplus/len(arr))
print(countneg/len(arr))
p... |
e573281ff63819c9d6049a932e8175d8275ee30e | rachit-mishra/Hackerrank | /Algorithms grading students.py | 554 | 3.53125 | 4 | n = int(input().strip())
grades = []
grades_i = 0
newgrades = []
for grades_i in range(n):
grades_t = int(input().strip())
grades.append(grades_t)
for value in grades:
if value>=38:
tempvalue = int(value/5) + 1
finaltempvalue = tempvalue*5
if abs(value-finaltempvalue)<3:
... |
4c83d0eb7f110bf6777d4b7ccf58717a6437191d | Evanlec/transport | /models.py | 3,277 | 3.796875 | 4 | from datetime import date
class InvalidPassError(Exception):
"""Exception raised when a pass is swiped and user shall not be allowed further"""
pass
class Pass(object):
def __init__(self, customer_type):
self.customer_type = customer_type
class BalancePass(Pass):
def __init__(self, balance=0.... |
a5daff0eccc74862ba2f2cd962971a27f2ec7099 | tinybeauts/LPTHW | /ex15_mac.py | 1,197 | 4.375 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
# Extra Credit 4
# from sys import argv
#
# script, filename = argv
#
# t... |
57df0687054d9fdaebce872ccc29309e1f575170 | dagar07/pyo | /flatten_array.py | 331 | 3.78125 | 4 | def flatten_array(arr = []):
if not bool(arr):
return 'Invalid Array from user'
modifiedArr = []
for item in arr:
if isinstance(item, list):
modifiedArr.extend(flatten_array(item))
else:
modifiedArr.append(item)
return modifiedArr
print(flatten_array([[1, 2, 3], 4, [5, [6, 7, [8, 9... |
2d6fa90cf80bd4e3281dfb8321719bc073f5c16b | dagar07/pyo | /multiply_arr.py | 216 | 3.75 | 4 | def arr_multiply(a, b):
if not bool(a) or not bool(b):
return "Invalid Inputs"
c = []
for index in range(len(a)):
c.append(a[index] * b[index])
return c
print(arr_multiply([1, 2, 3], [4, 5, 6]))
|
6820cd610205e5d107aacd5ebd7b19cc9680011b | Den44/MDS | /1.py | 268 | 3.78125 | 4 | import datetime
def printTimeStamp(name):
print("Марчик Денис: " + name)
print("Час компіляції: " + str(datetime.datetime.now()))
P=int(input("Tension:"))
V=int(input("Volume:"))
t=int(input("Temperature:"))
n=P*V/float(8.314)*float(t+273.15)
print(n) |
6bcc6db87af03a64ac7622b8b21972d71fef7bfc | manchenkoff/geekbrains-python-homework | /lesson01/task06.py | 1,321 | 3.9375 | 4 | """
Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
Требуется определить номер дня, на который результат спортсмена составит не менее b километров.
Программа должна принимать значения параметро... |
3d81349f7a5be8d25833b98a3e01bc23279352ee | manchenkoff/geekbrains-python-homework | /lesson06/task03.py | 1,834 | 3.6875 | 4 | """
Реализовать базовый класс Worker (работник), в котором определить атрибуты:
name, surname, position (должность), income (доход).
Последний атрибут должен быть защищенным и ссылаться на словарь, содержащий элементы:
оклад и премия, например, {"wage": wage, "bonus": bonus}.
Создать класс Position (должн... |
63916cfe0ea97c7241fe8609609a0eae1a8cb60c | manchenkoff/geekbrains-python-homework | /lesson04/task05.py | 679 | 4 | 4 | """
Реализовать формирование списка, используя функцию range() и возможности генератора.
В список должны войти четные числа от 100 до 1000 (включая границы).
Необходимо получить результат вычисления произведения всех элементов списка.
Подсказка: использовать функцию reduce().
"""
from functools import reduce
numb... |
d6846c5fdeaf0b2680e0ab99ab31480a1bf093aa | manchenkoff/geekbrains-python-homework | /lesson01/task04.py | 634 | 4.1875 | 4 | """
Пользователь вводит целое положительное число.
Найдите самую большую цифру в числе.
Для решения используйте цикл while и арифметические операции.
"""
user_input = input("Введите число >>> ")
if not user_input.isdigit():
print("Неверный формат числа")
exit()
number = int(user_input)
max_num = 0
while num... |
8d0182b080285dee235c2aba6a4cedd24079735b | manchenkoff/geekbrains-python-homework | /lesson04/task01.py | 732 | 3.796875 | 4 | """
Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия.
Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
"""
import sys
_, work_hours, hour_cos... |
97588e53dfe8da3b6519c640ea70c4df6dcbc058 | Werayoot/CP3-Werayoot-Phongphanuwat | /Exercise5_2_Werayoot_Ph.py | 113 | 3.75 | 4 | s = float(input("Distant(S) (km) :"))
t = float(input("Time(t) (hr) :"))
v = s/t
print("Velocity(v) =",v,"km/h")
|
c8074d63574ce50e30501df02cf1e70a25689095 | simenhu/prog.prosj | /oving2/stoneRockPaper.py | 6,594 | 3.71875 | 4 | import random
from matplotlib import pyplot as plt
import numpy as np
class Action:
type = None
typeDict = {0:"stone", 1:"scissors", 2:"paper"}
def __init__(self, type):
if isinstance(type, int):
self.type = self.typeDict.get(type)
elif isinstance(type, str):
self.ty... |
3fc1aea54c2fd2ee853ca9b704e2f9cd661dddd7 | MrBarbo/Builder-Pattern-Python | /codigo/builder_interface.py | 798 | 3.921875 | 4 | from abc import ABCMeta, abstractmethod
# Las clases abstractas tienen que usar una metaclase ABCMeta
# ABCMeta metaclass provides a method called register method that can be invoked by its instance.
class PizzaBuilderInterface(metaclass=ABCMeta):
"Interface de la pizza"
#Declaramos los métodos base del const... |
8c30740166ac59f10230b0cc7ebf7ff9b34cfb7a | kpkrishGit/scripts | /fib.py | 498 | 3.6875 | 4 | # length of fib series for the max value <= x
"""
print the length of array to reach a value <= x
"""
print('{:<15} {:>10} {:>20}'.format('Below', 'Length', 'Series'))
for x in [10, 100, 1000, 10000, 100000, 1000000, 10000000, \
100000000, 1000000000, 10000000000, 100000000000, 1000000000000, 10000000000000]:... |
1118e37c9f75ab99d0446b881e7ba6fb473368da | mdayunus/dsa-in-py | /quicksort_lomuto.py | 1,201 | 3.734375 | 4 | # Lomuto partition
# pivot = last element
# pindex = i = 0 in the start
# move pindex,i to right untill you find value > pivot
# move i to right untill you find value < pivot
#swap value at pindex and i
# continue
def swap(data_list, start, end):
if start != end:
tmp = data_list[start]
data_list[st... |
9459fe48f49b96059f6d6482c23db2220bf56dd8 | mdayunus/dsa-in-py | /mergesort.py | 906 | 4.03125 | 4 | def mergesort(data_list):
if len(data_list) <= 1:
return data_list
mid = len(data_list) // 2
left = data_list[:mid]
right = data_list[mid:]
left = mergesort(left)
right = mergesort(right)
return merge_two_array(left, right)
def merge_two_array(a1,a2):
sortedList = []
... |
16f872d870eec841c95e8a1828e1e36eba269d86 | BChip/scurvy | /miner.py | 393 | 3.5625 | 4 | def get_bytes_from_file(filename):
return open(filename, "rb").read()
byte_arr = get_bytes_from_file("file.gz")
for byte in byte_arr:
try:
byte.encode("ascii")
except UnicodeDecodeError as error:
hex = byte.encode("hex")
num = int(hex,16)
print(hex, num)
if(num... |
2eec93d7b03f827dea517c4eecdf593d8f5c7786 | Invalid-coder/Engine | /matrix.py | 1,037 | 3.71875 | 4 | def matrix_multiplication(a, b):
columns_a = len(a[0])
rows_a = len(a)
columns_b = len(b[0])
rows_b = len(b)
result_matrix = [[j for j in range(columns_b)] for i in range(rows_a)]
if columns_a == rows_b:
for x in range(rows_a):
for y in range(columns_b):
sum ... |
cab9cb6acaaa9ca5244ecbc125a9bdb0d1cebbe2 | aiorosxul/algo | /python/12_sorts/merge_sort.py | 540 | 4.09375 | 4 | def merge_sort(list):
if len(list) == 1:
return list
else:
mid = len(list) // 2
left = list[:mid]
right = list[mid:]
l1 = merge_sort(left)
r1 = merge_sort(right)
return merge(l1, r1)
def merge(left, right):
result = []
while len(left) > 0 and len... |
952b53302b651bd20a8e1722d37cacfa08e2af80 | Md-Hiccup/Problem-Solving | /Job/pelatro.py | 1,825 | 3.546875 | 4 | """
Size of the Matrix is N x M
The upper left and lower right indexes of 4 submatrices formed are:
1. (0,0) - (N/2-1, M/2-1)
2. (0,M/2) - (N/2-1, M-1)
3. (N/2,M/2) - (N-1, M-1)
4. (N/2,0) - (N-1, M/2-1)
INPUT
1
4 4
1 3 5 2
6 7 -3 -10
15 14 -1 12
1 3 1 3
OUTPUT
78
After changing A[0][2] f... |
38224f08235c8eb54db0e792c33362c24b711a1a | Md-Hiccup/Problem-Solving | /CTCI/Array/8_zero_matrix.py | 3,625 | 4.0625 | 4 | """
Zero Matrix: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and
column are set to 0.
Hints:
#17 : If you just cleared the rows and columns as you found Os, you'd likely wind up clearing
the whole matrix. Try finding the cells with zeros first before making any changes to the... |
de7f58a8084ee33e834c6487c65ef0cf13a19913 | Md-Hiccup/Problem-Solving | /HackerRank/Rank/easy/symmetric_difference.py | 2,623 | 4.125 | 4 | """
a new data type: sets.
Concept:
If the inputs are given on one line separated by a space character, use split() to get the separate values in the form of a list:
>> a = raw_input()
5 4 3 2
>> lis = a.split()
>> print (lis)
['5', '4', '3', '2']
If the list values are all integer types, use the map() method to conve... |
28333560794fe12a562659ecd236a6047d0693b9 | Md-Hiccup/Problem-Solving | /LeetCode/easy/02-reverse_integer.py | 1,628 | 4.03125 | 4 | """ PROBLEM: REVERSE INTEGER
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer ran... |
acfbd6ce55de265ead5aa37b15d13d6ad78c6060 | Md-Hiccup/Problem-Solving | /HackerRank/Rank/easy/any_or_all.py | 719 | 4.125 | 4 | """
any():
This expression returns True if any element of the iterable is true.
If the iterable is empty, it will return False.
all():
This expression returns True if all of the elements of the iterable are true. If the iterable is empty, it will return True.
Prob: Print True if all the conditions of the problem s... |
23c87cb01d8e4ceb608ee2c7087291d6582149ee | Md-Hiccup/Problem-Solving | /HackerEarth/Earth/company-tests/samsung/samsung-1.py | 2,262 | 3.921875 | 4 | """ Bit even arrays
You are given an array A with entries A(i). Some of the entries in the array have The value of A(i) in some of the entries is equal to -1. This means that A(i) should be replaced by a bit even number.
A bit even number satisfies two properties:
1. All the bits at the odd position of the binary rep... |
1ef078d6c92399bc43e5737112cf6d41105963de | Md-Hiccup/Problem-Solving | /HackerRank/Rank/easy/collection_namedtuple.py | 924 | 4.4375 | 4 | """
collections.namedtuple()
Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for accessing members of a tuple.
Example:
>>> from collections import namedtuple
>>> Point = namedtu... |
0b05fa2efff3dceebfc23c35e3ce3a42e02cb2eb | smoczis/python_bash_roguelike_game | /trash/hot_cold_game.py | 2,313 | 3.859375 | 4 | """
start menue
win/lose screen
map!!!
hot_cold with pop_up
"""
from random import randint, choice
from text_in_out import *
def hot_cold(board, number_length, attempts, is_binary=False, is_even=False):
number = generate_number(number_length, is_binary, is_even)
win = guess_number(board, number, attempts, num... |
1f8becd0336a65fe1ac3b526c57e622096936e85 | pleszkoactvf/lesson8 | /Lesson8/problem1.py | 379 | 4 | 4 | print('-' * 65)
print('<Morbid Death Predictor> ')
print()
print('Description: This program asks you for your current age and tells you the year you will die (on average).')
print()
x = input('What is your age today? ')
x = int(x)
print('...thinking...')
print('...thinking...')
birthyear = 2018 - x
y = birthyear + ... |
1c50edab74bea2750e560cda2c358b491dcc08e6 | jo3rn/word_counter | /whatsapp_word_counter.py | 1,622 | 3.671875 | 4 | import sys
import re
import operator
###### initialize variables
# text to be parsed, encoded in UTF-8
whole_text = open('text.txt', encoding='utf-8').readlines()
# stores the count for each word
dictionary = {}
# helper to delete characters not in UTF-8
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1),... |
0303096a5bec7f82d252df9f55c884dd4029aabf | glsnh/shiyanlou-code | /jump7.py | 109 | 3.59375 | 4 | i=0
while i<100:
i=i+1
if(i%7==0):
continue
if(i%10==7):
continue
if(i//10==7):
continue
print(i)
|
45e3d146678b9483d20e76ba84c09a4b75b78741 | adamhartleb/bbopp | /project_1/bagels.py | 1,491 | 3.921875 | 4 | import random
def blurb():
print("Bagels, a deductive logic game.")
print("")
print("I am thinking of a 3-digit number. Try to guess what it is.")
print("")
print("Here are some clues:")
print("When I say: That means:")
print("Pico One digit is correct but in the wrong posi... |
020e021c57f47dae785b66cdb538080e7764e5b8 | sivaprakashSP/Python-Stuffs | /Skillrack DC/HCF_Ranges.py | 1,890 | 3.578125 | 4 | '''
def find_gcd(x,y):
while(y):
x,y=y,x%y
return x
lis=[int(x) for x in input().split()]
m=lis[0]
n=lis[1]
lis2=[]
for i in range(m):
lis2.append(int(input()))
print(lis2)
x=lis2[0]
y=lis2[1]
gcd=find_gcd(x,y)
for i in range(2,len(lis2)):
gcd=find_gcd(gcd,lis2[i])
print(gcd)
lis2=[]
lis3=[]
for... |
45abb3ea814eed513fbdc13796a597ffc6eeda36 | sivaprakashSP/Python-Stuffs | /Skillrack DC/sort_row_even_integer_count.py | 284 | 3.5 | 4 | def getEvenCount(numList):
count=0
for val in numList:
if val%2==0:
count+=1
return count
R,C=map(int,input().split())
matrix=[list(map(int,input().split())) for row in range(R)]
matrix=sorted(matrix,key=getEvenCount)
for row in matrix:
print(*row) |
d6d1608cce42f64be59f89c80ef98e8d82d4116c | sivaprakashSP/Python-Stuffs | /Skillrack DC/Reverse_Substrings_bet_underscores.py | 170 | 3.921875 | 4 | a=input().split('_')
if len(a)>1:
print(a[0],end='_')
for x in range(1,len(a)-1):
print(*(list(reversed(a[x]))),sep='',end='_')
print(a[-1])
else:
print(a[0]) |
0b778af43bb6ab139e9cf499ab901876d4597014 | halliejr/comp110-21f-workspace | /exercises/ex04/utils.py | 1,321 | 4.09375 | 4 | """List utility functions."""
__author__ = "123456789"
# TODO: Implement your functions here.
def main() -> None:
"""Import Numbers for List."""
print(all([1, 1], 1))
print(is_equal([1, 2], [2]))
print(max([10, 5, 200, 20]))
return None
def all(x: list[int], y: int) -> bool:
"""All will ... |
823bfe004d15009ef4e9c63be9872b681956ddf3 | AkshaySingh566/tathastu_week_of_code | /Day 1/Program2.py | 88 | 4 | 4 | import math
a = int(input("Enter the no: "))
print("The square root is:",math.sqrt(a)) |
1c365cf9402667c9bb18524a7152316c097e696a | SleepToWin/Scrape-Yellow-Pages | /scrape_yp.py | 1,374 | 3.515625 | 4 | #!/usr/bin/env python3
from bs4 import BeautifulSoup
import requests
print('Enter a city to search and what to find there.',
'\nExample:\nWhere do you want to search? manchester nh',
'\nWhat are you looking for? pawn shops',
'\nHow many pages of results? 2\n')
# spaces are replaced by dashes for use in the url
locat... |
93e27f8878e2ae0071acfdcb5d13f7cf9b897a50 | hecvd/python_algorithms | /exercises/fibonacci.py | 683 | 3.90625 | 4 |
def memoize(func):
mem = {}
def inner(self, value):
if value not in mem:
mem[value] = func(self, value)
return mem[value]
return inner
class Fibonacci(object):
def __init__(self):
pass
def generator(self, n):
a, b = 1, 1
for t in range(n - ... |
67735303f4d4a95aa579ebf115b5c50ca0e2aecc | LucaLio-codes/sortvisual_python | /sorters/insertion.py | 359 | 3.625 | 4 | from sorters.sorter import Sorter
class InsertionSort(Sorter):
def __init__(self, data):
super(InsertionSort, self).__init__(data)
def algo(self):
for i in range(len(self.data)):
j = i
while j > 0 and self.data[j-1] > self.data[j]:
self.swap(j, j-1)
... |
ee5c05427279e88c03e4826ae5632e2a8e7d469f | ErenBtrk/Python-Fundamentals | /Numpy/NumpyStatistics/Exercise11.py | 1,012 | 3.59375 | 4 | '''
11. Write a NumPy program to test element-wise of a given array for finiteness
(not infinity or not Not a Number), positive or negative infinity, for NaN,
for NaT (not a time), for negative infinity, for positive infinity.
'''
import numpy as np
print("\nTest element-wise for finiteness (not infinity or not Not ... |
d45ac81e82215547446443f6f40b6a0a82526221 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyStrings/Exercise5.py | 247 | 4.03125 | 4 | '''
5. Write a NumPy program to insert a space between characters of all the elements of a given array.
'''
import numpy as np
np_array = np.array(["Kevin Durant","Lebron James","Michael Jordan"])
idx = (1,3)
new_array = np.char.join("-",np_array)
print(new_array) |
c97180f8da45af325f6e204fc2679494eff365f1 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyStatistics/Exercise4.py | 246 | 3.921875 | 4 | '''
4. Write a NumPy program to compute the 80th percentile
for all elements in a given array along the second axis.
'''
import numpy as np
np_array = np.random.randint(0,10,12).reshape(2,6)
print(np_array)
print(np.percentile(np_array,50,1)) |
c2c0745b71a66464daf21d104a2831c38de9d9bb | ErenBtrk/Python-Fundamentals | /Numpy/NumpyStrings/Exercise16.py | 313 | 4.125 | 4 | '''
16. Write a NumPy program to count the lowest index of "P" in a given array, element-wise.
'''
import numpy as np
np_array = np.array(['Python' ,'PHP' ,'JS' ,'examples' ,'html'])
print("\nOriginal Array:")
print(np_array)
print("count the lowest index of ‘P’:")
r = np.char.find(np_array, "P")
print(r) |
339a24e71cbd4b32a815332c1ad9426a1d99c335 | ErenBtrk/Python-Fundamentals | /Python Operators/4-ComparisonOperatorsExercises.py | 1,368 | 4.34375 | 4 | #1 - Prompt user to enter two numbers and print larger one
number1 = int(input("Please enter a number : "))
number2 = int(input("Please enter a number : "))
result = number1 > number2
print(f"number1 : {number1} is greater than number2 : {number2} => {result}")
#2 - Prompt user to enter 2 exam notes and calculate avera... |
e28261b1b1dbc1e236111391cc195f3a438e9607 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyRandom/Exercise6.py | 174 | 3.6875 | 4 | '''
6. Write a NumPy program to shuffle numbers between 0 and 10 (inclusive).
'''
import numpy as np
np_array = np.arange(11)
np.random.shuffle(np_array)
print(np_array) |
7fb07b19e24d0a25f6ff71c79914c2b6e8eb82f2 | ErenBtrk/Python-Fundamentals | /Python Error Handling/3-ExceptionObject.py | 1,128 | 3.9375 | 4 | # x = 10
# if x > 5:
# raise Exception("x cant be greater than 5")
def check_password(password):
import re
if len(password) < 8:
raise Exception("Password must be atleast 8 characters.")
elif not re.search("[a-z]",password):
raise Exception("Password must include lower character.")
... |
b9d440a9aafd661b1d1ed641cc8921e5e24ebd02 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyLinearAlgebra/Exercise14.py | 256 | 4.1875 | 4 | '''
14. Write a NumPy program to compute the condition number of a given matrix.
'''
import numpy as np
m = np.array([[1,2],[3,4]])
print("Original matrix:")
print(m)
result = np.linalg.cond(m)
print("Condition number of the said matrix:")
print(result) |
b99c2578051bef4298f3c7110ac76b9b3c0c9063 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyLinearAlgebra/Exercise10.py | 270 | 4.125 | 4 | '''
10. Write a NumPy program to find a matrix or vector norm.
'''
import numpy as np
v = np.arange(7)
result = np.linalg.norm(v)
print("Vector norm:")
print(result)
m = np.matrix('1, 2; 3, 4')
print(m)
result1 = np.linalg.norm(m)
print("Matrix norm:")
print(result1) |
d888cf76ca3c466760c7c6397a7c056aa44f9368 | ErenBtrk/Python-Fundamentals | /Python Conditional Statements/4-IfElseExercises2.py | 2,940 | 4.46875 | 4 | #1- Prompt the user to enter a number and check if its between 0-100
number1 = int(input("Please enter a number : "))
if(number1>0) and (number1<100):
print(f"{number1} is between 0-100")
else:
print(f"{number1} is NOT between 0-100")
#2- Prompt the user to enter a number and check if its positive even number
... |
31e0a2c1b41f587b63bb213ebda6c68d96d83d36 | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataSeries/Exercise13.py | 289 | 4.15625 | 4 | '''
13. Write a Pandas program to create a subset of a given series based on value and condition.
'''
import pandas as pd
pd_series = pd.Series([1,2,3,4,5])
print(pd_series)
relationalVar = pd_series > 3
new_series = pd_series[relationalVar]
new_series.index = [0,1]
print(new_series) |
66c7b75d33b882e78fc35a61720bd25ded68c7cf | ErenBtrk/Python-Fundamentals | /Numpy/NumpyStatistics/Exercise13.py | 515 | 4.4375 | 4 | '''
13. Write a Python program to count number of occurrences of each value
in a given array of non-negative integers.
Note: bincount() function count number of occurrences of each value
in an array of non-negative integers in the range of the array between
the minimum and maximum values including the values that did ... |
b8fb1233979708c7ea192f82a6df4d46d0b25366 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyLinearAlgebra/Exercise19.py | 314 | 4.09375 | 4 | '''
19. Write a NumPy program to calculate the Frobenius norm and the condition number of a given array.
'''
import numpy as np
a = np.arange(1, 10).reshape((3, 3))
print("Original array:")
print(a)
print("Frobenius norm and the condition number:")
print(np.linalg.norm(a, 'fro'))
print(np.linalg.cond(a, 'fro')) |
a8f9a363b9710a8f7c3941e34a99ef9c9da89bd8 | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataframe/Exercise21.py | 362 | 4.34375 | 4 | '''
21. Write a Pandas program to iterate over rows in a DataFrame.
'''
import pandas as pd
import numpy as np
import pandas as pd
import numpy as np
exam_data = [{'name':'Anastasia', 'score':12.5}, {'name':'Dima','score':9}, {'name':'Katherine','score':16.5}]
df = pd.DataFrame(exam_data)
for index, row in df.iterro... |
dd07c492b76d1079edc9f2e76dbd71de44c55f9e | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataframe/Exercise61.py | 453 | 4.3125 | 4 | '''
61-Write a Pandas program to get topmost n records within each group of a DataFrame.
'''
import pandas as pd
d = {'col1': [1, 2, 3, 4, 7, 11], 'col2': [4, 5, 6, 9, 5, 0], 'col3': [7, 5, 8, 12, 1,11]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
print("\ntopmost n records within each group of a... |
10ec2988fd07fa78f2eb48c1b1129b251b6971af | ErenBtrk/Python-Fundamentals | /Numpy/NumpyRandom/Exercise3.py | 159 | 4.25 | 4 | '''
3. Write a NumPy program to create a 3x3x3 array with random values.
'''
import numpy as np
np_matrix = np.arange(0,27).reshape(3,3,3)
print(np_matrix) |
1591438dbb897ede18c1a27964188bae46176ce6 | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataframe/Exercise27.py | 325 | 3.828125 | 4 | '''
27. Write a Pandas program to write a DataFrame to CSV file using tab separator.
'''
import pandas as pd
import numpy as np
d = {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, 7, 8], 'col3': [7, 8, 9, 0, 1]}
df = pd.DataFrame(data=d)
df.to_csv("exercise27.csv",sep='\t',index=False)
print(pd.read_csv("exercise27.c... |
427acb10edbf4b8ced9a44f21674a4e050e2e257 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyRandom/Exercise1.py | 168 | 3.890625 | 4 | '''
1. Write a NumPy program to generate five random numbers from the normal distribution.
'''
import numpy as np
np_array = np.random.normal(size=5)
print(np_array) |
bb499595c002cdbb6442c185d1448b4dd0556be3 | ErenBtrk/Python-Fundamentals | /Python Object & Data Structures/7-DataTypeCasting.py | 597 | 3.984375 | 4 | # x = input("1.number: ")
# y = input("2.number: ")
# print(type(x))
# print(type(y))
# total = int(x)+int(y)
# print(total)
x = 5 #int
y = 2.5 #float
name = "Yarasa" #string
isOnline = True #bool
# print(type(x),type(y),type(name),type(isOnline))
#Type Conversion
#int to float
x = float(x)
print(x)
print(type... |
f614043e21abd506720c73a8ee3ee9bc603fc7fb | ErenBtrk/Python-Fundamentals | /Python Operators/1-AssignmentOperator.py | 318 | 3.78125 | 4 | # x = 5
# y = 10
# z = 20
x,y,z = 5,10,20
# x,y = y,x
# x += 5 #x = x+5
# x -= 5 #x = x-5
# x *= 5 #x = x*5
# x /= 5 #x = x/5
print(x,y,z)
values = 1,2,3
print(values)
print(type(values))
x,y,z = values
print(x,y,z)
values2 = 1,2,3,4,5
print(values2)
print(type(values2))
a,b,*c = values2
print(a,b,c)
print(c)
|
daa22fddbd6ba074563e49c432d60fdfbaf498f5 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyRandom/Exercise8.py | 179 | 3.84375 | 4 | '''
8. Write a NumPy program to create a random vector of size 10 and sort it.
'''
import numpy as np
np_vector = np.random.randint(1,20,10)
np_vector.sort()
print(np_vector) |
2461f2c598528a6a45b35da2708517717532fd3a | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataframe/Exercise53.py | 425 | 4.5 | 4 | '''
53. Write a Pandas program to insert a given column at a specific column index in a DataFrame.
'''
import pandas as pd
d = {'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
new_col = [1, 2, 3, 4, 7]
# insert the said column at the beginning in ... |
4dd47859a458a67d5e61b8f941a867c3e95b2b76 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyRandom/Exercise11.py | 274 | 4.03125 | 4 | '''
11. Write a NumPy program to create random vector of size 15 and replace the maximum value by -1
'''
import numpy as np
np_vector = np.random.random(size=15)
print(np_vector)
print("Max value = ",np_vector.max())
np_vector[np_vector.argmax()] = -1
print(np_vector) |
287ac1b857ee91f615f5a8c10c112fa8a2bf8496 | ErenBtrk/Python-Fundamentals | /Python File Management/4-UpdatingFile.py | 928 | 3.84375 | 4 | # with open("newfile2.txt","r+") as file:
# file.seek(20)
# file.write(" deneme ")
# with open("newfile2.txt","r+") as file: #r+ is both reading and writing
# print(file.read())
####################################################
#******** Updating at end of page ********
# with open("newfile2.txt","a"... |
789d52f7c4e9b6fd3a91586d188bd06fec4da709 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyRandom/Exercise13.py | 288 | 4.4375 | 4 | '''
13. Write a NumPy program to find the most frequent value in an array.
'''
import numpy as np
x = np.random.randint(0, 10, 40)
print("Original array:")
print(x)
print("Most frequent value in the above array:")
print(np.unique(x))
print(np.bincount(x))
print(np.bincount(x).argmax()) |
dcecd4f5f65e24e8bcf2bb130d180b590c3aae74 | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataSeries/Exercise24.py | 311 | 4.25 | 4 | '''
24. Write a Pandas program convert the first and last character
of each word to upper case in each word of a given series.
'''
import pandas as pd
import numpy as np
pd_series = pd.Series(["kevin","lebron","kobe","michael"])
print(pd_series.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper() ))
|
7f8643452482fdc6be9be7c91e8e24b2afcae2d6 | ErenBtrk/Python-Fundamentals | /Pandas/pandas-files.py | 828 | 3.984375 | 4 | from sqlite3.dbapi2 import connect
import pandas as pd
import sqlite3
from pandas.io import sql
df1 = pd.read_csv("addresses.csv")
df1.columns = ["First Name","Last Name","Street Name","City","Abbr","Postal Code"]
df1.index = [1,2,3,4,5]
print(df1)
df2 = pd.read_json("sample.json")
print(df2)
df3 = pd.read_excel("... |
5feffbf991ad5558f23181cdce21396930a98fb5 | ErenBtrk/Python-Fundamentals | /Python Object-Oriented Programming/3-ClassMethods.py | 1,428 | 4.1875 | 4 | #class
class Person:
#pass #keyword for classes without attributes or methods
#class attributes
adress = "No information"
#constructor
def __init__(self,name,year):
#object attributes
self.name = name
self.year = year
print("init method is working.")
#inst... |
683b66c1c2d05cdb93da1bbb884747a1a5c6d4d2 | ErenBtrk/Python-Fundamentals | /Matplotlib/graphs3.py | 289 | 3.515625 | 4 | import matplotlib.pyplot as plt
#Bar Plot
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],label="BMW",width= 0.5)
plt.bar([0.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],label="AUDI",width= 0.5)
plt.legend()
plt.xlabel("Day")
plt.ylabel("Distance(km)")
plt.title("Car Info")
plt.show() |
68131c94887ff1da6069d0a22c3a07352769ea24 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyLinearAlgebra/Exercise1.py | 304 | 4.40625 | 4 | '''
1. Write a NumPy program to compute the multiplication of two given matrixes.
'''
import numpy as np
np_matrix1 = np.arange(0,15).reshape(5,3)
print(np_matrix1)
np_matrix2 = (np.ones(9,int)*2).reshape(3,3)
print(np_matrix2)
print(f"Multiplication of matrixes :\n{np.dot(np_matrix1,np_matrix2)}")
|
b2f234264d137b44ee87170a389296bd0b84b9fa | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataSeries/Exercise9.py | 237 | 4.09375 | 4 | '''
9. Write a Pandas program to convert a given Series to an array.
'''
import pandas as pd
import numpy as np
pd_series = pd.Series([1,2,3,4,5])
np_array = np.array(pd_series.values.tolist())
print(np_array)
print(type(np_array))
|
5f8d4ce3d986989f319055ee06fc4b00d4ed1a68 | ErenBtrk/Python-Fundamentals | /Python Object & Data Structures/9-Strings.py | 630 | 3.921875 | 4 | name = "Yarasa"
surname = "Reis"
age = 99
greeting = "My name is "+ name + ' ' + surname + " and \nI am " + str(age) + " years old"
length = len(greeting)
# #print(greeting)
# print(greeting[0]) #printing char at 0.index
# print(greeting[3]) #printing char at 3.index
# print(greeting[length-1]) #printing char at last... |
5802078b29d8753c500cf7d3793bc5e9cf76742b | ErenBtrk/Python-Fundamentals | /Python Object-Oriented Programming/4-Inheritance.py | 1,295 | 4.1875 | 4 | # Inheritance :
# Person => name , lastname , age , eat() , run() , drink()
# Student(Person),Teacher(Person)
#Animal => Dog(Animal),Cat(Animal)
class Person():
def __init__(self,firstName,lastName):
self.firstName = firstName
self.lastName = lastName
print("Person created")
def who... |
513b4ae303517c3adf54e7420fff2efccbe5ec11 | ErenBtrk/Python-Fundamentals | /Matplotlib/Plotting Exercises/Exercise9.py | 683 | 3.71875 | 4 | '''
9. Write a Pandas program to draw a horizontal and cumulative histograms
plot of opening stock prices of Alphabet Inc. between two specific dates.
'''
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet-stock-data.txt")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime(... |
ebebdc38e2e5f43c53bee8a800882b1e556c432d | ErenBtrk/Python-Fundamentals | /Python Object & Data Structures/10-Format.py | 349 | 3.90625 | 4 | name = "Yarasa"
surname = "Reis"
age = 99
print("My name is {0} {1}".format(name,surname))
print("My name is {1} {0}".format(name,surname))
print("My name is {} {} and I am {} years old".format(name,surname,age))
print(f"My name is {name} {surname} and I am {age} years old")
result = 200 / 700
print('the result is {r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.