blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9bab5fd87b6001562f610dd2b47dfb511690a2c8 | anubhav-shukla/Learnpyhton | /function.py | 476 | 4.21875 | 4 | # Before we use some function
# name='Anubhav'
# print(len(name)) #before we use it .
# python function.py
def add_two(a,b):
return a+b
# a=int(input("Enter first number : "))
# b= int (input("Enter second number: "))
# total = add_two(a,b)
# print(total)
a=input("Enter first name : ")
b= input("Enter second n... |
3f978806d6177954ce7b5fd04ef83a7e8e065cee | anubhav-shukla/Learnpyhton | /zip_func.py | 696 | 4.53125 | 5 | # zip function
user_id=['user1','user2','user3']
names=['Anubhav','mohit','rohit']
# it gives zip object as a tuple
# ('user1','Anubhav'),('user2','mohit')
print(list(zip(user_id,names))) #now you get expected output
# second condition
user_id1=['user1','user2']
names1=['Anubhav','mohit','rohit']
p... |
dabdf6e666399abf2dca439444a9efe9890a03be | anubhav-shukla/Learnpyhton | /pillow_module.py | 1,393 | 3.796875 | 4 | # installation of pillow library
# change the image extension
# resize image file
# resize multiple images using for loop
# sharpness
# brightness
# color
# Contrast
# Image blur , GauuianBlur
from PIL import Image , ImageEnhance , ImageFilter
import os
# how can we change extension of image
image1 = Ima... |
22674f1aee6e3e3dc6c5686e79e4596f567b9137 | anubhav-shukla/Learnpyhton | /Lst.py | 274 | 3.984375 | 4 | # today we check list inside A lsit and print output as input of the list
# python Lst.py
def checklist_inside(l):
count =0
for i in l:
if type(i) == list:
count+=1
return count
b=[1,2,3,[4,5,6],[7,8,9]]
print(checklist_inside(b))
|
22c3755df5092f439573485354c5a534cfda4195 | anubhav-shukla/Learnpyhton | /chapter5_exe2.py | 262 | 4.4375 | 4 | # here we reverse any list using pop and append
# python chapter5_exe2.py
def reverse_list(l):
reverse=[]
for i in l:
j=l.pop()
reverse.append(j)
return reverse
list2=list(range(1,13))
print(reverse_list(list2))
|
da9e01425601c8280e55cefebfd5076ce1ceefec | anubhav-shukla/Learnpyhton | /lambda_expression_prac.py | 692 | 4.28125 | 4 | # lambda expression practice
# def is_even(a):
# return a%2==0 #get same output
# if a%2==0:
# return True
# # return False
# print(is_even(5))
# # now we use lambda expression
# is_even1=lambda a:a%2==0
# print(is_even1(8)) #true
# def last_char(s):
# return s[-1]
last_... |
e9421d500edf622c393b7419b7d593ec31d3b509 | anubhav-shukla/Learnpyhton | /lc_with_if_else.py | 381 | 3.984375 | 4 | # list comprehension with if else
nums=[1,2,3,4,5,6,7,8]
# new_list=[-1,4,-3,8]
new_list=[]
for i in nums:
if i%2==0:
new_list.append(i*2)
else:
new_list.append(-i)
print(new_list)
# now see using list comprehension
new_list2=[i*2 if(i%2==0) else -i for i in num... |
6ad206e4d2b4fb583ad00bc037093af6a8042713 | anubhav-shukla/Learnpyhton | /nested_list_comprehensive.py | 271 | 4.40625 | 4 | # list comprehension in nested list
example=[[1,2,3],[1,2,3],[1,2,3]]
nestes_comp=[[i for i in range(1,4)] for j in range(3)]
print(nestes_comp)
# how can be do it simply
new_list=[]
for j in range(3):
new_list.append([1,2,3])
print(new_list)
|
e04cb35e3c290e566bc39c0f04dc8c12502f6545 | anubhav-shukla/Learnpyhton | /advance_sorted_func.py | 878 | 4.375 | 4 | # here we understand about advance sorted function
fruits=['grapes','mango','apple']
# sort
fruits.sort()
print(fruits) #see your list is sorted
# But sort method is only available in list
fruits1=('grapes','mango','apple')
# if you use sort in it than you get error
# you can use sorted
print(sorted(... |
8de40aefc935a54a78757a30b36560af535c1123 | anubhav-shukla/Learnpyhton | /string_vs_Lists.py | 324 | 4.25 | 4 | # list vs strings
# strings are immutable
# lists are mutable
# python string_vs_Lists.py
s="string"
s.title()#you can't change it
t=s.title() #here we make new string and now result is different
# hope immutable is clear
print(t)
# now see lists
l =['word','apple','word3']
l.append('word3')
prin... |
e6f6cf2720d8f79847900256f357c117f65f5d8e | anubhav-shukla/Learnpyhton | /intro_arg.py | 534 | 4.25 | 4 | # make flexible function
# *operator
# *args
# why we need it
def total(a,b):
return a+b
# print(total(3,4,5,7))#it give error
# but we can solve it using * operator
def all_total(*args): #according to convetion we use args
print(args)
print(type(args))
all_total(1,2,3,4,4,5,6)
... |
a60dc9ede5370a3b34d3d83dfed02829c74b6ddf | anubhav-shukla/Learnpyhton | /more_about_set.py | 945 | 4.40625 | 4 | # like before we see in the other chapter see here how can use loop and some other thing in set\\
# python more_about_set.py
s={'a','b','c','d','e','f'}
# in keyword in set and for loop
# we check here item is present or not in the list
if 'a' in s:
print('present')
else:
print('not presen... |
122bf229d1bb35788194f0b83bc3ca79334c1d84 | anubhav-shukla/Learnpyhton | /read_write_csv.py | 593 | 3.625 | 4 | # reader , DR
# writer ,DictWriter
from csv import DictReader , DictWriter
with open('file.csv','r') as rf:
with open('file2.csv','w',newline='') as wf:
csv_reader = DictReader(rf)
csv_writer = DictWriter(wf,fieldnames=['first_name','last_name','age'])
csv_writer.writeheader(... |
6b2fad0ec74984139d7f2a980a94956e7a1fe216 | samantha-huang/Python-2021 | /Extracting Data from XML.py | 1,228 | 3.75 | 4 | ##################################################################################################
#Purpose: The program will prompt for a URL, read the XML data from that URL using urllib
# and then parse and extract the comment counts from the XML data, compute the sum of the numbers
# in the file.
# Look through a... |
86f3de5aa7d94253224fac86850e2781e55e52ca | SydHzf/Python-Practice | /ch3ex/ex35.py | 255 | 3.515625 | 4 | # quantity of alphabates in a word or sentence
user=input('enter your name : ')
i=0
v=''
while i<len(user):
if user[i] not in v:
v+=user[i]
print(v)
print(f'{user[i]} : {user.count(user[i])}')
i+=1
# boht hard boht hard |
d015e123c379a1e7808f32b550dcaa4cda3e8134 | jowilf/devchampignon2020 | /c.py | 954 | 3.609375 | 4 | def rotate(input, d):
# slice string in two parts for left and right
Lfirst = input[0: d]
Lsecond = input[d:]
Rfirst = input[0: len(input) - d]
Rsecond = input[len(input) - d:]
return Rsecond + Rfirst
# now concatenate two parts together
# print("Left Rotation : ", (Lsecond + Lfirst))
... |
eff09d5e6237b171402bece44afe0203dfb8dc8c | TMJ12/fibonacci | /fibonacci.py | 188 | 4.34375 | 4 | #Program to display fibonacci series up to a limit
n=int(input("Enter the limit:"))
x=0
y=1
z=1
print("Fibonacci Series")
print(x,y,end=' ')
while z<=n:
print(z,end=' ')
x=y
y=z
z=x+y
|
be1850c7ff654435fcc511677b3a7f5b2745981b | Lymielyn/Recommender_for_skintype | /Web_scraping.py | 5,214 | 3.546875 | 4 | """
This function is designed to scrape SpaceNK website to get information about the products' ingredients, price, rating, and more
"""
from bs4 import BeautifulSoup
import urllib.request
import pandas as pd
import numpy as np
import re
from urllib.request import urlopen
url = "https://www.spacenk.com/uk/en_GB/skinc... |
b03ec37c7cf0695348b7ab73f40cdb091d458d93 | shuxinzhang/nltk-learning | /exercises/Chapter 08/08-30.py | 459 | 3.5 | 4 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import nltk
'''
★ Write a function that takes a grammar (such as the one defined in
3.1) and returns a random sentence generated by the grammar.
(Use grammar.start() to find the start symbol of the grammar;
grammar.productions(lhs) to get the list of pr... |
4a560bd2f597689f8f2415ac172cbf6168226412 | shuxinzhang/nltk-learning | /exercises/Chapter 01/01-28.py | 303 | 3.953125 | 4 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import nltk
'''
◑ Define a function percent(word, text) that calculates
how often a given word occurs in a text, and expresses the result
as a percentage.
'''
def percent(word,text):
return str(100*(text.count(word)/len(text)))+"%" |
1f5c30b9fa37fc7d08d0943b472468f223c00555 | shuxinzhang/nltk-learning | /exercises/Chapter 01/01-23.py | 408 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import nltk
'''
◑ Review the discussion of looping with conditions in 4.
Use a combination of for and if statements to loop over the words of
the movie script for Monty Python and the Holy Grail (text6)
and print all the uppercase words, one per line.
... |
1fa3999fb2686ea3c79ea997a7bba0f492f0660c | shuxinzhang/nltk-learning | /exercises/Chapter 04/04-9.py | 328 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import nltk
'''
☼ Write code that removes whitespace at the beginning and end of a
string, and normalizes whitespace between words to be a single
space character.
do this task using split() and join()
do this task using regular expression substitutions... |
505c1f68eb5d6b7a31279619ebc1fd39e925c641 | shuxinzhang/nltk-learning | /exercises/Chapter 04/04-11.py | 762 | 4.09375 | 4 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import nltk
'''
◑ Create a list of words and store it in a variable sent1.
Now assign sent2 = sent1. Modify one of the items in sent1
and verify that sent2 has changed.
Now try the same exercise but instead assign sent2 = sent1[:].
Modify sent1 again ... |
ea953ede871032c479a16185d674a3622b894501 | shuxinzhang/nltk-learning | /exercises/Chapter 04/04-29.py | 240 | 3.640625 | 4 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import nltk
'''
★ Write a recursive function that pretty prints a trie in alphabetically
sorted order, e.g.:
chair: 'flesh'
---t: 'cat'
--ic: 'stylish'
---en: 'dog'
''' |
ffcbf4cfedc88b0dfe62fb88ad2db28164e44eb9 | shuxinzhang/nltk-learning | /exercises/Chapter 02/02-14.py | 793 | 3.625 | 4 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import nltk
'''
◑ Define a function supergloss(s) that takes a synset s as its argument
and returns a string consisting of the concatenation of the definition of s, and
the definitions of all the hypernyms and hyponyms of s.
'''
from nltk.corpus import ... |
4aa1d6c8e93590829e2c838e67ecdafa283ac7f3 | shuxinzhang/nltk-learning | /exercises/Chapter 03/03-19.py | 489 | 3.921875 | 4 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import nltk
'''
◑ Create a file consisting of words and (made up) frequencies, where each
line consists of a word, the space character, and a positive integer,
e.g. fuzzy 53. Read the file into a Python list using open(filename).readlines().
Next, brea... |
e29e79f3c3f3e7fb28d2fb53273571ff4432b73e | carol8562/lecture2 | /python_basics/08-dictionaries.py | 99 | 3.8125 | 4 | ages = {"Alice": 97, "Bob": 3}
ages["Methuselah"] = 969
print(ages)
ages["Alice"] += 3
print(ages)
|
847c2df7837345167e40b685b0e444ded82c60c3 | xandmaga/migracao_py-upsert | /csv2json.py | 714 | 3.5625 | 4 | import csv
import sys
import json
import codecs
def convert(filename):
csv_filename = filename[0]
print "Opening CSV file: ",csv_filename
f = open(csv_filename, 'r') #codecs.open(csv_filename, 'r', 'utf-8')
csv_reader = csv.DictReader(f, quoting=csv.QUOTE_NONE, quotechar='')
json_filename = csv_filename.rp... |
9b20d7e9b38e96c5660ebf397e6ad7d271c4c3d7 | jcbroe/showcase | /Games/Python/15puzzle/15puzzleGUI.py | 7,912 | 3.734375 | 4 | from tkinter import *
from tkinter import messagebox
import random
# ************************************************
class Board:
def __init__(self, playable=True):
while True:
# list of text for game squares:
self.lot = [str(i) for i in range(1,16)] + ['']
if not pl... |
40820e4dd33a05bb20760194e0354da91a4de470 | jcbroe/showcase | /Miscellaneous/Python/Fizzbuzz.py | 586 | 4.40625 | 4 | # Write a short program that prints each number from 1 to 100 on a new line.
# For each multiple of 3, print "Fizz" instead of the number.
# For each multiple of 5, print "Buzz" instead of the number.
# For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
def fizzbuzz():
for ... |
6b93c93a3afee03573c143e0d8110b887ac0e63c | HeyYou-dev/ninjaRepo | /Easy/TwoSumProblem/twoSUM_GreedyApproach.py | 1,066 | 3.625 | 4 | class Solution:
def twoSum (self,nums,target):
temp =[]
#Sort the arrary first
nums.sort()
#Getting forward and backward index
forward = 0
backward = len(nums)-1 #Last index of nums
while (forward<backward):
sum = nums[forward]+nums[backward]
... |
7df71a30d4493208029d52c3059e59726cf99885 | LRSFC-ComputerScience/A-Level-Year-1 | /bubbleSort.py | 768 | 4.125 | 4 | import random #To be used to generate the array.
"""Bubble Sort Algorithm"""
def bubbleSort(arrayOne):
for passing in range(len(arrayOne)-1,0,-1):
for i in range(passing):
if arrayOne[i]>arrayOne[i+1]:
number = arrayOne[i]
arrayOne[i] = arrayOne[i+1]
... |
e7e0005de746eed4868f65b3a8ec9a5486d3be1e | yamonc/bigData_course | /01_python基础/格式化输出.py | 299 | 3.640625 | 4 | name="小明"
print("我的名字叫%s,"%name)
student_no=11234568
print("我的学号是:%06d"%student_no)
price=9.00
weight=1.5
money=price*weight
print("苹果单价%.2f元/斤,购买了%.2f斤,需要支付%.2f元"%(price,weight,money))
scale=0.25
print("数据比例是%.2f%%"%(scale*100)) |
90c39908230abbf1340584233139ceb57cbfb4b3 | yamonc/bigData_course | /base_python/0118/Fibonacci_sequence.py | 571 | 4.09375 | 4 | # 斐波那契数列(Fibonacci sequence),又称黄金分割数列,是意大利数学家莱昂纳多·斐波那契(Leonardoda Fibonacci)
# 在《计算之书》中提出一个在理想假设条件下兔子成长率的问题而引入的数列,所以这个数列也被戏称为"兔子数列"。
# 斐波那契数列的特点是数列的前两个数都是1,从第三个数开始,每个数都是它前面两个数的和,
# 形如:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...。
a = 0
b = 1
for _ in range(20):
a, b = b, a + b
print(a, end=' ')
|
04c1f4c7b55f72259b693774bd4bc667ec3c0d75 | yamonc/bigData_course | /base_python/0406/demo.py | 1,035 | 3.640625 | 4 | # 编写一个函数,读取文件 words.txt ,建立一个列表,其中每个单词为一个元素。
# 编写两个版本,一个使用 append 方法,另一个使用 t = t + [x] 。
# 那个版本运行得慢?为什么?
import time
def make_word_list1():
"""
读取文件中的单词
:return:
"""
t = []
# 读取文件
fin = open('words.txt')
for line in fin:
word = line.strip()
t.append(word)
return t
... |
ddbfd5c0cca9c7d59287a5783ce3f5e846daf570 | yamonc/bigData_course | /base_python/0127/listComprehensions.py | 1,070 | 3.734375 | 4 | # 列表解析:根据已有列表,高效创建新列表的方式。
# 列表解析是Python迭代机制的一种应用,它常用于实现创建新的列表,因此用在[]中。
# 语法:
# [expression for iter_val in iterable]
# [expression for iter_val in iterable if cond_expr]
# 1. 要求:列出1-10所有的数字之和的平方
# 1. 直接的方法:
l = []
for i in range(1, 11):
l.append(i ** 2)
print(l)
# 2. 使用列表解析
l = [i ** 2 for i in range(1, 11)]... |
5a587dbf1a0bf28f4c1fa73b45c1dff1f9826371 | L-Q-K/C4TAdHW | /Backtrack/n_queen.py | 856 | 3.875 | 4 | board_out = [0,0,0,0]
def is_safe(board,row,col):
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 1:
if (i == row) or (j == col):
return False
if abs(i-row) - abs(j-col) == 0:
return False
retu... |
cfcd4f399a5d714b86a0449389d105a687af57df | L-Q-K/C4TAdHW | /Test/test1.py | 100 | 3.515625 | 4 | so_1 = input('So thu 1: ')
so_2 = input('So thu 2: ')
t = int(so_1) + int(so_2)
print('Tong: ', t) |
470ac6de3f8b596d7a42bd3ff27a370b361fd6fe | emrbzr/BookMe | /app/core/user.py | 590 | 3.640625 | 4 | # User object
class User:
# Constructor
def __init__(self):
pass
def __init__(self,userId, name,password):
self.name = name
self.password = password
self.userId = userId
# Accessors and Mutators
def getName(self):
return self.name
def setName(self,name... |
7c965614fbc67a3e00ec9af2363a463596bf03d0 | LukeJaffe/classes | /cs231a/work/hw/pset1/ps1_code/p3.py | 7,190 | 4.0625 | 4 | #!/usr/bin/env python3
# CS231A Homework 1, Problem 3
import numpy as np
from utils import mat2euler
import math
def compute_vanishing_point(points):
'''
COMPUTE_VANISHING_POINTS
Arguments:
points - a list of all the points where each row is (x, y). Generally,
it will contain four ... |
ca35ae5f0513bb7dacaaa2cc5e16e0adf3415852 | cadmusgo/Python-002 | /week08-09/homework03.py | 609 | 3.890625 | 4 | """
作业三:
实现一个 @timer 装饰器,记录函数的运行时间,注意需要考虑函数可能会接收不定长参数。
"""
import time
from functools import wraps
def timer(func):
print("timer...")
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print("{} ran in {}s".forma... |
c4378cba74b7d6321ffb49108aa43909835a7ebb | bi4ok/python-lessons | /data structure/OrderedList/orderedlist.py | 4,635 | 3.921875 | 4 | class Node:
def __init__(self, v):
self.value = v
self.next = None
self.prev = None
class OrderedList:
def __init__(self, asc):
self.head = None
self.tail = None
self.ascending = asc
def compare(self, v1, v2):
if v1.value < v2.value:
ret... |
c189d2bc7a56d74f7a1d97620f4da61c325063a3 | holliwid/first_task | /first_task.py | 1,195 | 3.625 | 4 | import string
def data_preparation(filepath):
with open(filepath) as file:
sorted_list = []
lines = file.read()
lines_list = lines.split(',')
lines_list_without_quotes = [name[1:-1] for name in lines_list]
sorted_list = sorted(lines_list_without_quotes)
return so... |
a96811b0b2c249fb73ea0322da8fadb8ffaca7ad | Zero-Cube/Matematika | /Linearne funkcie.py | 1,466 | 3.78125 | 4 |
x1 = int(input("Zadaj X:"))
y1 = int(input("Zadaj Y:"))
x2 = int(input("Zadaj X:"))
y2 = int(input("Zadaj Y:"))
Q = [x1, y1]
P = [x2, y2]
q = 1
print("Q =", Q)
print("P =", P)
print("____________")
# Y = kx + q
Y1: y1 = x1 + q
Y2: y2 = x2 + q
Y_vysledok = y1 - y2
kx = Y1-Y2
X = Y_vysledok/kx
na = X * x1
q_ = kx * x... |
50c14821fca0429092b1609071f7c16d292c8715 | aemmadi/trainTheAi | /web-apps/TicTacToe/empty_file.py | 2,932 | 3.5625 | 4 | import numpy
import random
class TicTacToeNN:
w1 = random.uniform(0,1) * .2 - .1
w2 = random.uniform(0,1) * .2 - .1
w3 = random.uniform(0,1) * .2 - .1
w4 = random.uniform(0,1) * .2 - .1
w5 = random.uniform(0,1) * .2 - .1
w6 = random.uniform(0,1) * .2 - .1
w7 = random.uniform(0,1) * .2 - .... |
504b36dcc6c622d346aa8b515273d75d6649010c | OwaisBadat/assignment3 | /sortingarray.py | 1,755 | 4.25 | 4 |
def bubble_sort(new_list):
print("bubble_sort")
#The outter loop controls the number of passes needed to sort everything
for k in range(0,len(new_list)-1,1):
#each pass of the bubble sorts one element. The number of passes needed are len(new_list)-1
#the inner loop is moving the bubble ... |
93e0f677a64f04dcb5dad70c0e8ec0c950aaa494 | trmckean/Machine-Learning | /SVM/SVM.py | 12,314 | 3.703125 | 4 | #Tyler McKean - February 16th, 2016 - Machine Learning
#The following program uses SVM's to predict whether or not a specific email is spam. There are three experiments carried out.
#Imports including the package for the SVM to be used as well as the package to produce an ROC curve
from sklearn import svm
import random... |
89298a5f1b64bc858c0e53b5e354f416da42353c | michaelharms6010/Intro-Python-II | /src/player.py | 1,627 | 3.640625 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, starting_room):
self.name = name
self.current_room = starting_room
self.inventory = []
def hasItem(self, item):
for i in self.inventory:
if i.na... |
ff6e676e4c55eeadaca9d2b5ca985e2302846dc7 | Andrew-Gair/Project_Cat_v2 | /Project_Cat_v2/Source/fileIO.py | 452 | 3.84375 | 4 | # Author: Andrew Gair
# Date: September 2020
# Purpose: Helper functions to manage input and output to/from files.
import sys
import os
# Opens 'FileName' and appends 'Value' to it
def WriteToFile(FileName, Value):
FileHandle = open(FileName, "a")
FileHandle.write(Value)
FileHandle.close()
# Opens 'FileName'... |
747775486ae05129c22274355dd9b7c159311b05 | bella013/Python.questions.decision | /questao16.py | 516 | 3.9375 | 4 | a = float(input("Informe o valor 'a' da equação de segundo grau: "))
b = float(input("Informe o valor 'b' da equação de segundo grau: "))
c = float(input("Informe o valor 'c' da equação de segundo grau: "))
if(a==0):
print("Não é uma equação de segundo grau")
else:
delta = b*b - 4*a*c
if(delta<0):
... |
3dd140ef9e9d9c921db2ec884547679f569944a0 | ellotecnologia/dojo | /python/dictionary_replacer.py | 1,536 | 3.578125 | 4 | import unittest
def substitui(template, dicionario):
dentro = False
resultado = ''
termo = ''
for l in template:
if l != '$':
if dentro:
termo += l
else:
resultado += l
else:
if not dentro :
dent... |
0465933061f4f789f44848c53cfb987cf3fde13d | unibe-geodata-modelling/exercise-network-analysis | /01_intro_networkx.py | 1,895 | 3.6875 | 4 | #importing the libraries
import networkx as nx
import numpy as np
import itertools
import matplotlib.pyplot as plt
#initializing an empty (here undirected) graph
G = nx.Graph()
#adding nodes
G.add_node("Rome")
G.add_node("Bern")
G.add_node("Zurich")
G.add_node("Vienna")
G.add_node("Berlin")
G.add_node("Paris")
#addin... |
0630d0635fdd3ec1e9e2126e631c0da7353697de | PREN1718-G03/pi-sensor | /camera_sensor/DistanceCalculation.py | 393 | 3.75 | 4 | import abc
from TargetModel import TargetModel
class DistanceCalculation(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def calculate_distance(self, target):
if not isinstance(target, TargetModel):
raise TypeError('target not of type TargetModel')
raise NotImplemente... |
c8184500cfc6c0c5b2310a4b9414f0431b249ddc | PREN1718-G03/pi-sensor | /camera_sensor/SensorController.py | 446 | 3.65625 | 4 | import abc
class SensorController(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def get_target_and_distance(self):
"""Returns if target is found and the distance to the target in cm"""
@abc.abstractmethod
def set_height(self, height):
"""Sets the current camera height"""
... |
d0117029594bcb5942b3b5a4be867d350e91a088 | berlin75/study | /python/mysite/sqlite.py | 762 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sqlite3
conn = sqlite3.connect('db.sqlite3')
cursor = conn.cursor()
cursor.execute('drop TABLE if EXISTS session;')
# 获得数据库中所有表的列表
cursor.execute('SELECT name FROM sqlite_master WHERE type="table" ORDER BY name')
values = cursor.fetchall()
print(values)
tns = ... |
7f3539979b08f8890d98251d7400d369062d0905 | abhijit-mitra/Competitive_Programming | /13_find_duplicates.py | 678 | 4.125 | 4 | '''
Find duplicates with time Complexity O(n) and space Complexity O(1)
Input: [1,2,3,1,3,6,6]
Output: 1,3,6
Solution:
Traverse the list from i=0 to n-1
{
if arr[abs(arr[i])]>=0: //if postive
then make it negative
arr[abs(arr[i])] = -arr[abs(arr[i])]
else:
print(arr[i]) // is the repeate... |
899389ba7888d726ba77a19fceff402bc59629c5 | abhijit-mitra/Competitive_Programming | /3_leaders_in_arr.py | 561 | 4.15625 | 4 | '''Leader in arr mean the elm which does not have any number greater than that on right side'''
'''Trick is: Scan all the elements from rigth to left in array and keep track of maximum till now. When maximum chnages its value print it'''
def get_leaders_in_arr(arr):
cur_max = 0
for index in range(len(arr)-1, ... |
1341418fc7927f4b19903bec0fdd846104554085 | fengjutian/code | /insertion_sort.py | 365 | 4.125 | 4 | # 插入排序
def insertion_sort(arr):
for i in range(1, len(arr)):
position = i
temp_value = arr[i]
while position > 0 and arr[position - 1] > temp_value:
arr[position] = arr[position - 1]
position = position - 1
arr[position] = temp_value
list = [4, 5, 6, 2, 3, ... |
e332abe21eb3ffdfd765101d797e6e9569e3c672 | lvapeab/art | /art/scores.py | 2,392 | 3.703125 | 4 | """ Contains classes fore managing scores and lists of scores."""
__author__ = 'smartschat'
class Score(object):
"""A score for an individual document.
Attributes:
values: A list of floats, which constitutes the score for the document
under consideration.
"""
def __init__(sel... |
901ffaed6f05227621ddf4781074e0aef38f872f | junggri/algorithm | /4.py | 611 | 3.59375 | 4 | import collections
import re
paragraph = 'Bob hit a ball, the hit BALL flew far after it was hit'
banned = ['hit']
#
# word2 = [word for word in re.sub(r'[^\w]', " ", paragraph).lower().split() if word not in banned]
# print(word2)
#
# most, count = ("", 0)
#
# for a in word2:
# count2 = word2.count(a)
# if co... |
8d7dbec301621ebbfc8a3081f13312908714ce36 | junggri/algorithm | /5.py | 133 | 3.84375 | 4 | strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
lists = []
for word in strs:
list.append("".join(sorted(word)))
print(list)
|
9965e7ae097855aa6a8bf25df04c0c801d623fe5 | Teodora-tart/LeetCode-exercise | /Array/permutationSequence.py | 495 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 3 14:48:03 2021
@author: Song Yifan
"""
from math import factorial
def getPermutation(n, k):
string = ''
total = n
lst = [i for i in range(1,n+1)]
k = k-1
while (n > 0):
index, k = divmod(k, factorial(n-1))
string += st... |
b93e90fdbf7e6ed6d6901a978c28ccecc46fb9c0 | Teodora-tart/LeetCode-exercise | /Array/remove_duplicates2.py | 423 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 28 16:42:56 2021
@author: Song Yifan
"""
def removeDuplicates(nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
for n in nums:
if i<2 or n>nums[i-2]:
nums[i] = n
i += 1
return i
nums = [... |
ab7367dbcbc12207887462277caedd5da7fa048d | artiom-zayats/advent | /2019/problem_1.py | 653 | 3.5625 | 4 | def load(filename):
with open(filename) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [int(x.strip()) for x in content]
return content
def find_fuel(fuel):
ans = 0
while fuel > 0:
temp = fuel//3
... |
bf28e5d7df144937edfb0c7533e4c85eaf5c174d | cmontalvo251/Microcontrollers | /Clue/auto_watering_standalone.py | 2,004 | 3.53125 | 4 | import time
import board
import digitalio
import analogio
from adafruit_clue import clue
#print(dir(clue))
#print(clue.color)
# Turn off the NeoPixel
clue.pixel.fill(0)
##Button Presses
#buttonA = digitalio.DigitalInOut(board.BUTTON_A)
#buttonA.direction = digitalio.Direction.INPUT
#buttonA.pull = digitalio.Pull.DOW... |
22ba8da1217305bfa253c2a14aa3a7d64dd3688f | lzs1314/pythonWeb | /week4/面向对象/类属性分页.py | 584 | 3.65625 | 4 | #@coding :utf-8
#@FileName: 类属性分页.py
#@Author :辰晨
#@Time :2019/4/27 11:43
class Pergination:
def __init__(self,current_page):
try:
p = int(current_page)
except Exception as e:
p = 1
self.page = p
@property
def start(self):
val = (self.page -... |
d1194cf5583977ad8c6a676f02815862491e8126 | lzs1314/pythonWeb | /week1/1.py | 1,290 | 3.53125 | 4 | for i in range(1,10):
for j in range(1,i+1):
print('%d x %d = %d '%(j,i,i*j),end='') #通过指定end参数的值,可以取消在末尾输出回车符,实现不换行。
print()
import random
list1=[]
for i in range(65,91):
list1.append(chr(i)) #通过for循环遍历asii追加到空列表中
for j in range (97,123):
list1.append(chr(j))
for k in range(48,58):
... |
5b7612a9c86ba95381856f2d84f0ca5980c8ac3a | Subhamp7/Python_Code | /Lucky_number/Lucky_Number_selection.py | 1,019 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 10 17:27:58 2020
@author: subham
"""
from pop_up import index_name
def Vehicle_Lucky_Number_Generator():
Required_Lucky_Number=index_name('Required')
Any_Unwanted_Number=index_name('Unwanted')
Final_List=[]
My_List=9999
for index1 in range(... |
b3ec06a35b435e00f4aee59b543409e6d8519b6b | AmeerTamoorKhan/Fake-Real-News | /streamlitUI.py | 2,848 | 3.65625 | 4 | import streamlit as st
import tensorflow.keras as keras
import pickle
import numpy as np
import pandas as pd
example_data = [('Donald Trump Sends Out Embarrassing New Year’s Eve Message; This is Disturbing', 'Fake'),
('U.S. military to accept transgender recruits on Monday: Pentagon', 'Real'),
... |
2dae024cbb7b7a22b4187e482aaabe169724aea3 | haga-/battleship | /player.py | 2,434 | 3.59375 | 4 | from sys import stdout
from board import Board
class Player:
# constructor
def __init__(self):
self.my_board = Board()
self.opponent_board = Board()
# sends board as string
def send_my_board(self):
return self.my_board.send_board()
# set a ship on players own board
de... |
ddf4ff51eedda9a7c56ccc444d8efc03be0c3370 | jexiamaris/python-homework | /PyRamen/PyRamen.py | 2,953 | 3.625 | 4 | from pathlib import Path
import csv
# Set the file path
menu_csv = Path("Resources/menu_data.csv")
sales_csv = Path("Resources/sales_data.csv")
# @TODO: Initialize list objects to hold our menu and sales data
menu = []
sales = []
# @TODO: Read in the menu data into the menu list
with open (menu_csv, "r") as csvmenu... |
cc3414cd8159889657fe73c0b6b7915b4893d566 | rfdickerson/cs241-data-structures | /A6/app/astar/pathfinder.py | 1,887 | 3.9375 | 4 | import math
from priorityqueue import PriorityQueue
# You can set the cost of moving these directions in the following constants
LAT_COST = 10
DIAG_COST = 14
class MapTile (object):
""" Holds information about a tile on the map.
g is the cost of travelling from the start to that node. Allows diagonal moves.
... |
00c2d5ba0a49b686a7411dd23a4fd0ef93fe57fd | rfdickerson/cs241-data-structures | /final/spellchecker.py | 579 | 3.5625 | 4 | from trie import Trie
def loadDictionary(t):
d = open('data/brit-a-z.txt','r')
for w in d:
wl = w.lower()
t.insert(wl)
pass
def testSentence(t,s):
# get rid of punctuation
s = s.replace('.','')
s = s.replace(',','')
s = s.split()
for w in s:
r = t.is... |
4a186f46aab59059bdabcf7b8131c4ee742def12 | 40013015/PythonLearning | /FACTORIAL1.py | 139 | 3.78125 | 4 | def fact(num):
n=1
for num1 in range(1,num+1):
res=n*int(num1)
n=res
return n
print(fact(int(input()))) |
a054465c34bf110666524e6211e851ad0328e933 | 40013015/PythonLearning | /powerof2.py | 192 | 4.3125 | 4 | def powerofTwo(num):
while num%2==0:
num=num/2
if num==1:
return "Given num is power of two"
return "not power of two"
print(powerofTwo(int(input()))) |
415ca3dc72b94254bb5fc69d56dbcbb8db1c58f5 | 40013015/PythonLearning | /swapcase.py | 300 | 3.609375 | 4 | '''str1=str(input())
print(str1.swapcase())
print(str1.upper())
print(str1.lower())'''
def grtdub(num):
res=0
str1=str(num)
for i in range(len(str1)-1):
if int(str1[i]+str1[i+1])>res:
res=int(str1[i]+str1[i+1])
return res
print(grtdub(int(input())))
|
b2aabef4ae89a1c6be88847889e0170c5acc435a | ArthurKhakimov/python_hw | /hw19_server.py | 1,728 | 3.5 | 4 | #!/usr/bin/env python3
# Полученные от клиента данные перевдим в строку. При нахождении в строке подстроки ADD, записываем пару в словарь.
# При запросе клиента, имя ищем в первую очередь из словаря, если там нет уже запрашиваем через gethostbyname.
# В пару мест добавил обработку исключений, чтоб при ошибочном вводе ... |
fdb45b711b7244614597ff8452cd5dc138a1b4c7 | ArthurKhakimov/python_hw | /hw13.py | 919 | 4.28125 | 4 | #!/usr/bin/env python3
# Переделал и начал принимать тип шкалы в параметрах к функции
def temperature_converter(t, scale):
"""Функция для конвертации температуры из Цельсия в Фаренгейт и наоборот.
Передаваемые параметры: температура и тип шкалы('f' для Фаренгейта, 'с' для Цельсия)"""
if scale == 'f':
... |
7b87bcab3e86ebb38b5c0d0c7eb9d94279956394 | ArthurKhakimov/python_hw | /hw10.py | 734 | 4.125 | 4 | #!/usr/bin/env python3
def even_and_action(e): # функция для проверки четности и выполнения вычисления
if e % 2:
return int(3 * e + 1)
else:
return int(e / 2)
num = int(input('Введите натуральное число:'))
i = 0
while num != 1:
num = even_and_action(num)
i = i + 1
print("Число шагов:"... |
244fc69ecc71de062b33bd7c4a55d7c4a0c3d297 | maddevred/recursion_rocks | /factorial.py | 292 | 4.375 | 4 | # You will have to figure out what parameters to include
# 🚨 All functions must use recursion 🚨
# This function returns the factorial of a given number.
def factorial(n):
if (n < 2):
return 1
else:
return n*factorial(n-1)
print(factorial(5))
# DONE/ WORKING |
588788440219a6775a2deea7a30d4090f68f5315 | atirpetkar/Show_Me_The_Data_Structures | /problem_5.py | 2,883 | 3.90625 | 4 | import hashlib
import time
class Block(object):
"""
Block class
- every block will maintain a reference to the previous block within a chain
"""
def __init__(self, timestamp, data, previous_hash):
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_ha... |
99f31c85fd2a9becd14e7b03073db5a66a09ca07 | elkasoapy/google_codejam | /2016/IO_2016_for_Women/problem_A/codys_jams.py | 2,345 | 3.703125 | 4 | #!/usr/bin/env python
################################################################################
#
# Google Code Jam to I/O for Women 2016
#
# Problem A - Cody's Jams
#
# Victoria Lopez Morales - elkasoapy@gmail.com
#
################################################################################
import sys
im... |
f1bbd30866e21bc83bb57193b0575d8b54d68fb3 | rexsutton/GPML | /LaplaceBinaryGpClassifier.py | 24,001 | 3.578125 | 4 | #!/usr/bin/env python
"""
!!! Not certified fit for any purpose, use at your own risk !!!
Copyright (c) Rex Sutton 2016.
Python implementation of binary classification (machine learning),
using a Gaussian Process with Laplace's approximation for the posterior.
See `Rasmussen, Williams 2006 Gaussia... |
0ce89ae74d0124a733b0960f728714248fb044a7 | rabotaresp/Phyton | /Test/HW_Bones.py | 20,698 | 3.734375 | 4 | import random
print('Для выхода из игры введите любой символ не соответствующий цифре')
answer = str()
while answer != "n":
x = input("Выбирете тип игры: \n Игра угадай чисело (с PC), введите 1: \n Игра угадай число (Один игрок), введите 2: "
" \n Игра угадай число (Два игрока), введите 3: \n Игр... |
6b89daf3806de3ced477d795324474a879a1c286 | rabotaresp/Phyton | /Test/CW_15.py | 326 | 3.9375 | 4 | # l = zip([-2,-5,-2],[1,2,3],['a','b','c'])
# for q in l:
# print(q)
def f(x):
return x*x
nums = [1, 2, 3]
for num in nums:
print (f(num))
def f(x):
return x * x
print([f(num)for num in nums])
def f(x, y):
return x*y
a = [1,3,4]
b = [3,4,5]
y = list(map(f, a, b))
print (y)
[3, 1... |
867c694302cd9bb2b681a3a3ff68675272693f95 | ElcimarSilva/python-aula2 | /exe7.py | 2,310 | 4.03125 | 4 | #7 - Escreva um algoritmo que leia 10 números informados pelo usuário e,
#depois, informe o
#menor número
#o maior número
#a soma dos números informados e a
#média aritmética dos números informados.
#self é utilizado para puxar variaveis quando se estar dentro de classes e métodos
class DezNumeros():
numero = 0
... |
89e90a57d33375924a850b1e1f416f4259d98270 | ElcimarSilva/python-aula2 | /exe12.py | 302 | 3.84375 | 4 | #12 - Ler dois valores (considere que não serão lidos valores iguais) e escrever o maior deles.
valor1 = int(input("Digite o primeiro valor: "))
valor2 = int(input("Digite o segundo valor: "))
if valor1 > valor2:
print(f"O valor maior é:{valor1}")
else:
print("O valor maior é: ", valor2) |
1683493d4cb18d32d2cfdd80b2dd992570bc0888 | wizardcapone/Basic-IT-Center-Python | /old/main9.py | 606 | 3.625 | 4 | # 111 xndir
def input_num(message):
while True:
try:
i = int(input(message))
return i
except ValueError:
print("Mutqagreq bnakan n tiv!")
def input_float(message):
while True:
try:
i = float(input(message))
return i
except ValueError:
print("Mutqagreq irakan x tiv!")
while True:
x = input_f... |
886dad240fee282eb7bc931193550daf5fe64978 | wizardcapone/Basic-IT-Center-Python | /homework3/240.py | 364 | 3.5625 | 4 | def input_num(message):
try:
i = float(input(message))
return i
except:
print("mutqagreq miayn tiv")
while True:
my_arr = []
for i in range(1,5):
n = input_num('mutqagreq drakan tiv-' + str(i) + '\n')
my_arr.append(n)
count = 0
for j in range(len(my_arr)):
if my_arr[j] % 7 == 0:
count += 1
print('... |
b9d4fa3a4ac116df3d63d22436d269ec16a7da62 | wizardcapone/Basic-IT-Center-Python | /old/main10.py | 156 | 3.65625 | 4 | import math
pi = -math.pi
other_pi = math.pi / 8
for i in range(int(pi), int(math.pi)):
y = ((math.sin(pi)) ** 2) + math.cos(pi)
print(y)
pi += other_pi |
6ddf7c29635bee5a2e11f1e9b24b24429820896e | wizardcapone/Basic-IT-Center-Python | /homework3/249.py | 353 | 3.53125 | 4 | def input_num(message):
try:
i = float(input(message))
return i
except:
print("mutqagreq miayn tiv")
while True:
my_arr = []
result = 0
for i in range(1,5):
n = input_num('mutqagreq drakan tiv-' + str(i) + '\n')
my_arr.append(n)
if my_arr[i] > i:
count += 1
result += my_arr[i] ** 2
print('Mijin ... |
055ce055dc9ab895a57e3efe25da542b0cdfc36d | vdivakar/PyTorch_learnings | /pyOOP.py | 711 | 3.765625 | 4 | #class encapsulates attributes and methods
class Lizard:
def __init__(self, name):
self.name = name #attribute
print("Created Lizard object with name: ", name)
def set_name(self, name): #method
self.name = name
print("Changed name to: ", name)
lizard = Lizard("Blue Lizard")... |
fe5e143d05dcc236f5ff1e7578300a3765668de4 | Rim-El-Ballouli/Python-Crash-Course | /solutions/chapter7/ex_7_3.py | 160 | 4.25 | 4 | number = input('enter a number ')
if int(number) % 10 == 0:
print(number + ' is multiple of 10')
else :
print( number + ' is not multiple of 10')
|
c2abc4fd7a34941be8ef0651ea1ae888723d4e78 | Rim-El-Ballouli/Python-Crash-Course | /solutions/chapter9/ex_9_13.py | 618 | 3.78125 | 4 | from collections import OrderedDict
glossary = OrderedDict()
glossary['keywords'] = 'words reserved for '
glossary['conditional'] = 'an expression that either evaluates to true or false, used to control flow in code '
glossary['dictonary'] = 'a key value pair of elements '
glossary['tuple'] = 'a list of elements... |
342578e5cb08ffadcd48174b3257ee50f5133f32 | Rim-El-Ballouli/Python-Crash-Course | /solutions/chapter8/ex_8_7.py | 233 | 3.65625 | 4 | def make_album(name, title, tracks=''):
dict = {'name': name, 'title': title}
if tracks:
dict['tracks'] = tracks
return dict
print(make_album('Mini World','Indila'))
print(make_album('Mini World','Indila','10'))
|
d9ef1b55d1b092c2c63f96a3a26405be175a599c | Rim-El-Ballouli/Python-Crash-Course | /solutions/chapter5/ex_5_7.py | 436 | 4.03125 | 4 | favorite_fruits = ['Berries', 'Apples', 'Bananas', 'Watermelon']
if 'Berries' in favorite_fruits:
print('You really like Berries')
if 'Strawberries' in favorite_fruits:
print('You really like Strawberries')
if 'Pears' in favorite_fruits:
print('You really like Pears')
if 'Orange' in favorite_fruits:
... |
455b525188701b6508a8365b61043470ef0fe410 | diksha2112/Projects | /Projects/AML Project/Task1/Twitter_data/Common_words.py | 1,370 | 3.65625 | 4 | __author__ = 'yatinsharma'
import nltk
#function to open text file
def file_open(path):
f = open(path,'rU')
text = f.read().split()
return text
#function to return most common words
def frequency_distribution_words(text,n):
a = []
for word in text:
if len(word)>=6:
a.append(wor... |
d171474fbe6711dfa2cecced020a46c7133ac093 | kvigen/cooking | /src/python/double.py | 445 | 3.578125 | 4 | # This class implements the double recipe optimization
# TODO: We should probably create a pseudo abstract class for this...
class Double(object):
def name(self):
return "Double Recipe"
# The double method is always applicable
def is_applicable(self, recipe):
return True
def apply_to(self, recipe):
... |
44a974054be3abfc779a73cbe99a539b6d3ccc6a | liamhawkins/rosalind | /tests/test_algorithmic heights.py | 1,119 | 3.75 | 4 | import unittest
from algorithmic_heights import fibonacci_numbers, degree_array, binary_search, insertion_sort, double_degree_array, \
majority_element
def test_fibonacci_numbers() -> None:
in_: int = 6
out: int = 8
assert fibonacci_numbers(in_) == out
def test_degree_array() -> None:
in_: str ... |
63c4278a7fb95575e81db0182df5235d8fbf0aab | Dkjaikar/batch89 | /V_turtle_star.py | 209 | 3.53125 | 4 | from turtle import *
s= Turtle()
s.pensize(10)
lst=["red","black","blue","green","orange"]
s.begin_fill()
s.color("pink")
for i in lst:
s.pencolor(i)
s.forward(250)
s.left(144)
s.end_fill()
done() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.