blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3653fb07ef390ea208e4ab92336efeb713f24d67 | vishal-nirne/DAA-LAB-WORK | /lab8/HuE.py | 2,000 | 3.515625 | 4 | import heapq as heapq
import collections
G=[]
class Node:
def __init__(self,freq,sym):
self.freq=freq
self.sym=sym
self.left=None
self.right=None
def __lt__(self,other):
return self.freq<other.freq
def printCode(root,s):
if root.left==None and root.right==None:
print(root.sym,":",s)
G.append([root.s... |
09fe8746d378e21a5ddbffc69dd5baa4239b74d4 | CMU-A-Data-Science-Club/olpy | /olpy/classifiers/pa.py | 2,745 | 3.625 | 4 | import numpy as np
from numpy import linalg as LA
from . __base import OnlineLearningModel
class PA(OnlineLearningModel):
"""Passive-Aggressive Model.
Crammer, K. et al., Online Passive-Aggressive algorithms,
Journal of Machine Learning Research, 106, 7, 551-585
Attributes:
num_iterat... |
7742c9b11a532fad176711500706fd74f53cfe48 | panjialpras/git2 | /Code/Py/for while 2.py | 592 | 3.78125 | 4 | # 7
# for i in range(7):
# print("Python")
# 20
# for i in range(21) :
# print(i)
# menu = 0
# while (menu !=5):
# menu = int(input("Masukkan menu 1 s.d 5: "))
# print("Menu yang Anda pilih =", menu)
# print("Anda telah keluar dari menu")
# ulang = 100
# for i in range(ulang):
# print("Per... |
36f6e8bcdcdd15aca5207f1a2d6f82338f821464 | panjialpras/git2 | /Code/Py/for while.py | 743 | 3.640625 | 4 | # i = 4
#while (i<40):
# print(i)
# i=i+4
#else :
# print("Perulangan anda telah selesai")
# n = int(input("Masukkan jumlah bintang yang ingin ditentukan:"))
# for i in range(1,n+1) :
# print("*"*i)
#i = 15
#while(i>=0) :
# print(i)
# i=i-1
#else:
# print("Perulangan telah selesai")
#data = i... |
6d5147ff3b05dcb211e2044540af222e1011fe9c | panjialpras/git2 | /Code/Py/procedure.py | 1,037 | 3.5625 | 4 | import os
def clear () :
os.system("cls")
def ulang () :
ulang = str(input("Ingin menghitung lagi? y/n : "))
if ulang == "y":
menu ()
else :
"Anda telah keluar"
def persegi (a, b) :
x = a * b
print ("Hasil", x)
ulang ()
def segitiga (c, a, b) :
y = 1/2 * a * b
prin... |
58bcf36bf52f03a3b673682c2c5feb867f133f95 | panjialpras/git2 | /Code/Py/kuis 1.py | 1,685 | 3.734375 | 4 | # Panji Al Muqsith Prasetyo
# 5200411249
menu = [["Baju", 120000], ["Kaos", 80000], ["Celana pendek", 100000], ["Celana Panjang", 150000], ["Jaket", 250000],["Rok",60000]]
def daftar_barang():
print(" No | Nama Barang | Harga ")
i = 1
for item in menu:
print(" " + str(i) + " |" +... |
98c61a90a62c31a2bcaa636719bece9085338f02 | boynikova/decode | /hill_cipher.py | 4,001 | 3.78125 | 4 | from string import ascii_lowercase
import numpy as np
from fractions import gcd
'''
encode/decode messages using the Hill cipher.
usage:
ciphertext, key = hill_cipher_encode('secret message')
plaintext, key = hill_cipher_decode(ciphertext, key)
'''
def hill_cipher_encode(message, key = None,
block_size = 4, a... |
da7cdf633beed9bb53385667fac128dbd49910cc | marcosD67/HackerEarth | /JanCircuits2021/equal.py | 2,109 | 3.71875 | 4 | #Result: 100/100
#Solved: 155:02:46
#Count inversions (if they're both the same parity, then YES)
# However, if they have a character in common (occurence > 1) then it's always YES
# If none of the rules above apply, then NO
def mergeSort(arr, n):
temp_arr = [0]*n
return _mergeSort(arr, temp_arr, 0, n-1)
... |
073ea46532f0ee61c27256fc5226bab7eb30255f | Runtime-Learner/McGill-BattleBots-Club | /Workshops/Workshop-3/calculate-resistances.py | 1,389 | 4.0625 | 4 | import itertools
# Python program to get equivalent resistance
def getEquivalentR(myList) :
# Multiply elements one by one
result = 0
for x in myList:
result = result + 1/x
return 1/result
###############################################################
#get resistances that will ... |
57a5263d997419cb45ca61b4b24c3b676193b734 | voraparth1337/System-Programming-and-Compiler-Construction-Solutions | /lexical analyser/lexical_analyser.py | 3,702 | 3.71875 | 4 | # Written by Parth V
# Disclaimer : I am no expert in python, just a learner. In no way is this code perfect or the most 'pythonic' implementaion
# It was written for practice and understanding the concepts. Feel free to extend it or make it better. Cheers !!
# www.parthvora.tk
# Implementation of a lexical an... |
cea87f3e30969f6878fc1715edc08df02a56b398 | DanishHudani/Client-Server-Calculator | /Client.py | 1,270 | 3.859375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#importing socket module of python
import socket
# In[2]:
#creating a socket object named client
client = socket.socket()
# In[3]:
#if client object has been created then print the message and client contents.
if client:
print("Socket created successfully!",... |
4bae30b9221c421b1fca167b1a0f00783ab290b5 | ishanzo/exam_one_take_two | /donuts.py | 1,316 | 4.25 | 4 | # Create a function to help Mr. James plan for a donut celebration
arr = [90,80,66,75,88]
def donut_celeb(arr):
## Input: Exam Scores for all students
# Conditions
for avg in arr:
add = sum(arr)
average = add/len(arr)
print(average)
## Output: How many donuts
donuts = len(ar... |
f295f88f12b71047ccaa0eb3698a467a4ef5f56b | arina773/p_test | /app.py | 3,304 | 3.625 | 4 | from flask import Flask, render_template
app = Flask(__name__)
result = ''
@app.route("/")
def start():
text = """1. You are totally exhausted because your week was endless and less than great. How are you going to spend
your weekend? """
choices = [
('','second_q', 'E', """"I'll call my friend... |
494a65f52da5456030816c5dde8b6f035df22346 | emptyHeap/study | /stepic/python/usage/2.2.1.py | 195 | 3.640625 | 4 | import datetime
date = datetime.datetime(*[int(i) for i in input().split()])
dif = datetime.timedelta(days = int(input()))
newdate = (date + dif)
print(newdate.year, newdate.month, newdate.day)
|
a10d082183a11fa982dc23b2e4410b6323ddc194 | nageshnnazare/PythonDataStructures | /Queue/2.QueuePyListsSizeLimit.py | 2,158 | 4 | 4 | """
DESC: Queue Implementation using Lists with size limit (Circular Queue)
Author: Nagesh N Nazare
Date: 13-08-2021
"""
class Queue:
def __init__(self, max_size):
self.items = max_size * [None]
self.max_size = max_size
self.start = -1
self.top = -1
def __str__(self):
... |
78b919c6a08d28c27460e0b0a3df4e74d347da2f | nageshnnazare/PythonDataStructures | /Recursion/6.decTobin.py | 638 | 4 | 4 | """
DESC: Convert a decimal number into binary
Author: Nagesh N Nazare
Date: 31-05-2021
RUN:
python3 ./6.decTobin.py
NOTE:
decTobin(13):
13/2 = 6, rem = 1
6/2 = 3, rem = 0
3/2 = 1, rem = 1
1/2 = 0, rem = 1
d'13 = b'1101
METHOD:
decTobin(n) = n mod 2 + 10 * decTobin(n/2)
OUTPUT:
The decimal form of the number is... |
6671cb93b77776193a8a1f0d7bb3b928a1e711ea | nageshnnazare/PythonDataStructures | /LinkedList/Examples/1.RemoveDuplicates.py | 1,300 | 3.875 | 4 | """
DESC: Remove Duplicates from the Linked List
Author: Nagesh N Nazare
Date: 09-08-2021
"""
from LinkedList import LinkedList
# using a temporary buffer
def removeDuplicates_1(linkedList):
if linkedList.head is None:
return
else:
currentNode = linkedList.head
visited = set([current... |
c1b56e0498071b05f897d1d6d483c1227e23fdcc | sihyeonn/Sunday | /Python/모두의 파이썬/15A-typing.py | 607 | 3.8125 | 4 | import random
import time
wordList = ["cat", "dog", "fox", "monkey",
"mouse", "panda", "frog", "snake", "wolf"]
print("[Typing Game] Press the enter key if you are ready.")
input()
start = time.time()
for n in range(1, 5+1):
question = random.choice(wordList)
print("\n*Question", n)
print(qu... |
941c69c9c771a59c59336ff39d690a1a2aff21dc | crazyalok/TikTakToe | /functions.py | 4,088 | 3.75 | 4 | def check_col(a,b,c) :
for i in range(3) :
if a[i]==b[i]==c[i] :
print a[i] , " winner"
return 1
else :
return 0;
def check_row(a,b,c) :
for i in range(1):
if a[i]==a[i+1]==a[i+2] :
print a[i] , " winner"
... |
c0d0d0a2152796e9ec33a6a6ea9a4e72c1c8b5ee | amirayehia/Equalizer-task2 | /dsp_task3/plot.py | 2,103 | 4.15625 | 4 | # import matplotlib.pyplot as plt
# # line 1 points
# x1 = [1,2,3]
# y1 = [2,4,1]
# # plotting the line 1 points
# plt.plot(x1, y1, label = "line 1")
# # line 2 points
# x2 = [1,2,3]
# y2 = [4,1,3]
# # plotting the line 2 points
# plt.plot(x2, y2, label = "line 2")
# # naming the x axis
# plt.xlabel('x - axi... |
52fe878e52b7e014a6b65af8978ae648a6c2bb26 | salilnaik/FBLA-coding-and-programming-2020 | /main.py | 17,919 | 3.828125 | 4 | from tkinter import *
import csv
from tkinter import messagebox
from tkinter import ttk
current_index = 0
current_id = 0
current_student = ""
current_grade = 0
current_hour = 0
current_community = 0
current_service = 0
current_achievement = 0
student_info = []
sorted_rev = False
sorted_ = False
# C... |
fb8de09b074213413800c9b62234f15d1644fc9d | Nearlybird/05-circle-area | /circle_area.py | 307 | 4.21875 | 4 | # TODO: DEFINE a function using the def keyword called `area_of_circle`
# TODO: implement the function to RETURN (NOT PRINT) the area of a circle whose radius is r
# HINT: You'll need to import math to solve this problem correctly.
import math
def area_of_circle(r):
a = math.pi * (r**2)
return a
|
51a0b835e8ce697a9ee829e8e3800f3a000a6675 | Wolfgang89/Python101 | /graph.py | 1,968 | 3.765625 | 4 |
from collections import deque
# 图 中 反映映射关系 使用散列表
# python 中的缩进必须要严格注意
graph = {}
graph ["you"] = ["alice","bob","claire"]
graph ["bob"] = ["anuj","peggy"]
graph ["claire"]= ["thom","jhon"]
graph ["alice"] = ["peggym","mary","man"]
graph ["thom"] = []
graph ["peggy"] = []
graph ["jhon"] = []
graph ["anuj"] = []
gra... |
a5ea87ce35606685b53398aad025529c6ba80a57 | romanpindela/keymaker-progbasic-python-codecool | /keymaker.py | 3,485 | 4.125 | 4 | import string
def shift_characters(word, shift):
"""
>>> shift_characters('abby', 5)
'fggd'
"""
alphabet = string.ascii_lowercase
alphabet_lenght = len(alphabet)
shifted_word = []
for letter in word:
shifted_letter = alphabet[(alphabet.index(letter)+shift) % alphabet_lenght]
... |
d45ddf14637c95e6b28172a04600b02472d511a0 | HavrylenkoM/hw | /hw3/stud.py | 431 | 3.765625 | 4 | import random
students = ['Anton', 'Gleb', 'Masha', 'Katya', 'Dima', 'Vasya', 'Petya']
stud_dict = {}
for student in students:
stud_dict[student] = []
for j in range(1,11):
stud_dict[student].append(random.randint(1,5))
print(stud_dict)
for name in stud_dict:
print ("student {name} has average mark ... |
6e72f163df52a83de6f10fb78b9c65b2595e0b4c | AUniyat/Bank_Account_App | /Bank Account.py | 4,475 | 4.34375 | 4 | __author__ = 'ALEX'
#A Bank Account App that has deposit, withdraw, and account creation functions
import BankAccountFiles #importing the python file with some necessary functions
#The function that runs at the start of the program and asks what the user wishes to do
def start_bank_app():
print "Welcome to Alex's ... |
ed3df3c21f2cb993d22a05c0464f4da09f8cdf5e | adclleva/Python-Learning-Material | /automate_the_boring_stuff_material/02-Flow-Control/if_example.py | 295 | 4.03125 | 4 | name = 'Alice'
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
#blocks and clauses
# Blocks begin when the indentation increases.
# Blocks can contain other blocks.
# Blocks end when the indentation decreases to zero or to a containing block’s indentation. |
a5c88b8449b661ebe0ccac0fb64296a9958b0096 | adclleva/Python-Learning-Material | /automate_the_boring_stuff_material/02-Flow-Control/while_example.py | 358 | 3.96875 | 4 | spam = 0
if spam < 5:
print('Hello, world.')
spam = spam + 1
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
# input validation
# break statements breaks out of the loop
# continue statements goes back to the loop
spam = 0
while spam < 5:
spam += 1
if spam == 3:
cont... |
f8c64ee617bfc944f23c3330d3e6e37524625150 | nikzayn/Full-Stack-Web-Developer-I-Nanodegree-Program-udacity | /triangles.py | 866 | 3.953125 | 4 | import turtle
def turtle_triangle(some_turtle):
for i in range(1,3):
some_turtle.forward(100)
some_turtle.left(120)
def turtle_triangle1(some_turtle1):
for i in range(1,3):
some_turtle1.forward(40)
some_turtle1.left(120)
def turtle_triangle2(some_turtle2):
for... |
367ceee9ec3857192f43dfd4ec98d22e10a15248 | bashbash96/InterviewPreparation | /LeetCode/Facebook/Medium/29. Divide Two Integers.py | 2,432 | 4.03125 | 4 | """
Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.... |
fe5e7241ad2c2ba7ba6f1ae1d1ad863c91040cf3 | bashbash96/InterviewPreparation | /LeetCode/Facebook/Hard/76. Minimum Window Substring.py | 2,598 | 4.15625 | 4 | """
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".
The testcases will be generated such that the answer is unique.
A substrin... |
9e217ccb7490d668609091a0b7ccb8b6251416af | bashbash96/InterviewPreparation | /InterviewBit/Heaps.py | 1,950 | 4.0625 | 4 | # -----------------------------------------------------------------------
"""
Merge K Sorted Lists
Merge k sorted linked lists and return it as one sorted list.
Example :
1 -> 10 -> 20
4 -> 11 -> 13
3 -> 8 -> 9
will result in
1 -> 3 -> 4 -> 8 -> 9 -> 10 -> 11 -> 13 -> 20
"""
# Definition for singly-linked list.
#... |
72675d47ea59a73034b4a4eb56a60e1b9112df7f | bashbash96/InterviewPreparation | /Cracking The Coding Interview/TreesAndGraphs.py | 22,639 | 4.1875 | 4 | import sys
import random
# ------------------- Linked List Trees ------------------
class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class Node2:
def __init__(self, data):
self.data = data
self.next = None
# ------------... |
04087b9b34ddefbd17676e58cf0b1c35d2fa937a | bashbash96/InterviewPreparation | /LeetCode/Facebook/Medium/986. Interval List Intersections.py | 2,074 | 3.96875 | 4 | """
You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
A closed interval [a, b] (with a < b) denotes the set... |
0e2e8b1dbe4bf9291c8ae73f461a47b1cfe1ab37 | bashbash96/InterviewPreparation | /LeetCode/Facebook/Medium/43. Multiply Strings.py | 1,742 | 4.125 | 4 | """
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1... |
47f3e891b5445312b8f8917761f3b384f1ea2507 | bashbash96/InterviewPreparation | /InterviewBit/BackTracking.py | 4,939 | 3.8125 | 4 | # -----------------------------------------------------------------------
"""
A
ll Unique Permutations
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example :
[1,1,2] have the following unique permutations:
[1,1,2]
[1,2,1]
[2,1,1]
NOTE : No 2 entries in the ... |
1f88588f90724714a7aedc1de10b7331c44bcd24 | bashbash96/InterviewPreparation | /LeetCode/easy.py | 86,890 | 3.96875 | 4 | import collections
import heapq
# -----------------------------------------------------------------------
"""
198. House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed,
the only constraint stopping you from robbing each of them is that adja... |
52746c7bedbc2d309977ed7b28d8c5e0a0c42365 | bashbash96/InterviewPreparation | /InterviewBit/GoogleQuestions.py | 14,859 | 3.703125 | 4 | """
Kth Row of Pascal's Triangle
Given an index k, return the kth row of the Pascal’s triangle.
Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.
Example:
Input : k = 3
Return : [1,3,3,1]
"""
class Solution:
# @param A : integer
# @return a list of integers
... |
404c9f34e859a6eecf248843475b72f734d246c5 | bashbash96/InterviewPreparation | /Cracking The Coding Interview/Hard.py | 13,984 | 4.34375 | 4 | # -----------------------------------------------------------------------
"""
17.1 Add Without Plus: Write a function that adds two numbers. You should not use + or any arithmetic
operators.
"""
def add(num1, num2):
if num2 == 0:
return num1
curr_sum = num1 ^ num2
carry = (num1 & num2) << 1
... |
a42248de96621509aaa514e8065c311ecd3cdfbb | bashbash96/InterviewPreparation | /LeetCode/Facebook/Medium/161. One Edit Distance.py | 2,199 | 3.875 | 4 | """
Given two strings s and t, return true if they are both one edit distance apart, otherwise return false.
A string s is said to be one distance apart from a string t if you can:
Insert exactly one character into s to get t.
Delete exactly one character from s to get t.
Replace exactly one character of s with a dif... |
c394aeb231a1ae8643aae44937cbddff11751874 | bashbash96/InterviewPreparation | /LeetCode/Facebook/Easy/680. Valid Palindrome II.py | 1,423 | 3.953125 | 4 | """
Given a string s, return true if the s can be palindrome after deleting at most one character from it.
Example 1:
Input: s = "aba"
Output: true
Example 2:
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c'.
Example 3:
Input: s = "abc"
Output: false
Constraints:
1 <= s.length <= ... |
34a6efaaf2fb44a7333b253b2378ecfc28faa475 | bashbash96/InterviewPreparation | /InterviewBit/DP.py | 17,823 | 3.75 | 4 | # -----------------------------------------------------------------------
"""
Max Rectangle in Binary Matrix
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.
Bonus if you can solve it in O(n^2) or less.
Example :
A : [ 1 1 1
0 1 1
1... |
9787a1faf583b229b70e0da53ae75aad7275300d | codingXllama/TicTacToe | /TicTacHoe.py | 2,332 | 3.78125 | 4 | import random
board = ["☐", "☐", "☐",
"☐", "☐", "☐",
"☐", "☐", "☐"]
# board = range(0, 9)
def show_board():
print(board[0], "|", board[1], "|", board[2], "|")
print("- - " * 3)
print(board[3], "|", board[4], "|", board[5], "|")
print("- - " * 3)
print(board[6], "|", board[7], ... |
b066fa760ed4533d133c2a5b34f26f5187f32a57 | VladOsiichuk/python_base_public | /lesson_11/classes_1.py | 904 | 4.09375 | 4 | class Human:
def __init__(self, age, name, sex):
"""
Метод з ім`ям __init__ автоматично викликається, коли ми створюємо об'єкт.
В даному методі створюють поля об'єкта і присовуюють їм значення.
У кожному методі класу першим обов'язковим аргументом є self. self вказує на самого себе (... |
8788f0fec153d954f11446f43311efc44b9e4857 | VladOsiichuk/python_base_public | /lesson_5/nested_arrays.py | 604 | 3.859375 | 4 | columns = int(input("Введіть к-сть стовпчиків матриці: "))
rows = int(input("Введіть к-сть рядків: "))
matrix = []
for row_index in range(columns):
matrix.append(list())
for column_index in range(rows):
print(row_index, column_index)
value = int(input(f"Введіть значення [{row_index}][{column_in... |
4bca4d70532c405363a5f0b22fd17de6db557c0a | VladOsiichuk/python_base_public | /lesson_9/dict_usage_example.py | 509 | 3.890625 | 4 | def get_answer(prompt=""):
"""
:param prompt: Some question
:return: Get Yes or Not answer from user. returns True or False
"""
prompt += "?" if prompt.endswith("?") else ""
answers = {
"yes": True,
"no": False
}
while True:
user_input = input(f"{prompt} (Yes/No)... |
af00fcd5485a464792b0ac2c58c9a15549db4e57 | VladOsiichuk/python_base_public | /lesson_10/decorators_1.py | 894 | 3.875 | 4 | import os
def file_exists(get_data_from_file):
def wrapper(file_path):
"""
file_path - це аргумент, який приймає функція, що була огорнута
даним декоратором
Тобто це аргумент, що був переданий у рядку 30 у функції main
"""
if os.path.exists(file_path):
... |
cde1278e596c44102f9cf5daff0ec2d062c03aaf | VladOsiichuk/python_base_public | /lesson_2/quest_5.py | 423 | 3.984375 | 4 | def main():
first_number = float(input("Enter first number: "))
print("Квадрат числа:", first_number ** 2)
print("Корінь числа:", first_number ** 0.5)
second_number = float(input("Enter second number: "))
print("Остача від ділення:", first_number % second_number)
print("Частка:", first_number... |
341c059d21ad8347cc2bf21addec6dc981f67887 | VladOsiichuk/python_base_public | /lesson_10/main.py | 389 | 3.5625 | 4 | # as simple string
import json
def get_json_from_file():
with open("test.json", "r") as f:
result = json.loads(f.read())
return result
d = get_json_from_file()
# d = {"1": 1}
print(type(d))
print(d)
key = input("new enter key ")
pas = input("new enter pas ")
d.update({key: pas})
# save(writen) in... |
1538cb61c41dca7d17dc29c2f8dacc9b62b8547b | VladOsiichuk/python_base_public | /lesson_10/function_object_example.py | 2,652 | 3.59375 | 4 | from actions import show_list_of_articles, add_article, remove_article
ADMIN_CREDENTIALS = {
"username": "admin",
"password": "1234567"
}
EDITOR_CREDENTIALS = {
"username": "Editor",
"password": "123"
}
VISITOR_CREDENTIALS = {
"username": "Visitor",
"password": "11"
}
def get_admin_actions():
... |
3842378b626f662c54c73a5c35cadc276efbb776 | VladOsiichuk/python_base_public | /lesson_7/string_is_int.py | 347 | 4.1875 | 4 |
s = input("Enter number")
if s.isdigit():
print("entered value is number")
else:
print("entered value is NOT a number")
def get_int():
while True:
value = input("Enter a number: ")
if value.isdigit():
return int(value)
else:
print("Entered value is incorre... |
4206f808de54f1bedf62a684ce6e0636719851af | RxDx/playfair | /cifrador.py | 4,456 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
def constroiListaAlfabeto():
alfabeto = "abcdefghiklmnopqrstuvwxyz"
lista = []
for letra in alfabeto:
lista.append(letra)
return lista
def normalizaTextoOriginal(textoOriginal):
posicaoAtual = 0
novoTexto = ""
texto... |
017765356b612580ce531299986caffd5472a9bc | sberthely/D06 | /HW06_ch09_ex03.py | 3,443 | 4.40625 | 4 | #!/usr/bin/env python3
# HW06_ch09_ex03.py
# (1)
# Write a function named avoids that takes a word and a string of forbidden
# letters, and that returns True if the word doesn't use any of the forbidden
# letters.
# - write avoids
# (2)
# Modify your program to prompt the user to enter a string of forbidden
# letter... |
e1ab8cd661608735a0d3865c317cd610f10e69cd | allisongorman/LearnPython | /ex5.py | 796 | 3.75 | 4 | name = 'Allison M. Gorman'
age = 26
height = 72 # inches
weight = 150 #pounds
centimeters_per_inch = 2.54
kilograms_per_pound = 0.453592
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "She's %d inches tall." % height
print "She's %d pounds heavy." % weight
print "A... |
d4ee7cacb4e7674b33ca5fc5b899c0a71c3a3f60 | neutronest/owiki | /src/test.py | 685 | 3.859375 | 4 | #-*- coding:utf-8 -*-
class tiantong(object):
val = "456"
def __init__(self):
self.v = "123"
return
def change_val(self):
self.val = "4567"
class Trainer:
inputs = [0, 0, 0, 0, 0]
def __init__(self, x, y, a):
self.inputs = [0, 0, 0]
self.inputs[3] = 42
... |
024f9eba809cc8d806ff8c81223c0a92acce35f7 | amirkazi/dockless-bikes | /postgres_connection.py | 1,048 | 3.5 | 4 | '''
24th August 2018
File contains function to append data from dataframe to a Postgres database
table
'''
import pandas as pd
from sqlalchemy import create_engine
import psycopg2
username = ''
password = ''
host = ''
port = ''
database = ''
dataframe = df
table_name = ''
def pushing_dataframes_to_postgres(u... |
d90ba9490710b1754cd6c940cd5e2d840dcca5e9 | 6democratickim9/python_basic | /mycode/pythonic/compre.py | 138 | 3.59375 | 4 | words = 'Arguments are made by me and you so we should solve it'.split()
for word in words:
print(word)
for w in words:
print(w) |
fa99eaeb68d3b5923a0c398194bcd7d5cff5f614 | 6democratickim9/python_basic | /matplotlib_examples/error_catch.py | 138 | 3.75 | 4 | rice = input("Enter the price: ")
try:
price = float(price)
print('Price =', price)
except ValueError:
print('Not a number!')
|
e0d3797b42c964bf5e087050e789dbe5e25d61a9 | 6democratickim9/python_basic | /exercise/midterm_score.py | 434 | 3.5 | 4 | kor_score=[49,79,20,100,80]
math_score=[43,59,85,30,90]
eng_score=[49,79,48,60,100]
midterm_score=[kor_score,math_score,eng_score]
student_score = [0,0,0,0,0]
student_score_avg=[0,0,0,0,0]
idx=0
for key in midterm_score:
for val in key:
student_score[idx]+=val
idx+=1
idx=0
# for i in student_scor... |
8d34b8e7422e857faefedb3a2a20c59ee5ed5ade | SpenDallas/NQueens | /NQueens.py | 4,765 | 3.734375 | 4 | import secrets
import time
def main():
# initial variables
# board dimensions / number of queens
x = 16
# maximum number of queen movements allowed
max_steps = 10000000000000
# time variables
endTime = time.time()+20
# x by x board with x queens randomly placed
board... |
e46a04f86626d470ac4b4a880f05648fd92130a1 | veeteeran/bookBook | /functions/setup_matrices.py | 6,685 | 3.65625 | 4 | #!/usr/bin/env python3
"""
Defines functions to create initial pivot table and
transform that pivot table into Numpy ndarrays and Pandas DataFrame
"""
import numpy as np
# import pandas as pd
def pivot_table(ratings_list):
"""
Creates a pivot table with users as rows and books as columns
parameters:
... |
78c556123d3dc0faed3b252fdeb7c63a989e4443 | depas98/modern_python_3_bootcamp | /ascii_art.py | 707 | 3.90625 | 4 | import pyfiglet
from termcolor import colored
from termcolor import COLORS
# help(pyfiglet)
msg = input("what message do you want to print? ")
color = input("what color? ").upper()
if color not in pyfiglet.COLOR_CODES:
color = "GREEN"
pyfiglet.print_figlet(msg, 'standard', color)
# another way to do it
color =... |
5e89c75bc6356f4bbb5b15ea9f17caab8c9969ac | depas98/modern_python_3_bootcamp | /bank_account_class_ex.py | 449 | 3.546875 | 4 | class BankAccount:
def __init__(self, owner):
self.owner = owner
self.balance = 0.0
def get_balance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
mike_account = BankAccount("mi... |
9c7b79d89a3763b4f1e6326f3c8fbedfc76e7f7b | depas98/modern_python_3_bootcamp | /fib_calculate.py | 2,780 | 4.3125 | 4 | from math import sqrt
def calculate_fibonacci(index):
if index < 0:
raise ValueError("Index values need to be positive")
if index == 0:
return 0
if index < 3:
return 1
return calculate_fibonacci(index - 2) + calculate_fibonacci(index - 1)
def calculate_fibonacci2(index):
... |
1486f00d1de02af99e42fccd64dd52c3c4b61856 | prkuna/Python | /21_Split_Multi_Input.py | 1,202 | 4.125 | 4 | text = 'geeks for geeks'
# splits at space
print(text.split())
word = 'geeks, for, geeks'
# splits at ','
print(word.split(','))
word = 'geeks:for:geeks'
# split at ':'
print(word.split(':'))
word = 'CatBatSatFatOr'
# split at 3
print([word[i:i+3] for i in range(0,len(word),3)])
print()
"""
"""
... |
e25350cbc1ce5915203bb0de1bbbcbeb0906e233 | prkuna/Python | /34_Operator_Functions1.py | 3,701 | 4.75 | 5 | # importing operator module
import operator
# Initializing variables
a = 4
b = 3
# 1. add(a, b) :- This functions returns addition of the given arguments.
# Operation – a + b.
# using add() to add two numbers
print ('The addition of numbers is : ',end='');
print (operator.add(a, b))
# 2. sub(a, b) ... |
0fc8e8ae08fc286d3cddc828bfab9d1d99792bb7 | prkuna/Python | /07_Selection.py | 165 | 3.984375 | 4 | # selection statement
num1 = 34
if(num1>12):
print("Num1 is good")
elif(num1>35):
print("Num2 is not gooooo....")
else:
print("Num2 is great")
|
bc5990afe7c21de2238c7c411be28d4622bfcda6 | divyanemuri/SmartInternz-IoT-Externship-2021 | /Smart Home security codes/facedetectioncode.py | 933 | 3.515625 | 4 | import cv2
import numpy as np
face_classifier=cv2.CascadeClassifier("haar-face.xml")
#It will read the first frame/image of the video
video=cv2.VideoCapture(0)
while True:
#capture the first frame
check,frame=video.read()
gray=cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#detect the faces fr... |
5db0cc8d69196ac38869c4f4a03d88a342629815 | miss-jain-16/Array-Problems | /decreasingfrequency.py | 511 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 10 22:38:30 2019
@author: Lavi
"""
# Python code to demonstrate
# sort list by frequency
# of elements
from collections import Counter
ini_list = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]
# printing initial ini_list
print ( ini_list)
# sorting on ba... |
f1b9c44a124e5455076441cf55a54ef82828ab08 | DCA-28/UriCodes | /Data-Structures-And-Libraries/Python/URI-2091.py | 462 | 3.53125 | 4 | def main():
while True:
numbers = int(input())
if numbers == 0:
break
values = input().split()
values_dict = {}
for value in values:
try:
values_dict[value] += 1
except KeyError:
values_dict[value] = 1
... |
556f6b516801efb75bced257a1bccd34fefbaf10 | DCA-28/UriCodes | /Ad-Hoc/Python/URI-1105.py | 906 | 3.6875 | 4 | #hereafter implement OOP
def balance(a,b,c):
reserves[a-1] -= c #debtor reserve
reserves[b-1] += c #credor reserve
banks, debentures = input().split()
banks = int(banks)
debentures = int(debentures)
results = []
while(banks + debentures != 0):
reserves = []
need_loan = False
monetary_r... |
8b1b1b5c4cfe5f53a99bd6a08a735406c8726f51 | DCA-28/UriCodes | /Ad-Hoc/Python/URI-1089.py | 1,237 | 3.8125 | 4 | def loop(samples, values):
n = samples
vector = values
peaks = 0
countedPeaks = []
magnitude = []
#creating my magnitude sequence to find peaks
magnitude.append(vector[n-1])
for i in range(0, n):
magnitude.append(vector[i])
magnitude.append(vector[0])
#vector to find ... |
17e631ae0223e64ff1ad1dd576f09ba10ec66d83 | DCA-28/UriCodes | /Data-Structures-And-Libraries/Python/URI-1022.py | 1,884 | 3.59375 | 4 | from fractions import gcd
def value(N1, D1, N2, D2: int, operation: chr) -> int:
if operation == "+":
first_term = N1 * D2 + N2 * D1
second_term = D1 * D2
elif operation == "-":
first_term = N1 * D2 - N2 * D1
second_term = D1 * D2
elif operation == "*":
first_term ... |
d2f2d08879eccb4bdca27296588f6d953e3a3aad | dmonisankar/pythonworks | /the_basics/read_file1.py | 462 | 3.5 | 4 | # myfile = open("C:/Moni/PythonWorks/the_basics/fruits.txt")
# content = myfile.read()
# myfile.close()
# print(content[:10])
def str_count(character, filepath):
# myfile = open(filepath)
# content = myfile.read()
# myfile.close()
with open(filepath) as myfile :
content = myfile.read()
re... |
9f48a5ca7dc44bed0befa144df7654c4dd357555 | dmonisankar/pythonworks | /the_basics/test9.py | 323 | 3.890625 | 4 | phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for key, value in phone_numbers.items():
print("{} has as phone number {}".format(key, value))
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
for number in phone_numbers.items() :
print(number[... |
519bbfc3252fd118b41cf573ae827da7aea81933 | dmonisankar/pythonworks | /the_basics/test6.py | 442 | 4.125 | 4 |
def say_hi(name):
message = "Hi " + name.capitalize()
return message
name = input("Enter your name:")
surname = input("Enter your surname:")
#message = "Hello %s %s" % (name,surname) # works in all version of python
#message = "Hello %s " % user_input
#message = f"Hello {user_input}" # only works for python... |
956d00679adf9485fdf6b9fb90403047b78a0704 | dmonisankar/pythonworks | /the_basics/test2.py | 404 | 3.9375 | 4 | def mean(value):
#if type(value) == dict : # this is also another way of checking
if isinstance(value, dict):
the_mean = sum(value.values())/len(value)
print("inside if")
else:
print("inside else")
the_mean = sum(value)/ len(value)
return the_mean
student_marks = {"joy... |
3e0f0f48eed889eafc5deae5db9ed2c35fbe28a5 | dmonisankar/pythonworks | /DataScienceWithPython/sample_python_code/statistic/stat8.py | 367 | 3.5 | 4 | # example of box plot
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
df = pd.read_csv('iris.csv')
# df1= df.loc[df['species'] =='versicolor']
# versicolor_petal_length = df1['petal_length']
_= sns.boxplot(x='species', y='petal_length', data=df)
_ = plt.xlabel('specie... |
09a414069e8c5b9a4ceb796266b693f3fef1b42c | dmonisankar/pythonworks | /DataScienceWithPython/sample_python_code/iteration/zip_lesson2.py | 730 | 3.515625 | 4 | mutants = ['charles xavier','bobby drake', 'kurt wagner','max eisenhardt','kitty pride']
aliases =['prof x', 'iceman', 'nightcrawler', 'magneto', 'shadowcat']
powers = ['telepathy','thermokinesis','teleportation','magnetokinesis','intangibility']
# Create a zip object from mutants and powers: z1
z1 = zip(mutants,... |
a3238ec2b34187580376e8c0bf5883710f39d64b | Chronographer/DampedAndDrivenSHM | /animated_pendulum.py | 3,710 | 4.03125 | 4 | """Make a VPython simple pendulum with pedestal and stand.
Moving system is ball attached to (potentially massive) bar.
This is a modified version of a piece of example code provided by Dr. Cancio in the PHYS336 Computational Physics course
at Ball State University during the spring 2020 semester.
"""
from vpython imp... |
af4c0964d9c64d203f37ec73d213792a87a87740 | Piyushvishnoi/python-beginners | /if-else/if-else.py | 173 | 3.734375 | 4 | is_cold = True
is_hot = False
if is_hot:
print("Very Hot")
elif is_cold:
print("Very cold")
else:
print("Not cold")
|
8db67649717edc122e3f0016e76d7125fbbca76b | Piyushvishnoi/python-beginners | /type conversion/int to string/typeconversion.py | 129 | 3.703125 | 4 | birth_year = input('Enter year of Birth: ')
print(type(birth_year))
age = 2019 - int(birth_year)
print(type(age))
print(age)
|
db254ed889b5948feda20aa66eb966541ca406f7 | wangpatrick57/leetcode | /groupAnagrams.py/sol.py | 1,476 | 3.5 | 4 | class Solution:
def groupAnagrams(self, words: [str]) -> [[str]]:
processed_words = []
groups = []
for word in words:
processed_words.append(self._process(word))
for word in processed_words:
found_group = False
for group in groups:
... |
cc9db148a84d84832619838662350148a650dc10 | wangpatrick57/leetcode | /addTwoNumbers/direct_add_sol.py | 1,215 | 3.859375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
curr_... |
d1b02cc91b1a62f94c6c5317a42b26cec8a52543 | GregGiovanniello/Converter- | /decimaltobinary.py | 390 | 4.09375 | 4 | """
program: decimaltobinary.py
converts a decimal iteger to a string of bits.
"""
decimal = int(input("Enter a decimal iteger: "))
if decimal == 0:
print(0)
else:
print("Quotent remainder binary")
bstring = ""
while decimal > 0:
remainder = decimal % 2
decimal = decimal // 2
bstring = str(rema... |
b3dec043af36109069bedfd03dbd9712f41acc3e | timothythiecke/ComputerVisieProject | /Modules/highgui.py | 2,163 | 3.78125 | 4 | import cv2
from Modules import colors
def loadImage(imagePath):
"""
Loads and returns an image
Parameters
----------
imagePath : string
The absolute or relative path pointing to an image.
Returns
-------
The image
"""
return cv2.imread(imagePath)
def creat... |
26e4c7a82419e36f36147e3c59538f856548b71b | rajpande111/Python-codes | /Dictionary_List_Functions.py | 514 | 3.796875 | 4 | #Dictionary
di = {'Raj':'Pvg','Avi':'Sinhgad','Shreemay':'Pccoe'}
print di
#Updation of Dictionary (Enter value of s in quotes)
s = input("Enter new entry for Raj:")
di['Raj'] = s
#Updated Dictionary
print di
#Lists
print "List created"
li = ['raj','avi','shree','karan']
print li
print "extend function on list"
print "... |
8d4babecfba87bf84f17d550f6726dbdaa4bf2f0 | wsramen/report_0306 | /leapYear.py | 400 | 3.6875 | 4 | #-*- coding: utf-8 -*-
def LEAP_YEAR(n):
if (n % 4 == 0) & (n % 100 == 0) & (n % 400 == 0):
a="윤년"
elif (n % 4 == 0) & (n % 100 == 0):
a="평년"
elif (n % 4 == 0):
a="윤년"
else:
a="평범한년"
return a
if __name__ == "__main__":
print LEAP_YEAR(1988)
print LEAP_YEA... |
f4aaa40da599a69680a57fa1e5dca2f8a598531f | richa1200/tic-tac-toe-AI | /tictactoe.py | 4,192 | 3.859375 | 4 | from random import randrange
class Player(object):
def __init__(self, symbol, isComputer):
self.symbol = symbol
self.isComputer = isComputer
def play(self, gameBoard):
if self.isComputer:
print('\nComputer\'s Turn...')
global count
depth, alpha, beta, isMax = 9-count, -10, 10, True
... |
acf26aae692d12d3a84dcd4d70dcebb7657ed442 | rashida048/Algorithms-QuickFind | /quickFind.py | 471 | 3.578125 | 4 | class QuickFind(object):
def __init__(self, N):
self.lst = list(range(N))
def find(self, a, b):
return self.lst[a] == self.lst[b]
def union(self, a, b):
old = self.lst[a]
new = self.lst[b]
for ind, x in enumerate(self.lst):
if x == old:
... |
a45ce1ba5dbf1205376572faa26ccdfec1f0b655 | trichimtrich/ctfstuffs | /LZW.py | 4,064 | 3.6875 | 4 | def compress(uncompressed):
"""Compress a string to a list of output symbols."""
# Build the dictionary.
dict_size = 256
dictionary = dict((chr(i), chr(i)) for i in xrange(dict_size))
# in Python 3: dictionary = {chr(i): chr(i) for i in range(dict_size)}
w = ""
result = []
fo... |
7cfabad3cde5009619fb26dd1d57dfdbfbda2281 | marinatic2/marinatic2 | /edad_media.py | 278 | 3.640625 | 4 | def edad_media():
menor=0
print "INTRODUCE NUMERO"
for cont in range (1,11):
print "nuevo nmero"
numero= input();
if(numero<menor):
menor=numero
print "menor",menor
edad_media()
|
507640e92f7e2d1b0208d0480605d750ecadfab8 | ultralegendary/100-days-of-code | /Day-017.py | 702 | 3.640625 | 4 | """Day 17
QUEUE
"""
#https://www.hackerrank.com/challenges/queue-using-two-stacks/problem
q=[]
for i in range(int(input())):
l=input().split()
if(l[0]=='1'):
q.append(int(l[1]))
elif l[0]=='2':
q.pop(0)
else:
print(q[0])
#https://www.hackerrank.com/challenges/truck-tour/problem
... |
2f1d36738806ccac42c63c1f3fbb2456b4df2d1d | m1258218761/Data-Structure | /Example/BinaryTree.py | 3,872 | 3.96875 | 4 | #coding=utf-8
'''包括二叉树的建立等操作以及前序,中序,后序,深度优先,广度优先遍历'''
class Node(object):
def __init__(self,value,left=None,right=None):
self.value = value
self.left = left
self.right = right
class Binary_Tree(object):
# 创建二叉树
def create(self,List):
root = Node(List[0])
lens = l... |
6ca5dc1c8cdabfd686228573188d4575461daae3 | terriwong/melon-sales-report | /accounting-new.py | 2,108 | 3.625 | 4 | SALESPERSON_INDEX = 0
INTERNET_INDEX = 1
DORKY_LINE_LENGTH = 80
def print_separate_line():
"""print dorky line as fancy style"""
print "*" * DORKY_LINE_LENGTH
return
print_separate_line()
def print_sales_summary(melon_type, melon_price):
"""given the melon type and price, counts the sold amount and r... |
404d7ab74e5823617b35fa12b92aae2d59da54ab | Satan012/Algorithms | /leetcode/24-两两交换链表中的节点/alg.py | 1,416 | 3.90625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def swapPairs(self, head):
if head is None or head.next is None:
return head
guard = ListNode(-1) # 哨兵节点
guard.next = head
sta... |
cad8869634bfe26ec78eb2d268aa13f5e520f455 | Satan012/Algorithms | /leetcode/26-删除排序数组的重复项/alg.py | 460 | 3.65625 | 4 | class Solution:
def removeDuplicates(self, nums):
length = len(nums)
if length == 0:
return 0
cur_index = 0
for i in range(1, length):
if nums[i] != nums[cur_index]:
cur_index += 1
nums[cur_index] = nums[i]
return cu... |
a79ea68efe5905fd7c9ae4ef164e09944e0cf4cd | Abishek-Git/HackerRank | /Merge the Tools-HackerRank/Merge the tools.py | 839 | 4.3125 | 4 | """
https://www.hackerrank.com/challenges/merge-the-tools/problem
HACKERRANK
Practice > Python > Strings > Merge the Tools!
------------------Athlete Sort---------------------
Sample Input
STDIN Function
----- --------
AABCAAADA s = 'AABCAAADA'
3 k = 3
Samp... |
33ddace5ee29a0d0e21b056896155a71e14cfe17 | Abishek-Git/HackerRank | /Array Mathematics-HackerRank/Array Mathematics.py | 1,830 | 4 | 4 | """
HACKERRANK
Practice > Python > Numpy > Array Mathematics
------------------Array Mathematics---------------------
Basic mathematical functions operate element-wise on arrays.
They are available both as operator overloads and as functions
in the NumPy module.
import numpy
a = numpy.... |
0fff5bde6458364856a6e51021c6403233e20cf4 | XMK233/Information-Security-Experiment | /14061075 修闽珂 第四次实验/MoChongFuPingFang.py | 1,292 | 3.65625 | 4 | #coding=utf-8
import time
#模重复平房算法
def mochongfupingfang( b, n, m):
c = '{0:b}'.format(n)
a = 1
n = []
for i in range( 1 , len(c) + 1):
n.append( int( c[-i] ) )
for i in range( len(c) ):
if n[ i ] == 1:
a = a * b % m
if i < len(c) - 1:
b = b **... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.