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 |
|---|---|---|---|---|---|---|
256990003e5d17856435c73e2faac0e495a2001f | DavidQiuUCSD/CSE-107 | /Discussions/Week1/OTP.py | 2,104 | 4.375 | 4 | import random #importing functions from Lib/random
"""
Author: David Qiu
The purpose of this program is to implement Shannon's One-Time Pad (OTP)
and to illustrate the correctness of the encryption scheme.
OTP is an example of a private-key encryption as the encryption key (K_e)
is equal to the decrypti... |
09d364548fb4bd79657ae483f2a8d281a645bfdd | athomsen115/Playing-with-Words | /PigLatin/pigLatin.py | 798 | 3.921875 | 4 | import sys
def main():
vowels = 'aeiouy'
while True:
words = input("Enter a word/phrase to convert to pig latin: ").lower()
pig = []
for word in words.split(' '):
if word[0] in vowels:
pigLatin = word + 'way'
else:
... |
13acd6a239784b3be128dbd4e1380c75566c9f51 | pramodith/AIMA | /search_algos.py | 22,631 | 4.125 | 4 | # coding=utf-8
"""
This file is your main submission that will be graded against. Only copy-paste
code on the relevant classes included here. Do not add any classes or functions
to this file that are not part of the classes that we want.
"""
from __future__ import division
from heapq import heapify, heappop, heappush... |
78617bcaf6b8ec7f4e275d23aa28641519f4d1a9 | jero98772/SandCripts | /scripts/logic/no_for.py | 101 | 3.609375 | 4 | def listIndex(i):
print(i,list1[-i-1])
if i < 1:return
else: listIndex(i-1) ;return
listIndex(5)
|
c91f1158cc7454c92a04e095a83d59eafdffcae0 | aniruthn/Projects | /battleship/battleship.py | 979 | 3.828125 | 4 | class battleship(object):
#initializer
def __init__ (self):
self.letter = "B"
#method that updates board with location of battleship
def updateBoard(self, object, locations):
#determines whether x or y is the same and increments the other
if locations[1][4] == locations[1][5]:
... |
530c6bbaae00d149ed41a1ae201d53a6a390851d | DanielMagen/Multidimensional-Binary-Tree | /BaseTreeInterface.py | 5,533 | 4.09375 | 4 | """
this class is a base class/interface for the implementation of any sort of binary tree
it leaves the implementation of insertion and deletion of both the node and the tree to the user,
for example, one could implement an avl tree with leaving the rest of the functions intact
"""
KEYS_ARE_EQUAL = 0
FIRST_KEY_BIGGER... |
15f91012d9614d46fe03d9b4ff7b83dd53ad31b5 | vihahuynh/CompletePythonDeveloper2021 | /break-the-ice-with-python/question81.py | 321 | 4.21875 | 4 | """
By using list comprehension, please write a program to print the list
after removing numbers which are divisible by 5 and 7 in [12,24,35,70,88,120,155].
"""
my_lst = [12,24,35,70,88,120,155]
# using filter
print(list(filter(lambda i: i % 35, my_lst)))
# using comprehensive
print([i for i in my_lst if i % 35])... |
cc06f5cfbd73b918a1be7434d93386638cf24514 | vihahuynh/CompletePythonDeveloper2021 | /break-the-ice-with-python/question46.py | 370 | 3.890625 | 4 | """
Define a class named American and its subclass NewYorker.
"""
class American:
pass
class NewYorker(American):
pass
american = American()
newyorker = NewYorker()
print(american)
print(newyorker)
print(isinstance(american, American))
print(isinstance(newyorker, NewYorker))
print(isinstance(american, N... |
c33fdc4d69260776fa2c9842a86452dd0e05eb09 | vihahuynh/CompletePythonDeveloper2021 | /break-the-ice-with-python/question76.py | 346 | 3.640625 | 4 | """
Please write a program to compress and decompress the string "hello world!hello world!hello world!hello world!".
"""
import zlib
my_str = "hello world!hello world!hello world!hello world!"
my_str_encode = my_str.encode('utf-8')
my_str_compress = zlib.compress(my_str_encode)
print(my_str_compress)
print(zlib.dec... |
a9400ebc82e237b5b2336a4a880f3569f55f32dc | vihahuynh/CompletePythonDeveloper2021 | /break-the-ice-with-python/question20.py | 437 | 3.9375 | 4 | """
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.
"""
class MyGen:
def __init__(self, num):
self.num = num + 1
def is_divisible_by_7(self):
for i in range(self.num):
if i % 7 == 0:
yield i
... |
ac6385c7e3233f3741124d1ef9847666558a2f1a | vihahuynh/CompletePythonDeveloper2021 | /break-the-ice-with-python/question11.py | 664 | 3.875 | 4 | """
Input:
Write a program which accepts a sequence of comma separated 4 digit binary numbers
Output:
check whether they are divisible by 5 or not.
The numbers that are divisible by 5 are to be printed in a comma separated sequence.
"""
lst_bi_num = input().split(',')
lst_result = []
# using for loop
for num in lst_b... |
9cc284d8bb87873882c68440c1ee19f0d4bcf094 | vihahuynh/CompletePythonDeveloper2021 | /break-the-ice-with-python/question4.py | 336 | 4.1875 | 4 | """
Input:
Write a program which accepts a sequence of comma-separated numbers from console
Output:
generate a list and a tuple which contains every number.Suppose the following input is supplied to the program
"""
seq = input('Please in out a sequence of comma-separated numbers\n')
print(seq.split(","))
print(tuple(s... |
ea15f2d096d049c8651eb81d3fcb119b5ef28429 | vihahuynh/CompletePythonDeveloper2021 | /break-the-ice-with-python/question63.py | 351 | 4.03125 | 4 | """
Please write a program using generator to print the even numbers between 0 and n in comma separated form while n is input by console.
"""
def even_num(num):
for i in range(num):
if i % 2 == 0:
yield i
num = int(input('Please input a number: \n'))
results = [str(i) for i in even_num(num +... |
3503e1859b0f61b18254c8eb58e5501773c4a84f | vihahuynh/CompletePythonDeveloper2021 | /break-the-ice-with-python/question39.py | 241 | 4.1875 | 4 | """
Write a program to generate and print another tuple whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).
"""
my_tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
even_tup = tuple(i for i in my_tup if i % 2 == 0)
print(even_tup) |
c0d25f7b67a112eb142eb02e885bf080a2b4e6be | vihahuynh/CompletePythonDeveloper2021 | /break-the-ice-with-python/question44.py | 193 | 3.8125 | 4 | """
Write a program which can map() to make a list whose elements are square of numbers between 1 and 20 (both included).
"""
my_lst = list(map(lambda i: i ** 2, range(1, 21)))
print(my_lst)
|
154f1639865eb98d55ea566ccb0894b949ad14d3 | vihahuynh/CompletePythonDeveloper2021 | /break-the-ice-with-python/question28.py | 291 | 4.15625 | 4 | """
Define a function that can receive two integer numbers in string form and compute their sum and then print it in console.
"""
def sum_2_num():
num1 = input('Input the first number: \n')
num2 = input('Input the second number: \n')
print(int(num1) + int(num2))
sum_2_num()
|
94430ceb826f66d79d37980518daf160f789e5ae | C7110Emir/Python | /python/bitwiseoperations.py | 632 | 4.09375 | 4 |
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
print(is_power_of_two(8))
# & operator
# if they are different turns out as 0
a = 6 | 5
#110
#101
#=111
print(a)
#If there is 1 turns out as 1
b = 6 ^ 5
#110
#101
# = 011
#If they are different turns out 1
print(b)
c = 6 >> 1
#110
# = 011... |
95b78dce493d3491a60356036b88fa62ef02776c | varun21290/leetcode_solutions | /Construct BST/bst.py | 791 | 3.5625 | 4 | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def bstFromPreorder(self, preorder: [int]) -> TreeNode:
root=TreeNode(preorder[0])
for i in range(1,len(preorder)):
no... |
c72a523f7acd0791edf59a2f3d2e50f633bf833c | komatsushoya/natsuyasumi | /addressbook.py | 525 | 3.765625 | 4 | class addressbook:
person_list =[]
def add(self, person):
self.person_list.append(person)
def show_all(self):
for person in self.person_list:
print(person.lastname + " " + person.firstname)
def serch(self,keyword):
for person in self.person_list:
if keyw... |
d487edfcc6620aab79b546df6aefaa9ff4bdc9f7 | AikaHasanova/week2-AikaHasanova | /05-Gasoline-medium/unsolved.py | 311 | 3.515625 | 4 | gallon= float(input("Enter the amount of oil in gallons : "))
litr = gallon*3.7854
barrel=gallon/19.5
CO2= 20*gallon
energy= gallon* 115000
price=gallon*4
print("in litres : ", litr, "in barrels : ", barrel,
"Amount of CO2 :", CO2,"Amount of Energy :",
energy,"Price in dollars :", price)
|
c6a62ed548563defa473bad188580ab5f56b6c8e | dvjr22/IST_736_TextMining | /HW/007/001_mnb_edit.py | 17,346 | 3.90625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Tutorial - build MNB with sklearn
# This tutorial demonstrates how to use the Sci-kit Learn (sklearn) package to build Multinomial Naive Bayes model, rank features, and use the model for prediction.
#
# The data from the Kaggle Sentiment Analysis on Movie Review Competition... |
71f0770f0aaef10c43092a891e75281257a99e21 | IrVallejo/Datacademy | /Calculadora_Volúmenes.py | 1,594 | 3.78125 | 4 |
import math
def VolumenCilindro(radio, altura):
return print(round(math.pi * altura * radio**2,2))
def VolumenEsfera(radio):
return print(round((4/3)*math.pi*radio**3,2))
def VolumenCubo(longitud):
return print(round(longitud**3))
def VolumenPrisma(largo, ancho, altura):
return print(round((largo *... |
0800b959b8ff2a1687b1c883135a06d5cec4776c | Pritheeev/Practice-ML | /matrix.py | 1,665 | 4.1875 | 4 | #getting dimension of matrix
print "enter n for nxn matrix"
n = input()
matrix1 = []
matrix2 = []
#taking elements of first matrix
print "Enter elements of first matrix"
for i in range(0,n):
#taking elements of first column
print "Enter elements of ",i,"column, seperated by space"
#raw_input().split() will... |
056b94834aa1634f384525e9484ebf49889c9438 | walas83/edX-6.00.1x | /ps2.py | 752 | 3.625 | 4 |
balance = 4000
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
total = 0
for month in range(1, 13):
monthlyInterestRate= (annualInterestRate) / 12.0
minimumMonthlyPayment = (monthlyPaymentRate) * (balance)
monthlyUnpaidBalance = (balance) - (minimumMonthlyPayment)
updatedBalanceEachMonth = (monthly... |
b842976fa5f1804a1bb6ec7d108038bf48e3e502 | saffron-finance/saffron | /recovery/epoch-1-recovery/rSFI/jsonToCsv.py | 739 | 3.703125 | 4 | import sys
import json
import csv
if len(sys.argv) != 3:
print("Usage: jsonToCsv.py [input file] [output file]")
sys.exit(1)
inFile = sys.argv[1]
outFile = sys.argv[2]
with open(inFile) as json_file:
data = json.load(json_file)
rsfi_data = data
# now we will open a file for writing
data_file = open(ou... |
1be795be43eba46056b161ee30ec8b008d3612cf | AbeDillon/RenAdventure | /Database.py | 4,442 | 3.96875 | 4 |
"""
Work in progress. main() is there to test dbManager.
"""
import sqlite3
import datetime
import os
class dbManager(object):
# Creates the necessary file and folder to put the db in. A single file can hold multiple tables but it
# is probably wise to not put more than one in a file at a time.
def __... |
67f22a74eedc6c07c1841e2848930856b3acccfc | jnwki/blackjack | /game.py | 2,246 | 3.6875 | 4 | from deck import Deck
from hand import Hand
def game():
# Instantiate game deck, player and dealer
deck = Deck()
player = Hand()
dealer = Hand()
# Initial Deal
player.hand = [deck.hit() for _ in range(2)]
dealer.hand = [deck.hit() for _ in range(2)]
print("\n\nWelcome to Blackjack.\n... |
950e8a7439e8f9068162f7770b09e7d4467c711e | yangzongwu/tkinter | /tkinter/label&button.py | 566 | 3.828125 | 4 | #Author:YZW
#窗口label&button
import tkinter as tk
window=tk.Tk()
window.title('my window')
#size of window
window.geometry('200x100')
var=tk.StringVar()
l=tk.Label(window,textvariable=var,bg='green',
font=('Arial',12),width=15,height=2)#text='This is TK!'
l.pack()#location, l.place ok
on_hit=False
def hit_m... |
88ece663319c8b627cbf801911d49b7db936aafe | victornovais/euler | /004.py | 415 | 4.0625 | 4 | # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is
# 9009 = 91 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
from tools import is_palindromic
result = 0
for i in range(999, 100, -1):
for j in range(i, 100, -1):... |
e592eb929a2cc216924947682b0079c50079012f | victornovais/euler | /020.py | 266 | 4 | 4 | # For example, 10! = 10 9 ... 3 2 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
# Find the sum of the digits in the number 100!
from math import factorial
digits = map(int, str(factorial(100)))
print sum(digits) |
6e9ccc3c8c978e83ff7e50d952ca725baf901e21 | sandipdeshmukh77/python-practice-code | /operater overloading demo 1.py | 180 | 3.59375 | 4 | class book:
def __init__(self,pages):
self.pages=pages
def __add__(self,other):
total_pages=self.pages+other.pages
return total_pages
b1=book(100)
b2=book(200)
print(b1+b2) |
92585234624572b3d8e5194d09956c7d2229ded2 | sandipdeshmukh77/python-practice-code | /wap to accept student data from user and display it on screen also find stud marks by their name.py | 679 | 4.03125 | 4 | n=int(input('enter the no. of students:'))
d={}
for ch in range(n):
name=input('eneter student name:')
marks=int(input('enter students marks:'))
d[name]=marks
print('student data taken succefully')
print('*'*30)
print('name','\t\t','marks')
print('*'*30)
for k,v in d.items():
print(k,'\t\t',v)
print('serching opera... |
bd8e8f3dc0349cab75af9a40a17171b5dfb4eb2f | sandipdeshmukh77/python-practice-code | /IS-A relationship demo 2.py | 610 | 3.9375 | 4 | class person:
def __init__(self,name,age):
self.name=name
self.age=age
def eatdrink(self):
print('eats biryani and drink beer')
class employee(person):
def __init__(self,name,age,eno,esal):
#self.name=name no need to write again we can use this from parent class
#self.age=age by using 'super().__ini... |
1318e70e01707c2c5abb7fba6f4ef729f96592ea | BOSONCODE/Homework | /Q-Learning-mze/run_this.py | 1,240 | 3.609375 | 4 | """
迷宫的奖赏函数设计为:
红框是agent, 进行游戏的探索
黑框是墙,墙的reward为-1
红框是目的地,reward为1
其他框的reward为0
"""
from maze_env import Maze
from RL_brain import QLearningTable
import matplotlib.pyplot as plt
def update():
x = []; y = [];
for episode in range(300):
observation = env.reset()
while True:
env.ren... |
d0fbc9054ab59004b445c14310651e871aecc01d | AmberJBlue/aima-python | /submissions/LaMartina/mygames.py | 12,146 | 3.890625 | 4 | from collections import namedtuple
from games import (Game)
class GameState:
# def __init__(self, to_move, board, start_player,
# label=None,):
# self.to_move = to_move
# self.board = board
# self.label = label
# self.start_player = start_player
def __init__(sel... |
a7b749042cef31a0462bdc445c4a60d4abbb6e44 | AmberJBlue/aima-python | /submissions/Ban/mygames.py | 3,465 | 3.625 | 4 | from collections import namedtuple
from games import (Game)
class GameState:
def __init__(self, to_move, board, label=None):
self.to_move = to_move
self.board = board
self.label = label
def __str__(self):
if self.label == None:
return super(GameState, self).__str__(... |
062669d807df19c91bb26f19aaa6dd1dc9153772 | AmberJBlue/aima-python | /submissions/Johnson/mygames.py | 9,663 | 3.796875 | 4 | from collections import namedtuple
from games import (Game)
class GameState:
def __init__(self, to_move, board, label=None):
self.to_move = to_move
self.board = board
self.label = label
def __str__(self):
if self.label == None:
return super(GameState, self).__str__... |
d45e3f7e39e1153f4ff4ef1da79487cac2297d66 | AmberJBlue/aima-python | /submissions/Sery/myNN.py | 3,375 | 3.734375 | 4 | from sklearn.neural_network import MLPClassifier
import traceback
from submissions.Sery import aids
class DataFrame:
data = []
feature_names = []
target = []
target_names = []
aidsECHP = DataFrame()
aidsECHP.data = []
target_data = []
list_of_report = aids.get_reports()
for record in list_of_report:
... |
edf448bc4f4d4c8bbfc7dc54636b7d6f021d4c1a | mahindra1728/Python | /Linear_regression.py | 3,843 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 12 11:17:48 2021
@author: mahindra.choudhary
"""
#######################
# Simple Linear regression
#######################
# Step 1
"""
The first step is to import the package numpy and the class LinearRegression
from sklearn.linear_model:
"""
impo... |
b87aba8ebe59443beff892da2b915b3a718c4e1e | mahindra1728/Python | /Dealing with missing values.py | 1,601 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 5 16:10:30 2021
@author: mahindra.choudhary
"""
#######################
# Dealing with missing values
#######################
# Identifying the missing values
# Approaches to fill the missing values
# Importing the necessary libraries
import os
imp... |
397faad6d0b02b99411ea874f5e3dc15c584cdfc | amishas157/osm-fudge | /osm_fudge/index/bk_tree.py | 2,498 | 3.671875 | 4 | '''An implementation of bk-tree
More: https://en.wikipedia.org/wiki/BK-tree
'''
from recordclass import recordclass
from bisect import bisect_left
from bisect import bisect_right
Node = recordclass('Node', ['value', 'edges', 'children'])
def binary_search(values, min_value, max_value, lo=0, hi=None):
hi = (hi ... |
a9ba6d5ee6958f9bb1958d1d0c7523ae947ade68 | wmaxlloyd/CodingQuestions | /Recursion/subsets.py | 2,105 | 3.953125 | 4 | # Given a set of distinct integers, nums, return all possible subsets (the power set).
# Note: The solution set must not contain duplicate subsets.
#
# Assumptions:
# - Any array is a subset of itself
# - Empty array is subset of all possible sets
# - Sets are given as arrays
# - For recursion: There are less than 100... |
92f3706abfde30f26a4ee16e6cc9111cde99f9c2 | wmaxlloyd/CodingQuestions | /Trees/treeDepth.py | 355 | 3.6875 | 4 | from createATree import BiNode
tree = BiNode(5)
tree.createTree(range(2**6 - 2))
def findDepth(tree, depth=1):
if tree.left:
leftDepth = findDepth(tree.left, depth + 1)
else:
leftDepth = depth
if tree.right:
rightDepth = findDepth(tree.right, depth + 1)
else:
rightDepth = depth
return max([leftDepth, ri... |
20815d2320a6119040708c7017cc484d3d21e923 | wmaxlloyd/CodingQuestions | /Strings/longestPalendromaticSubstring.py | 1,063 | 4 | 4 | # Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
# Example:
# Input: "babad"
# Output: "bab"
# Note: "aba" is also a valid answer.
# Example:
# Input: "cbbd"
# Output: "bb"
#
s = "ababjabab"
print "brute force"
# Time complexity O(n^3)
# Space C... |
a586bcfe643f3d205136714172bf386a7b8c0e1f | wmaxlloyd/CodingQuestions | /Strings/validAnagram.py | 1,380 | 4.125 | 4 | # Given two strings s and t, write a function to determine if t is an anagram of s.
# For example,
# s = "anagram", t = "nagaram", return true.
# s = "rat", t = "car", return false.
# Note:
# You may assume the string contains only lowercase alphabets.
# Follow up:
# What if the inputs contain unicode characters? Ho... |
421f563fe072c328c30202ee455c2dd1a3fc3e50 | jasneetkaurarora/database | /Final/Final_1.py | 1,473 | 3.59375 | 4 | #!/usr/bin/env python
import ipaddress
import sys
import re
import ipcalc
import socket
def enter_ip():
global ip
ip = raw_input ("Enter Ip address:");
check_ip(ip)
def enter_mask():
global mask
global p
mask = raw_input("Enter subnet mask in decimal format:");
p = int(mask)
check_mas... |
4572f989d6306611cf17728ef4da8e80d2746e31 | angelinaossimetha/bookstore | /books.py | 8,070 | 3.828125 | 4 | #new submit 12/11
import csv # https://docs.python.org/3/library/csv.html
import random # https://docs.python.org/3/library/random.html
from dataclasses import dataclass
with open('books.csv', encoding='utf-8') as f:
lines = list(csv.reader(f)) # loads lines of books.csv into list of lists
with open('genres.t... |
55c330dc2f58a2e7a89fc04f6d38000f250073c8 | harshparihar/python | /dsa/queue/queue1.py | 656 | 3.84375 | 4 | class Queue:
def __init__(self):
self.array = []
def EnQueue(self, item):
self.array.append(item)
print("%s enqueued to queue" %str(item))
def DeQueue(self):
item = self.array.pop(0)
print("%s dequeued from queue" %str(item))
def que_front(self):
print("Front item is", self.array[0])
... |
230a89eb7d760eabf5e8aee36a2793ea5f4f2605 | harshparihar/python | /dsa/queue.py | 467 | 3.921875 | 4 | class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
print("Size of queue is " + str(len(self.items)))
def show(self):
print(self.items)
print("=========================")
q = ... |
a9005aba3650c82c91ded3b1de3d7e642dbde6f4 | Bappy200/Data-Structure-And-Algorithm-With-Python | /binarySearch.py | 436 | 3.9375 | 4 | def binary_search(numbers, search_number):
left = 0
right = len(numbers) - 1
while(left < right):
mid = (left + right) // 2
if numbers[mid] == search_number:
return numbers[mid]
elif numbers[mid] > search_number:
right = mid - 1
else:
lef... |
7a4aec18ce12b7339641d563a39df94fa06f92c5 | sahmed95/Attacks-on-RSA | /Cryptomath.py | 946 | 3.5 | 4 |
def gcd(a, b):
# Returns the GCD of positive integers a and b using the Euclidean Algorithm.
x, y = a, b
while y != 0:
r = x % y
x = y
y = r
return x
def extendedGCD(a,b):
# Returns integers u, v such that au + bv = gcd(a,b).
x, y = a, b
u1, v1 = 1, 0
u2, v2 = 0... |
5aa6e4bbf864c2182bb1fec921c9dd7fbe93249b | wszy5/Turtle_Crossing | /car_manager.py | 569 | 3.5 | 4 | from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager(Turtle):
def __init__(self):
super().__init__()
self.shape("square")
self.penup()
self.color(random.choice(COLOR... |
b5cecd11717288f94c62e9cf90b36672152eef0f | vuong9/General | /Networking_Security_Basics/socket_io/socket_reverse_lookup.py | 275 | 3.5 | 4 | import socket
try:
result = socket.gethostbyaddr("8.8.8.8")
print("The host name is:")
print(" " + result[0])
print("\nAddress:")
for item in result[2]:
print(" " + item)
except socket.herror as e:
print("error for resolving ip address:", e)
|
5a7bd74450fc1adddec433ea2acb037d55615b44 | tarunjr/coding-questions | /python/ds/arr/max_area.py | 581 | 3.6875 | 4 | import unittest
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i, j = 0, len(height)-1
maxSoFar = 0
max_i, max_j = i, j
while i < j:
max = min(height[i], height[j]) * (j-i)
if max > maxSo... |
d8880f0923859f0efcbd15c5cb0b346dfd5229c9 | DJimmie/data-structures-and-algorithms | /genetic_algorithms/jim_one_max.py | 10,245 | 3.59375 | 4 | """My attempt to build a genetic algorithm from scratch to solve the onemax problem"""
# %%
import random
import pprint
import matplotlib.pyplot as plt
import sys
## Constants
NUM_GENES=20
POP_SIZE=100
P_MUTATION=.05
P_CROSSOVER=.7
GEN_COUNT=10
# %%
class Individuals():
"""Random generated Binary chromosomes... |
8a382ea768f217cc8edadb181a0da968dcd9f0d3 | ramalholuiz/durc | /durc/db.py | 1,029 | 3.765625 | 4 | from abc import ABC, abstractmethod
class DB(ABC):
@staticmethod
@abstractmethod
def init(config):
pass
@abstractmethod
def get(self, id, collection_id):
# This method returns an entry by the given id from a collection
pass
@abstractmethod
def get_one(self, collec... |
0f4c64e5e50ace672bf2bc8f2731e844cf9dd1ee | TeamBitBox/URI_Questions | /1012 - Área(Iniciante)Python3 | 275 | 3.609375 | 4 | valor = [float(i) for i in input().split(" ")]
a, b, c = valor
pi = 3.14159
t = (a*c)/2
C = pi * (c**2)
tr = (c*(a+b))/2
q = b**2
r = a*b
print('TRIANGULO: %0.3f'%t)
print('CIRCULO: %0.3f'%C)
print('TRAPEZIO: %0.3f'%tr)
print('QUADRADO: %0.3f'%q)
print('RETANGULO: %0.3f'%r)
|
580f7a9098c047cd686a330755ca58c31c12e945 | Bearded-Programmer/Random-Programming-and-Designing-Stuff | /Socket Programming[Python 3]/GetIPAddressServer.py | 655 | 3.5 | 4 | import socket
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#Here AF_INET represents the address family IPv4 which uses IP + Port for connection
#Lets bind the created serverSocket to an address
serverSocket.bind(('127.0.0.1',1225))
if serverSocket is not None:
print("Server is up & running ... "... |
ce7f9ff854877784afa165357f8e4c8dc8ae991b | wdlsvnit/SMP-2017-Python | /smp2017-Python-maulik/cs50/pset6/caesar.py | 576 | 3.859375 | 4 | import sys
if len(sys.argv) is not 2 :
print('Usage: Python3 caesar.py k')
exit(1)
cyp=[]
j=int(sys.argv[1])
pText=input('plain text: ')
for i in range(len(pText)):
if pText[i].islower():
n=ord(pText[i])-ord('a')+1
n=(n+j)%26
n=n-1+ord('a')
cyp.append(chr(n))
elif p... |
54f9eee09ecc211fc0cc378746ceb92c6ca76c8b | wdlsvnit/SMP-2017-Python | /smp2017-Python-maulik/extra/lesson8/madLibs.py | 909 | 4.40625 | 4 | #! python3
#To read from text files and let user add their own text anywhere the word-
#ADJECTIVE, NOUN, ADVERB or VERB
import re,sys
try:
fileAddress=input("Enter path of file :")
file = open(fileAddress)
except FileNotFoundError:
print("Please enter an existing path.")
sys.exit(1)
fileContent = file... |
ba3f49d757fed424c62a0d84fb66060b9b30f78e | wdlsvnit/SMP-2017-Python | /smp2017-python-kevin/udemy/lesson12/raise_example.py | 495 | 4 | 4 | '''
*********
* *
* *
* *
* *
*********
'''
print('Enter symbol:')
symbol = input()
print('Enter width:')
width = input()
print('Enter height:')
height = input()
def Box(symbol,width,height):
if(len(symbol)!=1):
raise Exception('symbol length should be 1')
if(width<2) or (height<2):
raise Exception('Width & H... |
a9168c043a62aa636fa733243da4ea1f3bab15ae | wdlsvnit/SMP-2017-Python | /smp2017-python-kevin/udemy/lesson5/guessgame.py | 660 | 3.8125 | 4 | #game pgm to guess a number b/w 1 and 40
import random
print('What is your name, human?')
name = input()
print('Yo '+name+', guess a number between 1 and 40')
ans = random.randint(1,40)
#max chances to guess is 8
for totguess in range(1,9):
print('Your guess?')
guess = int(input())
if(guess<1 or guess> 40):
... |
fe59db7b1a08053585d40019fa344a8afe2564aa | j-a-c-k-goes/replace_character | /replace_this_character.py | 2,085 | 4.21875 | 4 | """
For a list containing strings,
check which characters exist,
then replace that character with a random character.
"""
# ................................................................ Imports
from random import *
# ................................................................ Main Function
def make_words(words=... |
e6af21b06ed59dee8236c11d92d74d49b05410f1 | fataik1/Graphs | /y.py | 1,707 | 4 | 4 | import string
class Queue():
def __init__(self):
self.queue = []
def enqueue(self, value):
self.queue.append(value)
def dequeue(self):
if self.size() > 0:
return self.queue.pop(0)
else:
return None
def size(self):
return len(self.queue)
#... |
9fb119e40820a3379e529293f83ecbdad6040804 | Himanshu-Mishr/todoManager | /RunMe.py | 2,947 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2013 Himanshu Mishra <himanshu.m786@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the ... |
b77771e39c8f557589d11430bd86dc4a74227736 | shamirpatel89/leet-code | /palindrome-number/solution.py | 377 | 3.5625 | 4 | class Solution:
def isPalindrome(self, x: int) -> bool:
x_string = str(x)
length = len(x_string)
for index, digit in enumerate(x_string):
opposite_index = length - 1 - index
if index >= opposite_index:
break
if digit != x_string[opposite_i... |
038243091d643dafa3655ead93604aa26680f378 | shamirpatel89/leet-code | /valid-parentheses/solution.py | 490 | 3.578125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
closing_map = {
')': '(',
'}': '{',
']': '[',
}
tracker: List[str] = []
for char in s:
if char in closing_map:
if tracker and tracker[-1] == closing_map[char]:
... |
2aeab72686a8c4f15a654a1cead9449175b1e243 | Tarrke/python-firstAI | /population.py | 3,343 | 3.90625 | 4 | """A Population is a set of dots that form a generation."""
from dots import dots
from random import random
class population:
"""Population population, oh my population"""
def __init__(self, dotNumber=0, color="black"):
self.myDots = []
self.dotNumber = dotNumber
self.Best = None
... |
9e60b869bac0e28dea0f6b050472c0784b825957 | darkknight161/crash_course_projects | /stage_of_life.py | 364 | 3.921875 | 4 | age = 65
life_stage = ''
if age < 2:
life_stage = 'baby'
elif (age >= 2) and (age < 4):
life_stage = 'toddler'
elif (age >=4) and (age < 13):
life_stage = 'kid'
elif (age >= 13) and (age < 20):
life_stage = 'teenager'
elif (age >= 20) and (age < 65):
life_stage = 'adult'
else:
life_stage = 'elder'
... |
82f7a717f8a5c603322ba64eb4859b0170fbec2d | darkknight161/crash_course_projects | /cars2.py | 1,074 | 4 | 4 | car = 'subaru'
print('Is car == to "subaru"? I predict True.')
print(car == 'subaru')
print('\nIs car == to "bmw"? I prdict False.')
print(car == 'bmw')
print('\nIs car == to "Subaru"? I predict False')
print(car == 'Subaru')
print('\nIs car == to "Subaru" when using the .title() tag? I predict True.')... |
b18cb0ad7ea82d7658bfb957eec60bb047c55971 | darkknight161/crash_course_projects | /pizza_toppings_while.py | 513 | 4.21875 | 4 | prompt = "Welcome to Zingo Pizza! Let's start with Toppings!"
prompt += "\nType quit at any time when you're done with your pizza masterpiece!"
prompt += "\nWhat's your name? "
name = input(prompt)
print(f'Hello {name}!')
toppings = []
topping = ""
while topping != 'quit':
topping = input('Name a toppi... |
065f4dc7ecf1a723021a24ff519c498bf7f3582c | pburakov/pole | /pole.py | 2,457 | 3.921875 | 4 | import random
MAX_SCORE = 100
ALPHABET = "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЫЭЮЯ-"
def process_word(word: str):
return word.replace("ё", "е").upper()
def load_vocabulary(filename: str) -> list:
vocabulary = []
with open(filename) as file:
for line in file:
word = line.replace("\n", "")
... |
af6dc6c5cbd156509363a9b8f5d28f8a3ffba399 | frederichtig/python-chat-server | /server/test_server.py | 1,968 | 3.671875 | 4 | import unittest
import socket
from server import Server
class Tests(unittest.TestCase):
def create_server(self):
port = 889
host = 'localhost'
# Creates a new instant of the Server class, it will also inherit
# the Thread class.
server = Server(port)
# Start the ... |
34ac248435ebefe05f1414159ea877aa59f16182 | ArpitaSakshee/PythonProjects | /LinkedList/LinkedListClass.py | 1,132 | 3.875 | 4 | class Node():
def __init__(self, val):
self.val=val
self.next=None
class LinkedList():
def __init__(self):
self.head=None
self.tail=None
def add(self, val):
node=Node(val)
if self.head==None:
self.head=node
self.tail=node
else... |
a0fdc98359d9d727a6d0edd2b99b400503f491e7 | GeneralMing/codeforces | /Python/69A-Young Physicist.py | 350 | 3.6875 | 4 | """
Solution to Codeforces problem 69A
Copyright (c) GeneralMing. All rights reserved.
https://github.com/GeneralMing/codeforces
"""
n = int(input())
arr = [0, 0, 0]
for i in range(n):
num = input().split(" ")
arr[0] += int(num[0])
arr[1] += int(num[1])
arr[2] += int(num[2])
if(arr[0] or arr[1] or arr[2]):
p... |
640c1b68233d7fe7ee1cdc0a44b30dd0afce9c1b | umangag07/Python_Array | /array manipulation/changing shape.py | 1,019 | 4.625 | 5 | """
Changing shapes
1)reshape() -:gives a new shape without changing its data.
2)flat() -:return the element given in the flat index
3)flatten() -:return the copied array in 1-d.
4)ravel() -:returns a contiguous flatten array.
"""
import numpy as np
#1 array_variable.reshape(newshape)
a=np.arange(... |
31050593b4252bf94fb491e37e0a0628017d2b69 | 90-shalini/python-edification | /collections/tuples.py | 785 | 4.59375 | 5 | # Tuples: group of items
num = (1,2,3,4)
# IMUTABLE: you can't update them like a list
print(3 in num)
# num[1] = 'changed' # will throw error
# Faster than list, for the data which we know we will not change use TUPLE
# tuple can be a key on dictionary
# creating/accessing -> () or tuple
xyz = tuple(('a', 'b'))
print(... |
06f8606487aae8e51b575c0508c150a9aa1e88e2 | rishitha97/256 | /1_a.py | 922 | 3.6875 | 4 | import pandas as p
import numpy as n
data=[197,199,234,267,269,276,281,289,299,301,339] # list of numbers for which box plot is plotted and outliers are determined
outliers=[] # initialising list for outliers
d=p.DataFrame(data) # converting list to data frame
boxplot=d.boxplot() # initialising box plot object
Q1, ... |
f3b113c41bdc7a96e8a80fd654d0a8432419a943 | LeeSangJun/pythonStudy | /20170419/example01.py | 3,217 | 4 | 4 | #if, elseif else
disaster = True #선언
if disaster : #조건이 참이면 실행 #파이썬에서의 IF문은 콜론(:)으로 조건을 명시
print("Woe!")
else:
print("Whee!")
#비교연산자
'''
==
!=
<
<=
>
>=
in : 멤버십(셋...등등)
'''
#부울 연산자(and, or, not) 는 비교연산자보다 우선순위 낮음
x = 8
print(5 < x and x < 10)
#순서 헷갈리고 싶지 않다면 괄호를 쓰면 된당
#파이썬에서는 여러번 비교 가능
#각각의 연산자는 위치에따라서... |
55864a2f8392db2db85dd7dc07203f3d386be88e | Aimery1990/gitRepository | /py_learning/basic_skills.py | 1,220 | 3.984375 | 4 |
# about eval using
res = eval(input("please input your expression: "))
print(res)
# swap value
x, y = 10, 20
print("x is %d y is %d" %(x, y))
x, y = y, x
print("x is %d y is %d" %(x, y))
# multi inputs
score1, score2 = eval(input("Please input 2 scores separated by a comma: "))
print(score1)
print(score2)
# error... |
6f22ef4aaa336d35ed64b0b227b2870f137ab6ca | Aimery1990/gitRepository | /py_learning/noob_master/enumerate_class.py | 584 | 3.875 | 4 |
import enum
class Weekdays(enum.Enum):
MON = 1
TUE = 2
WED = 3
THR = 4
FRI = 5
SAT = 6
SUN = 0
END = "DONE"
day = Weekdays.FRI
print(day)
print(day.value)
print(day.name)
if day == Weekdays.FRI:
print("F")
@enum.unique # make sure enumerate value is unique
class Weekdays2(... |
983b4ba8e51e8363e14287eb10dbbc86b94025b7 | defrense/CA_Python_Study | /Reggie's+Linear+Regression/Linear_Regression.py | 1,372 | 3.90625 | 4 | """
This is a practice projects on list/loop concepts from CodeAcademy
codes use trial and error approach to find the best linear parameter of
a given data sets
"""
datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)]
possible_ms = [ms * 0.1 for ms in range (-100, 100)]
possible_bs = [ms * 0.1 for ms in range (-200, ... |
d4157a23df6b5a4e3427727b0df3c69cd7de1ff2 | SoeunLee/ps | /programmers/43163.py | 846 | 3.65625 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/43163
def replace(src, i, X):
dst = list(src[:])
dst[i] = X
return str(dst)
def solution(begin, target, words):
answer = 0
if target not in words:
return 0
visit = [ -1 for _ in words ]
length = len(begin)
... |
99923fad77e734dc2cc705964a19cedb9f670af0 | SoeunLee/ps | /programmers/42587.py | 563 | 3.5 | 4 | # https://programmers.co.kr/learn/courses/30/lessons/42587
def solution(priorities, location):
answer = 0
queue = []
for idx, val in enumerate(priorities):
queue.append((val, idx))
result = []
while queue:
val = max(queue, key=(lambda x: x[0]))
idx = queue.index(va... |
7ba700c910a6a9c33f8ee7b67983325da07968dc | kletcka/Plots | /main.py | 1,217 | 3.78125 | 4 | from matplotlib import pyplot as plt
import os
counter = 1
def create_plot(xl, yl, x, y, y1, name):
plt.xlabel(xl)
plt.ylabel(yl)
if y == y1:
plt.plot(x, y)
print(xl, yl, x, y, y1, name)
plt.grid(axis = 'x')
plt.grid(axis = 'y')
plt.savefig(f'{name}.png')
... |
b10d72c233f55f12a75f114fd5bd235679d651ab | Elesh-Norn/Advent-of-Code | /Advent of Code 2018/Day 7/Day_7.py | 4,142 | 3.6875 | 4 | class Step:
def __init__(self, name):
self.name = name
self.step = set()
def add_step(self, step):
self.step.add(step)
def get_input(filename):
file = open(filename, "r")
step_dic = {}
for line in file:
line = line.split(" ")
after = line[-3]
before... |
c88101b0e8d1bb96e1ae3e4769d893bc089cf57c | Elesh-Norn/Advent-of-Code | /Advent of Code 2018/Day 5/Day_5.py | 1,106 | 3.828125 | 4 | import sys
test = 'dabAcCaCBAcCcaDA'
count = 0
def get_input(filename):
file = open(filename, "r")
word = None
for line in file:
word = line
file.close()
return line
def check(list, idx):
if list[idx].islower() and list[idx - 1].isupper() and list[idx] == list[idx-1].lower():
... |
30dee2de70599c0c6aea3144e58a051fc02acdc1 | prometheus61/lpthw | /ex5.py | 622 | 3.84375 | 4 | name = 'Zed A. Shaw'
age = 35 # not a lie
height = 74 # inches
weight = 180 # lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print ("Let's talk about %(name)s. who is %(height)d inches tall" % ({'name':'Zed Shaw' , 'height':79}))
print "He's %x inches tall." % height # hexadecimal values
print "He's %o pounds heavy.... |
f88c8674b368cf2a293c8f88c0e7cf430577a83e | TITONIChen/Fiora | /2/p32.py | 283 | 3.875 | 4 | #删除元素
number = [0, 1, 2, 3, 4, 5, 6]
#del number[1:6]
number [1:6] = []
print(number)
#给切片赋值
number = [0, 6]
number[1:1] = [1, 2, 3, 4, 5]
print(number)
name = list('Pioneer')
print(name)
name[1:] = list('ython')
#name[1:] = ['y', 't', 'h', 'o', 'n']
print(name)
|
90e609fb4c893e52f2ec8edbed0892375b3f6bd9 | TITONIChen/Fiora | /2/p33_2.3.3.py | 1,453 | 3.828125 | 4 | #列表方法
#object.method(arguments)
#1. append
lst = [1, 2, 3]
lst.append(4)
print(lst)
print('\r')
#2. clear
lst = [1, 2, 3]
lst.clear()
print(lst)
print('\r')
#3, copy
a = [1, 2, 3]
b = a
b[1] = 5
print(a)
a = [1, 2, 3]
b = a.copy() #b = a[:] #b = list(a)
b[1] = 5
print(a)
print(b)
print('\r')
#4. court
LOL = [... |
c49a83c97d439ae29ee0b9533ddfe5d68dd48d58 | spolischook/codewars | /python/test_your_order.py | 892 | 3.625 | 4 | def order3(sentence):
words = {}
for word in sentence.split():
for i in range(0, len(word)):
if word[i].isnumeric():
words[word] = int(word[i])
break
return ' '.join(sorted(words, key=words.__getitem__))
def order2(sentence):
words = {}
for word ... |
6da5c21f9afba1783b19e3a5e94cbb88629b28a7 | annafeferman/colloquium_2 | /19.py | 1,145 | 4.09375 | 4 | """Знайти суму всіх елементів масиву цілих чисел що задовольняють умові:
остача від ділення на 2 дорівнює 3. Розмірність масиву - 20. Заповнення масиву
здійснити випадковими числами від 200 до 300.
Anna Feferman"""
from random import randint # імортуємо рандом
array = [] # створюємо порожній масив
summa =... |
17972900941f65afbf58e22a4ffb2b717f30f052 | annafeferman/colloquium_2 | /40.py | 854 | 3.796875 | 4 | """Обчислити суму парних елементів одновимірного масиву до першого
зустрінутого нульового елемента.
Anna Feferman"""
from random import randint # імпортуємо рандом
summa = 0 # змінна суми
array = [] # створюємо порожній список
length = int(input('Input the length of the array: ')) # довжина масиву
for i ... |
4654ae6236ecf24b2c2e018b787ce5b62fc44236 | annafeferman/colloquium_2 | /22.py | 950 | 3.9375 | 4 | """Знайти добуток елементів масиву, кратних 3 і 9. Розмірність масиву - 10.
Заповнення масиву здійснити випадковими числами від 5 до 500.
Anna Feferman"""
from random import randint # імпортуємо рандом
array = [] # порожній масив
dobutok = 1 # зміна добутку
for i in range(10):
array.append(randint(5, ... |
b0b8ae6cfc887563ced48394bed4f4909694574f | annafeferman/colloquium_2 | /13.py | 506 | 3.6875 | 4 | """Створіть масив з 15 цілочисельних елементів і визначте серед них
мінімальне значення.
Anna Feferman"""
from random import randint # імпортуємо рандом
array = []
for i in range(15):
array.append(randint(-20, 20)) # заповнюємо список рандомом
print(f'{array}\n'
f'Мінімальне значення: {min(array... |
7e6a9ef2140609c5e3af3b227b6471f21ade2e79 | annafeferman/colloquium_2 | /56.py | 754 | 3.9375 | 4 | """Якщо в одновимірному масиві є три поспіль однакових елемента, то
змінній r привласнити значення істина.
Anna Feferman"""
from random import randint # імпортуємо рандом
array = [] # порожній список
r = False # ставимо флаг
for i in range(15):
array.append(randint(2, 7)) # заповнюємо рандінтом
prin... |
91039029eb70633744498be6f68fe1435f08ba96 | annafeferman/colloquium_2 | /45.py | 950 | 4.3125 | 4 | """Перетин даху має форму півкола з радіусом R м. Сформувати таблицю,
яка містить довжини опор, які встановлюються через кожні R / 5 м.
Anna Feferman"""
import math # імпортуємо math
radius = int(input('Введіть радіус: ')) # користувач вводить радіус
interval = radius / 5 # зазначаємо інтервал встановлення ... |
f186287b1ee163bc38e8c5488f4508c29b6e007f | kukayatan/django | /bodycalculator/classbodycalc.py | 1,908 | 3.640625 | 4 | class Calculation:
def __init__(self):
pass
def bmi(self,weight, heigh):
self.weight = weight
self.heigh = heigh
ws = "Your weight status"
bmi_res = round(weight / ( (heigh/100) ** 2 ),1)
if bmi_res < 18.5:
return str("{} is underweight.... |
bdaf7d9c215ab9507c43b3cda2d0a910b4b8cecc | kadirbulut/CSE321-Introduction-to-Algorithm-Design | /HW5/theft_121044005.py | 1,230 | 3.65625 | 4 | def helper(inputArr,allCosts,row,column):
if row>=0 and row<len(allCosts) and column<len(allCosts[0]):
# if it has already been passed
if allCosts[row][column] != -1:
return allCosts[row][column]
right=inputArr[row][column] + helper(inputArr, allCosts, row, column+1) # go right
... |
df65feb69de3f336f17102f0bb07f03dbbdd7f48 | st2013hk/pylab | /execise/lab1.py | 253 | 3.75 | 4 | # s = input("please enter a number")
# s = int(s)
# if s == 1:
# print('Hello')
# elif s == 2:
# print('Howdy')
# else:
# print('Greeting')
# for s in range(1,11):
# print(s)
# s = 1
# while s < 11:
# print(s)
# s += 1
abs(123) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.